Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf produces segfault when the program is run with a custom entry point (using gcc 7.4.0)

Tags:

c

gcc

Consider the following code:

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

int main() {
    printf("main\n");
    int a;
    scanf("%d", &a);
    printf("a = %d\n", a);
    return 0;
}

int main1() {
    printf("main1\n");
    int a;
    scanf("%d", &a);
    printf("a = %d\n", a);
    exit(0);
    return 0;
}

int main2() {
    printf("main2\n");
    int a = getchar() - '0';
    int b = getchar() - '0';
    int c = getchar() - '0';
    printf("a = %d\n", 100 * a + 10 * b + c);
    exit(0);
    return 0;
}

Assuming that the code resides in a file called test.c, the following works fine (it prints "a = 123"):

gcc -o test test.c
echo 123 | ./test

If, however, I run the program with a custom entry point, I get the dreaded Segmentation fault:

gcc -o test test.c -e"main1"
echo 123 | ./test

But if I replace the scanf with three getchars, the program runs fine again despite being run with a custom entry point:

gcc -o test test.c -e"main2"
echo 123 | ./test

To make things even more interesting, these problems occur with gcc 7.4.0 but not with gcc 4.8.4.

Any ideas?

like image 892
Luka Fürst Avatar asked Jun 04 '19 09:06

Luka Fürst


1 Answers

The -e command line flag redefines the actual entry point of your program, not the “user” entry point. By default, using GCC with the GNU C standard library (glibc) this entry point is called _start, and it performs further setup before invoking the user-provided main function.

If you want to replace this entry point and continue using glibc you’ll need to perform further setup yourself. But alternatively you can use the following method to replace the main entry point, which is much simpler:

gcc -c test.c
objcopy --redefine-sym main1=main test.o
gcc -o test test.o

Note, this will only work if you don’t define main in your code, otherwise you’ll get a “multiple definition of `main'” error from the linker.

like image 126
Konrad Rudolph Avatar answered Apr 29 '23 06:04

Konrad Rudolph