How to 'link' object file to executable/compiled binary?

后端 未结 6 2194
失恋的感觉
失恋的感觉 2020-12-24 08:41

Problem

I wish to inject an object file into an existing binary. As a concrete example, consider a source Hello.c:

#inc         


        
6条回答
  •  太阳男子
    2020-12-24 09:26

    If it were me, I'd look to create Embed.c into a shared object, libembed.so, like so:

    gcc -Wall -shared -fPIC -o libembed.so Embed.c
    

    That should created a relocatable shared object from Embed.c. With that, you can force your target binary to load this shared object by setting the environment variable LD_PRELOAD when running it (see more information here):

    LD_PRELOAD=/path/to/libembed.so Hello
    

    The "trick" here will be to figure out how to do your instrumentation, especially considering it's a static executable. There, I can't help you, but this is one way to have code present in a process' memory space. You'll probably want to do some sort of initialization in a constructor, which you can do with an attribute (if you're using gcc, at least):

    void __attribute__ ((constructor)) my_init()
    {
        // put code here!
    }
    

提交回复
热议问题