ExternalFunctions.cpp 17 KB

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