main を蹂躙する Hello, world!

http://d.hatena.ne.jp/yupo5656/20061215

に書かれている Hello, world! で遊んでみました。そのままだと、ubuntu amd64 だとデフォルトでデータ実行不可になっていてセグってしまう。

http://en.wikipedia.org/wiki/NX_bit

.plt セクションに配置すると良いらしい(教えてもらいました)

#include <stdio.h>

__attribute__((section(".plt"))) main;

__attribute__((constructor, destructor)) void _()
{
    if (main)
    {
        __attribute__((cleanup(puts))) char _[] = "world!";
    }
    else
    {
        __attribute__((cleanup(printf))) char _[] = "Hello, ";
        main = 0xc3;
    }
}
$ gcc main.c
main.c: In function ‘_’:
main.c:9: warning: passing argument 1 of ‘puts’ from incompatible pointer type
main.c:13: warning: passing argument 1 of ‘printf’ from incompatible pointer type
/tmp/ccEJroWC.s: Assembler messages:
/tmp/ccEJroWC.s:57: Warning: setting incorrect section attributes for .plt

と警告が出ますが、

$ ./a.out
Hello, world!