I wrote some PoC for load library with best optimization version during application startup. The goal for it check in the _init
function code checking by cpuid available opcode extensions and load "the best" variant. I only don't know, how to avoid linking bypass.
Part of selecting procedure:
x86_sse41_plus:
test ecx, 0x00100000
jnz x86_sse42_plus
mov edx, lib_x86_sse41 wrt ..gotoff
jmp load_lib
x86_sse42_plus:
test ecx, 0x10000000
jnz x86_avx_plus
mov edx, lib_x86_sse42 wrt ..gotoff
jmp load_lib
x86_avx_plus:
mov edx, lib_x86_avx wrt ..gotoff
load_lib:
call _init_pc
_init_pc:
pop ebx
lea ebx, [ebx + _GLOBAL_OFFSET_TABLE_+$$-_init_pc wrt ..gotpc]
lea eax, [ebx + edx]
sub esp, 8
push dword 0x0110A
push eax
call dlopen wrt ..plt
add esp, 16
test eax, eax
jz _init_end
sub esp, 12
push eax
call dlclose wrt ..plt
add esp, 16
_init_end:
pop ebx
ret
In Makefile I made linking in that way e.g.:
${BINOUT}/libkitdynload_x86_sse42.so: ${OBJECTS_COMMON} ${OBJECTS_X86_SSE42}
@echo ld libkitdynload_x86_sse42.so
@ld -m elf_i386 -shared -o $@ ${OBJECTS_COMMON} ${OBJECTS_X86_SSE42} ${LDFLAGS} -T ${SRCDIR}/linker.ld
example application linking:
${BINOUT}/test: ${SRCDIR}/test.c
@echo cc test
@${CC} -m32 ${CFLAGS} -L${BINOUT}/link -o ${BINOUT}/test ${SRCDIR}/test.c -lkitdynload
Part of this bypass is that:
-L${BINOUT}/link
I have to link in that directory any of optimized variant and linking with that fs symbolic link.
Simple application:
#include "version.h"
#include <stdio.h>
int main(int argc, char * argv)
{
printf("%s %s %s\n", get_kit_dynload_name(), get_kit_dynload_version_str(),
get_kit_dynload_variant_str());
return 0;
}
During dynamic linking code will select "the best" variant transparent.
Full code version is available here on github
How can it be coded better?
-
1\$\begingroup\$ Welcome to Code Review! It appears you took the tour (since you earned the informed badge). Did you review the help center pages like What topics can I ask about here? to ensure your question is on-topic? \$\endgroup\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2025年06月29日 03:15:53 +00:00Commented Jun 29 at 3:15
-
1\$\begingroup\$ Also: I changed the title so that it describes what the code does per site goals: "State what your code does in your title, not your main concerns about it.". Feel free to edit and give it a different title if there is something more appropriate. \$\endgroup\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2025年06月29日 03:16:59 +00:00Commented Jun 29 at 3:16
-
2\$\begingroup\$ Have a look at function multiversioning and target specific optimization, which might do what you want without resorting to writing your own assembly for variant selection. \$\endgroup\$G. Sliepen– G. Sliepen2025年06月29日 15:48:48 +00:00Commented Jun 29 at 15:48
-
\$\begingroup\$ @G.Sliepen your solution make that, what I want to. Thanks! \$\endgroup\$Jakub Juszczakiewicz– Jakub Juszczakiewicz2025年06月29日 19:41:29 +00:00Commented Jun 29 at 19:41