Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a compiler warning (GNU GCC) when overwriting a weak function

Library functions have the weak attribute set by default (see [1]) and could be "overwritten" with functions having the same signature by accident. For example printf internally calls fputc and I could easily declare one of my functions int fputc(int, FILE *). If that happens, I would like to receive a compiler warning.

Is there a way to tell the compiler to warn me in case of overwriting a weak function?

[1] https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attributes.html

like image 419
floquet22 Avatar asked Mar 04 '16 07:03

floquet22


1 Answers

(I am guessing you are on Linux, and compiling and linking your application as usual, in particular with the libc.so dynamically linked)

Library functions have the weak attribute set by default

This is not always true; on my system fputc is not a weak symbol:

% nm -D /lib/x86_64-linux-gnu/libc-2.21.so|grep fputc
000000000006fdf0 T fputc
0000000000071ea0 T fputc_unlocked

(if it was weak, the T would be a W, and indeed write is weak)

BTW, redefining your own fputc (or malloc) is legitimate (and could be useful, but is very tricky), provided it keeps a semantic conforming to the standard. More generally weak symbols are expected to be redefinable (but this is tricky).

Is there a way to tell the compiler to warn me in case of overwriting a weak function?

No (the compiler cannot warn you reliably).

Since the only thing which could give you some warning is not the compiler (which does not know which particular libc would be used at runtime, you might upgrade your libc.so after compilation) but the linker, and more precisely the dynamic linker, that is ld-linux(8). And the warnings could reliably only be given at runtime (because the libc.so might be different at build time and at run time). Perhaps you want LD_DYNAMIC_WEAK.

If you are ready to spend weeks working on a solution, you might consider using GCC MELT with your own MELT extension and customize a recent GCC to emit a warning when a weak symbol from the libc available at compile time (which might not be the same libc dynamically linked at runtime, so such a check has limited usefulness) is redefined.

Perhaps you might use some LD_PRELOAD trick.

Also, if you linked statically your application, the linker could give you diagnostics if you redefine a libc function.

Read also Drepper's How to Write a Shared Library & Levine's Linkers & loaders book.

like image 150
Basile Starynkevitch Avatar answered Sep 28 '22 01:09

Basile Starynkevitch