2013-12-08 25 views
3

使用Xcode時,我正在尋找從mach-o包二進制文件中重新導出符號(一個函數),其中符號最初在dylib。如何從依賴包中重新導出dylib符號

我已經試過-sub_library鏈接器開關,但似乎並沒有再出口的dylib符號,可能是因爲我不是建立一個dylib我自己(?)

而再出口-L/reexport_library開關似乎在Xcode的鏈接器中不受支持。

任何想法?

回答

3

如果我正確地理解了你,這可能就是你要找的。我將使用libpthread作爲包含想要重新導出的函數的假想dylib。

mybundle.c

#include <pthread.h> 
#include <stdio.h> 
void *foo(void *ctx) { 
    puts((char *)ctx); 
    return 0; 
} 

mybundle.exp

_foo 
_pthread_create 
_pthread_join 

編譯束,動態鏈接到libpthread.dylib:

josh$ gcc -bundle -lpthread -Wl,-exported_symbols_list,mybundle.exp -o mybundle.so mybundle.c 

myloader.c

#include <dlfcn.h> 
#include <pthread.h> // merely for type definitions 
#include <assert.h> 
#include <stdio.h> 

int main() { 
    void *(*foo)(void *ctx); 
    /* the following cannot be declared globally without changing their names, 
     as they are already (and unnecessarily) declared in <pthread.h> */ 
    int (*pthread_create)(pthread_t *thrd, const pthread_attr_t *attr, void *(*proc)(void *), void *arg); 
    int (*pthread_join)(pthread_t thrd, void **val); 

    void *bundle; 
    assert(bundle = dlopen("mybundle.so", RTLD_NOW)); 
    assert(foo = dlsym(bundle, "foo")); 
    assert(pthread_create = dlsym(bundle, "pthread_create")); 
    assert(pthread_join = dlsym(bundle, "pthread_join")); 

    pthread_t myThrd; 
    pthread_create(&myThrd, 0, foo, "in another thread"); 
    pthread_join(myThrd, 0); 

    return 0; 
} 

編譯裝載機:

josh$ gcc myloader.c -o myloader 

運行:

josh$ ./myloader 
in another thread 

觀察到myloader是沒有辦法連接到並行線程,但並行線程功能的加載和通過捆綁包在運行時可用。

+0

感謝jrodatus。我真的很感興趣從我的包中導出一個符號,它將直接指向它所鏈接的dylib中的地址。 – Danra

+0

@Danra,根據定義,鏈接到dylib的AFAIK意味着dylib代碼實際上並不包含在bundle中,只有在運行時重定向的「dyld stub」函數存在。任何dylib函數的地址,無論是puts(),printf()還是pthread_create(),在編譯時都是不確定的,僅在運行時由dylinker決定。例如,甚至來自foo()的puts()調用實際上也不會引用dylib中的地址,而只是調用dylinker以獲取該系統在該運行時恰好具有的任何地址puts()的存根函數的地址(見'otool -tV')。 – jrodatus

+0

@Danra,...因此,在我看來,你可以要求的最好的辦法是從bundle中導出本地的dyld存根地址,這就是我的代碼所做的(如果我沒有弄錯的話)。在任何編譯的二進制文件上運行'nm'會將鏈接的dylib駐留函數列爲「U」(未定義),因爲它們的代碼在編譯時不存在,因此它們的符號地址是未確定的。或者,也許我只是誤解了你? – jrodatus