ExternalFunctions.cpp 17 KB

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