beehive-lab / mambo

A low-overhead dynamic binary instrumentation and modification tool for ARM (both AArch32 and AArch64 support) and RISC-V (RV64GC).
Apache License 2.0
318 stars 69 forks source link

Segmentation fault when main thread finishes before its children #82

Closed IgWod closed 2 years ago

IgWod commented 2 years ago

Hi,

While running some tests extracted from Valgrind I encountered an interesting issue. Basically if the main thread finishes before its children mambo will crash. Not sure if it is a known limitation of MAMBO, an actual bug, or a corner case that was never accounted for; but I though I would report it here.

An example:

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

static void *th(void *v)
{
    fprintf(stderr, "Hello from th!\n");

    sleep(1);

    pthread_exit(0);
}

int main()
{
    pthread_t t;

    pthread_create(&t, NULL, th, NULL);

    fprintf(stderr, "Hello main!\n");

    pthread_exit(0);
}

This program crashes with a segmentation fault. When running with gdb it shows the crash happens in util.S:119, and the cause of it is sp being 0.

Adding join before exit from main fixes the problem, as it ensures the child thread finishes before main:

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

static void *th(void *v)
{
    fprintf(stderr, "Hello from th!\n");

    sleep(1);

    pthread_exit(0);
}

int main()
{
    pthread_t t;

    pthread_create(&t, NULL, th, NULL);

    fprintf(stderr, "Hello main!\n");

    pthread_join(t, NULL);

    pthread_exit(0);
}

Anyway, not sure if mambo should support it, but Stack Overflow suggests such a program is a legitimate use case, so the limitation should either be stated, mambo should have an appropriate check so it does not seg faults, or the support for it should be added.

System configuration:

MAMBO version: f23fc760d69fd9fa68f7ce65d80fedbf73e9d330 OS: Debian GNU/Linux 10 (buster) Compiler: gcc version 8.3.0 (Debian 8.3.0-6)