When I'm trying to use the DYLD_INSERT_LIBRARIES
environmental variable to insert a .dylib
file to a running process on macOS Mojave, I'm encountering a segmentation fault.
System version: macOS 14.4.4
Compiler version:
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
(compiles to the dylib file):
#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);
The running process is a test program written in C, which does nothing except calling malloc
once:
test.c
(compiles to test
)
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("before malloc\n");
void *a= malloc(900);
return 0;
}
Compile & execute commands
gcc -odbg.dylib -dynamiclib ./debug_malloc.c
gcc -otest ./test.c
DYLD_INSERT_LIBRARIES=./dbg.dylib ./test
Running the last command yields
Segmentation fault: 11
Whereas just running test
without dylib preload works fine.