The segmentation fault in malloc_trim(0) when run ASAN

100 Views Asked by At

The code 1.c :

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

void* thread_function(void* arg) {
    char* ptr = (char *)malloc(10);
    printf("%p\n", ptr);
    free(ptr);
    malloc_trim(0);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[2];

    for (long i = 0; i < 2; ++i) {
        pthread_create(&threads[i], NULL, thread_function, (void*)i);
    }
    for (int i = 0; i < 2; ++i) {
        pthread_join(threads[i], NULL);
    }
    return 0;
}

compile use -fsanitize=address gcc -pthread -o ASANtest -fsanitize=address -O1 1.c And then run ASANtest multiple times. An error occured.

The error information:

bash-4.4$ ./ASANtest
ASAN:DEADLYSIGNAL
=================================================================
==7076==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000008 (pc 0x7f95439d87d9 bp 0x000000000fff sp 0x7f953f8fde00 T2)
==7076==The signal is caused by a READ memory access.
==7076==Hint: address points to the zero page.
#0 0x7f95439d87d8 in malloc_trim (/lib64/libc.so.6+0x9e7d8)
#1 0x400a8f in thread_function (/workspace/git/ehaauwn/PCPB-22713/2024/eric-pc-routing-engine/raas/product/docker/build/ASANtest+0x400a8f)
#2 0x7f9543d396e9 in start_thread (/lib64/libpthread.so.0+0xa6e9)
#3 0x7f9543a51a8e in clone (/lib64/libc.so.6+0x117a8e)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/lib64/libc.so.6+0x9e7d8) in malloc_trim
Thread T2 created by T0 here:
#0 0x7f9543f8bc80 in pthread_create (/usr/lib64/libasan.so.4+0x39c80)
#1 0x400b32 in main (/workspace/git/ehaauwn/PCPB-22713/2024/eric-pc-routing-engine/raas/product/docker/build/ASANtest+0x400b32)
#2 0x400d13 in _IO_stdin_used (/workspace/git/ehaauwn/PCPB-22713/2024/eric-pc-routing-engine/raas/product/docker/build/ASANtest+0x400d13)

==7076==ABORTING

If I compile without -fsanitize=address , the program runs normally.

I want to know if the malloc_trim function has any security risks, or if there are any bugs in ASAN

1

There are 1 best solutions below

0
Employed Russian On

As previous commenters said, malloc_trim is a GLIBC extension, which Address Sanitizer knows nothing about.

I just checked: as of this moment malloc_trim is not mentioned at all anywhere in compiler-rt/lib/asan/.

When you call malloc_trim, you get the GLIBC version, which crashes because GLIBC malloc internals have not been initialized (because Address Sanitizer replaces GLIBC malloc).

It would be trivial for ASan developers to intercept malloc_trim and do nothing when it is called, but they probably haven't seen this reported yet.

So do report it in the appropriate bug tracker, and in the mean time you should likely remove all calls to malloc_trim -- it is very unlikely that these calls are doing anything useful in your program.