ExternalFunctions.cpp 17 KB

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