The Microsoft C/C++ compiler allows you to specify link order of functions or variables. Using the #pragma
directive with either code_seg
or data_seg
and specifying the segment name and its sorting key, you can tell the linker how to place the object code in the final executable.
Let’s start with a simple example:
#pragma code_seg(push, ".text$EB009") __declspec(noinline) void f1() { printf("this is f1()\n"); } #pragma code_seg(pop) #pragma code_seg(push, ".text$EB005") __declspec(noinline) void f2() { printf("this is f2()\n"); } #pragma code_seg(pop) #pragma code_seg(push, ".text$EB001") __declspec(noinline) void f3() { printf("this is f3()\n"); } #pragma code_seg(pop) int main() { f1(); f2(); f3(); return 0; }
When the code_seg
pragma is used, we can specify where the subsequent code should lie (in which section in the PE file). When the section name contains the “$” sign, then the subsequent text is not part of the section name (the string prior to the “$”) and instead is used as a sorting key. Continue reading “Shuffling function addresses in C/C++ with MSVC”