ExternalFunctions.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. #include "Interpreter.h"
  22. #include "llvm/Config/config.h" // Detect libffi
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/Support/DynamicLibrary.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/ManagedStatic.h"
  29. #include "llvm/Support/Mutex.h"
  30. #include <cmath>
  31. #include <csignal>
  32. #include <cstdio>
  33. #include <cstring>
  34. #include <map>
  35. #ifdef HAVE_FFI_CALL
  36. #ifdef HAVE_FFI_H
  37. #include <ffi.h>
  38. #define USE_LIBFFI
  39. #elif HAVE_FFI_FFI_H
  40. #include <ffi/ffi.h>
  41. #define USE_LIBFFI
  42. #endif
  43. #endif
  44. using namespace llvm;
  45. static ManagedStatic<sys::Mutex> FunctionsLock;
  46. typedef GenericValue (*ExFunc)(FunctionType *,
  47. const std::vector<GenericValue> &);
  48. static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
  49. static std::map<std::string, ExFunc> FuncNames;
  50. #ifdef USE_LIBFFI
  51. typedef void (*RawFunc)();
  52. static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
  53. #endif
  54. static Interpreter *TheInterpreter;
  55. static char getTypeID(Type *Ty) {
  56. switch (Ty->getTypeID()) {
  57. case Type::VoidTyID: return 'V';
  58. case Type::IntegerTyID:
  59. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  60. case 1: return 'o';
  61. case 8: return 'B';
  62. case 16: return 'S';
  63. case 32: return 'I';
  64. case 64: return 'L';
  65. default: return 'N';
  66. }
  67. case Type::FloatTyID: return 'F';
  68. case Type::DoubleTyID: return 'D';
  69. case Type::PointerTyID: return 'P';
  70. case Type::FunctionTyID:return 'M';
  71. case Type::StructTyID: return 'T';
  72. case Type::ArrayTyID: return 'A';
  73. default: return 'U';
  74. }
  75. }
  76. // Try to find address of external function given a Function object.
  77. // Please note, that interpreter doesn't know how to assemble a
  78. // real call in general case (this is JIT job), that's why it assumes,
  79. // that all external functions has the same (and pretty "general") signature.
  80. // The typical example of such functions are "lle_X_" ones.
  81. static ExFunc lookupFunction(const Function *F) {
  82. // Function not found, look it up... start by figuring out what the
  83. // composite function name should be.
  84. std::string ExtName = "lle_";
  85. FunctionType *FT = F->getFunctionType();
  86. for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
  87. ExtName += getTypeID(FT->getContainedType(i));
  88. ExtName += "_" + F->getName().str();
  89. sys::ScopedLock Writer(*FunctionsLock);
  90. ExFunc FnPtr = FuncNames[ExtName];
  91. if (FnPtr == 0)
  92. FnPtr = FuncNames["lle_X_" + F->getName().str()];
  93. if (FnPtr == 0) // Try calling a generic function... if it exists...
  94. FnPtr = (ExFunc)(intptr_t)
  95. sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_" +
  96. F->getName().str());
  97. if (FnPtr != 0)
  98. ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
  99. return FnPtr;
  100. }
  101. #ifdef USE_LIBFFI
  102. static ffi_type *ffiTypeFor(Type *Ty) {
  103. switch (Ty->getTypeID()) {
  104. case Type::VoidTyID: return &ffi_type_void;
  105. case Type::IntegerTyID:
  106. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  107. case 8: return &ffi_type_sint8;
  108. case 16: return &ffi_type_sint16;
  109. case 32: return &ffi_type_sint32;
  110. case 64: return &ffi_type_sint64;
  111. }
  112. case Type::FloatTyID: return &ffi_type_float;
  113. case Type::DoubleTyID: return &ffi_type_double;
  114. case Type::PointerTyID: return &ffi_type_pointer;
  115. default: break;
  116. }
  117. // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  118. report_fatal_error("Type could not be mapped for use with libffi.");
  119. return NULL;
  120. }
  121. static void *ffiValueFor(Type *Ty, const GenericValue &AV,
  122. void *ArgDataPtr) {
  123. switch (Ty->getTypeID()) {
  124. case Type::IntegerTyID:
  125. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  126. case 8: {
  127. int8_t *I8Ptr = (int8_t *) ArgDataPtr;
  128. *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
  129. return ArgDataPtr;
  130. }
  131. case 16: {
  132. int16_t *I16Ptr = (int16_t *) ArgDataPtr;
  133. *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
  134. return ArgDataPtr;
  135. }
  136. case 32: {
  137. int32_t *I32Ptr = (int32_t *) ArgDataPtr;
  138. *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
  139. return ArgDataPtr;
  140. }
  141. case 64: {
  142. int64_t *I64Ptr = (int64_t *) ArgDataPtr;
  143. *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
  144. return ArgDataPtr;
  145. }
  146. }
  147. case Type::FloatTyID: {
  148. float *FloatPtr = (float *) ArgDataPtr;
  149. *FloatPtr = AV.FloatVal;
  150. return ArgDataPtr;
  151. }
  152. case Type::DoubleTyID: {
  153. double *DoublePtr = (double *) ArgDataPtr;
  154. *DoublePtr = AV.DoubleVal;
  155. return ArgDataPtr;
  156. }
  157. case Type::PointerTyID: {
  158. void **PtrPtr = (void **) ArgDataPtr;
  159. *PtrPtr = GVTOP(AV);
  160. return ArgDataPtr;
  161. }
  162. default: break;
  163. }
  164. // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  165. report_fatal_error("Type value could not be mapped for use with libffi.");
  166. return NULL;
  167. }
  168. static bool ffiInvoke(RawFunc Fn, Function *F,
  169. const std::vector<GenericValue> &ArgVals,
  170. const DataLayout *TD, GenericValue &Result) {
  171. ffi_cif cif;
  172. FunctionType *FTy = F->getFunctionType();
  173. const unsigned NumArgs = F->arg_size();
  174. // TODO: We don't have type information about the remaining arguments, because
  175. // this information is never passed into ExecutionEngine::runFunction().
  176. if (ArgVals.size() > NumArgs && F->isVarArg()) {
  177. report_fatal_error("Calling external var arg function '" + F->getName()
  178. + "' is not supported by the Interpreter.");
  179. }
  180. unsigned ArgBytes = 0;
  181. std::vector<ffi_type*> args(NumArgs);
  182. for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
  183. A != E; ++A) {
  184. const unsigned ArgNo = A->getArgNo();
  185. Type *ArgTy = FTy->getParamType(ArgNo);
  186. args[ArgNo] = ffiTypeFor(ArgTy);
  187. ArgBytes += TD->getTypeStoreSize(ArgTy);
  188. }
  189. SmallVector<uint8_t, 128> ArgData;
  190. ArgData.resize(ArgBytes);
  191. uint8_t *ArgDataPtr = ArgData.data();
  192. SmallVector<void*, 16> values(NumArgs);
  193. for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
  194. A != E; ++A) {
  195. const unsigned ArgNo = A->getArgNo();
  196. Type *ArgTy = FTy->getParamType(ArgNo);
  197. values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
  198. ArgDataPtr += TD->getTypeStoreSize(ArgTy);
  199. }
  200. Type *RetTy = FTy->getReturnType();
  201. ffi_type *rtype = ffiTypeFor(RetTy);
  202. if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
  203. SmallVector<uint8_t, 128> ret;
  204. if (RetTy->getTypeID() != Type::VoidTyID)
  205. ret.resize(TD->getTypeStoreSize(RetTy));
  206. ffi_call(&cif, Fn, ret.data(), values.data());
  207. switch (RetTy->getTypeID()) {
  208. case Type::IntegerTyID:
  209. switch (cast<IntegerType>(RetTy)->getBitWidth()) {
  210. case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
  211. case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
  212. case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
  213. case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
  214. }
  215. break;
  216. case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
  217. case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
  218. case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
  219. default: break;
  220. }
  221. return true;
  222. }
  223. return false;
  224. }
  225. #endif // USE_LIBFFI
  226. GenericValue Interpreter::callExternalFunction(Function *F,
  227. const std::vector<GenericValue> &ArgVals) {
  228. TheInterpreter = this;
  229. FunctionsLock->acquire();
  230. // Do a lookup to see if the function is in our cache... this should just be a
  231. // deferred annotation!
  232. std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
  233. if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
  234. : FI->second) {
  235. FunctionsLock->release();
  236. return Fn(F->getFunctionType(), ArgVals);
  237. }
  238. #ifdef USE_LIBFFI
  239. std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
  240. RawFunc RawFn;
  241. if (RF == RawFunctions->end()) {
  242. RawFn = (RawFunc)(intptr_t)
  243. sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
  244. if (!RawFn)
  245. RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
  246. if (RawFn != 0)
  247. RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
  248. } else {
  249. RawFn = RF->second;
  250. }
  251. FunctionsLock->release();
  252. GenericValue Result;
  253. if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
  254. return Result;
  255. #endif // USE_LIBFFI
  256. if (F->getName() == "__main")
  257. errs() << "Tried to execute an unknown external function: "
  258. << *F->getType() << " __main\n";
  259. else
  260. report_fatal_error("Tried to execute an unknown external function: " +
  261. F->getName());
  262. #ifndef USE_LIBFFI
  263. errs() << "Recompiling LLVM with --enable-libffi might help.\n";
  264. #endif
  265. return GenericValue();
  266. }
  267. //===----------------------------------------------------------------------===//
  268. // Functions "exported" to the running application...
  269. //
  270. // void atexit(Function*)
  271. static
  272. GenericValue lle_X_atexit(FunctionType *FT,
  273. const std::vector<GenericValue> &Args) {
  274. assert(Args.size() == 1);
  275. TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
  276. GenericValue GV;
  277. GV.IntVal = 0;
  278. return GV;
  279. }
  280. // void exit(int)
  281. static
  282. GenericValue lle_X_exit(FunctionType *FT,
  283. const std::vector<GenericValue> &Args) {
  284. TheInterpreter->exitCalled(Args[0]);
  285. return GenericValue();
  286. }
  287. // void abort(void)
  288. static
  289. GenericValue lle_X_abort(FunctionType *FT,
  290. const std::vector<GenericValue> &Args) {
  291. //FIXME: should we report or raise here?
  292. //report_fatal_error("Interpreted program raised SIGABRT");
  293. raise (SIGABRT);
  294. return GenericValue();
  295. }
  296. // int sprintf(char *, const char *, ...) - a very rough implementation to make
  297. // output useful.
  298. static
  299. GenericValue lle_X_sprintf(FunctionType *FT,
  300. const std::vector<GenericValue> &Args) {
  301. char *OutputBuffer = (char *)GVTOP(Args[0]);
  302. const char *FmtStr = (const char *)GVTOP(Args[1]);
  303. unsigned ArgNo = 2;
  304. // printf should return # chars printed. This is completely incorrect, but
  305. // close enough for now.
  306. GenericValue GV;
  307. GV.IntVal = APInt(32, strlen(FmtStr));
  308. while (1) {
  309. switch (*FmtStr) {
  310. case 0: return GV; // Null terminator...
  311. default: // Normal nonspecial character
  312. sprintf(OutputBuffer++, "%c", *FmtStr++);
  313. break;
  314. case '\\': { // Handle escape codes
  315. sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
  316. FmtStr += 2; OutputBuffer += 2;
  317. break;
  318. }
  319. case '%': { // Handle format specifiers
  320. char FmtBuf[100] = "", Buffer[1000] = "";
  321. char *FB = FmtBuf;
  322. *FB++ = *FmtStr++;
  323. char Last = *FB++ = *FmtStr++;
  324. unsigned HowLong = 0;
  325. while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
  326. Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
  327. Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
  328. Last != 'p' && Last != 's' && Last != '%') {
  329. if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
  330. Last = *FB++ = *FmtStr++;
  331. }
  332. *FB = 0;
  333. switch (Last) {
  334. case '%':
  335. memcpy(Buffer, "%", 2); break;
  336. case 'c':
  337. sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
  338. break;
  339. case 'd': case 'i':
  340. case 'u': case 'o':
  341. case 'x': case 'X':
  342. if (HowLong >= 1) {
  343. if (HowLong == 1 &&
  344. TheInterpreter->getDataLayout()->getPointerSizeInBits() == 64 &&
  345. sizeof(long) < sizeof(int64_t)) {
  346. // Make sure we use %lld with a 64 bit argument because we might be
  347. // compiling LLI on a 32 bit compiler.
  348. unsigned Size = strlen(FmtBuf);
  349. FmtBuf[Size] = FmtBuf[Size-1];
  350. FmtBuf[Size+1] = 0;
  351. FmtBuf[Size-1] = 'l';
  352. }
  353. sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
  354. } else
  355. sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
  356. break;
  357. case 'e': case 'E': case 'g': case 'G': case 'f':
  358. sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
  359. case 'p':
  360. sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
  361. case 's':
  362. sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
  363. default:
  364. errs() << "<unknown printf code '" << *FmtStr << "'!>";
  365. ArgNo++; break;
  366. }
  367. size_t Len = strlen(Buffer);
  368. memcpy(OutputBuffer, Buffer, Len + 1);
  369. OutputBuffer += Len;
  370. }
  371. break;
  372. }
  373. }
  374. return GV;
  375. }
  376. // int printf(const char *, ...) - a very rough implementation to make output
  377. // useful.
  378. static
  379. GenericValue lle_X_printf(FunctionType *FT,
  380. const std::vector<GenericValue> &Args) {
  381. char Buffer[10000];
  382. std::vector<GenericValue> NewArgs;
  383. NewArgs.push_back(PTOGV((void*)&Buffer[0]));
  384. NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
  385. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  386. outs() << Buffer;
  387. return GV;
  388. }
  389. // int sscanf(const char *format, ...);
  390. static
  391. GenericValue lle_X_sscanf(FunctionType *FT,
  392. const std::vector<GenericValue> &args) {
  393. assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
  394. char *Args[10];
  395. for (unsigned i = 0; i < args.size(); ++i)
  396. Args[i] = (char*)GVTOP(args[i]);
  397. GenericValue GV;
  398. GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
  399. Args[5], Args[6], Args[7], Args[8], Args[9]));
  400. return GV;
  401. }
  402. // int scanf(const char *format, ...);
  403. static
  404. GenericValue lle_X_scanf(FunctionType *FT,
  405. const std::vector<GenericValue> &args) {
  406. assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
  407. char *Args[10];
  408. for (unsigned i = 0; i < args.size(); ++i)
  409. Args[i] = (char*)GVTOP(args[i]);
  410. GenericValue GV;
  411. GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
  412. Args[5], Args[6], Args[7], Args[8], Args[9]));
  413. return GV;
  414. }
  415. // int fprintf(FILE *, const char *, ...) - a very rough implementation to make
  416. // output useful.
  417. static
  418. GenericValue lle_X_fprintf(FunctionType *FT,
  419. const std::vector<GenericValue> &Args) {
  420. assert(Args.size() >= 2);
  421. char Buffer[10000];
  422. std::vector<GenericValue> NewArgs;
  423. NewArgs.push_back(PTOGV(Buffer));
  424. NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
  425. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  426. fputs(Buffer, (FILE *) GVTOP(Args[0]));
  427. return GV;
  428. }
  429. GenericValue lle_X_memset(FunctionType *FT,
  430. const std::vector<GenericValue> &Args) {
  431. int val = (int)Args[1].IntVal.getSExtValue();
  432. size_t len = (size_t)Args[2].IntVal.getZExtValue();
  433. memset((void*)GVTOP(Args[0]),val, len);
  434. // llvm.memset.* returns void, lle_X_* returns GenericValue,
  435. // so here we return GenericValue with IntVal set to zero
  436. GenericValue GV;
  437. GV.IntVal = 0;
  438. return GV;
  439. }
  440. GenericValue lle_X_memcpy(FunctionType *FT,
  441. const std::vector<GenericValue> &Args) {
  442. memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
  443. (size_t)(Args[2].IntVal.getLimitedValue()));
  444. // llvm.mecpy* returns void, lle_X_* returns GenericValue,
  445. // so here we return GenericValue with IntVal set to zero
  446. GenericValue GV;
  447. GV.IntVal = 0;
  448. return GV;
  449. }
  450. void Interpreter::initializeExternalFunctions() {
  451. sys::ScopedLock Writer(*FunctionsLock);
  452. FuncNames["lle_X_atexit"] = lle_X_atexit;
  453. FuncNames["lle_X_exit"] = lle_X_exit;
  454. FuncNames["lle_X_abort"] = lle_X_abort;
  455. FuncNames["lle_X_printf"] = lle_X_printf;
  456. FuncNames["lle_X_sprintf"] = lle_X_sprintf;
  457. FuncNames["lle_X_sscanf"] = lle_X_sscanf;
  458. FuncNames["lle_X_scanf"] = lle_X_scanf;
  459. FuncNames["lle_X_fprintf"] = lle_X_fprintf;
  460. FuncNames["lle_X_memset"] = lle_X_memset;
  461. FuncNames["lle_X_memcpy"] = lle_X_memcpy;
  462. }