Finding Offsets of Local Symbols in Shared Libraries Programmatically on OS X

前端 未结 1 1359
南笙
南笙 2021-02-15 13:49

I need to find the offset of a local symbol in a shared library on OS X. Local symbol as in non-exported symbol. Therefore dyld(\"symbol_name\") will not work.

相关标签:
1条回答
  • 2021-02-15 14:17

    Another possibility (what I ended up using) is Apple's private CoreSymbolication framework:

    void *resolve_private(const char *symbol_owner, const char *symbol_to_resolve)
    {
        task_t targetTask;
        int err = task_for_pid(mach_task_self(), getpid(), &targetTask);
        if (err) {
            fprintf(stderr, "couldn't get my Mach task\n");
            return NULL;
        }
    
        CSSymbolicatorRef targetSymbolicator;
    
        targetSymbolicator = CSSymbolicatorCreateWithTaskFlagsAndNotification(targetTask,
                                                                                  kCSSymbolicatorTrackDyldActivity,
                                                                              ^(uint32_t     notification_type, CSNotificationData data) {
                                                                              });
        if(CSIsNull(targetSymbolicator)) {
            fprintf("CSSymbolicatorCreateWithTaskFlagsAndNotification failed\n");
            return NULL;
        }
    
        __block CSSymbolOwnerRef symbolOwner = kCSNull;
        CSSymbolicatorForeachSymbolOwnerWithNameAtTime(targetSymbolicator,
                                                       symbol_owner,
                                                       kCSNow,
                                                       ^(CSSymbolOwnerRef owner) {
                                                           symbolOwner = owner;
                                                       });
        if (CSIsNull(symbolOwner)) {
            CSRelease(targetSymbolicator);
            fprintf("CSSymbolicatorForeachSymbolOwnerWithNameAtTime failed\n");
            return NULL;
        }
    
        __block uintptr_t p = (uintptr_t)NULL;
        CSSymbolOwnerForeachSymbol(symbolOwner, ^(CSSymbolRef symbol) {
            const char *symbol_name = CSSymbolGetMangledName(symbol);
            if (0 == strcmp(symbol_name, symbol_to_resolve)) {
                p = CSSymbolGetRange(symbol).location;
            }
        });
    
        CSRelease(targetSymbolicator);
        if ((uintptr_t)NULL == p) {
            fprintf("symbol not found\n");
            return NULL;
        } else {
            return (void *)p;
        }
    }
    
    0 讨论(0)
提交回复
热议问题