Stubbing noreturn Functions

From OC Systems Wiki!
Jump to: navigation, search


NeedsWork

coverage.ual does its own probe on abort() to trigger a coverage snapshot, and the presence of that probe causes problems for this one. As a workaround, run with a coverage.ual built without that probe. Options for a more permanent solution are under consideration.

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 functions carrying 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_StubRoutine 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.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 to.
      $$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.
    }
  }
}

C Source

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

void fatal()
{
   abort();
   printf("I returned from abort()?\n");
}

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