Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
│ 80482f6 !   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?

like image 685
beta Avatar asked Mar 06 '11 21:03

beta


1 Answers

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.

like image 111
ughoavgfhw Avatar answered Oct 13 '22 00:10

ughoavgfhw