C dl *如何将函数指针交换为另一个函数指针

时间:2018-05-29 19:08:00

标签: c algorithm function dynamic wrapper

如何在C中安全地交换另一个函数的函数,因为我有这个

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void *(*malloc_mem_real)(size_t);
void *(*calloc_mem_real)(void*,size_t);
void *(*realloc_mem_real)(void*,size_t);
void (*free_mem_real)(void*);

void memory__init(void) {
    if (!malloc_mem_real) malloc_mem_real = dlsym(RTLD_NEXT, "malloc");
    if (!calloc_mem_real) calloc_mem_real = dlsym(RTLD_NEXT, "calloc");
    if (!realloc_mem_real) realloc_mem_real = dlsym(RTLD_NEXT, "realloc");
    if (!free_mem_real) free_mem_real = dlsym(RTLD_NEXT, "free");
}

/*
const char *getObjectName (object *anObject) {
    static char * (*func)();

    if(!func)
        func =  dlsym(RTLD_NEXT, "getObjectName");
    printf("Overridden!\n");     
    return(func(anObject));    // call original function
}
*/

void* _malloc(size_t sz);

int bit, saved;

void swap_malloc() {
    if (bit == 0) {
        void *(* malloc)() = &_malloc;
        bit = 1;
        write(1, "1\n", 2);
    }
    else if (bit == 1) {
        void *(* malloc)() = &malloc_mem_real;
        bit = 0;
        write(1, "0\n", 2);
    }
}


void* _malloc(size_t sz) {
    swap_malloc(); // should swap void* _malloc(size_t sz) for void* malloc(size_t __size), bit = 0
    return malloc(sz*2); // returns libc malloc(sz*2);
}

void* malloc(size_t sz) {
    if (saved == 0) {
        memory__init(); // save real malloc address
        saved = 1;
    }
    swap_malloc(); // should swap void* malloc(size_t sz) for void* _malloc(size_t sz), bit = 1
    return malloc(sz); // returns _malloc(sz);
}

int main() {
    char * h;
    h = malloc(50); // should allocate 100 instead
    printf("%p\n", h);
    free(h);
    return 0;
}

这意味着将文件malloc交换为libc malloc但是swap_malloc继续被递归调用,导致write:stack overflow

基本理念是:

调用malloc wrapper

swich malloc包装到libc malloc

需要libc malloc的函数,例如printf

将libc malloc切换回malloc包装器

0 个答案:

没有答案