Add support for atexit handlers to the JIT, fixing 2003-05-14-AtExit.c
[oota-llvm.git] / lib / ExecutionEngine / JIT / Intercept.cpp
1 //===-- Intercept.cpp - System function interception routines -------------===//
2 //
3 // If a function call occurs to an external function, the JIT is designed to use
4 // dlsym on the current process to find a function to call.  This is useful for
5 // calling system calls and library functions that are not available in LLVM.
6 // Some system calls, however, need to be handled specially.  For this reason,
7 // we intercept some of them here and use our own stubs to handle them.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "VM.h"
12 #include <dlfcn.h>    // dlsym access
13 #include <iostream>
14
15 // AtExitList - List of functions registered with the at_exit function
16 static std::vector<void (*)()> AtExitList;
17
18 void VM::runAtExitHandlers() {
19   while (!AtExitList.empty()) {
20     void (*Fn)() = AtExitList.back();
21     AtExitList.pop_back();
22     Fn();
23   }
24 }
25
26 //===----------------------------------------------------------------------===//
27 // Function stubs that are invoked instead of raw system calls
28 //===----------------------------------------------------------------------===//
29
30 // NoopFn - Used if we have nothing else to call...
31 static void NoopFn() {}
32
33 // jit_exit - Used to intercept the "exit" system call.
34 static void jit_exit(int Status) {
35   VM::runAtExitHandlers();   // Run at_exit handlers...
36   exit(Status);
37 }
38
39 // jit_atexit - Used to intercept the "at_exit" system call.
40 static int jit_atexit(void (*Fn)(void)) {
41   AtExitList.push_back(Fn);    // Take note of at_exit handler...
42   return 0;  // Always successful
43 }
44
45 //===----------------------------------------------------------------------===//
46 // 
47 /// getPointerToNamedFunction - This method returns the address of the specified
48 /// function by using the dlsym function call.  As such it is only useful for
49 /// resolving library symbols, not code generated symbols.
50 ///
51 void *VM::getPointerToNamedFunction(const std::string &Name) {
52   // Check to see if this is one of the functions we want to intercept...
53   if (Name == "exit") return (void*)&jit_exit;
54   if (Name == "atexit") return (void*)&jit_atexit;
55
56   // If it's an external function, look it up in the process image...
57   void *Ptr = dlsym(0, Name.c_str());
58   if (Ptr == 0) {
59     std::cerr << "WARNING: Cannot resolve fn '" << Name
60               << "' using a dummy noop function instead!\n";
61     Ptr = (void*)NoopFn;
62   }
63   
64   return Ptr;
65 }
66