blob: 64dca930722e61ee7eadb2600b3eafad04d7ed05 [file] [log] [blame]
Chris Lattner62b7fd12002-04-07 20:49:59 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
Misha Brukman91fb9ab2005-04-21 22:43:08 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman91fb9ab2005-04-21 22:43:08 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman91fb9ab2005-04-21 22:43:08 +00009//
Chris Lattner62b7fd12002-04-07 20:49:59 +000010// This file contains both code to deal with invoking "external" functions, but
11// also contains code that implements "exported" external functions.
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000012//
Nick Lewyckya89ec992009-02-04 06:26:47 +000013// 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.
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/Config/config.h" // Detect libffi
Eugene Zelenko33d7b762016-08-23 17:14:32 +000026#include "llvm/ExecutionEngine/GenericValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/Casting.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000032#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/ErrorHandling.h"
Chuck Rose III1a39a2d12007-07-27 18:26:35 +000034#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000035#include "llvm/Support/Mutex.h"
Dylan Noblesmithc4c51802014-08-23 23:07:14 +000036#include "llvm/Support/UniqueLock.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include <cassert>
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include <cmath>
Brian Gaeke4e106f02003-11-05 01:18:49 +000040#include <csignal>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000041#include <cstdint>
Duncan Sands26ff6f92008-10-08 07:23:46 +000042#include <cstdio>
Anton Korobeynikov579f0712008-02-20 11:08:44 +000043#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include <map>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include <string>
46#include <utility>
47#include <vector>
Zhou Sheng3115ba32007-12-12 06:16:47 +000048
Nick Lewyckye54da992009-04-13 04:26:06 +000049#ifdef HAVE_FFI_CALL
Nick Lewyckya89ec992009-02-04 06:26:47 +000050#ifdef HAVE_FFI_H
51#include <ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000052#define USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +000053#elif HAVE_FFI_FFI_H
54#include <ffi/ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000055#define USE_LIBFFI
Zhou Sheng3115ba32007-12-12 06:16:47 +000056#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +000057#endif
Tanya Lattner9a8602c2009-01-22 20:09:20 +000058
Chris Lattner18099662003-12-14 23:25:48 +000059using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000060
Owen Andersonda19a132009-06-22 22:30:56 +000061static ManagedStatic<sys::Mutex> FunctionsLock;
62
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +000063typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
Nick Lewyckya89ec992009-02-04 06:26:47 +000064static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Bieneman3b1fd572014-09-19 21:07:01 +000065static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000066
Nick Lewyckye54da992009-04-13 04:26:06 +000067#ifdef USE_LIBFFI
Dan Gohman1432ef82009-08-12 22:10:57 +000068typedef void (*RawFunc)();
Nick Lewyckya89ec992009-02-04 06:26:47 +000069static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
70#endif
71
Chris Lattner15157b82001-10-27 04:15:57 +000072static Interpreter *TheInterpreter;
73
Chris Lattner229907c2011-07-18 04:54:35 +000074static char getTypeID(Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000075 switch (Ty->getTypeID()) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000076 case Type::VoidTyID: return 'V';
Reid Spencer7a9c62b2007-01-12 07:05:14 +000077 case Type::IntegerTyID:
78 switch (cast<IntegerType>(Ty)->getBitWidth()) {
79 case 1: return 'o';
80 case 8: return 'B';
81 case 16: return 'S';
82 case 32: return 'I';
83 case 64: return 'L';
84 default: return 'N';
85 }
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000086 case Type::FloatTyID: return 'F';
87 case Type::DoubleTyID: return 'D';
88 case Type::PointerTyID: return 'P';
Reid Spencer0d54e782006-12-31 05:51:36 +000089 case Type::FunctionTyID:return 'M';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000090 case Type::StructTyID: return 'T';
91 case Type::ArrayTyID: return 'A';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000092 default: return 'U';
93 }
94}
95
Anton Korobeynikov187bf732007-07-30 23:03:25 +000096// Try to find address of external function given a Function object.
97// Please note, that interpreter doesn't know how to assemble a
98// real call in general case (this is JIT job), that's why it assumes,
99// that all external functions has the same (and pretty "general") signature.
100// The typical example of such functions are "lle_X_" ones.
Brian Gaeke6cc20de2003-10-10 17:03:10 +0000101static ExFunc lookupFunction(const Function *F) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000102 // Function not found, look it up... start by figuring out what the
103 // composite function name should be.
Chris Lattner7f74a562002-01-20 22:54:45 +0000104 std::string ExtName = "lle_";
Chris Lattner229907c2011-07-18 04:54:35 +0000105 FunctionType *FT = F->getFunctionType();
Brian Gaeke6cc20de2003-10-10 17:03:10 +0000106 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
107 ExtName += getTypeID(FT->getContainedType(i));
Yaron Keren075759a2015-03-30 15:42:36 +0000108 ExtName += ("_" + F->getName()).str();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000109
Owen Anderson5c96ef72009-07-07 18:33:04 +0000110 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000111 ExFunc FnPtr = (*FuncNames)[ExtName];
Craig Topper353eda42014-04-24 06:44:33 +0000112 if (!FnPtr)
Yaron Keren075759a2015-03-30 15:42:36 +0000113 FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
Craig Topper353eda42014-04-24 06:44:33 +0000114 if (!FnPtr) // Try calling a generic function... if it exists...
Yaron Keren075759a2015-03-30 15:42:36 +0000115 FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
116 ("lle_X_" + F->getName()).str());
Craig Topper353eda42014-04-24 06:44:33 +0000117 if (FnPtr)
Nick Lewyckya89ec992009-02-04 06:26:47 +0000118 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000119 return FnPtr;
120}
121
Nick Lewyckye54da992009-04-13 04:26:06 +0000122#ifdef USE_LIBFFI
Chris Lattner229907c2011-07-18 04:54:35 +0000123static ffi_type *ffiTypeFor(Type *Ty) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000124 switch (Ty->getTypeID()) {
125 case Type::VoidTyID: return &ffi_type_void;
126 case Type::IntegerTyID:
127 switch (cast<IntegerType>(Ty)->getBitWidth()) {
128 case 8: return &ffi_type_sint8;
129 case 16: return &ffi_type_sint16;
130 case 32: return &ffi_type_sint32;
131 case 64: return &ffi_type_sint64;
132 }
133 case Type::FloatTyID: return &ffi_type_float;
134 case Type::DoubleTyID: return &ffi_type_double;
135 case Type::PointerTyID: return &ffi_type_pointer;
136 default: break;
137 }
138 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000139 report_fatal_error("Type could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000140 return NULL;
141}
142
Chris Lattner229907c2011-07-18 04:54:35 +0000143static void *ffiValueFor(Type *Ty, const GenericValue &AV,
Nick Lewyckya89ec992009-02-04 06:26:47 +0000144 void *ArgDataPtr) {
145 switch (Ty->getTypeID()) {
146 case Type::IntegerTyID:
147 switch (cast<IntegerType>(Ty)->getBitWidth()) {
148 case 8: {
149 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
150 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
151 return ArgDataPtr;
152 }
153 case 16: {
154 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
155 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
156 return ArgDataPtr;
157 }
158 case 32: {
159 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
160 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
161 return ArgDataPtr;
162 }
163 case 64: {
164 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
165 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
166 return ArgDataPtr;
167 }
168 }
169 case Type::FloatTyID: {
170 float *FloatPtr = (float *) ArgDataPtr;
Nick Lewycky41ee7922009-11-18 05:43:15 +0000171 *FloatPtr = AV.FloatVal;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000172 return ArgDataPtr;
173 }
174 case Type::DoubleTyID: {
175 double *DoublePtr = (double *) ArgDataPtr;
176 *DoublePtr = AV.DoubleVal;
177 return ArgDataPtr;
178 }
179 case Type::PointerTyID: {
180 void **PtrPtr = (void **) ArgDataPtr;
181 *PtrPtr = GVTOP(AV);
182 return ArgDataPtr;
183 }
184 default: break;
185 }
186 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000187 report_fatal_error("Type value could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000188 return NULL;
189}
190
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000191static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000192 const DataLayout &TD, GenericValue &Result) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000193 ffi_cif cif;
Chris Lattner229907c2011-07-18 04:54:35 +0000194 FunctionType *FTy = F->getFunctionType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000195 const unsigned NumArgs = F->arg_size();
196
197 // TODO: We don't have type information about the remaining arguments, because
198 // this information is never passed into ExecutionEngine::runFunction().
199 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000200 report_fatal_error("Calling external var arg function '" + F->getName()
Torok Edwinccb29cd2009-07-11 13:10:19 +0000201 + "' is not supported by the Interpreter.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000202 }
203
204 unsigned ArgBytes = 0;
205
206 std::vector<ffi_type*> args(NumArgs);
207 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
208 A != E; ++A) {
209 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000210 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000211 args[ArgNo] = ffiTypeFor(ArgTy);
Mehdi Amini731ad622015-07-16 22:23:09 +0000212 ArgBytes += TD.getTypeStoreSize(ArgTy);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000213 }
214
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000215 SmallVector<uint8_t, 128> ArgData;
216 ArgData.resize(ArgBytes);
217 uint8_t *ArgDataPtr = ArgData.data();
218 SmallVector<void*, 16> values(NumArgs);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000219 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
220 A != E; ++A) {
221 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000222 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000223 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
Mehdi Amini731ad622015-07-16 22:23:09 +0000224 ArgDataPtr += TD.getTypeStoreSize(ArgTy);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000225 }
226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *RetTy = FTy->getReturnType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000228 ffi_type *rtype = ffiTypeFor(RetTy);
229
230 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000231 SmallVector<uint8_t, 128> ret;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000232 if (RetTy->getTypeID() != Type::VoidTyID)
Mehdi Amini731ad622015-07-16 22:23:09 +0000233 ret.resize(TD.getTypeStoreSize(RetTy));
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000234 ffi_call(&cif, Fn, ret.data(), values.data());
Nick Lewyckya89ec992009-02-04 06:26:47 +0000235 switch (RetTy->getTypeID()) {
236 case Type::IntegerTyID:
237 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000238 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
239 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
240 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
241 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000242 }
243 break;
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000244 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
245 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
246 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000247 default: break;
248 }
249 return true;
250 }
251
252 return false;
253}
Nick Lewyckye54da992009-04-13 04:26:06 +0000254#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000255
Chris Lattner28edd692005-01-21 19:59:37 +0000256GenericValue Interpreter::callExternalFunction(Function *F,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000257 ArrayRef<GenericValue> ArgVals) {
Chris Lattner15157b82001-10-27 04:15:57 +0000258 TheInterpreter = this;
259
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000260 unique_lock<sys::Mutex> Guard(*FunctionsLock);
Owen Andersonda19a132009-06-22 22:30:56 +0000261
Chris Lattner62b7fd12002-04-07 20:49:59 +0000262 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmanaa7d26c2003-10-10 17:42:19 +0000263 // deferred annotation!
Nick Lewyckya89ec992009-02-04 06:26:47 +0000264 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
265 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonda19a132009-06-22 22:30:56 +0000266 : FI->second) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000267 Guard.unlock();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000268 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonda19a132009-06-22 22:30:56 +0000269 }
Nick Lewyckya89ec992009-02-04 06:26:47 +0000270
Nick Lewyckye54da992009-04-13 04:26:06 +0000271#ifdef USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000272 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
273 RawFunc RawFn;
274 if (RF == RawFunctions->end()) {
275 RawFn = (RawFunc)(intptr_t)
276 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
Torok Edwin921e80b2010-03-30 20:15:13 +0000277 if (!RawFn)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000278 RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000279 if (RawFn != 0)
280 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
281 } else {
282 RawFn = RF->second;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000283 }
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000284
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000285 Guard.unlock();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000286
Nick Lewyckya89ec992009-02-04 06:26:47 +0000287 GenericValue Result;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000288 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
Nick Lewyckya89ec992009-02-04 06:26:47 +0000289 return Result;
Nick Lewyckye54da992009-04-13 04:26:06 +0000290#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000291
Torok Edwinccb29cd2009-07-11 13:10:19 +0000292 if (F->getName() == "__main")
David Greene1df14c42010-01-05 01:53:59 +0000293 errs() << "Tried to execute an unknown external function: "
Chris Lattner0f214eb2011-06-18 21:18:23 +0000294 << *F->getType() << " __main\n";
Torok Edwinccb29cd2009-07-11 13:10:19 +0000295 else
Chris Lattner2104b8d2010-04-07 22:58:41 +0000296 report_fatal_error("Tried to execute an unknown external function: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +0000297 F->getName());
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000298#ifndef USE_LIBFFI
David Greene1df14c42010-01-05 01:53:59 +0000299 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000300#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +0000301 return GenericValue();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000302}
303
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000304//===----------------------------------------------------------------------===//
Chris Lattnerf94811a2002-03-29 03:57:15 +0000305// Functions "exported" to the running application...
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000306//
Daniel Dunbar86ec7ba2009-08-07 20:50:09 +0000307
Chris Lattner4a5bb952003-05-14 14:21:30 +0000308// void atexit(Function*)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000309static GenericValue lle_X_atexit(FunctionType *FT,
310 ArrayRef<GenericValue> Args) {
Chris Lattner4a5bb952003-05-14 14:21:30 +0000311 assert(Args.size() == 1);
312 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
313 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000314 GV.IntVal = 0;
Chris Lattner4a5bb952003-05-14 14:21:30 +0000315 return GV;
Chris Lattnerd299dba2001-10-18 21:55:32 +0000316}
317
Chris Lattner0313db62002-10-02 21:12:13 +0000318// void exit(int)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000319static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
Chris Lattner15157b82001-10-27 04:15:57 +0000320 TheInterpreter->exitCalled(Args[0]);
321 return GenericValue();
322}
323
Chris Lattner0313db62002-10-02 21:12:13 +0000324// void abort(void)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000325static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000326 //FIXME: should we report or raise here?
Chris Lattner2104b8d2010-04-07 22:58:41 +0000327 //report_fatal_error("Interpreted program raised SIGABRT");
Brian Gaeke4e106f02003-11-05 01:18:49 +0000328 raise (SIGABRT);
Chris Lattner13194292002-05-20 21:17:16 +0000329 return GenericValue();
330}
331
Nick Lewyckya89ec992009-02-04 06:26:47 +0000332// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattner60a9a232001-12-13 00:43:47 +0000333// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000334static GenericValue lle_X_sprintf(FunctionType *FT,
335 ArrayRef<GenericValue> Args) {
Chris Lattnerd49518c2003-01-13 00:59:47 +0000336 char *OutputBuffer = (char *)GVTOP(Args[0]);
337 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattner60a9a232001-12-13 00:43:47 +0000338 unsigned ArgNo = 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000339
340 // printf should return # chars printed. This is completely incorrect, but
341 // close enough for now.
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000342 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000343 GV.IntVal = APInt(32, strlen(FmtStr));
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000344 while (true) {
Chris Lattner490d2a82001-10-29 20:27:45 +0000345 switch (*FmtStr) {
346 case 0: return GV; // Null terminator...
347 default: // Normal nonspecial character
Chris Lattner60a9a232001-12-13 00:43:47 +0000348 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner490d2a82001-10-29 20:27:45 +0000349 break;
350 case '\\': { // Handle escape codes
Chris Lattner60a9a232001-12-13 00:43:47 +0000351 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
352 FmtStr += 2; OutputBuffer += 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000353 break;
354 }
355 case '%': { // Handle format specifiers
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000356 char FmtBuf[100] = "", Buffer[1000] = "";
357 char *FB = FmtBuf;
358 *FB++ = *FmtStr++;
359 char Last = *FB++ = *FmtStr++;
360 unsigned HowLong = 0;
361 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
362 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
363 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
364 Last != 'p' && Last != 's' && Last != '%') {
365 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
366 Last = *FB++ = *FmtStr++;
Chris Lattner490d2a82001-10-29 20:27:45 +0000367 }
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000368 *FB = 0;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000369
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000370 switch (Last) {
371 case '%':
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000372 memcpy(Buffer, "%", 2); break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000373 case 'c':
Reid Spencerc45e1042007-03-06 03:08:12 +0000374 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
375 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000376 case 'd': case 'i':
377 case 'u': case 'o':
378 case 'x': case 'X':
Chris Lattner33b3b962002-08-02 23:08:32 +0000379 if (HowLong >= 1) {
Chris Lattner47985402003-08-24 14:02:47 +0000380 if (HowLong == 1 &&
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000381 TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
Reid Spencer6e641802006-05-24 19:21:13 +0000382 sizeof(long) < sizeof(int64_t)) {
Chris Lattner33b3b962002-08-02 23:08:32 +0000383 // Make sure we use %lld with a 64 bit argument because we might be
384 // compiling LLI on a 32 bit compiler.
385 unsigned Size = strlen(FmtBuf);
386 FmtBuf[Size] = FmtBuf[Size-1];
387 FmtBuf[Size+1] = 0;
388 FmtBuf[Size-1] = 'l';
389 }
Reid Spencerc45e1042007-03-06 03:08:12 +0000390 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner33b3b962002-08-02 23:08:32 +0000391 } else
Reid Spencerc45e1042007-03-06 03:08:12 +0000392 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
393 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000394 case 'e': case 'E': case 'g': case 'G': case 'f':
395 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
396 case 'p':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000397 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000398 case 's':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000399 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattner471ba482009-08-23 08:43:55 +0000400 default:
David Greene1df14c42010-01-05 01:53:59 +0000401 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000402 ArgNo++; break;
Chris Lattner490d2a82001-10-29 20:27:45 +0000403 }
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000404 size_t Len = strlen(Buffer);
405 memcpy(OutputBuffer, Buffer, Len + 1);
406 OutputBuffer += Len;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000407 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000408 break;
409 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000410 }
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000411 return GV;
Chris Lattner490d2a82001-10-29 20:27:45 +0000412}
413
Nick Lewyckya89ec992009-02-04 06:26:47 +0000414// int printf(const char *, ...) - a very rough implementation to make output
415// useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000416static GenericValue lle_X_printf(FunctionType *FT,
417 ArrayRef<GenericValue> Args) {
Chris Lattner60a9a232001-12-13 00:43:47 +0000418 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000419 std::vector<GenericValue> NewArgs;
Reid Spencera68c3742007-04-21 17:11:45 +0000420 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattner60a9a232001-12-13 00:43:47 +0000421 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000422 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattner471ba482009-08-23 08:43:55 +0000423 outs() << Buffer;
Chris Lattner60a9a232001-12-13 00:43:47 +0000424 return GV;
425}
426
Chris Lattner5dec4602002-03-08 22:51:07 +0000427// int sscanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000428static GenericValue lle_X_sscanf(FunctionType *FT,
429 ArrayRef<GenericValue> args) {
Chris Lattner5dec4602002-03-08 22:51:07 +0000430 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
431
Chris Lattnerd3183712003-03-31 22:12:37 +0000432 char *Args[10];
Chris Lattner5dec4602002-03-08 22:51:07 +0000433 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerd3183712003-03-31 22:12:37 +0000434 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner5dec4602002-03-08 22:51:07 +0000435
436 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000437 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000438 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerd3183712003-03-31 22:12:37 +0000439 return GV;
440}
441
442// int scanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000443static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
Chris Lattnerd3183712003-03-31 22:12:37 +0000444 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
445
446 char *Args[10];
447 for (unsigned i = 0; i < args.size(); ++i)
448 Args[i] = (char*)GVTOP(args[i]);
449
450 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000451 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000452 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattner5dec4602002-03-08 22:51:07 +0000453 return GV;
454}
455
Nick Lewyckya89ec992009-02-04 06:26:47 +0000456// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
457// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000458static GenericValue lle_X_fprintf(FunctionType *FT,
459 ArrayRef<GenericValue> Args) {
Chris Lattner16106662003-04-21 22:43:20 +0000460 assert(Args.size() >= 2);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000461 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000462 std::vector<GenericValue> NewArgs;
Chris Lattnerd49518c2003-01-13 00:59:47 +0000463 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000464 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000465 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000466
Nick Lewyckya89ec992009-02-04 06:26:47 +0000467 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000468 return GV;
469}
470
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000471static GenericValue lle_X_memset(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000472 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000473 int val = (int)Args[1].IntVal.getSExtValue();
474 size_t len = (size_t)Args[2].IntVal.getZExtValue();
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000475 memset((void *)GVTOP(Args[0]), val, len);
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000476 // llvm.memset.* returns void, lle_X_* returns GenericValue,
477 // so here we return GenericValue with IntVal set to zero
478 GenericValue GV;
479 GV.IntVal = 0;
480 return GV;
481}
482
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000483static GenericValue lle_X_memcpy(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000484 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000485 memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
486 (size_t)(Args[2].IntVal.getLimitedValue()));
487
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000488 // llvm.memcpy* returns void, lle_X_* returns GenericValue,
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000489 // so here we return GenericValue with IntVal set to zero
490 GenericValue GV;
491 GV.IntVal = 0;
492 return GV;
493}
494
Chris Lattner470754e2003-05-08 16:18:31 +0000495void Interpreter::initializeExternalFunctions() {
Owen Anderson5c96ef72009-07-07 18:33:04 +0000496 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000497 (*FuncNames)["lle_X_atexit"] = lle_X_atexit;
498 (*FuncNames)["lle_X_exit"] = lle_X_exit;
499 (*FuncNames)["lle_X_abort"] = lle_X_abort;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000500
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000501 (*FuncNames)["lle_X_printf"] = lle_X_printf;
502 (*FuncNames)["lle_X_sprintf"] = lle_X_sprintf;
503 (*FuncNames)["lle_X_sscanf"] = lle_X_sscanf;
504 (*FuncNames)["lle_X_scanf"] = lle_X_scanf;
505 (*FuncNames)["lle_X_fprintf"] = lle_X_fprintf;
506 (*FuncNames)["lle_X_memset"] = lle_X_memset;
507 (*FuncNames)["lle_X_memcpy"] = lle_X_memcpy;
Chris Lattner7fd51b52001-10-30 20:28:00 +0000508}