Skip to content

enhancement: add __builtin_set_counted_by(P->FAM, COUNT) or equivalent #99774

@kees

Description

@kees

With the wonderful addition of the 'counted_by' attribute and its wide roll-out within the Linux kernel, we have found a use case that would be very nice to have for object allocators: being able to set the counted_by counter variable without knowing its name.

For example, given:

  struct foo {
    ...
    int counter;
    ...
    struct bar array[] __attribute__((counted_by(counter)));
  } *p;

one thought was to have __builtin_set_counted_by(P->FAM, COUNT), which would have the behavior of:

  if has_counted_by_attribute(P->FAM):
    P->COUNT_MEMBER = COUNT
  else
    do nothing

The existing Linux object allocators are roughly:

  #define alloc(P, FAM, COUNT) ({ \
    size_t __size = sizeof(*P) + sizeof(*P->FAM) * COUNT; \
    kmalloc(__size, GFP); \
  })

Right now, any addition of a counted_by annotation must also include an open-coded assignment of the counter variable after the allocation:

  p = alloc(p, array, how_many);
  p->counter = how_many;

Instead, the central allocator could be updated to:

  #define alloc(P, FAM, COUNT) ({ \
    typeof(P) __p; \
    size_t __size = sizeof(*P) + sizeof(*P->FAM) * COUNT; \
    __p = kmalloc(__size, GFP); \
    __builtin_set_counted_by(__p->FAM, COUNT); \
    __p; \
  })

And now structs can gain the counted_by attribute without needing additional open-coded counter assignments for each struct, and unannotated structs could still use the same allocator. (i.e. we are able to more cleanly continue to migrate FAM structs.)

GCC feature request exists as well:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=116016

Metadata

Metadata

Assignees

Labels

clang:bounds-safetyIssue/PR relating to the experimental -fbounds-safety feature in Clangclang:codegenIR generation bugs: mangling, exceptions, etc.clang:frontendLanguage frontend issues, e.g. anything involving "Sema"clang:headersHeaders provided by Clang, e.g. for intrinsics

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions