John McGrath
John McGrath

Reputation: 151

gcc / Linux : hook exit() call to prevent exit from happening

I have a pretty unique case where I am calling a 3rd party library (which I cannot modify) from a higher-level C program.

This code has a clean-up routine that calls exit() - which terminates the whole application.

However, I do not want to terminate the whole application at this time, as there is still some work that must be done by the main application.

So to solve this, I tried to 'trick' this 3rd party library by temporarily 'aliasing' the exit() function call to a dummy function using dlsym - and then later restoring exit() to its normal state. This solution almost works - using LD_PRELOAD to point to the dummy exit wrapper I can see this dummy exit function being called - however, imminently after this I get a segmentation fault when this function goes out of scope.

I suspect this has to do with the fact that gcc by default puts an attribute called noreturn on this function.

Is there a way to remove this noreturn attribite, or better still another way of preventing this 3rd party library from calling exit()?

Any and all suggestions would be most appreciated.

Upvotes: 2

Views: 1922

Answers (1)

evading
evading

Reputation: 3090

Ignoring the fact that this may be a bad idea and that this is an old question and it seams to be answered in the comments. There is an alternative solution to this if using gcc on Linux (maybe other systems to, I wouldn't know).

/* compile with "gcc -Wl,-wrap,exit -o test wrap_exit.c" */
/* check exit status with "echo $?" */

#include <stdio.h>
#include <stdlib.h>

void __real_exit(int status);

void __wrap_exit(int status)
{
  int stat = 2;
  printf("trying to exit with status %d\n", status);
  printf("now exiting for real with status %d\n", stat);
  __real_exit(stat);
}

int main(void)
{
  exit(1);

  return 0;
}

Upvotes: 1

Related Questions