LLVM API Documentation
00001 //===-- ExternalFunctions.cpp - Implement External Functions --------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains both code to deal with invoking "external" functions, but 00011 // also contains code that implements "exported" external functions. 00012 // 00013 // There are currently two mechanisms for handling external functions in the 00014 // Interpreter. The first is to implement lle_* wrapper functions that are 00015 // specific to well-known library functions which manually translate the 00016 // arguments from GenericValues and make the call. If such a wrapper does 00017 // not exist, and libffi is available, then the Interpreter will attempt to 00018 // invoke the function using libffi, after finding its address. 00019 // 00020 //===----------------------------------------------------------------------===// 00021 00022 #include "Interpreter.h" 00023 #include "llvm/DerivedTypes.h" 00024 #include "llvm/Module.h" 00025 #include "llvm/Config/config.h" // Detect libffi 00026 #include "llvm/Support/ErrorHandling.h" 00027 #include "llvm/Support/Streams.h" 00028 #include "llvm/System/DynamicLibrary.h" 00029 #include "llvm/Target/TargetData.h" 00030 #include "llvm/Support/ManagedStatic.h" 00031 #include "llvm/System/Mutex.h" 00032 #include <csignal> 00033 #include <cstdio> 00034 #include <map> 00035 #include <cmath> 00036 #include <cstring> 00037 00038 #ifdef HAVE_FFI_CALL 00039 #ifdef HAVE_FFI_H 00040 #include <ffi.h> 00041 #define USE_LIBFFI 00042 #elif HAVE_FFI_FFI_H 00043 #include <ffi/ffi.h> 00044 #define USE_LIBFFI 00045 #endif 00046 #endif 00047 00048 using namespace llvm; 00049 00050 static ManagedStatic<sys::Mutex> FunctionsLock; 00051 00052 typedef GenericValue (*ExFunc)(const FunctionType *, 00053 const std::vector<GenericValue> &); 00054 static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions; 00055 static std::map<std::string, ExFunc> FuncNames; 00056 00057 #ifdef USE_LIBFFI 00058 typedef void (*RawFunc)(); 00059 static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions; 00060 #endif 00061 00062 static Interpreter *TheInterpreter; 00063 00064 static char getTypeID(const Type *Ty) { 00065 switch (Ty->getTypeID()) { 00066 case Type::VoidTyID: return 'V'; 00067 case Type::IntegerTyID: 00068 switch (cast<IntegerType>(Ty)->getBitWidth()) { 00069 case 1: return 'o'; 00070 case 8: return 'B'; 00071 case 16: return 'S'; 00072 case 32: return 'I'; 00073 case 64: return 'L'; 00074 default: return 'N'; 00075 } 00076 case Type::FloatTyID: return 'F'; 00077 case Type::DoubleTyID: return 'D'; 00078 case Type::PointerTyID: return 'P'; 00079 case Type::FunctionTyID:return 'M'; 00080 case Type::StructTyID: return 'T'; 00081 case Type::ArrayTyID: return 'A'; 00082 case Type::OpaqueTyID: return 'O'; 00083 default: return 'U'; 00084 } 00085 } 00086 00087 // Try to find address of external function given a Function object. 00088 // Please note, that interpreter doesn't know how to assemble a 00089 // real call in general case (this is JIT job), that's why it assumes, 00090 // that all external functions has the same (and pretty "general") signature. 00091 // The typical example of such functions are "lle_X_" ones. 00092 static ExFunc lookupFunction(const Function *F) { 00093 // Function not found, look it up... start by figuring out what the 00094 // composite function name should be. 00095 std::string ExtName = "lle_"; 00096 const FunctionType *FT = F->getFunctionType(); 00097 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i) 00098 ExtName += getTypeID(FT->getContainedType(i)); 00099 ExtName + "_" + F->getNameStr(); 00100 00101 sys::ScopedLock Writer(*FunctionsLock); 00102 ExFunc FnPtr = FuncNames[ExtName]; 00103 if (FnPtr == 0) 00104 FnPtr = FuncNames["lle_X_" + F->getNameStr()]; 00105 if (FnPtr == 0) // Try calling a generic function... if it exists... 00106 FnPtr = (ExFunc)(intptr_t) 00107 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr()); 00108 if (FnPtr != 0) 00109 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later 00110 return FnPtr; 00111 } 00112 00113 #ifdef USE_LIBFFI 00114 static ffi_type *ffiTypeFor(const Type *Ty) { 00115 switch (Ty->getTypeID()) { 00116 case Type::VoidTyID: return &ffi_type_void; 00117 case Type::IntegerTyID: 00118 switch (cast<IntegerType>(Ty)->getBitWidth()) { 00119 case 8: return &ffi_type_sint8; 00120 case 16: return &ffi_type_sint16; 00121 case 32: return &ffi_type_sint32; 00122 case 64: return &ffi_type_sint64; 00123 } 00124 case Type::FloatTyID: return &ffi_type_float; 00125 case Type::DoubleTyID: return &ffi_type_double; 00126 case Type::PointerTyID: return &ffi_type_pointer; 00127 default: break; 00128 } 00129 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 00130 llvm_report_error("Type could not be mapped for use with libffi."); 00131 return NULL; 00132 } 00133 00134 static void *ffiValueFor(const Type *Ty, const GenericValue &AV, 00135 void *ArgDataPtr) { 00136 switch (Ty->getTypeID()) { 00137 case Type::IntegerTyID: 00138 switch (cast<IntegerType>(Ty)->getBitWidth()) { 00139 case 8: { 00140 int8_t *I8Ptr = (int8_t *) ArgDataPtr; 00141 *I8Ptr = (int8_t) AV.IntVal.getZExtValue(); 00142 return ArgDataPtr; 00143 } 00144 case 16: { 00145 int16_t *I16Ptr = (int16_t *) ArgDataPtr; 00146 *I16Ptr = (int16_t) AV.IntVal.getZExtValue(); 00147 return ArgDataPtr; 00148 } 00149 case 32: { 00150 int32_t *I32Ptr = (int32_t *) ArgDataPtr; 00151 *I32Ptr = (int32_t) AV.IntVal.getZExtValue(); 00152 return ArgDataPtr; 00153 } 00154 case 64: { 00155 int64_t *I64Ptr = (int64_t *) ArgDataPtr; 00156 *I64Ptr = (int64_t) AV.IntVal.getZExtValue(); 00157 return ArgDataPtr; 00158 } 00159 } 00160 case Type::FloatTyID: { 00161 float *FloatPtr = (float *) ArgDataPtr; 00162 *FloatPtr = AV.DoubleVal; 00163 return ArgDataPtr; 00164 } 00165 case Type::DoubleTyID: { 00166 double *DoublePtr = (double *) ArgDataPtr; 00167 *DoublePtr = AV.DoubleVal; 00168 return ArgDataPtr; 00169 } 00170 case Type::PointerTyID: { 00171 void **PtrPtr = (void **) ArgDataPtr; 00172 *PtrPtr = GVTOP(AV); 00173 return ArgDataPtr; 00174 } 00175 default: break; 00176 } 00177 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 00178 llvm_report_error("Type value could not be mapped for use with libffi."); 00179 return NULL; 00180 } 00181 00182 static bool ffiInvoke(RawFunc Fn, Function *F, 00183 const std::vector<GenericValue> &ArgVals, 00184 const TargetData *TD, GenericValue &Result) { 00185 ffi_cif cif; 00186 const FunctionType *FTy = F->getFunctionType(); 00187 const unsigned NumArgs = F->arg_size(); 00188 00189 // TODO: We don't have type information about the remaining arguments, because 00190 // this information is never passed into ExecutionEngine::runFunction(). 00191 if (ArgVals.size() > NumArgs && F->isVarArg()) { 00192 llvm_report_error("Calling external var arg function '" + F->getName() 00193 + "' is not supported by the Interpreter."); 00194 } 00195 00196 unsigned ArgBytes = 0; 00197 00198 std::vector<ffi_type*> args(NumArgs); 00199 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end(); 00200 A != E; ++A) { 00201 const unsigned ArgNo = A->getArgNo(); 00202 const Type *ArgTy = FTy->getParamType(ArgNo); 00203 args[ArgNo] = ffiTypeFor(ArgTy); 00204 ArgBytes += TD->getTypeStoreSize(ArgTy); 00205 } 00206 00207 uint8_t *ArgData = (uint8_t*) alloca(ArgBytes); 00208 uint8_t *ArgDataPtr = ArgData; 00209 std::vector<void*> values(NumArgs); 00210 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end(); 00211 A != E; ++A) { 00212 const unsigned ArgNo = A->getArgNo(); 00213 const Type *ArgTy = FTy->getParamType(ArgNo); 00214 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr); 00215 ArgDataPtr += TD->getTypeStoreSize(ArgTy); 00216 } 00217 00218 const Type *RetTy = FTy->getReturnType(); 00219 ffi_type *rtype = ffiTypeFor(RetTy); 00220 00221 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) { 00222 void *ret = NULL; 00223 if (RetTy->getTypeID() != Type::VoidTyID) 00224 ret = alloca(TD->getTypeStoreSize(RetTy)); 00225 ffi_call(&cif, Fn, ret, &values[0]); 00226 switch (RetTy->getTypeID()) { 00227 case Type::IntegerTyID: 00228 switch (cast<IntegerType>(RetTy)->getBitWidth()) { 00229 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret); break; 00230 case 16: Result.IntVal = APInt(16, *(int16_t*) ret); break; 00231 case 32: Result.IntVal = APInt(32, *(int32_t*) ret); break; 00232 case 64: Result.IntVal = APInt(64, *(int64_t*) ret); break; 00233 } 00234 break; 00235 case Type::FloatTyID: Result.FloatVal = *(float *) ret; break; 00236 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret; break; 00237 case Type::PointerTyID: Result.PointerVal = *(void **) ret; break; 00238 default: break; 00239 } 00240 return true; 00241 } 00242 00243 return false; 00244 } 00245 #endif // USE_LIBFFI 00246 00247 GenericValue Interpreter::callExternalFunction(Function *F, 00248 const std::vector<GenericValue> &ArgVals) { 00249 TheInterpreter = this; 00250 00251 FunctionsLock->acquire(); 00252 00253 // Do a lookup to see if the function is in our cache... this should just be a 00254 // deferred annotation! 00255 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F); 00256 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F) 00257 : FI->second) { 00258 FunctionsLock->release(); 00259 return Fn(F->getFunctionType(), ArgVals); 00260 } 00261 00262 #ifdef USE_LIBFFI 00263 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F); 00264 RawFunc RawFn; 00265 if (RF == RawFunctions->end()) { 00266 RawFn = (RawFunc)(intptr_t) 00267 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName()); 00268 if (RawFn != 0) 00269 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later 00270 } else { 00271 RawFn = RF->second; 00272 } 00273 00274 FunctionsLock->release(); 00275 00276 GenericValue Result; 00277 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result)) 00278 return Result; 00279 #endif // USE_LIBFFI 00280 00281 if (F->getName() == "__main") 00282 cerr << "Tried to execute an unknown external function: " 00283 << F->getType()->getDescription() << " __main\n"; 00284 else 00285 llvm_report_error("Tried to execute an unknown external function: " + 00286 F->getType()->getDescription() + " " +F->getName()); 00287 return GenericValue(); 00288 } 00289 00290 00291 //===----------------------------------------------------------------------===// 00292 // Functions "exported" to the running application... 00293 // 00294 00295 // Visual Studio warns about returning GenericValue in extern "C" linkage 00296 #ifdef _MSC_VER 00297 #pragma warning(disable : 4190) 00298 #endif 00299 00300 extern "C" { // Don't add C++ manglings to llvm mangling :) 00301 00302 // void atexit(Function*) 00303 GenericValue lle_X_atexit(const FunctionType *FT, 00304 const std::vector<GenericValue> &Args) { 00305 assert(Args.size() == 1); 00306 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0])); 00307 GenericValue GV; 00308 GV.IntVal = 0; 00309 return GV; 00310 } 00311 00312 // void exit(int) 00313 GenericValue lle_X_exit(const FunctionType *FT, 00314 const std::vector<GenericValue> &Args) { 00315 TheInterpreter->exitCalled(Args[0]); 00316 return GenericValue(); 00317 } 00318 00319 // void abort(void) 00320 GenericValue lle_X_abort(const FunctionType *FT, 00321 const std::vector<GenericValue> &Args) { 00322 //FIXME: should we report or raise here? 00323 //llvm_report_error("Interpreted program raised SIGABRT"); 00324 raise (SIGABRT); 00325 return GenericValue(); 00326 } 00327 00328 // int sprintf(char *, const char *, ...) - a very rough implementation to make 00329 // output useful. 00330 GenericValue lle_X_sprintf(const FunctionType *FT, 00331 const std::vector<GenericValue> &Args) { 00332 char *OutputBuffer = (char *)GVTOP(Args[0]); 00333 const char *FmtStr = (const char *)GVTOP(Args[1]); 00334 unsigned ArgNo = 2; 00335 00336 // printf should return # chars printed. This is completely incorrect, but 00337 // close enough for now. 00338 GenericValue GV; 00339 GV.IntVal = APInt(32, strlen(FmtStr)); 00340 while (1) { 00341 switch (*FmtStr) { 00342 case 0: return GV; // Null terminator... 00343 default: // Normal nonspecial character 00344 sprintf(OutputBuffer++, "%c", *FmtStr++); 00345 break; 00346 case '\\': { // Handle escape codes 00347 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1)); 00348 FmtStr += 2; OutputBuffer += 2; 00349 break; 00350 } 00351 case '%': { // Handle format specifiers 00352 char FmtBuf[100] = "", Buffer[1000] = ""; 00353 char *FB = FmtBuf; 00354 *FB++ = *FmtStr++; 00355 char Last = *FB++ = *FmtStr++; 00356 unsigned HowLong = 0; 00357 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' && 00358 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' && 00359 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' && 00360 Last != 'p' && Last != 's' && Last != '%') { 00361 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's 00362 Last = *FB++ = *FmtStr++; 00363 } 00364 *FB = 0; 00365 00366 switch (Last) { 00367 case '%': 00368 strcpy(Buffer, "%"); break; 00369 case 'c': 00370 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue())); 00371 break; 00372 case 'd': case 'i': 00373 case 'u': case 'o': 00374 case 'x': case 'X': 00375 if (HowLong >= 1) { 00376 if (HowLong == 1 && 00377 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 && 00378 sizeof(long) < sizeof(int64_t)) { 00379 // Make sure we use %lld with a 64 bit argument because we might be 00380 // compiling LLI on a 32 bit compiler. 00381 unsigned Size = strlen(FmtBuf); 00382 FmtBuf[Size] = FmtBuf[Size-1]; 00383 FmtBuf[Size+1] = 0; 00384 FmtBuf[Size-1] = 'l'; 00385 } 00386 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue()); 00387 } else 00388 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue())); 00389 break; 00390 case 'e': case 'E': case 'g': case 'G': case 'f': 00391 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break; 00392 case 'p': 00393 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break; 00394 case 's': 00395 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break; 00396 default: cerr << "<unknown printf code '" << *FmtStr << "'!>"; 00397 ArgNo++; break; 00398 } 00399 strcpy(OutputBuffer, Buffer); 00400 OutputBuffer += strlen(Buffer); 00401 } 00402 break; 00403 } 00404 } 00405 return GV; 00406 } 00407 00408 // int printf(const char *, ...) - a very rough implementation to make output 00409 // useful. 00410 GenericValue lle_X_printf(const FunctionType *FT, 00411 const std::vector<GenericValue> &Args) { 00412 char Buffer[10000]; 00413 std::vector<GenericValue> NewArgs; 00414 NewArgs.push_back(PTOGV((void*)&Buffer[0])); 00415 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end()); 00416 GenericValue GV = lle_X_sprintf(FT, NewArgs); 00417 cout << Buffer; 00418 return GV; 00419 } 00420 00421 static void ByteswapSCANFResults(LLVMContext &C, 00422 const char *Fmt, void *Arg0, void *Arg1, 00423 void *Arg2, void *Arg3, void *Arg4, void *Arg5, 00424 void *Arg6, void *Arg7, void *Arg8) { 00425 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 }; 00426 00427 // Loop over the format string, munging read values as appropriate (performs 00428 // byteswaps as necessary). 00429 unsigned ArgNo = 0; 00430 while (*Fmt) { 00431 if (*Fmt++ == '%') { 00432 // Read any flag characters that may be present... 00433 bool Suppress = false; 00434 bool Half = false; 00435 bool Long = false; 00436 bool LongLong = false; // long long or long double 00437 00438 while (1) { 00439 switch (*Fmt++) { 00440 case '*': Suppress = true; break; 00441 case 'a': /*Allocate = true;*/ break; // We don't need to track this 00442 case 'h': Half = true; break; 00443 case 'l': Long = true; break; 00444 case 'q': 00445 case 'L': LongLong = true; break; 00446 default: 00447 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs 00448 goto Out; 00449 } 00450 } 00451 Out: 00452 00453 // Read the conversion character 00454 if (!Suppress && Fmt[-1] != '%') { // Nothing to do? 00455 unsigned Size = 0; 00456 const Type *Ty = 0; 00457 00458 switch (Fmt[-1]) { 00459 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p': 00460 case 'd': 00461 if (Long || LongLong) { 00462 Size = 8; Ty = Type::getInt64Ty(C); 00463 } else if (Half) { 00464 Size = 4; Ty = Type::getInt16Ty(C); 00465 } else { 00466 Size = 4; Ty = Type::getInt32Ty(C); 00467 } 00468 break; 00469 00470 case 'e': case 'g': case 'E': 00471 case 'f': 00472 if (Long || LongLong) { 00473 Size = 8; Ty = Type::getDoubleTy(C); 00474 } else { 00475 Size = 4; Ty = Type::getFloatTy(C); 00476 } 00477 break; 00478 00479 case 's': case 'c': case '[': // No byteswap needed 00480 Size = 1; 00481 Ty = Type::getInt8Ty(C); 00482 break; 00483 00484 default: break; 00485 } 00486 00487 if (Size) { 00488 GenericValue GV; 00489 void *Arg = Args[ArgNo++]; 00490 memcpy(&GV, Arg, Size); 00491 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty); 00492 } 00493 } 00494 } 00495 } 00496 } 00497 00498 // int sscanf(const char *format, ...); 00499 GenericValue lle_X_sscanf(const FunctionType *FT, 00500 const std::vector<GenericValue> &args) { 00501 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!"); 00502 00503 char *Args[10]; 00504 for (unsigned i = 0; i < args.size(); ++i) 00505 Args[i] = (char*)GVTOP(args[i]); 00506 00507 GenericValue GV; 00508 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4], 00509 Args[5], Args[6], Args[7], Args[8], Args[9])); 00510 ByteswapSCANFResults(FT->getContext(), 00511 Args[1], Args[2], Args[3], Args[4], 00512 Args[5], Args[6], Args[7], Args[8], Args[9], 0); 00513 return GV; 00514 } 00515 00516 // int scanf(const char *format, ...); 00517 GenericValue lle_X_scanf(const FunctionType *FT, 00518 const std::vector<GenericValue> &args) { 00519 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!"); 00520 00521 char *Args[10]; 00522 for (unsigned i = 0; i < args.size(); ++i) 00523 Args[i] = (char*)GVTOP(args[i]); 00524 00525 GenericValue GV; 00526 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4], 00527 Args[5], Args[6], Args[7], Args[8], Args[9])); 00528 ByteswapSCANFResults(FT->getContext(), 00529 Args[0], Args[1], Args[2], Args[3], Args[4], 00530 Args[5], Args[6], Args[7], Args[8], Args[9]); 00531 return GV; 00532 } 00533 00534 // int fprintf(FILE *, const char *, ...) - a very rough implementation to make 00535 // output useful. 00536 GenericValue lle_X_fprintf(const FunctionType *FT, 00537 const std::vector<GenericValue> &Args) { 00538 assert(Args.size() >= 2); 00539 char Buffer[10000]; 00540 std::vector<GenericValue> NewArgs; 00541 NewArgs.push_back(PTOGV(Buffer)); 00542 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end()); 00543 GenericValue GV = lle_X_sprintf(FT, NewArgs); 00544 00545 fputs(Buffer, (FILE *) GVTOP(Args[0])); 00546 return GV; 00547 } 00548 00549 } // End extern "C" 00550 00551 // Done with externals; turn the warning back on 00552 #ifdef _MSC_VER 00553 #pragma warning(default: 4190) 00554 #endif 00555 00556 00557 void Interpreter::initializeExternalFunctions() { 00558 sys::ScopedLock Writer(*FunctionsLock); 00559 FuncNames["lle_X_atexit"] = lle_X_atexit; 00560 FuncNames["lle_X_exit"] = lle_X_exit; 00561 FuncNames["lle_X_abort"] = lle_X_abort; 00562 00563 FuncNames["lle_X_printf"] = lle_X_printf; 00564 FuncNames["lle_X_sprintf"] = lle_X_sprintf; 00565 FuncNames["lle_X_sscanf"] = lle_X_sscanf; 00566 FuncNames["lle_X_scanf"] = lle_X_scanf; 00567 FuncNames["lle_X_fprintf"] = lle_X_fprintf; 00568 } 00569