0

I want to understand how .so works. Eventually I would like to make my own malloc(). But to get the infrastructure ready I just created a sample malloc() function and just printing inside it.

I compiled the following file (my_malloc.c):

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>

void* malloc(size_t sz)
{
    printf("malloc\n");
    return NULL;
}

void free(void *p)
{
    printf("free\n");
}

and created a .so using the following command:

 gcc -shared -fPIC -o my_malloc.so my_malloc.c

Now I created a hello.c file and I am using the malloc() function in this file:

#include <stdio.h>
#include <stdlib.h>

int main() {
    malloc(64);
    return 0;
}

Then I've compiled this file with the following command:

gcc hello.c -o hello.o

I used LD_PRELOAD to override the standard malloc() implementation. When I run hello.o I get the segmentation fault:

LD_PRELOAD=./my_malloc.so ./hello.o
Segmentation fault

Why?

Danila Kiver
  • 3,418
  • 1
  • 21
  • 31
user968000
  • 1,765
  • 3
  • 22
  • 31
  • Add the command line you are using to compile `hello.o`. – Marco Bonelli Sep 11 '19 at 22:04
  • gcc hello.c -o hello.o – user968000 Sep 11 '19 at 22:06
  • 4
    Analyzing the core dump with `gdb` shows that you have an infinite recursion between `puts` and `malloc`, hence stack overflow. Standard library also uses `malloc()`, keep this in mind :) – Danila Kiver Sep 11 '19 at 22:28
  • @DanilaKiver could you tell how you debugged it using gdb? I was not able to run gdb and analyse the failure. – user968000 Sep 11 '19 at 22:38
  • 1
    Run `hello` as you've specified in the question. After the crash the system will produce the core dump. Then run `coredumpctl debug hello` - it will find the last core dump from `hello` and open it with `gdb`. When you are in `gdb`, run `bt` - it will print you the stack trace with the recursion. – Danila Kiver Sep 11 '19 at 22:44
  • 1
    More to the point, `printf()` and [even `getchar()`](https://stackoverflow.com/a/57308691/10306503) will also use `malloc()`, and at least on Linux, they will not call it directly, but go through whatever `LD_PRELOAD` override. –  Sep 11 '19 at 23:01
  • 1
    *"I want to understand how .so works"* - You should read Drepper's [How To Write Shared Libraries](https://software.intel.com/sites/default/files/m/a/1/e/dsohowto.pdf). – jww Sep 11 '19 at 23:29

0 Answers0