如何获取已加载的 .so 文件在内存中的基址?

huangapple go评论69阅读模式
英文:

How to get the base address of a loaded .so in memory?

问题

我正在开发一个嵌入式Linux程序。情景是这样的:
有数千个配置项,它们在最终可执行文件中以静态方式编译,这些配置项的地址在链接器脚本中定义,例如,

firstConfigItem = .;
*(.SEGM_CONFIG)
lastConfigItem = .;

这样,变量firstConfigItemlastConfigItem直接在源代码中使用。

现在的问题是,即使只对一个配置项进行微小修改,也必须重新编译可执行文件。

因此,我的想法是将所有配置项编译为一个.so文件,然后动态加载它。

这可行吗?如果可以,如何初始化firstConfigItemlastConfigItem?Linux中是否有任何API可以获取指定.so文件的加载地址?

或者,有没有人能推荐一个更简单的方法?

提前感谢任何帮助。

英文:

I am working on an embedded Linux program. The scenario is:
There're thousands of configuration items which are compiled statically in the final executable, and the address of the items is defined in the linker script, e.g.,

firstConfigItem = .;
*(.SEGM_CONFIG)
lastConfigItem = .;

so that the variables firstConfigItem and lastConfigItem are used directly in source code.

Now the trouble is, even there's an insignificant modification in only one config item, the executable should be re-compiled.

So my idea is, to compile all the config items as an .so file then load it dynamically.

Is that feasible? If yes, how can I initialize firstConfigItem and lastConfigItem? Is there any api in Linux that can get the loaded addr of a specified so?

Or, can anyone recommend a easier way?

Thanks in advance for any help.

答案1

得分: 1

是的,你可以这样做。应该能正常工作:

  1. 使用 dlopen 打开共享对象。
  2. 使用 dlsym 获取所需符号的地址。
  3. 将该地址写入一个变量以供以后使用。

重要的是要将对象的句柄传递给 dlsym,以便从共享对象中获取符号,而不是从可能定义它的其他组件中获取。

你还可以在构建时生成一个虚拟配置对象并链接到它。在程序启动之前的运行时,将正确的配置对象放入 rpath 中,使你的程序能够自动找到它。然后在运行时你就不需要做任何事情了,它只是与一个共享库进行链接。

英文:

Yes, you can do this. Should work just fine:

  1. open the shared object with dlopen
  2. obtain the address of the desired symbol using dlsym
  3. write that address into a variable for later use

What's important is that you pass the handle of the object to dlsym so you get the symbol from the shared object and not from some other component that might define it.

You can also produce a dummy configuration object and link against it at build time. At runtime before starting the program, you place the correct configuration object into the rpath, allowing your program to automatically find it. Then you don't need to do anything at runtime, it's just a link with a shared library.

huangapple
  • 本文由 发表于 2023年5月29日 16:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定