KSPP / linux

Linux kernel source tree (Kernel Self Protection Project)
https://kernsec.org/wiki/index.php/Kernel_Self_Protection_Project
Other
80 stars 5 forks source link

Adjust struct_size() to be more accurate with strange alignment/padding/etc #250

Open kees opened 1 year ago

kees commented 1 year ago

Right now struct_size() will over-estimate in the cases where flexible arrays start within the struct (rather than exactly at the end). This isn't ideal, but is currently "just" a few bytes of extra space for allocations, etc. There is a risk of pathological problems, though, so it'd be better to make sure the macro can correctly handle weird structure layouts.

Perhaps something like this, adjusted to use size_mul(), size_add(), etc:

        if (offsetof(typeof(p), member) == sizeof(*p)) {
                /* flexible array exactly aligned at end of struct */
                size = sizeof(*p) + count * sizeof(*p->member);
        } else if (offsetof(typeof(p), member) < sizeof(*p)) {
                /* flexible array starts before end of struct */
                size = offsetof(typeof(p), member) + count * sizeof(*p->member);
                if (size < sizeof(*p))
                        size = sizeof(*p);
        } else {
                BUILD_BUG_ON(offsetof(typeof(p), member) > sizeof(*p));
        }