How can I inject or dynamically load an c function into another c program

1.1k views Asked by At

I want to build an interface in a c program which is running on an embedded system. This should accept some bytecode that represents a c function. This code will then be loaded into the memory and executed. This will then be something like remotely inject code into a running app. The only difference here is that i can implement, or change the running code and provide an interface.

The whole thing should be used to inject test code on a target system.

My current problem is that I do not know how to build such a byte code out of an existing c function. Mapping and executing this is no problem if I would knew the start address of the function.

Currently I am working with Ubuntu for testing purposes, this allows me to try some techniques which are not possible in the embedded system (according to missing operating system libs).

Is there another solution to do that? Did I miss something? Or can someone provide me another solution to this? I hope I did not miss something.

Thanks in advance

1

There are 1 answers

0
Philipp Claßen On

I see no easy solution. The closest that I am aware of is GCC's JIT backend (libgccjit). Here is a blog post about it.

As an alternative, you could using a scripting language for that code that needs to be injected. For instance, ChaiScript or Lua. In this question, there is a summary of options. As you are on an embedded device, the overhead might be significant, though.

If using an LLVM based backend instead of GCC is possible, you can have a look at Cling. It is a C++ interpreter based on LLVM and Clang. In my personal experience, it was not always stable, but it is used in production in CERN. I would except that the dynamic compilation features are more advanced in LLVM than in GCC.