ExternalFunctions.cpp revision 198090
1//===-- ExternalFunctions.cpp - Implement External Functions --------------===// 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// This file contains both code to deal with invoking "external" functions, but 11// also contains code that implements "exported" external functions. 12// 13// There are currently two mechanisms for handling external functions in the 14// Interpreter. The first is to implement lle_* wrapper functions that are 15// specific to well-known library functions which manually translate the 16// arguments from GenericValues and make the call. If such a wrapper does 17// not exist, and libffi is available, then the Interpreter will attempt to 18// invoke the function using libffi, after finding its address. 19// 20//===----------------------------------------------------------------------===// 21 22#include "Interpreter.h" 23#include "llvm/DerivedTypes.h" 24#include "llvm/Module.h" 25#include "llvm/Config/config.h" // Detect libffi 26#include "llvm/Support/ErrorHandling.h" 27#include "llvm/System/DynamicLibrary.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Support/ManagedStatic.h" 30#include "llvm/System/Mutex.h" 31#include <csignal> 32#include <cstdio> 33#include <map> 34#include <cmath> 35#include <cstring> 36 37#ifdef HAVE_FFI_CALL 38#ifdef HAVE_FFI_H 39#include <ffi.h> 40#define USE_LIBFFI 41#elif HAVE_FFI_FFI_H 42#include <ffi/ffi.h> 43#define USE_LIBFFI 44#endif 45#endif 46 47using namespace llvm; 48 49static ManagedStatic<sys::Mutex> FunctionsLock; 50 51typedef GenericValue (*ExFunc)(const FunctionType *, 52 const std::vector<GenericValue> &); 53static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions; 54static std::map<std::string, ExFunc> FuncNames; 55 56#ifdef USE_LIBFFI 57typedef void (*RawFunc)(); 58static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions; 59#endif 60 61static Interpreter *TheInterpreter; 62 63static char getTypeID(const Type *Ty) { 64 switch (Ty->getTypeID()) { 65 case Type::VoidTyID: return 'V'; 66 case Type::IntegerTyID: 67 switch (cast<IntegerType>(Ty)->getBitWidth()) { 68 case 1: return 'o'; 69 case 8: return 'B'; 70 case 16: return 'S'; 71 case 32: return 'I'; 72 case 64: return 'L'; 73 default: return 'N'; 74 } 75 case Type::FloatTyID: return 'F'; 76 case Type::DoubleTyID: return 'D'; 77 case Type::PointerTyID: return 'P'; 78 case Type::FunctionTyID:return 'M'; 79 case Type::StructTyID: return 'T'; 80 case Type::ArrayTyID: return 'A'; 81 case Type::OpaqueTyID: return 'O'; 82 default: return 'U'; 83 } 84} 85 86// Try to find address of external function given a Function object. 87// Please note, that interpreter doesn't know how to assemble a 88// real call in general case (this is JIT job), that's why it assumes, 89// that all external functions has the same (and pretty "general") signature. 90// The typical example of such functions are "lle_X_" ones. 91static ExFunc lookupFunction(const Function *F) { 92 // Function not found, look it up... start by figuring out what the 93 // composite function name should be. 94 std::string ExtName = "lle_"; 95 const FunctionType *FT = F->getFunctionType(); 96 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i) 97 ExtName += getTypeID(FT->getContainedType(i)); 98 ExtName + "_" + F->getNameStr(); 99 100 sys::ScopedLock Writer(*FunctionsLock); 101 ExFunc FnPtr = FuncNames[ExtName]; 102 if (FnPtr == 0) 103 FnPtr = FuncNames["lle_X_" + F->getNameStr()]; 104 if (FnPtr == 0) // Try calling a generic function... if it exists... 105 FnPtr = (ExFunc)(intptr_t) 106 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr()); 107 if (FnPtr != 0) 108 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later 109 return FnPtr; 110} 111 112#ifdef USE_LIBFFI 113static ffi_type *ffiTypeFor(const Type *Ty) { 114 switch (Ty->getTypeID()) { 115 case Type::VoidTyID: return &ffi_type_void; 116 case Type::IntegerTyID: 117 switch (cast<IntegerType>(Ty)->getBitWidth()) { 118 case 8: return &ffi_type_sint8; 119 case 16: return &ffi_type_sint16; 120 case 32: return &ffi_type_sint32; 121 case 64: return &ffi_type_sint64; 122 } 123 case Type::FloatTyID: return &ffi_type_float; 124 case Type::DoubleTyID: return &ffi_type_double; 125 case Type::PointerTyID: return &ffi_type_pointer; 126 default: break; 127 } 128 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 129 llvm_report_error("Type could not be mapped for use with libffi."); 130 return NULL; 131} 132 133static void *ffiValueFor(const Type *Ty, const GenericValue &AV, 134 void *ArgDataPtr) { 135 switch (Ty->getTypeID()) { 136 case Type::IntegerTyID: 137 switch (cast<IntegerType>(Ty)->getBitWidth()) { 138 case 8: { 139 int8_t *I8Ptr = (int8_t *) ArgDataPtr; 140 *I8Ptr = (int8_t) AV.IntVal.getZExtValue(); 141 return ArgDataPtr; 142 } 143 case 16: { 144 int16_t *I16Ptr = (int16_t *) ArgDataPtr; 145 *I16Ptr = (int16_t) AV.IntVal.getZExtValue(); 146 return ArgDataPtr; 147 } 148 case 32: { 149 int32_t *I32Ptr = (int32_t *) ArgDataPtr; 150 *I32Ptr = (int32_t) AV.IntVal.getZExtValue(); 151 return ArgDataPtr; 152 } 153 case 64: { 154 int64_t *I64Ptr = (int64_t *) ArgDataPtr; 155 *I64Ptr = (int64_t) AV.IntVal.getZExtValue(); 156 return ArgDataPtr; 157 } 158 } 159 case Type::FloatTyID: { 160 float *FloatPtr = (float *) ArgDataPtr; 161 *FloatPtr = AV.DoubleVal; 162 return ArgDataPtr; 163 } 164 case Type::DoubleTyID: { 165 double *DoublePtr = (double *) ArgDataPtr; 166 *DoublePtr = AV.DoubleVal; 167 return ArgDataPtr; 168 } 169 case Type::PointerTyID: { 170 void **PtrPtr = (void **) ArgDataPtr; 171 *PtrPtr = GVTOP(AV); 172 return ArgDataPtr; 173 } 174 default: break; 175 } 176 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 177 llvm_report_error("Type value could not be mapped for use with libffi."); 178 return NULL; 179} 180 181static bool ffiInvoke(RawFunc Fn, Function *F, 182 const std::vector<GenericValue> &ArgVals, 183 const TargetData *TD, GenericValue &Result) { 184 ffi_cif cif; 185 const FunctionType *FTy = F->getFunctionType(); 186 const unsigned NumArgs = F->arg_size(); 187 188 // TODO: We don't have type information about the remaining arguments, because 189 // this information is never passed into ExecutionEngine::runFunction(). 190 if (ArgVals.size() > NumArgs && F->isVarArg()) { 191 llvm_report_error("Calling external var arg function '" + F->getName() 192 + "' is not supported by the Interpreter."); 193 } 194 195 unsigned ArgBytes = 0; 196 197 std::vector<ffi_type*> args(NumArgs); 198 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end(); 199 A != E; ++A) { 200 const unsigned ArgNo = A->getArgNo(); 201 const Type *ArgTy = FTy->getParamType(ArgNo); 202 args[ArgNo] = ffiTypeFor(ArgTy); 203 ArgBytes += TD->getTypeStoreSize(ArgTy); 204 } 205 206 SmallVector<uint8_t, 128> ArgData; 207 ArgData.resize(ArgBytes); 208 uint8_t *ArgDataPtr = ArgData.data(); 209 SmallVector<void*, 16> values(NumArgs); 210 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end(); 211 A != E; ++A) { 212 const unsigned ArgNo = A->getArgNo(); 213 const Type *ArgTy = FTy->getParamType(ArgNo); 214 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr); 215 ArgDataPtr += TD->getTypeStoreSize(ArgTy); 216 } 217 218 const Type *RetTy = FTy->getReturnType(); 219 ffi_type *rtype = ffiTypeFor(RetTy); 220 221 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) { 222 SmallVector<uint8_t, 128> ret; 223 if (RetTy->getTypeID() != Type::VoidTyID) 224 ret.resize(TD->getTypeStoreSize(RetTy)); 225 ffi_call(&cif, Fn, ret.data(), values.data()); 226 switch (RetTy->getTypeID()) { 227 case Type::IntegerTyID: 228 switch (cast<IntegerType>(RetTy)->getBitWidth()) { 229 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break; 230 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break; 231 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break; 232 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break; 233 } 234 break; 235 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break; 236 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break; 237 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break; 238 default: break; 239 } 240 return true; 241 } 242 243 return false; 244} 245#endif // USE_LIBFFI 246 247GenericValue Interpreter::callExternalFunction(Function *F, 248 const std::vector<GenericValue> &ArgVals) { 249 TheInterpreter = this; 250 251 FunctionsLock->acquire(); 252 253 // Do a lookup to see if the function is in our cache... this should just be a 254 // deferred annotation! 255 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F); 256 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F) 257 : FI->second) { 258 FunctionsLock->release(); 259 return Fn(F->getFunctionType(), ArgVals); 260 } 261 262#ifdef USE_LIBFFI 263 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F); 264 RawFunc RawFn; 265 if (RF == RawFunctions->end()) { 266 RawFn = (RawFunc)(intptr_t) 267 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName()); 268 if (RawFn != 0) 269 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later 270 } else { 271 RawFn = RF->second; 272 } 273 274 FunctionsLock->release(); 275 276 GenericValue Result; 277 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result)) 278 return Result; 279#endif // USE_LIBFFI 280 281 if (F->getName() == "__main") 282 errs() << "Tried to execute an unknown external function: " 283 << F->getType()->getDescription() << " __main\n"; 284 else 285 llvm_report_error("Tried to execute an unknown external function: " + 286 F->getType()->getDescription() + " " +F->getName()); 287 return GenericValue(); 288} 289 290 291//===----------------------------------------------------------------------===// 292// Functions "exported" to the running application... 293// 294 295// Visual Studio warns about returning GenericValue in extern "C" linkage 296#ifdef _MSC_VER 297 #pragma warning(disable : 4190) 298#endif 299 300extern "C" { // Don't add C++ manglings to llvm mangling :) 301 302// void atexit(Function*) 303GenericValue lle_X_atexit(const FunctionType *FT, 304 const std::vector<GenericValue> &Args) { 305 assert(Args.size() == 1); 306 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0])); 307 GenericValue GV; 308 GV.IntVal = 0; 309 return GV; 310} 311 312// void exit(int) 313GenericValue lle_X_exit(const FunctionType *FT, 314 const std::vector<GenericValue> &Args) { 315 TheInterpreter->exitCalled(Args[0]); 316 return GenericValue(); 317} 318 319// void abort(void) 320GenericValue lle_X_abort(const FunctionType *FT, 321 const std::vector<GenericValue> &Args) { 322 //FIXME: should we report or raise here? 323 //llvm_report_error("Interpreted program raised SIGABRT"); 324 raise (SIGABRT); 325 return GenericValue(); 326} 327 328// int sprintf(char *, const char *, ...) - a very rough implementation to make 329// output useful. 330GenericValue lle_X_sprintf(const FunctionType *FT, 331 const std::vector<GenericValue> &Args) { 332 char *OutputBuffer = (char *)GVTOP(Args[0]); 333 const char *FmtStr = (const char *)GVTOP(Args[1]); 334 unsigned ArgNo = 2; 335 336 // printf should return # chars printed. This is completely incorrect, but 337 // close enough for now. 338 GenericValue GV; 339 GV.IntVal = APInt(32, strlen(FmtStr)); 340 while (1) { 341 switch (*FmtStr) { 342 case 0: return GV; // Null terminator... 343 default: // Normal nonspecial character 344 sprintf(OutputBuffer++, "%c", *FmtStr++); 345 break; 346 case '\\': { // Handle escape codes 347 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1)); 348 FmtStr += 2; OutputBuffer += 2; 349 break; 350 } 351 case '%': { // Handle format specifiers 352 char FmtBuf[100] = "", Buffer[1000] = ""; 353 char *FB = FmtBuf; 354 *FB++ = *FmtStr++; 355 char Last = *FB++ = *FmtStr++; 356 unsigned HowLong = 0; 357 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' && 358 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' && 359 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' && 360 Last != 'p' && Last != 's' && Last != '%') { 361 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's 362 Last = *FB++ = *FmtStr++; 363 } 364 *FB = 0; 365 366 switch (Last) { 367 case '%': 368 strcpy(Buffer, "%"); break; 369 case 'c': 370 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue())); 371 break; 372 case 'd': case 'i': 373 case 'u': case 'o': 374 case 'x': case 'X': 375 if (HowLong >= 1) { 376 if (HowLong == 1 && 377 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 && 378 sizeof(long) < sizeof(int64_t)) { 379 // Make sure we use %lld with a 64 bit argument because we might be 380 // compiling LLI on a 32 bit compiler. 381 unsigned Size = strlen(FmtBuf); 382 FmtBuf[Size] = FmtBuf[Size-1]; 383 FmtBuf[Size+1] = 0; 384 FmtBuf[Size-1] = 'l'; 385 } 386 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue()); 387 } else 388 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue())); 389 break; 390 case 'e': case 'E': case 'g': case 'G': case 'f': 391 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break; 392 case 'p': 393 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break; 394 case 's': 395 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break; 396 default: 397 errs() << "<unknown printf code '" << *FmtStr << "'!>"; 398 ArgNo++; break; 399 } 400 strcpy(OutputBuffer, Buffer); 401 OutputBuffer += strlen(Buffer); 402 } 403 break; 404 } 405 } 406 return GV; 407} 408 409// int printf(const char *, ...) - a very rough implementation to make output 410// useful. 411GenericValue lle_X_printf(const FunctionType *FT, 412 const std::vector<GenericValue> &Args) { 413 char Buffer[10000]; 414 std::vector<GenericValue> NewArgs; 415 NewArgs.push_back(PTOGV((void*)&Buffer[0])); 416 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end()); 417 GenericValue GV = lle_X_sprintf(FT, NewArgs); 418 outs() << Buffer; 419 return GV; 420} 421 422static void ByteswapSCANFResults(LLVMContext &C, 423 const char *Fmt, void *Arg0, void *Arg1, 424 void *Arg2, void *Arg3, void *Arg4, void *Arg5, 425 void *Arg6, void *Arg7, void *Arg8) { 426 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 }; 427 428 // Loop over the format string, munging read values as appropriate (performs 429 // byteswaps as necessary). 430 unsigned ArgNo = 0; 431 while (*Fmt) { 432 if (*Fmt++ == '%') { 433 // Read any flag characters that may be present... 434 bool Suppress = false; 435 bool Half = false; 436 bool Long = false; 437 bool LongLong = false; // long long or long double 438 439 while (1) { 440 switch (*Fmt++) { 441 case '*': Suppress = true; break; 442 case 'a': /*Allocate = true;*/ break; // We don't need to track this 443 case 'h': Half = true; break; 444 case 'l': Long = true; break; 445 case 'q': 446 case 'L': LongLong = true; break; 447 default: 448 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs 449 goto Out; 450 } 451 } 452 Out: 453 454 // Read the conversion character 455 if (!Suppress && Fmt[-1] != '%') { // Nothing to do? 456 unsigned Size = 0; 457 const Type *Ty = 0; 458 459 switch (Fmt[-1]) { 460 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p': 461 case 'd': 462 if (Long || LongLong) { 463 Size = 8; Ty = Type::getInt64Ty(C); 464 } else if (Half) { 465 Size = 4; Ty = Type::getInt16Ty(C); 466 } else { 467 Size = 4; Ty = Type::getInt32Ty(C); 468 } 469 break; 470 471 case 'e': case 'g': case 'E': 472 case 'f': 473 if (Long || LongLong) { 474 Size = 8; Ty = Type::getDoubleTy(C); 475 } else { 476 Size = 4; Ty = Type::getFloatTy(C); 477 } 478 break; 479 480 case 's': case 'c': case '[': // No byteswap needed 481 Size = 1; 482 Ty = Type::getInt8Ty(C); 483 break; 484 485 default: break; 486 } 487 488 if (Size) { 489 GenericValue GV; 490 void *Arg = Args[ArgNo++]; 491 memcpy(&GV, Arg, Size); 492 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty); 493 } 494 } 495 } 496 } 497} 498 499// int sscanf(const char *format, ...); 500GenericValue lle_X_sscanf(const FunctionType *FT, 501 const std::vector<GenericValue> &args) { 502 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!"); 503 504 char *Args[10]; 505 for (unsigned i = 0; i < args.size(); ++i) 506 Args[i] = (char*)GVTOP(args[i]); 507 508 GenericValue GV; 509 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4], 510 Args[5], Args[6], Args[7], Args[8], Args[9])); 511 ByteswapSCANFResults(FT->getContext(), 512 Args[1], Args[2], Args[3], Args[4], 513 Args[5], Args[6], Args[7], Args[8], Args[9], 0); 514 return GV; 515} 516 517// int scanf(const char *format, ...); 518GenericValue lle_X_scanf(const FunctionType *FT, 519 const std::vector<GenericValue> &args) { 520 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!"); 521 522 char *Args[10]; 523 for (unsigned i = 0; i < args.size(); ++i) 524 Args[i] = (char*)GVTOP(args[i]); 525 526 GenericValue GV; 527 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4], 528 Args[5], Args[6], Args[7], Args[8], Args[9])); 529 ByteswapSCANFResults(FT->getContext(), 530 Args[0], Args[1], Args[2], Args[3], Args[4], 531 Args[5], Args[6], Args[7], Args[8], Args[9]); 532 return GV; 533} 534 535// int fprintf(FILE *, const char *, ...) - a very rough implementation to make 536// output useful. 537GenericValue lle_X_fprintf(const FunctionType *FT, 538 const std::vector<GenericValue> &Args) { 539 assert(Args.size() >= 2); 540 char Buffer[10000]; 541 std::vector<GenericValue> NewArgs; 542 NewArgs.push_back(PTOGV(Buffer)); 543 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end()); 544 GenericValue GV = lle_X_sprintf(FT, NewArgs); 545 546 fputs(Buffer, (FILE *) GVTOP(Args[0])); 547 return GV; 548} 549 550} // End extern "C" 551 552// Done with externals; turn the warning back on 553#ifdef _MSC_VER 554 #pragma warning(default: 4190) 555#endif 556 557 558void Interpreter::initializeExternalFunctions() { 559 sys::ScopedLock Writer(*FunctionsLock); 560 FuncNames["lle_X_atexit"] = lle_X_atexit; 561 FuncNames["lle_X_exit"] = lle_X_exit; 562 FuncNames["lle_X_abort"] = lle_X_abort; 563 564 FuncNames["lle_X_printf"] = lle_X_printf; 565 FuncNames["lle_X_sprintf"] = lle_X_sprintf; 566 FuncNames["lle_X_sscanf"] = lle_X_sscanf; 567 FuncNames["lle_X_scanf"] = lle_X_scanf; 568 FuncNames["lle_X_fprintf"] = lle_X_fprintf; 569} 570