2

Assume we have a very small embedded system consisting only of the linux kernel and a single statically linked binary run as init. We want the binary to be able to dynamically load external plugins in runtime.

Is it possible on linux? Dlopen only works with shared libraries and dynamic linking cause static binaries don't export any symbols to the outside world, so is there any other way to do it?

Zbigh1
  • 379
  • 4
  • 13

2 Answers2

4

You could run the "plugins" as child processes, and communicate over IPC (shared memory, pipes, or so forth).

They would exist in their own process space, so you couldn't directly call functions in them (besides, if they're also statically linked, you won't have any function entry points other than main that you could reach), but you could (e.g.) send a command over a named pipe, or pass data in a shared memory structure.

Note that, the moment you load the second binary, you have lost one of the main benefits of static linking (because now you have two copies of your libc loaded), so you might want to consider just biting the bullet and using dynamic linking. You'll burn a few 100K's in adding the dynamic linking support, but the GNU libc is about 2M, so if you're loading one plug-in, you've gained maybe 1.8M in savings already; and for each additional plug-in you load, you're saving some 2M.

BRPocock
  • 13,638
  • 3
  • 31
  • 50
1

Dlopen only works with shared libraries and dynamic linking cause static binaries don't export any symbols to the outside world

You can dlopen a shared library from a statically linked binary when using glibc. If you need your plugin to reference symbols from the main executable, you would have to pass in pointers to them into the plugin, similar to this.

is there any other way to do it?

You could also write your own module loader. The Linux kernel does this, and so does Xorg.

Community
  • 1
  • 1
Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • Will I be able to pass C++ class member functions to the plugin as well? For example by passing a pointer to an extern C function which allocates a C++ class and returns a void pointer to it? I don't think it will work on it's own - the plugin won't know the member function symbols, but is there a way to access them from inside the plugin? – Zbigh1 Dec 16 '11 at 08:23
  • One more thing: what about the symbols read by nm from a statically linked binary? I compiled a simple "Hello World" program without any debug info with static linking and it still contains a whole lot of symbols from libc. – Zbigh1 Dec 16 '11 at 12:02
  • Yes, you can pass pointers to C++ member functions. Your second question is unclear. You probably should ask additional questions separately. – Employed Russian Dec 16 '11 at 18:24