Home | History | Annotate | Download | only in MCJIT
      1 //===-- Intercept.cpp - System function interception routines -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // If a function call occurs to an external function, the JIT is designed to use
     11 // the dynamic loader interface to find a function to call.  This is useful for
     12 // calling system calls and library functions that are not available in LLVM.
     13 // Some system calls, however, need to be handled specially.  For this reason,
     14 // we intercept some of them here and use our own stubs to handle them.
     15 //
     16 //===----------------------------------------------------------------------===//
     17 
     18 #include "MCJIT.h"
     19 #include "llvm/Support/ErrorHandling.h"
     20 #include "llvm/Support/DynamicLibrary.h"
     21 #include "llvm/Config/config.h"
     22 using namespace llvm;
     23 
     24 // AtExitHandlers - List of functions to call when the program exits,
     25 // registered with the atexit() library function.
     26 static std::vector<void (*)()> AtExitHandlers;
     27 
     28 /// runAtExitHandlers - Run any functions registered by the program's
     29 /// calls to atexit(3), which we intercept and store in
     30 /// AtExitHandlers.
     31 ///
     32 static void runAtExitHandlers() {
     33   while (!AtExitHandlers.empty()) {
     34     void (*Fn)() = AtExitHandlers.back();
     35     AtExitHandlers.pop_back();
     36     Fn();
     37   }
     38 }
     39 
     40 //===----------------------------------------------------------------------===//
     41 // Function stubs that are invoked instead of certain library calls
     42 //===----------------------------------------------------------------------===//
     43 
     44 // Force the following functions to be linked in to anything that uses the
     45 // JIT. This is a hack designed to work around the all-too-clever Glibc
     46 // strategy of making these functions work differently when inlined vs. when
     47 // not inlined, and hiding their real definitions in a separate archive file
     48 // that the dynamic linker can't see. For more info, search for
     49 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
     50 #if defined(__linux__)
     51 #if defined(HAVE_SYS_STAT_H)
     52 #include <sys/stat.h>
     53 #endif
     54 #include <fcntl.h>
     55 #include <unistd.h>
     56 /* stat functions are redirecting to __xstat with a version number.  On x86-64
     57  * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
     58  * available as an exported symbol, so we have to add it explicitly.
     59  */
     60 namespace {
     61 class StatSymbols {
     62 public:
     63   StatSymbols() {
     64     sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
     65     sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
     66     sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
     67     sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
     68     sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
     69     sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
     70     sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
     71     sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
     72     sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
     73     sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
     74     sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
     75   }
     76 };
     77 }
     78 static StatSymbols initStatSymbols;
     79 #endif // __linux__
     80 
     81 // jit_exit - Used to intercept the "exit" library call.
     82 static void jit_exit(int Status) {
     83   runAtExitHandlers();   // Run atexit handlers...
     84   exit(Status);
     85 }
     86 
     87 // jit_atexit - Used to intercept the "atexit" library call.
     88 static int jit_atexit(void (*Fn)()) {
     89   AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
     90   return 0;  // Always successful
     91 }
     92 
     93 static int jit_noop() {
     94   return 0;
     95 }
     96 
     97 //===----------------------------------------------------------------------===//
     98 //
     99 /// getPointerToNamedFunction - This method returns the address of the specified
    100 /// function by using the dynamic loader interface.  As such it is only useful
    101 /// for resolving library symbols, not code generated symbols.
    102 ///
    103 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
    104                                        bool AbortOnFailure) {
    105   if (!isSymbolSearchingDisabled()) {
    106     // Check to see if this is one of the functions we want to intercept.  Note,
    107     // we cast to intptr_t here to silence a -pedantic warning that complains
    108     // about casting a function pointer to a normal pointer.
    109     if (Name == "exit") return (void*)(intptr_t)&jit_exit;
    110     if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
    111 
    112     // We should not invoke parent's ctors/dtors from generated main()!
    113     // On Mingw and Cygwin, the symbol __main is resolved to
    114     // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
    115     // (and register wrong callee's dtors with atexit(3)).
    116     // We expect ExecutionEngine::runStaticConstructorsDestructors()
    117     // is called before ExecutionEngine::runFunctionAsMain() is called.
    118     if (Name == "__main") return (void*)(intptr_t)&jit_noop;
    119 
    120     const char *NameStr = Name.c_str();
    121     // If this is an asm specifier, skip the sentinal.
    122     if (NameStr[0] == 1) ++NameStr;
    123 
    124     // If it's an external function, look it up in the process image...
    125     void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
    126     if (Ptr) return Ptr;
    127 
    128     // If it wasn't found and if it starts with an underscore ('_') character,
    129     // and has an asm specifier, try again without the underscore.
    130     if (Name[0] == 1 && NameStr[0] == '_') {
    131       Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
    132       if (Ptr) return Ptr;
    133     }
    134 
    135     // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf.  These
    136     // are references to hidden visibility symbols that dlsym cannot resolve.
    137     // If we have one of these, strip off $LDBLStub and try again.
    138 #if defined(__APPLE__) && defined(__ppc__)
    139     if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
    140         memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
    141       // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
    142       // This mirrors logic in libSystemStubs.a.
    143       std::string Prefix = std::string(Name.begin(), Name.end()-9);
    144       if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
    145         return Ptr;
    146       if (void *Ptr = getPointerToNamedFunction(Prefix, false))
    147         return Ptr;
    148     }
    149 #endif
    150   }
    151 
    152   /// If a LazyFunctionCreator is installed, use it to get/create the function.
    153   if (LazyFunctionCreator)
    154     if (void *RP = LazyFunctionCreator(Name))
    155       return RP;
    156 
    157   if (AbortOnFailure) {
    158     report_fatal_error("Program used external function '"+Name+
    159                       "' which could not be resolved!");
    160   }
    161   return 0;
    162 }
    163