Issue
Example of usage:
void closefrom (int lowfd);
int main()
{
// expected warning
closefrom(-1);
return 0;
}
Specifically: I should implement diagnostics (compiler warning) for function calls. Function located in glibc:
void closefrom (int lowfd);
If lowfd
is negative compiler should issue a warning.
Here is some information about closefrom
:
https://sourceware.org/pipermail/libc-alpha/2021-August/129718.html
Maybe attribute of the function will somehow help in this?
Solution
want to issue warning only if compiler is able to calculate the value (by optimizations, or if the value is constant). Otherwise just use function without warnin
In short, with GNU extensions:
void foo (int lowfd);
#if defined(__GNUC__) && defined(__OPTIMIZE__)
#define curb(expr, msg) \
__extension__({ \
if (__builtin_constant_p(expr)) { \
if (!(expr)) { \
__attribute__((__noinline__, \
__warning__(msg))) void warnit() {__asm__("");}; warnit(); \
} \
} \
})
#else
#define curb(expr, msg) (void)0
#endif
#define foo(x) (curb(x >= 0, "x is lower than 0"), foo(x))
int main()
{
// expected warning
foo(-1);
return 0;
}
I have this https://gitlab.com/Kamcuk/kamillibc/-/blob/master/libs/curb/src/curb.h#L46 in my tree about the idea of issuing a warning or error if the expression is known at compile time, and if it isn't, failing at runtime or not. The && defined(__OPTIMIZE__)
seems not to be needed in this case.
Answered By - KamilCuk Answer Checked By - Senaida (WPSolving Volunteer)