Linux 函数重定向
嘿,我正在尝试在不使用 LD_PRELOAD 的情况下在程序中包装一个函数。
我有两个具有相同签名的函数:
void someFunc () {
puts ("someFunc");
}
void someFunc_wrapper () {
puts ("someFunc_wrapper");
}
并且我想通过调用包装函数将任何函数调用重定向到 someFunc。 当然,我可以通过定义宏或将包装函数放入共享库中,然后像这样调用程序:
LD_PRELOAD=./mylib.so my_program
但是,我想在运行时重定向函数调用,而不修改程序调用。
据我了解,应该可以通过在运行时修改可执行文件的符号表来重定向这些调用。
任何帮助将不胜感激:)
Hey, I'm trying to wrap a function in my program without using LD_PRELOAD.
I have two functions with the same signature:
void someFunc () {
puts ("someFunc");
}
void someFunc_wrapper () {
puts ("someFunc_wrapper");
}
And I want to redirect any function call to someFunc with a call to the wrapper function.
Of course I could do that with defining macros or put the wrapper function into a shared library and then call the program like this:
LD_PRELOAD=./mylib.so my_program
However, I want to redirect the function calls at runtime, without modifying the program call.
As I understand, it should be possible to redirect these calls by modifying the executable's symbol table at runtime.
Any help will be appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ld
有选项--wrap=symbol
应该可以做你想要的事情。手册页有一个示例,它是如何工作的。ld
has the option--wrap=symbol
that should do what you want. The manual page has an example how it works.即使这是可行的,在一般情况下修改程序的符号表可能还不够 - 考虑一下编译器内联您的函数。
不过,您可以通过使用间接函数调用来完成此操作,而无需使用肮脏的技巧(始终通过函数指针调用该函数,当您想要切换实现时更新该指针)。
请注意,这会产生一些运行时开销(又一个间接)。这是否重要取决于用例。如果这只是您正在实现的调试功能,则可以在编译时使用宏技巧将其关闭。
Even if it is doable, modifying your program's symbol table might not be enough in the general case - think about the compiler inlining your function.
You could do this without dirty tricks by using an indirect function call though (always call that function via a pointer-to-function, update that pointer when you want to switch implementations).
Note that this has some runtime overhead (one more indirection). Whether that's important or not depends on the use case. And it can be turned off at compile time with macro tricks if that's just a debug feature you're implementing.