当我尝试使用DYLD_INSERT_LIBRARIES
环境变量将.dylib
文件插入到macOS Mojave上正在运行的进程中时,遇到了分段错误。
系统版本: macOS 14.4.4
编译器版本:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
debug_malloc.c
(编译为dylib文件):
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#define DYLD_INTERPOSE(_replacment,_replacee) \
__attribute__((used)) static struct{ const void* replacment; const void* replacee; } _interpose_##_replacee \
__attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacment, (const void*)(unsigned long)&_replacee };
void* pMalloc(size_t size) //would be nice if I didn't have to rename my function..
{
printf("Allocated: %zu\n", size);
return malloc(size);
}
DYLD_INTERPOSE(pMalloc, malloc);
正在运行的进程是一个用C编写的测试程序,除了调用malloc
一次之外,什么都不做:
test.c
(编译为test
)
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("before malloc\n");
void *a= malloc(900);
return 0;
}
编译并执行命令
gcc -odbg.dylib -dynamiclib ./debug_malloc.c
gcc -otest ./test.c
DYLD_INSERT_LIBRARIES=./dbg.dylib ./test
运行最后一条命令会产生
Segmentation fault: 11
在没有dylib预加载的情况下仅运行test
即可。