在运行时动态修改符号表(在C中) [英] Dynamically modify symbol table at runtime (in C)

查看:202
本文介绍了在运行时动态修改符号表(在C中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时以C(在Linux上为elf格式)动态修改符号表?

Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?

我的最终目标是:

在某些函数中说foo,我想将malloc函数覆盖到我的自定义处理程序my_malloc中.但是在foo之外,任何malloc仍应像在glibc中一样调用malloc.

Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.

注意:这与LD_PRELOAD不同,后者将在整个程序执行期间覆盖malloc.

Note: this is different from LD_PRELOAD which would override malloc during the entire program execution.

推荐答案

是否可以在运行时以C(在Linux上为elf格式)动态修改符号表?

Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?

从理论上讲这是可能的,但实际上很难做到.

In theory this is possible, but in practice it's too hard to do.

在某些函数中说foo,我想将malloc函数覆盖到我的自定义处理程序my_malloc中.但是在foo之外,任何malloc仍应像在glibc中一样调用malloc.

Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.

修改符号表(即使可能的话)也不会 使您达到期望的目标.

Modifying symbol table (even if it were possible) would not get you to your desired goal.

All 调用(假设foo在主可执行文件中),解析为 same PLT导入插槽malloc@plt.第一次调用时,该插槽将解析为glibc malloc(假设您未使用LD_BIND_NOW=1或类似名称,则可以从程序中的任何位置).解决该插槽后,对符号表的任何进一步修改将无效.

All calls from anywhere inside your ELF binary (let's assume foo is in the main executable), resolve to the same PLT import slot malloc@plt. That slot is resolved to glibc malloc on the first call (from anywhere in your program, assuming you are not using LD_BIND_NOW=1 or similar). After that slot has been resolved, any further modification to the symbol table will have no effect.

您没有说您对foo有多少控制权.

You didn't say how much control over foo you have.

如果可以重新编译,则问题将变得微不足道:

If you can recompile it, the problem becomes trivial:

#define malloc my_malloc
int foo() {
  // same code as before
}
#undef malloc

如果将预编译的foo.o交给您,则将其与my_malloc.o链接,并且您希望将foo.o内部的所有调用从malloc重定向到my_malloc,这实际上很简单对象级别(即在最终链接之前).

If you are handed a precompiled foo.o, you are linking it with my_malloc.o, and you want to redirect all calls from inside foo.o from malloc to my_malloc, that's actually quite simple to do at the object level (i.e. before final link).

所有您需要做的是浏览foo.o重定位记录,并将外部malloc的放置地址在这里"更改为外部my_malloc的放置地址在这里".

All you have to do is go through foo.o relocation records, and change the ones that say "put address of external malloc here" to "put address of external my_malloc here".

如果foo.ofoo之外还包含其他功能,将重定位重写限制为仅在foo内部的重定位非常简单.

If foo.o contains additional functions besides foo, it's quite simple to limit the relocation rewrite to just the relocations inside foo.

这篇关于在运行时动态修改符号表(在C中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆