c - Can I change the Global Offset Table/GOT or Procedural Linkage Table/PLT programmatically? -
the availability of platform-specific features, such sse or avx, can determined during runtime, useful, if not want compile , ship different objects different features.
the following code example allows me check avx , compiles gcc, provides cpuid.h
header:
#include "stdbool.h" #include "cpuid.h" bool has_avx(void) { uint32_t eax, ebx, ecx, edx; __get_cpuid(1, &eax, &ebx, &ecx, &edx); return ecx & bit_avx; }
instead of littering code runtime checks, such above, repeatedly perform checks, slow , introduce branching (the checks cached reduce overhead, there branching nonetheless), figured use infrastructure provided dynamic linker/loader.
calls functions external linkage on platforms elf indirect , go through procedural linkage table/plt , global offset table/got.
suppose there 2 internal functions, basic _do_something_basic
, somehow optimized version _do_something_avx
, uses avx. export generic do_something
symbol, , alias basic add:
static void _do_something_basic(…) { // basic implementation } static void _do_something_avx(…) { // optimized implementation using avx } void do_something(…) __attribute__((alias("_do_something_basic")));
during load-time of library or program, check availability of avx once using has_avx
, depending on result of check point do_something
symbol _do_something_avx
.
even better be, if point initial version of do_something
symbol self-modifying function checks availability of avx using has_avx
, replaces _do_something_basic
or _do_something_avx
.
in theory should possible, how can find location of plt/got programmatically? there abi/api provided elf loader, e.g. ld-linux.so.2, use this? need linker script obtain plt/got location? security considerations, can write plt/got, if obtain pointer it?
maybe project has done or similar already.
i'm aware, solution highly platform-specific, since i'm having deal low-level platform-specific details, features of instruction set, fine.
as others have suggested can go platform-specific versions of libs. or if ok sticking linux, can use (relatively) new ifunc relocations want.
edit: noted sebastian, ifuncs seem supported other platforms (freebsd, android). note however, feature not used may have rough edges.
Comments
Post a Comment