Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c++ - Error when trying to link to a shared library I created using LD_PRELOAD

I'm trying to test if I can override the glibc's malloc interface by linking a shared library on Linux. I don't have the details for the malloc functions yet.

So I created a nullmalloc.cpp that has the required replacements for malloc, but all returns null. The code looks like this:

# include <cstddef>

void* malloc(size_t size) { return 0; }
void* calloc(size_t n, size_t size) { return 0; }
void free(void* ptr) { return; }
void* realloc(void* ptr, size_t size) { return 0; }
void* valloc(size_t size) { return 0; }
void* memalign(size_t align, size_t s) { return 0; }
void cfree(void* ptr) { return; }
void* aligned_alloc(size_t align, size_t s) { return 0; }
void* pvalloc(size_t size) { return 0; }
struct mallinfo mallinfo(void);
int mallopt(int cmd, int value) { return 0; }

And then I tried to make a shared library of the cpp file by these commands:

gcc -Wall -fPIC -g -c nullmalloc.cpp // creates nullmalloc.o
gcc -shared -Wl,-soname,nullmalloc.so -o nullmalloc.so nullmalloc.o // creates nullmalloc.so

When I used LD_PRELOAD to link nullmalloc.so to a test code I wrote called test.cpp, I got an error saying that the .so file could not be found.

The command I used with LD_PRELOAD is this:

g++ -g test.cpp -o test.o -std=c++11 LD_PRELOAD=/home/nullmalloc/nullmalloc.so

And the error I got is this:

g++: error: LD_PRELOAD=/home/nullmalloc/nullmalloc.so: No such file or directory

I'm confused because the nullmalloc.so file exists when I use the ls command.

[root@a nullmalloc]$ ls
nullmalloc.cpp  nullmalloc.o  nullmalloc.so  test.cpp

I've only started studying about malloc, linux, and shared libraries, so I'm not sure where I've made a mistake. Could anyone give advice on where to start fixing?

Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not know how to add compiler flag, but you can make it works as follows.

Compile test as usual:

g++ -Wall -g test.cpp -o test -std=c++11 

Invoke it like this:

LD_PRELOAD=/home/nullmalloc/nullmalloc.so ./test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...