gcc 動態連結


在今天 Jserv 大師 的

你所不知道的 C 語言
動態連結器篇

( Youtube: https://www.youtube.com/c/GUTS4tech/live , 正播放中 )


有提到一個 malloc 動態連結置換 原程式 的方式.

我在 mac os x 上做個實驗.

1. 寫一個簡單測試程式 :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    char *buf;

    printf("Hello World\n");
    buf=malloc(50);
    sprintf(buf, "Hi, This is test\r\n");
    printf("%s", buf);
    free(buf);
    return 0;
}


Compile and test


gcc -Wall -o test test.c 

$ ./test
Hello World
Hi, This is test


2. 用原範例撰寫動態連結庫



void *malloc(size_t size)
{
    char buf[32];
    static void *(*real_malloc)(size_t) = NULL;
    if (real_malloc == NULL) {
        real_malloc = dlsym(RTLD_NEXT, "malloc");
    }
    sprintf(buf, "malloc called, size = %zu\n", size);
    write(2, buf, strlen(buf));
    return real_malloc(size);
}


Compiler


$ gcc -Wall -dynamiclib -o /tmp/libmcount.dylib malloc_count.c

測試 : 

$ DYLD_FORCE_FLAT_NAMESPACE=1  DYLD_INSERT_LIBRARIES=/tmp/libmcount.dylib ./test
malloc called, size = 8
malloc called, size = 16
malloc called, size = 32
malloc called, size = 32
malloc called, size = 32
malloc called, size = 32
malloc called, size = 8
malloc called, size = 27
malloc called, size = 22
malloc called, size = 11
malloc called, size = 45
malloc called, size = 99
malloc called, size = 45
malloc called, size = 50
malloc called, size = 47
malloc called, size = 15
malloc called, size = 64
malloc called, size = 49
malloc called, size = 67
malloc called, size = 52
malloc called, size = 54
malloc called, size = 12
malloc called, size = 45
malloc called, size = 32
malloc called, size = 16
malloc called, size = 64
malloc called, size = 14
malloc called, size = 4096
Hello World
malloc called, size = 16
malloc called, size = 50
Hi, This is test


不過很奇怪, mac 上這方式用在 /bin/ls 沒有用.
 找天 來深入 trace 一下 ls 看看原因 

--
延伸閱讀 :


Elf : 



回來繼續聽課.

個人 hackpad:


留言

熱門文章