title: Stack differences between a signal handler being called directly and by raise()?
body: <p>I'm trying to modify the return address on the stack within a segment fault handler, so that it skips over the faulting instruction. However, I get a segment fault whenever I try to modify the return address, if I do not call the signal handler directly.</p>
  
  <p>gdb is not great for debugging when the program does segfault, but when I do <code>info frame</code> I see that, after a segfault, there is "frame level 2" as opposed to "frame level 0"? I don't know where GDB gets that information, because when I try <code>x/12xw $ebp</code> or however many words, I don't see the return address to <code>main()</code>...</p>
  
  <p>Compiled with -m32 -z execstack -fno-stack-protector on CentOS linux</p>
  
  <pre><code>#include &lt;signal.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void segment_fault_handler(int signum)
  {
      char* ret = (char*)(&amp;signum)-4;
      *(ret) += 8;
  }
  
  int main()
  {
      int phail = 0;
  
      signal(SIGSEGV, segment_fault_handler);
  
      segment_fault_handler(7); //Only by using this can I skip the next instruction
  
      phail = *( (int *) 0);
  
      printf("Win!\n");
  
      return 0;
  } 
  </code></pre>
  
  <p>The reason that I increase by 8 is because the phail instruction in <code>main()</code> is 8 bytes:</p>
  
  <pre><code>0x080484e2 &lt;+37&gt;:   movl   $0x7,(%esp)
  0x080484e9 &lt;+44&gt;:   call   0x8048480 &lt;segment_fault_handler&gt;
  0x080484ee &lt;+49&gt;:   mov    $0x0,%eax
  0x080484f3 &lt;+54&gt;:   mov    (%eax),%eax
  0x080484f5 &lt;+56&gt;:   mov    %eax,0x1c(%esp)
  0x080484f9 &lt;+60&gt;:   movl   $0x80485b4,(%esp)
  0x08048500 &lt;+67&gt;:   call   0x8048350 &lt;puts@plt&gt;
  </code></pre>
  
  <p>Do I need to increase the offset a bit? Does my method of accessing the stack (which I think corresponds to EBP+4) need to change when dealing with a segment fault situation?</p>