On Thu, 2023-10-19 at 10:02 -0400, David Malcolm wrote: > This patch adds a new function attribute to GCC for marking that an > argument is expected to be a null-terminated string. > > For example, consider: > > void test_a (const char *p) > __attribute__((null_terminated_string_arg (1))); > > which would indicate to humans and compilers that argument 1 of > "test_a" > is expected to be a null-terminated string, with the idea: > > - we should complain if it's not valid to read from *p up to the > first > '\0' character in the buffer > > - we should complain if *p is not terminated, or if it's > uninitialized > before the first '\0' character > > This is independent of the nonnull-ness of the pointer: if you also > want > to express that the argument must be non-null, we already have > __attribute__((nonnull (N))), so the user can write e.g.: > > void test_b (const char *p) > __attribute__((null_terminated_string_arg (1)) > __attribute__((nonnull (1))); > > which can also be spelled as: > > void test_b (const char *p) > __attribute__((null_terminated_string_arg (1), > nonnull (1))); > > For a function similar to strncpy, we can use the "access" attribute > to > express a maximum size of the read: > > void test_c (const char *p, size_t sz) > __attribute__((null_terminated_string_arg (1), > nonnull (1), > access (read_only, 1, 2))); > > The patch implements: > (a) C/C++ frontends: recognition of this attribute > (b) analyzer: usage of this attribute > > The name is rather long; a shorter name might be "c_string_arg". > > Does anything like this already exist in GCC, or in any other > compilers or analysis tools? > > Thoughts? > > Successfully bootstrapped & regrtested on x86_64-pc-linux-gnu.
Given a week of no comments (apart from Andreas' typo fix), I've gone ahead and pushed this to trunk as r14-4958-gcd7dadcd2759d1 (with the typo fix). I kept the rather long but explicit spelling ("null_terminated_string_arg") since projects tend to use macros for function attributes rather than spelling them out each time, and so I don't see the length being a problem to end-users. Dave