【发布时间】:2024-01-22 21:50:01
【问题描述】:
我创建了一个小型共享库,它重载了 malloc 和 co。它编译成功,但是当我尝试用它执行其他程序时,它会导致段错误。
到目前为止,我为解决该问题所采取的步骤:
1. Make sure the .so is executable.
2. Tried debugging using Valgrind and gdb.(see GDB output below)
3. Looked at other related questions on SO and tried to adopt the suggestions given.
使用
执行 Test.cpp LD_PRELOAD=/home/absolute/path/mylib.so ./a.out
导致段错误。
Test.cpp
#include <stdlib.h>
#include <iostream>
int main () {
size_t size = sizeof(int);
void* ptr = malloc(size);
std::cout<<"Called malloc() " << ptr << std::endl;
free(ptr);
return 0;
}
这是我的一些共享库代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <dlfcn.h>
#include <iostream>
#include "runtime/Firstfit_heap.h"
#include "system/Auslagern.h"
#include "system/VirtualMem.h"
extern "C" {
void* malloc(size_t size) noexcept;
}
Auslagern swap(4,6);
VirtualMem mem(4, 6, swap, true);
Firstfit_heap heap(mem);
void* malloc(size_t size) noexcept{
void* handle = (void*) -1l;
auto fptr = (void* (*)(size_t))dlsym(handle, "malloc");
if (fptr == NULL) {
return NULL;
}
char* foo = "malloc\n";
write(2, foo, 7);
// I THINK THE ERROR IS IN THE NEXT LINE BECAUSE "malloc" is printed to the console before the segfault(core dump)
void* ptr = fptr(size);
std::cout<<"malloc"<<std::endl;
return ptr;
}
我的所有 .cpp 文件的编译和链接标志(在 makefile 中):
CXXFLAGS = -fPIC -g -Wall -std=c++1z
LDFLAGS = -shared
LIBS = $(XLIBS) $(PTHREADLIBS) -lboost_program_options -lrt -lc -ldl
Gdb 输出:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000002 in ?? ()
Valgrind 输出:
==19131== Jump to the invalid address stated on the next line
==19131== at 0x2: ???
==19131== by 0xFFF000082: ???
==19131== by 0xFFF000092: ???
==19131== Address 0x2 is not stack'd, malloc'd or (recently) free'd
==19131==
==19131==
==19131== Process terminating with default action of signal 11 (SIGSEGV)
==19131== Bad permissions for mapped region at address 0x2
==19131== at 0x2: ???
==19131== by 0xFFF000082: ???
==19131== by 0xFFF000092: ???
因为没有用于 mylib.so 的代码,所以我无法判断哪条指令试图寻址 0x2,并且无法想到任何可以帮助我更接近解决方案的方法。 任何指向我写作方向的帮助都会非常有用。
TIA。
【问题讨论】:
标签: c++ segmentation-fault shared-libraries