How to create stub shared libraries on Linux

2019-06-19 17:06发布

问题:

Let's first explain what I mean with a stub shared library: a shared library that can be used to link against (w/ a certain interface provided by a real library) but don't contain the actual code (so has no functionality).

Along with the header files it provides everything needed to develop against the library.

Stubs can allow linking to a certain library without having the code available, but also for compatibility it can be useful to link against a stub of a certain library. See for example In Linux stubs are used for standard libraries. Why are stubs required?

Ideally what I need is a way to generate a dummy library from a symbol map file. This map file is, in turn, generated either from an existing .so library or in the same build process.

Are there any tools for this freely available? Or would I need to roll my own?

回答1:

I guess that for simple C libraries, you could use the output of nm -D on your real shared library to make the stub. For instance you could pipe it into a small awk script which defines functions of that same name, etc.

Another approach would be to make your tiny MELT extension to a recent GCC compiler which would generate the stub (e.g. in C++ or C form) when compiling the real library, or which would clear every function body (in a special mode for compiling a stub-only library). This would work for any language compiled by GCC (but requires some understanding of GCC internals, e.g. Trees and Gimples). Ask on gcc-melt@googlegroups.com

However, I am not sure to understand the practical interest of such stubs. In practice a shared library has some specific coding rules and usage, and this is not verified when using stubs. To be concrete, if using Xlib, you need to call XOpenDisplay at first and XCloseDisplay at last, and such rule can't be checked with an automatically generated stub, etc...