开发者

Why does gcc place a “halt” instruction in programs after the call to “main”?

When looking at an elf executable produced by gcc on a Linux/i386 system, it seems that it alwas places a halt instruction (0xf4) after the call to “main” and before the “nop” padding, such as this:

│ ....... ! entrypoint:
│ ....... !   xor         ebp, ebp
│ 80482e2 !   pop         esi
│ 80482e3 !   mov         ecx, esp*emphasized text*
│ 80482e5 !   and         esp, 0fffffff0h
│ 80482e8 !   push        eax
│ 80482e9 !   push        esp
│ 80482ea !   push        edx
│ 80482eb !   push        __libc_csu_fini
│ 80482f0 !   push        __libc_csu_init
│ 80482f5 !   push        ecx
│ 804开发者_高级运维82f6 !   push        esi
│ 80482f7 !   push        main
│ 80482fc !   call        wrapper_804a004_80482c4
│ 8048301 !   hlt                                      <--- halt instruction
│ 8048302 !   nop
│ 8048303 !   nop
│ 8048304 !   nop
               ⋮

What is the purpose of this? This code should never be reached. Is it some kind of safeguard?


After main returns, exit will be called. The hlt is there in case the system's version of exit doesn't stop execution of the process immediately. In user mode, it will cause a protection fault, which will kill the process. If the process is for some reason running in ring 0, it will just stop the processor until the next interrupt, which will hopefully trigger the OS to remove the process. In processes designed to run in ring 0, there is often a jmp instruction after the hlt which will cause the hlt to be performed over and over until the process is terminated.


I would presume it to be a safeguard, that probably doesn't actually work. For one, hlt is a priveldged instruction, which means it will throw an exception upon execution in ring 3(where most applications run). At best, it may be useful for kernel code but if interrupts are enabled, then the hlt will only last until the processor gets an interrupt, and then the processor will continue and execute the nop padding.


you are right - this code should never be reached and was left there probably while developing as safeguard. There's stack manipulation to prevent call from returning.

more here: http://www.win.tue.nl/~aeb/linux/hh/stack-layout.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜