覆盖glibc中的函数实现

覆盖libc中的malloc,
类似https://dongbo.tech/post/2020/override-glibc-func/

main.c

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

int main(int argc, char **argv) {
        int *p = (int*)malloc(10 *sizeof(int));
        if (p) {
          for (int i = 0; i < 10; ++i) {
            p[i] = i;
          }
        }
        return 0;
}

malloc.c

#include<stdio.h>
#include <unistd.h>
#include<stddef.h>
int arr[100000];
void *malloc(size_t size) {
  write(STDOUT_FILENO, "my\n", 3);
  return (void*)arr;
}

makefile

.PHONY:main

main:main.c malloc.c
    gcc -g -c malloc.c -o malloc.o
    gcc -g -c main.c -o main.o
    gcc main.o malloc.o  -o main_static_o
    gcc -g -fPIC -shared -o libmalloc.so malloc.c
    gcc -L. -o  main_dynamic main.c -lmalloc
    gcc -o  main_not_touch main.c
    gcc -L. -o  main_dynamic_glibc_first main.o -lc -lmalloc

静态

调用自定义

D.Gen|icefire|2023-12-10 11:58:45[ice@ override-libc-new]./main_static
my

只link自定义

D.Gen|icefire|2023-12-10 11:59:01[ice@ override-libc-new]./main_dynamic
my

啥都不做

调用glibc

D.Gen|icefire|2023-12-10 12:06:27[ice@ override-libc-new]./main_not_touch

LD_PRELOAD+啥都不link

D.Gen|icefire|2023-12-10 12:06:55[ice@ override-libc-new]LD_PRELOAD=libmalloc.so ./main_not_touch 
my

先link libc再link malloc

./main_dynamic_glibc_first 

LD_PRELOAD在先link libc再link malloc时的表现

发现,编译时: -lc -lmalloc,运行时LD_PRELOAD,最终运行时LD_PRELOAD的优先级高

D.Gen|icefire|2023-12-10 12:08:08[ice@ override-libc-new]LD_PRELOAD=libmalloc.so ./main_dynamic_glibc_first 
my

相同函数签名的多个实现不一定会报multiple definition的错

main.c

// main.c
extern void test();
int main() {
    test();
}

test1.c

// test1.c
#include <stdio.h>

void test() {
    printf("call from test1.c\n");
}

test2.c

#include <stdio.h>

void test() {
    printf("call from test2.c\n");
}

makefile

.PHONY:main clean
%.o:%.c
    gcc -c $< -o $@
main:main.o test1.o test2.o
    #gcc -o main main.o test1.o test2.o
    ar rcs libtest1.a test1.o
    ar rcs libtest2.a test2.o
    gcc -fPIC -shared -o libtest1_dyn.so test1.o
    gcc -fPIC -shared -o libtest2_dyn.so test2.o
    gcc -L. -o main_static.elf main.o -ltest1 -ltest2
    gcc -L. -o main_dyn1.elf main.o -ltest1_dyn -ltest2_dyn
    gcc -L. -o main_dyn2.elf main.o -ltest2_dyn -ltest1_dyn 
clean:
    rm -rf *.a *.so *.o

Leave a Comment