Search code examples
cvisual-studiolinkerportable-executablepragma

Add section to executable on link


I'm currently using Visual Studio 2017, and trying to make my application a little more tamper resistant. Right now the critical code function I want to be protected will be decrypted at runtime, and for that I'm trying to add them to a custom section in the file, which will be called .foobar as an example. I'm using #pragma directives to add the section and later to specify what function should be linked there, however when I analyze the PE file there is no .foobar section.

The code with which I'm trying to add the function is as follows:

#pragma section(".foobar",execute, read, write)
#pragma comment(linker,"/SECTION:.foobar,ERW")
...
Main() function and others...
...
#pragma code_seg(".foobar")
int IWantThisToBeInFoobar() {...}

I also tried with the following:

int IWantThisToBeInFoobar();
...
#pragma alloc_text(".foobar", IWantThisToBeInFoobar)
...
int IWantThisToBeInFoobar() {...}

Neither of these worked so far, I'm using ExeInfo PE to view to sections and there is no sign of .foobar anywhere.

Any help or guidance is appreciated.


Solution

  • Figured it out, had to compile using /OPT:NOREF, and /LTCG.

    Hope this is useful for someone in the future.