Why does declaring main as an array compile?

前端 未结 6 1937
一整个雨季
一整个雨季 2021-01-31 07:35

I saw a snippet of code on CodeGolf that\'s intended as a compiler bomb, where main is declared as a huge array. I tried the following (non-bomb) version:



        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 07:55

    If you are interested how to create program in main array: https://jroweboy.github.io/c/asm/2015/01/26/when-is-main-not-a-function.html. The example source there just contains a char (and later int) array called main which is filled with machine instructions.

    The main steps and problems were:

    • Obtain the machine instructions of a main function from a gdb memory dump and copy it into the array
    • Tag the data in main[] executable by declaring it const (data is apparently either writable or executable)
    • Last detail: Change an address for actual string data.

    The resulting C code is just

    const int main[] = {
        -443987883, 440, 113408, -1922629632,
        4149, 899584, 84869120, 15544,
        266023168, 1818576901, 1461743468, 1684828783,
        -1017312735
    };
    

    but results in an executable program on a 64 bit PC:

    $ gcc -Wall final_array.c -o sixth
    final_array.c:1:11: warning: ‘main’ is usually a function [-Wmain]
     const int main[] = {
               ^
    $ ./sixth 
    Hello World!
    

提交回复
热议问题