[英]Link an ELF binary with a c program
如果只能訪問獨立的 ELF 程序,我希望能夠從我自己的程序中調用程序中的 function。 假設下面的代碼是main.c
#include <stdio.h>
extern int mystery(int a,int b);
int main() {
int a = 0;
int b = 1;
printf("mystery(a,b) = %d\n",mystery(a,b));
return 0;
}
function mystery
存在於一些精靈文件not_my_program
中。 我正在嘗試做的是類似的事情
gcc main.c not_my_program
然而,這給了我一個未定義的mystery
參考錯誤。 我在論壇上找了方法,發現無法將此elf文件轉換為共享的object文件。 我還研究了將main.c
編譯為可重定位的 object 文件
gcc -c main.c
然后使用ld
將精靈與main.o
鏈接,但我不知道該怎么做。 精靈是 32 位的,但我省略了-m32
標志。 如果ld
的標志不同,請告訴我。 任何幫助將不勝感激。
編輯: readelf -h not_my_program
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: Intel 80386
Version: 0x1
Entry point address: 0x10e0
Start of program headers: 52 (bytes into file)
Start of section headers: 15116 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 11
Size of section headers: 40 (bytes)
Number of section headers: 30
Section header string table index: 29
這種hacky方式適用於一個非常簡單的案例。
[ aquila ~ ] $ cat 1.c
int func (int a) { return a * (a-1) ; }
int main(int argc) { return func (argc) ; }
[ aquila ~ ] $ cc 1.c
[ aquila ~ ] $ ./a.out ; echo $?
0
[ aquila ~ ] $ readelf -s a.out | grep func
43: 0000000000400487 19 FUNC GLOBAL DEFAULT 11 func
[ aquila ~ ] $ cat 2.c
#include <stdlib.h>
static __attribute__((constructor)) void main() {
int (*func)() = (int (*)())0x0000000000400487;
exit(func(3));
}
[ aquila ~ ] $ cc -fPIC -shared 2.c -o a.so
[ aquila ~ ] $ LD_PRELOAD=./a.so ./a.out ; echo $?
6
2.c 中的調用者被制成帶有出口的構造函數,這樣主程序的main()
就不會被調用,以試圖限制調用者和func()
本身以外的代碼的執行。 返回值為 6 而不是 0 表明調用有效並且主程序的main()
沒有被調用。
如果只能訪問獨立的 ELF 程序,我希望能夠從我自己的程序中調用程序中的 function
聽起來你有一個XY 問題。
雖然你想要的在技術上是可行的,但這樣做的難度大約是你迄今為止嘗試的 1000 倍。 如果您不准備花一兩個月來完成這項工作,您應該尋找其他解決方案。
實際上,您必須編寫一個自定義 ELF 加載程序來將not_my_program
加載到 memory 並對其進行初始化,然后在其中調用mystery
而不是main
。
另請注意, mystery
可能取決於全局數據,並且數據可能在main
中初始化,因此不能保證mystery
在main
之前調用時會起作用。
PS 從調試器中調用mystery
就足夠了嗎? 這可以在 30 秒內完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.