Is it possible to load a function symbol from an executable

1 week ago 9
ARTICLE AD BOX

I have 2 files:

foo.c:

#include <stdio.h> int Main(int a) { printf("A%dB",a); } int main() { return Main(1); }

bar.c:

extern int Main(int); int main() { return Main(2); }

If I compile foo.c into an executable (gcc -fPIC foo.c -o foo.out) and run it, it correcty prints A1B.

Same for compiling foo.c into a shared object file (gcc -shared -fPIC foo.c -o libfoo.so) and bar.c into an executable that loads libfoo.so (gcc bar.c -L. -lfoo -o bar.out) and run it, it correctly prints A2B.

But if I try to (1) link bar.out with foo.out or (2) execute libfoo.so it (1) doesn't link (/usr/bin/ld: cannot use executable file './libfoo .so' as input to a link) or (2) crashes on startup with Segmentation fault (core dumped)

Is there a way to create a file that can be executed and is a valid shared object file at the same file, and if not, are there other ways to load the a.out executable (maybe some kind of a dlopen hack) from b.out to run a function from a.out

I am also interested if there is a way to load the executable using java's System.loadLibrary("native") (if possible, only changing the c side and not the java side)

FYI, I want to do this, so I can have an android executable that can be run from something like termux while also being able to be loaded from Android.jar to run as a standalone GUI app

Read Entire Article