6df6088a3a89c96b3119d896f3eeb3ae69a0ce94
[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 // the dynamic loader interface 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 "Support/DynamicLinker.h"
13 #include <iostream>
14
15 // AtExitHandlers - List of functions to call when the program exits,
16 // registered with the atexit() library function.
17 static std::vector<void (*)()> AtExitHandlers;
18
19 /// runAtExitHandlers - Run any functions registered by the program's
20 /// calls to atexit(3), which we intercept and store in
21 /// AtExitHandlers.
22 ///
23 void VM::runAtExitHandlers() {
24   while (!AtExitHandlers.empty()) {
25     void (*Fn)() = AtExitHandlers.back();
26     AtExitHandlers.pop_back();
27     Fn();
28   }
29 }
30
31 //===----------------------------------------------------------------------===//
32 // Function stubs that are invoked instead of certain library calls
33 //===----------------------------------------------------------------------===//
34
35 // NoopFn - Used if we have nothing else to call...
36 static void NoopFn() {}
37
38 // jit_exit - Used to intercept the "exit" library call.
39 static void jit_exit(int Status) {
40   VM::runAtExitHandlers();   // Run atexit handlers...
41   exit(Status);
42 }
43
44 // jit_atexit - Used to intercept the "atexit" library call.
45 static int jit_atexit(void (*Fn)(void)) {
46   AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
47   return 0;  // Always successful
48 }
49
50 //===----------------------------------------------------------------------===//
51 // 
52 /// getPointerToNamedFunction - This method returns the address of the specified
53 /// function by using the dynamic loader interface.  As such it is only useful 
54 /// for resolving library symbols, not code generated symbols.
55 ///
56 void *VM::getPointerToNamedFunction(const std::string &Name) {
57   // Check to see if this is one of the functions we want to intercept...
58   if (Name == "exit") return (void*)&jit_exit;
59   if (Name == "atexit") return (void*)&jit_atexit;
60
61   // If it's an external function, look it up in the process image...
62   void *Ptr = GetAddressOfSymbol(Name);
63   if (Ptr == 0) {
64     std::cerr << "WARNING: Cannot resolve fn '" << Name
65               << "' using a dummy noop function instead!\n";
66     Ptr = (void*)NoopFn;
67   }
68   
69   return Ptr;
70 }