Difference between revisions of "Stubbing noreturn Functions"

From OC Systems Wiki!
Jump to: navigation, search
(Created page with "== Background == The gcc compiler supports applying the "noreturn" attribute to functions, as described at https://gcc.gnu.org/onlinedocs/gcc-6.3.0/gcc/Common-Function-Attribu...")
 
Line 10: Line 10:
 
Note that because the compiler has deprived the caller of abort (in this example, <code>fatal()</code>) of a return sequence, we manipulate the instruction and frame pointer registers to effect a return to the caller of <code>fatal()</code>, in this case <code>main()</code>.  
 
Note that because the compiler has deprived the caller of abort (in this example, <code>fatal()</code>) of a return sequence, we manipulate the instruction and frame pointer registers to effect a return to the caller of <code>fatal()</code>, in this case <code>main()</code>.  
  
 +
=== APC Source ===
 
<source lang="c">
 
<source lang="c">
 
//
 
//
Line 30: Line 31:
 
</source>
 
</source>
  
 +
=== C Source ===
 
<source lang="c">
 
<source lang="c">
 
//
 
//

Revision as of 18:48, 13 March 2017

Background

The gcc compiler supports applying the "noreturn" attribute to functions, as described at https://gcc.gnu.org/onlinedocs/gcc-6.3.0/gcc/Common-Function-Attributes.html#index-functions-that-never-return-3249. This attribute enables the compiler to "optimize" callers of such functions by treating any statements following the call as unreachable code and eliminating them.

Two examples of this attribute are exit and abort.

This optimization is so aggressive that even the return sequence for calling functions can be eliminated if the call is at the end of the routine. Thus an attempt to stub such a routine with aprobe's ap_StubRoute will effectively result in a branch to random instructions, which in some cases may not have been intended as executable code at all.

Following are code for a simple program to demonstrate the issue, and a probe to allow the noreturn function to be stubbed.

Note that because the compiler has deprived the caller of abort (in this example, fatal()) of a return sequence, we manipulate the instruction and frame pointer registers to effect a return to the caller of fatal(), in this case main().

APC Source

//
// stub_abort.c
//
#include <stdlib.h>
#include <stdio.h>

void fatal()
{
   abort();
   printf("Control returned from abort().");
}

int main ()
{
   fatal();
   printf("I will survive!\n");
}

C Source

//
// stub_abort.apc
//
probe thread {
  probe "abort" in "libc.so" {
    on_entry {
      ap_ExecutionContextPtr->ReturnAddress = (ap_Uint32)(*(int *)($$EBP+4));
      // Get abort's caller's return address from the stack and use
      // it as the address this probe will return from.
      $$EBP = *(int *)($$EBP);
      // Pop the frame pointer so it's correct when we return to abort's
      // caller's caller.
      ap_StubRoutine;
      // Perform the usual stubbing.
    }
  }
}