Search code examples
c++cwindowsvisual-c++portable-executable

how to allocate code in specific section for C++ program developed in MS VC++


I am trying to use this code to allocate a slice of code to a independent section:

#ifdef _MSC_VER
#pragma section(".evil",execute)
#pragma code_seg(".evil")
#endif


#ifdef __GNUC__
static __attribute__((section (".evil")))
#elif defined _MSC_VER
static __declspec(allocate(".evil"))
#endif
void __invoke__start()
{//...

But that does not work and the compiler says

The __declspec( allocate()) syntax can be used for static data only.

I do this because I have to write some code to a new file ,and that file is a executable file.

Actually I can not find a way to get the exact address of a function in the memory when the program is running,if the program is compiled with MS VC++ debug mode For a full example,please see this code : full example

Now, the above problem has been solved, but I still want to make it clear that if it is possible to put some code to a independent section. There's other benefit when it is possible for my work, after all.

When I link two object file (COFF format), how can I make sure different code from different obj file will be in different section? Or is there another way to do this?

I am so sorry for my poor English.


Solution

  • you can find the memory address of the beginning of a function with inline assembler, then call a function to use the memory address, like:

    void foo(){
    
        __asm{
            CALL 0h          \\Put current address on top of stack
            CALL myFunction  \\Actually make a funciton call
        }
    
    ...
    
    
    }
    
    int myFunction( int addrFromASM){
        \\do something with addrFromASM+4, which will be where the rest of foo starts.
    }