ExternalFunctions.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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/ADT/APInt.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/Config/config.h" // Detect libffi
  25. #include "llvm/ExecutionEngine/GenericValue.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/Type.h"
  30. #include "llvm/Support/Casting.h"
  31. #include "llvm/Support/DynamicLibrary.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/ManagedStatic.h"
  34. #include "llvm/Support/Mutex.h"
  35. #include "llvm/Support/UniqueLock.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <cassert>
  38. #include <cmath>
  39. #include <csignal>
  40. #include <cstdint>
  41. #include <cstdio>
  42. #include <cstring>
  43. #include <map>
  44. #include <string>
  45. #include <utility>
  46. #include <vector>
  47. #ifdef HAVE_FFI_CALL
  48. #ifdef HAVE_FFI_H
  49. #include <ffi.h>
  50. #define USE_LIBFFI
  51. #elif HAVE_FFI_FFI_H
  52. #include <ffi/ffi.h>
  53. #define USE_LIBFFI
  54. #endif
  55. #endif
  56. #ifdef __APPLE__
  57. #include <TargetConditionals.h>
  58. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  59. #include <CoreFoundation/CoreFoundation.h>
  60. #include <objc/objc.h>
  61. #include <objc/message.h>
  62. #include "ios_error.h"
  63. #include <fcntl.h>
  64. #endif
  65. #endif
  66. using namespace llvm;
  67. static ManagedStatic<sys::Mutex> FunctionsLock;
  68. typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
  69. static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
  70. static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
  71. #ifdef USE_LIBFFI
  72. typedef void (*RawFunc)();
  73. static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
  74. #endif
  75. static Interpreter *TheInterpreter;
  76. static char getTypeID(Type *Ty) {
  77. switch (Ty->getTypeID()) {
  78. case Type::VoidTyID: return 'V';
  79. case Type::IntegerTyID:
  80. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  81. case 1: return 'o';
  82. case 8: return 'B';
  83. case 16: return 'S';
  84. case 32: return 'I';
  85. case 64: return 'L';
  86. default: return 'N';
  87. }
  88. case Type::FloatTyID: return 'F';
  89. case Type::DoubleTyID: return 'D';
  90. case Type::PointerTyID: return 'P';
  91. case Type::FunctionTyID:return 'M';
  92. case Type::StructTyID: return 'T';
  93. case Type::ArrayTyID: return 'A';
  94. default: return 'U';
  95. }
  96. }
  97. // Try to find address of external function given a Function object.
  98. // Please note, that interpreter doesn't know how to assemble a
  99. // real call in general case (this is JIT job), that's why it assumes,
  100. // that all external functions has the same (and pretty "general") signature.
  101. // The typical example of such functions are "lle_X_" ones.
  102. static ExFunc lookupFunction(const Function *F) {
  103. // Function not found, look it up... start by figuring out what the
  104. // composite function name should be.
  105. std::string ExtName = "lle_";
  106. FunctionType *FT = F->getFunctionType();
  107. for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
  108. ExtName += getTypeID(FT->getContainedType(i));
  109. ExtName += ("_" + F->getName()).str();
  110. sys::ScopedLock Writer(*FunctionsLock);
  111. ExFunc FnPtr = (*FuncNames)[ExtName];
  112. if (!FnPtr)
  113. FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
  114. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  115. if (!FnPtr && (F->getName().str().at(0) == '\x01')) {
  116. std::string funcName = F->getName().substr(1, F->getName().size() - 1);;
  117. FnPtr = (*FuncNames)[("lle_X_" + funcName)];
  118. }
  119. #endif
  120. if (!FnPtr) // Try calling a generic function... if it exists...
  121. FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
  122. ("lle_X_" + F->getName()).str());
  123. if (FnPtr)
  124. ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
  125. return FnPtr;
  126. }
  127. #ifdef USE_LIBFFI
  128. static ffi_type *ffiTypeFor(Type *Ty) {
  129. switch (Ty->getTypeID()) {
  130. case Type::VoidTyID: return &ffi_type_void;
  131. case Type::IntegerTyID:
  132. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  133. case 8: return &ffi_type_sint8;
  134. case 16: return &ffi_type_sint16;
  135. case 32: return &ffi_type_sint32;
  136. case 64: return &ffi_type_sint64;
  137. }
  138. case Type::FloatTyID: return &ffi_type_float;
  139. case Type::DoubleTyID: return &ffi_type_double;
  140. case Type::PointerTyID: return &ffi_type_pointer;
  141. default: break;
  142. }
  143. // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  144. // So, for Swift, it's a StructTyID that breaks things.
  145. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  146. fprintf(thread_stderr, "Type error: type= %d \n", Ty->getTypeID());
  147. #endif
  148. report_fatal_error("Type could not be mapped for use with libffi.");
  149. return NULL;
  150. }
  151. static void *ffiValueFor(Type *Ty, const GenericValue &AV,
  152. void *ArgDataPtr) {
  153. switch (Ty->getTypeID()) {
  154. case Type::IntegerTyID:
  155. switch (cast<IntegerType>(Ty)->getBitWidth()) {
  156. case 8: {
  157. int8_t *I8Ptr = (int8_t *) ArgDataPtr;
  158. *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
  159. return ArgDataPtr;
  160. }
  161. case 16: {
  162. int16_t *I16Ptr = (int16_t *) ArgDataPtr;
  163. *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
  164. return ArgDataPtr;
  165. }
  166. case 32: {
  167. int32_t *I32Ptr = (int32_t *) ArgDataPtr;
  168. *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
  169. return ArgDataPtr;
  170. }
  171. case 64: {
  172. int64_t *I64Ptr = (int64_t *) ArgDataPtr;
  173. *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
  174. return ArgDataPtr;
  175. }
  176. }
  177. case Type::FloatTyID: {
  178. float *FloatPtr = (float *) ArgDataPtr;
  179. *FloatPtr = AV.FloatVal;
  180. return ArgDataPtr;
  181. }
  182. case Type::DoubleTyID: {
  183. double *DoublePtr = (double *) ArgDataPtr;
  184. *DoublePtr = AV.DoubleVal;
  185. return ArgDataPtr;
  186. }
  187. case Type::PointerTyID: {
  188. void **PtrPtr = (void **) ArgDataPtr;
  189. *PtrPtr = GVTOP(AV);
  190. return ArgDataPtr;
  191. }
  192. default: break;
  193. }
  194. // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  195. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  196. fprintf(thread_stderr, "Type value error: type= %d \n", Ty->getTypeID());
  197. #endif
  198. report_fatal_error("Type value could not be mapped for use with libffi.");
  199. return NULL;
  200. }
  201. static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
  202. const DataLayout &TD, GenericValue &Result) {
  203. ffi_cif cif;
  204. FunctionType *FTy = F->getFunctionType();
  205. const unsigned NumArgs = F->arg_size();
  206. // TODO: We don't have type information about the remaining arguments, because
  207. // this information is never passed into ExecutionEngine::runFunction().
  208. if (ArgVals.size() > NumArgs && F->isVarArg()) {
  209. report_fatal_error("Calling external var arg function '" + F->getName()
  210. + "' is not supported by the Interpreter.");
  211. }
  212. unsigned ArgBytes = 0;
  213. std::vector<ffi_type*> args(NumArgs);
  214. for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
  215. A != E; ++A) {
  216. const unsigned ArgNo = A->getArgNo();
  217. Type *ArgTy = FTy->getParamType(ArgNo);
  218. args[ArgNo] = ffiTypeFor(ArgTy);
  219. ArgBytes += TD.getTypeStoreSize(ArgTy);
  220. }
  221. SmallVector<uint8_t, 128> ArgData;
  222. ArgData.resize(ArgBytes);
  223. uint8_t *ArgDataPtr = ArgData.data();
  224. SmallVector<void*, 16> values(NumArgs);
  225. for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
  226. A != E; ++A) {
  227. const unsigned ArgNo = A->getArgNo();
  228. Type *ArgTy = FTy->getParamType(ArgNo);
  229. values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
  230. ArgDataPtr += TD.getTypeStoreSize(ArgTy);
  231. }
  232. Type *RetTy = FTy->getReturnType();
  233. ffi_type *rtype = ffiTypeFor(RetTy);
  234. if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
  235. SmallVector<uint8_t, 128> ret;
  236. if (RetTy->getTypeID() != Type::VoidTyID)
  237. ret.resize(TD.getTypeStoreSize(RetTy));
  238. ffi_call(&cif, Fn, ret.data(), values.data());
  239. switch (RetTy->getTypeID()) {
  240. case Type::IntegerTyID:
  241. switch (cast<IntegerType>(RetTy)->getBitWidth()) {
  242. case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
  243. case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
  244. case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
  245. case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
  246. }
  247. break;
  248. case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
  249. case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
  250. case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
  251. default: break;
  252. }
  253. return true;
  254. }
  255. return false;
  256. }
  257. #endif // USE_LIBFFI
  258. GenericValue Interpreter::callExternalFunction(Function *F,
  259. ArrayRef<GenericValue> ArgVals) {
  260. TheInterpreter = this;
  261. unique_lock<sys::Mutex> Guard(*FunctionsLock);
  262. // Do a lookup to see if the function is in our cache... this should just be a
  263. // deferred annotation!
  264. std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
  265. if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
  266. : FI->second) {
  267. Guard.unlock();
  268. return Fn(F->getFunctionType(), ArgVals);
  269. }
  270. #ifdef USE_LIBFFI
  271. std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
  272. RawFunc RawFn;
  273. if (RF == RawFunctions->end()) {
  274. RawFn = (RawFunc)(intptr_t)
  275. sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
  276. if (!RawFn)
  277. RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
  278. if (RawFn != 0)
  279. RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
  280. } else {
  281. RawFn = RF->second;
  282. }
  283. Guard.unlock();
  284. GenericValue Result;
  285. if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
  286. return Result;
  287. #endif // USE_LIBFFI
  288. if (F->getName() == "__main")
  289. errs() << "Tried to execute an unknown external function: "
  290. << *F->getType() << " __main\n";
  291. else
  292. report_fatal_error("Tried to execute an unknown external function: " +
  293. F->getName());
  294. #ifndef USE_LIBFFI
  295. errs() << "Recompiling LLVM with --enable-libffi might help.\n";
  296. #endif
  297. return GenericValue();
  298. }
  299. //===----------------------------------------------------------------------===//
  300. // Functions "exported" to the running application...
  301. //
  302. // void atexit(Function*)
  303. static GenericValue lle_X_atexit(FunctionType *FT,
  304. ArrayRef<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. // void exit(int)
  312. static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
  313. // TODO: insert here cleanup functions, if required.
  314. TheInterpreter->exitCalled(Args[0]);
  315. return GenericValue();
  316. }
  317. // void abort(void)
  318. static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
  319. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  320. report_fatal_error("LLVM interpreter raised SIGABRT");
  321. #else
  322. //FIXME: should we report or raise here?
  323. //report_fatal_error("Interpreted program raised SIGABRT");
  324. raise (SIGABRT);
  325. #endif
  326. return GenericValue();
  327. }
  328. // int sprintf(char *, const char *, ...) - a very rough implementation to make
  329. // output useful.
  330. static GenericValue lle_X_sprintf(FunctionType *FT,
  331. ArrayRef<GenericValue> Args) {
  332. char *OutputBuffer = (char *)GVTOP(Args[0]);
  333. const char *FmtStr = (const char *)GVTOP(Args[1]);
  334. unsigned ArgNo = 2;
  335. // printf should return # chars printed. This is completely incorrect, but
  336. // close enough for now.
  337. GenericValue GV;
  338. GV.IntVal = APInt(32, strlen(FmtStr));
  339. while (true) {
  340. switch (*FmtStr) {
  341. case 0: return GV; // Null terminator...
  342. default: // Normal nonspecial character
  343. sprintf(OutputBuffer++, "%c", *FmtStr++);
  344. break;
  345. case '\\': { // Handle escape codes
  346. sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
  347. FmtStr += 2; OutputBuffer += 2;
  348. break;
  349. }
  350. case '%': { // Handle format specifiers
  351. char FmtBuf[100] = "", Buffer[1000] = "";
  352. char *FB = FmtBuf;
  353. *FB++ = *FmtStr++;
  354. char Last = *FB++ = *FmtStr++;
  355. unsigned HowLong = 0;
  356. while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
  357. Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
  358. Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
  359. Last != 'p' && Last != 's' && Last != '%') {
  360. if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
  361. Last = *FB++ = *FmtStr++;
  362. }
  363. *FB = 0;
  364. switch (Last) {
  365. case '%':
  366. memcpy(Buffer, "%", 2); break;
  367. case 'c':
  368. sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
  369. break;
  370. case 'd': case 'i':
  371. case 'u': case 'o':
  372. case 'x': case 'X':
  373. if (HowLong >= 1) {
  374. if (HowLong == 1 &&
  375. TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
  376. sizeof(long) < sizeof(int64_t)) {
  377. // Make sure we use %lld with a 64 bit argument because we might be
  378. // compiling LLI on a 32 bit compiler.
  379. unsigned Size = strlen(FmtBuf);
  380. FmtBuf[Size] = FmtBuf[Size-1];
  381. FmtBuf[Size+1] = 0;
  382. FmtBuf[Size-1] = 'l';
  383. }
  384. sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
  385. } else
  386. sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
  387. break;
  388. case 'e': case 'E': case 'g': case 'G': case 'f':
  389. sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
  390. case 'p':
  391. sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
  392. case 's':
  393. sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
  394. default:
  395. errs() << "<unknown printf code '" << *FmtStr << "'!>";
  396. ArgNo++; break;
  397. }
  398. size_t Len = strlen(Buffer);
  399. memcpy(OutputBuffer, Buffer, Len + 1);
  400. OutputBuffer += Len;
  401. }
  402. break;
  403. }
  404. }
  405. return GV;
  406. }
  407. // int printf(const char *, ...) - a very rough implementation to make output
  408. // useful.
  409. static GenericValue lle_X_printf(FunctionType *FT,
  410. ArrayRef<GenericValue> Args) {
  411. char Buffer[10000];
  412. std::vector<GenericValue> NewArgs;
  413. NewArgs.push_back(PTOGV((void*)&Buffer[0]));
  414. NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
  415. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  416. outs() << Buffer;
  417. return GV;
  418. }
  419. // int sscanf(const char *format, ...);
  420. static GenericValue lle_X_sscanf(FunctionType *FT,
  421. ArrayRef<GenericValue> args) {
  422. assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
  423. char *Args[10];
  424. for (unsigned i = 0; i < args.size(); ++i)
  425. Args[i] = (char*)GVTOP(args[i]);
  426. GenericValue GV;
  427. GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
  428. Args[5], Args[6], Args[7], Args[8], Args[9]));
  429. return GV;
  430. }
  431. // int scanf(const char *format, ...);
  432. static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
  433. assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
  434. char *Args[10];
  435. for (unsigned i = 0; i < args.size(); ++i)
  436. Args[i] = (char*)GVTOP(args[i]);
  437. GenericValue GV;
  438. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  439. outs().flush();
  440. fflush(thread_stdout);
  441. GV.IntVal = APInt(32, fscanf(thread_stdin, Args[0], Args[1], Args[2], Args[3], Args[4],
  442. Args[5], Args[6], Args[7], Args[8], Args[9]));
  443. #else
  444. GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
  445. Args[5], Args[6], Args[7], Args[8], Args[9]));
  446. #endif
  447. return GV;
  448. }
  449. // int fprintf(FILE *, const char *, ...) - a very rough implementation to make
  450. // output useful.
  451. static GenericValue lle_X_fprintf(FunctionType *FT,
  452. ArrayRef<GenericValue> Args) {
  453. assert(Args.size() >= 2);
  454. char Buffer[10000];
  455. std::vector<GenericValue> NewArgs;
  456. NewArgs.push_back(PTOGV(Buffer));
  457. NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
  458. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  459. fputs(Buffer, (FILE *) GVTOP(Args[0]));
  460. return GV;
  461. }
  462. static GenericValue lle_X_memset(FunctionType *FT,
  463. ArrayRef<GenericValue> Args) {
  464. int val = (int)Args[1].IntVal.getSExtValue();
  465. size_t len = (size_t)Args[2].IntVal.getZExtValue();
  466. memset((void *)GVTOP(Args[0]), val, len);
  467. // llvm.memset.* returns void, lle_X_* returns GenericValue,
  468. // so here we return GenericValue with IntVal set to zero
  469. GenericValue GV;
  470. GV.IntVal = 0;
  471. return GV;
  472. }
  473. static GenericValue lle_X_memcpy(FunctionType *FT,
  474. ArrayRef<GenericValue> Args) {
  475. memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
  476. (size_t)(Args[2].IntVal.getLimitedValue()));
  477. // llvm.memcpy* returns void, lle_X_* returns GenericValue,
  478. // so here we return GenericValue with IntVal set to zero
  479. GenericValue GV;
  480. GV.IntVal = 0;
  481. return GV;
  482. }
  483. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  484. // Required because it's a vararg function
  485. static GenericValue lle_X_open(FunctionType *FT,
  486. ArrayRef<GenericValue> Args) {
  487. int oflag = (int)Args[1].IntVal.getSExtValue();
  488. int returnValue;
  489. if (Args.size() == 2) {
  490. returnValue = ::open((char*)GVTOP(Args[0]), oflag);
  491. } else {
  492. int mode = (int)Args[2].IntVal.getSExtValue();
  493. returnValue = ::open((char*)GVTOP(Args[0]), oflag, mode);
  494. if (Args.size() > 3) errs() << "called open(" << (char*)GVTOP(Args[0]) << ", ...) with " << Args.size() << " arguments.\n";
  495. }
  496. GenericValue GV;
  497. GV.IntVal = APInt(32, returnValue);
  498. return GV;
  499. }
  500. //
  501. const char* llvm_ios_progname;
  502. // void warn(const char *fmt, ...);
  503. static GenericValue lle_X_warn(FunctionType *FT, ArrayRef<GenericValue> Args) {
  504. fputs(llvm_ios_progname, thread_stderr);
  505. const char *fmt = (const char *)GVTOP(Args[0]);
  506. if (fmt != NULL)
  507. {
  508. fputs(": ", thread_stderr);
  509. char Buffer[10000];
  510. std::vector<GenericValue> NewArgs;
  511. NewArgs.push_back(PTOGV((void*)&Buffer[0]));
  512. NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
  513. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  514. fputs(Buffer, thread_stderr);
  515. }
  516. fputs(": ", thread_stderr);
  517. fputs(strerror(errno), thread_stderr);
  518. putc('\n', thread_stderr);
  519. return GenericValue();
  520. }
  521. // void warnx(const char *fmt, ...);
  522. static GenericValue lle_X_warnx(FunctionType *FT, ArrayRef<GenericValue> Args) {
  523. fputs(llvm_ios_progname, thread_stderr);
  524. const char *fmt = (const char *)GVTOP(Args[0]);
  525. if (fmt != NULL)
  526. {
  527. fputs(": ", thread_stderr);
  528. char Buffer[10000];
  529. std::vector<GenericValue> NewArgs;
  530. NewArgs.push_back(PTOGV((void*)&Buffer[0]));
  531. NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
  532. GenericValue GV = lle_X_sprintf(FT, NewArgs);
  533. fputs(Buffer, thread_stderr);
  534. }
  535. putc('\n', thread_stderr);
  536. return GenericValue();
  537. }
  538. // void err(int eval, const char *fmt, ...);
  539. static GenericValue lle_X_err(FunctionType *FT, ArrayRef<GenericValue> Args) {
  540. std::vector<GenericValue> NewArgs = Args;
  541. NewArgs.erase(NewArgs.begin());
  542. lle_X_warn(FT, NewArgs);
  543. TheInterpreter->exitCalled(Args[0]);
  544. return GenericValue();
  545. }
  546. // void errx(int eval, const char *fmt, ...);
  547. static GenericValue lle_X_errx(FunctionType *FT, ArrayRef<GenericValue> Args) {
  548. std::vector<GenericValue> NewArgs = Args;
  549. NewArgs.erase(NewArgs.begin());
  550. lle_X_warnx(FT, NewArgs);
  551. TheInterpreter->exitCalled(Args[0]);
  552. return GenericValue();
  553. }
  554. // Objective-C:
  555. static GenericValue lle_X_objc_msgSend(FunctionType *FT,
  556. ArrayRef<GenericValue> args) {
  557. // Note: that method fails at runtime, with:
  558. // selector () for message 'stringByAppendingString:' does not match selector known to Objective C runtime ()-- abort
  559. // Needs linking with -f Foundation -f CoreFoundation. HOW?
  560. id self = (objc_object *)GVTOP(args[0]);
  561. SEL op = (SEL)GVTOP(args[1]);
  562. GenericValue GV;
  563. if (args.size() <= 2)
  564. GV.PointerVal = *(void **) objc_msgSend(self, op);
  565. else {
  566. objc_object *Args[10];
  567. for (unsigned i = 2; i < args.size(); ++i)
  568. Args[i - 2] = (objc_object *)GVTOP(args[i]);
  569. GenericValue GV;
  570. // Add -lobjc to bootstrap.sh before removal
  571. GV.PointerVal = *(void **) (id)objc_msgSend(self, op, Args[0], Args[1], Args[2], Args[3], Args[4],
  572. Args[5], Args[6], Args[7], Args[8], Args[9]);
  573. }
  574. return GV;
  575. }
  576. //
  577. #endif // (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  578. void Interpreter::initializeExternalFunctions() {
  579. sys::ScopedLock Writer(*FunctionsLock);
  580. (*FuncNames)["lle_X_atexit"] = lle_X_atexit;
  581. (*FuncNames)["lle_X_exit"] = lle_X_exit;
  582. (*FuncNames)["lle_X_abort"] = lle_X_abort;
  583. (*FuncNames)["lle_X_printf"] = lle_X_printf;
  584. (*FuncNames)["lle_X_sprintf"] = lle_X_sprintf;
  585. (*FuncNames)["lle_X_sscanf"] = lle_X_sscanf;
  586. (*FuncNames)["lle_X_scanf"] = lle_X_scanf;
  587. (*FuncNames)["lle_X_fprintf"] = lle_X_fprintf;
  588. (*FuncNames)["lle_X_memset"] = lle_X_memset;
  589. (*FuncNames)["lle_X_memcpy"] = lle_X_memcpy;
  590. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  591. // Variadic argument functions (vararg).
  592. (*FuncNames)["lle_X_open"] = lle_X_open;
  593. (*FuncNames)["lle_X__open"] = lle_X_open;
  594. (*FuncNames)["lle_X_err"] = lle_X_err;
  595. (*FuncNames)["lle_X_errx"] = lle_X_errx;
  596. (*FuncNames)["lle_X_warn"] = lle_X_warn;
  597. (*FuncNames)["lle_X_warnx"] = lle_X_warnx;
  598. // objective-C
  599. (*FuncNames)["lle_X_objc_msgSend"] = lle_X_objc_msgSend;
  600. #endif
  601. }