by to3m · 13y ago · 0 comments
(If execution of bytes in the data segment were possible, which I'm sure it used to be, then you'd still likely get a crash, but it's not guaranteed. (uint32_t)0 is a valid sequence of instructions - it's ADD BYTE PTR [EAX],AL - and so if EAX contained a valid value then it would execute without a problem. Then, if the following byte were 0xC3 (RET) then the program would execute. OK, so that's all rather unlikely, but you have to bear these things in mind. So I think 0xCC (INT 3) would be a better choice.)
(gdb) print &main
$1 = (int *) 0x600864 <main>
(gdb) run
Starting program: /tmp/s
Program received signal SIGSEGV, Segmentation fault.
0x0000000000600864 in main ()
If we are to mark the data segment as executable (quite easy for ELF), we can see execution starting at &main and continuing until end of the page and then segfaulting for trying to execute from an unmapped virtual address. (gdb) print &main
$1 = (int *) 0x600864 <main>
(gdb) run
Starting program: /tmp/s
Program received signal SIGSEGV, Segmentation fault.
0x0000000000601000 in ?? ()
If we change the source to main=0xC3; as per your suggestion and we mark the data segment as executable, the program exits correctly (but with an exit status we don't control). (gdb) x/i &main
0x600860 <main>: retq
(gdb) run
Starting program: /tmp/s_ret
[Inferior 1 (process 10588) exited with code 0140]mov $1, %eax
int $0x80
If you've got VS2012, you can see this code in the file at something like "c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\crt\src\crt0.c" (it should be easy to find for other versions - it's been in pretty much in that place, with that name, probably with those contents, since VC5 I think).
For glibc, see http://sourceware.org/git/?p=glibc.git;a=blob;f=csu/libc-sta....
My post was a bit x86/VC++-specific but the principles have been common to all the C environments I've used. I don't think I've ever used one that by default called your startup function directly, bypassing C runtime initialisation. (Though it's very easy to set this up with Visual Studio.)