blob: e738a8c65fe41db24c7ffd578b3f2659452192b8 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Config/config.h" // Detect libffi
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Module.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000027#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Support/ErrorHandling.h"
Chuck Rose III1a39a2d12007-07-27 18:26:35 +000029#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000030#include "llvm/Support/Mutex.h"
Dylan Noblesmithc4c51802014-08-23 23:07:14 +000031#include "llvm/Support/UniqueLock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include <cmath>
Brian Gaeke4e106f02003-11-05 01:18:49 +000033#include <csignal>
Duncan Sands26ff6f92008-10-08 07:23:46 +000034#include <cstdio>
Anton Korobeynikov579f0712008-02-20 11:08:44 +000035#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include <map>
Zhou Sheng3115ba32007-12-12 06:16:47 +000037
Nick Lewyckye54da992009-04-13 04:26:06 +000038#ifdef HAVE_FFI_CALL
Nick Lewyckya89ec992009-02-04 06:26:47 +000039#ifdef HAVE_FFI_H
40#include <ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000041#define USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +000042#elif HAVE_FFI_FFI_H
43#include <ffi/ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000044#define USE_LIBFFI
Zhou Sheng3115ba32007-12-12 06:16:47 +000045#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +000046#endif
Tanya Lattner9a8602c2009-01-22 20:09:20 +000047
Chris Lattner18099662003-12-14 23:25:48 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Owen Andersonda19a132009-06-22 22:30:56 +000050static ManagedStatic<sys::Mutex> FunctionsLock;
51
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +000052typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
Nick Lewyckya89ec992009-02-04 06:26:47 +000053static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Bieneman3b1fd572014-09-19 21:07:01 +000054static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000055
Nick Lewyckye54da992009-04-13 04:26:06 +000056#ifdef USE_LIBFFI
Dan Gohman1432ef82009-08-12 22:10:57 +000057typedef void (*RawFunc)();
Nick Lewyckya89ec992009-02-04 06:26:47 +000058static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
59#endif
60
Chris Lattner15157b82001-10-27 04:15:57 +000061static Interpreter *TheInterpreter;
62
Chris Lattner229907c2011-07-18 04:54:35 +000063static char getTypeID(Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000064 switch (Ty->getTypeID()) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000065 case Type::VoidTyID: return 'V';
Reid Spencer7a9c62b2007-01-12 07:05:14 +000066 case Type::IntegerTyID:
67 switch (cast<IntegerType>(Ty)->getBitWidth()) {
68 case 1: return 'o';
69 case 8: return 'B';
70 case 16: return 'S';
71 case 32: return 'I';
72 case 64: return 'L';
73 default: return 'N';
74 }
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000075 case Type::FloatTyID: return 'F';
76 case Type::DoubleTyID: return 'D';
77 case Type::PointerTyID: return 'P';
Reid Spencer0d54e782006-12-31 05:51:36 +000078 case Type::FunctionTyID:return 'M';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000079 case Type::StructTyID: return 'T';
80 case Type::ArrayTyID: return 'A';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000081 default: return 'U';
82 }
83}
84
Anton Korobeynikov187bf732007-07-30 23:03:25 +000085// Try to find address of external function given a Function object.
86// Please note, that interpreter doesn't know how to assemble a
87// real call in general case (this is JIT job), that's why it assumes,
88// that all external functions has the same (and pretty "general") signature.
89// The typical example of such functions are "lle_X_" ones.
Brian Gaeke6cc20de2003-10-10 17:03:10 +000090static ExFunc lookupFunction(const Function *F) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000091 // Function not found, look it up... start by figuring out what the
92 // composite function name should be.
Chris Lattner7f74a562002-01-20 22:54:45 +000093 std::string ExtName = "lle_";
Chris Lattner229907c2011-07-18 04:54:35 +000094 FunctionType *FT = F->getFunctionType();
Brian Gaeke6cc20de2003-10-10 17:03:10 +000095 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
96 ExtName += getTypeID(FT->getContainedType(i));
Yaron Keren075759a2015-03-30 15:42:36 +000097 ExtName += ("_" + F->getName()).str();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000098
Owen Anderson5c96ef72009-07-07 18:33:04 +000099 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000100 ExFunc FnPtr = (*FuncNames)[ExtName];
Craig Topper353eda42014-04-24 06:44:33 +0000101 if (!FnPtr)
Yaron Keren075759a2015-03-30 15:42:36 +0000102 FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
Craig Topper353eda42014-04-24 06:44:33 +0000103 if (!FnPtr) // Try calling a generic function... if it exists...
Yaron Keren075759a2015-03-30 15:42:36 +0000104 FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
105 ("lle_X_" + F->getName()).str());
Craig Topper353eda42014-04-24 06:44:33 +0000106 if (FnPtr)
Nick Lewyckya89ec992009-02-04 06:26:47 +0000107 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000108 return FnPtr;
109}
110
Nick Lewyckye54da992009-04-13 04:26:06 +0000111#ifdef USE_LIBFFI
Chris Lattner229907c2011-07-18 04:54:35 +0000112static ffi_type *ffiTypeFor(Type *Ty) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000113 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.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000128 report_fatal_error("Type could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000129 return NULL;
130}
131
Chris Lattner229907c2011-07-18 04:54:35 +0000132static void *ffiValueFor(Type *Ty, const GenericValue &AV,
Nick Lewyckya89ec992009-02-04 06:26:47 +0000133 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 case Type::FloatTyID: {
159 float *FloatPtr = (float *) ArgDataPtr;
Nick Lewycky41ee7922009-11-18 05:43:15 +0000160 *FloatPtr = AV.FloatVal;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000161 return ArgDataPtr;
162 }
163 case Type::DoubleTyID: {
164 double *DoublePtr = (double *) ArgDataPtr;
165 *DoublePtr = AV.DoubleVal;
166 return ArgDataPtr;
167 }
168 case Type::PointerTyID: {
169 void **PtrPtr = (void **) ArgDataPtr;
170 *PtrPtr = GVTOP(AV);
171 return ArgDataPtr;
172 }
173 default: break;
174 }
175 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000176 report_fatal_error("Type value could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000177 return NULL;
178}
179
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000180static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000181 const DataLayout *TD, GenericValue &Result) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000182 ffi_cif cif;
Chris Lattner229907c2011-07-18 04:54:35 +0000183 FunctionType *FTy = F->getFunctionType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000184 const unsigned NumArgs = F->arg_size();
185
186 // TODO: We don't have type information about the remaining arguments, because
187 // this information is never passed into ExecutionEngine::runFunction().
188 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000189 report_fatal_error("Calling external var arg function '" + F->getName()
Torok Edwinccb29cd2009-07-11 13:10:19 +0000190 + "' is not supported by the Interpreter.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000191 }
192
193 unsigned ArgBytes = 0;
194
195 std::vector<ffi_type*> args(NumArgs);
196 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
197 A != E; ++A) {
198 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000199 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000200 args[ArgNo] = ffiTypeFor(ArgTy);
201 ArgBytes += TD->getTypeStoreSize(ArgTy);
202 }
203
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000204 SmallVector<uint8_t, 128> ArgData;
205 ArgData.resize(ArgBytes);
206 uint8_t *ArgDataPtr = ArgData.data();
207 SmallVector<void*, 16> values(NumArgs);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000208 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
209 A != E; ++A) {
210 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000211 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000212 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
213 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
214 }
215
Chris Lattner229907c2011-07-18 04:54:35 +0000216 Type *RetTy = FTy->getReturnType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000217 ffi_type *rtype = ffiTypeFor(RetTy);
218
219 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000220 SmallVector<uint8_t, 128> ret;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000221 if (RetTy->getTypeID() != Type::VoidTyID)
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000222 ret.resize(TD->getTypeStoreSize(RetTy));
223 ffi_call(&cif, Fn, ret.data(), values.data());
Nick Lewyckya89ec992009-02-04 06:26:47 +0000224 switch (RetTy->getTypeID()) {
225 case Type::IntegerTyID:
226 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000227 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
228 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
229 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
230 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000231 }
232 break;
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000233 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
234 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
235 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000236 default: break;
237 }
238 return true;
239 }
240
241 return false;
242}
Nick Lewyckye54da992009-04-13 04:26:06 +0000243#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000244
Chris Lattner28edd692005-01-21 19:59:37 +0000245GenericValue Interpreter::callExternalFunction(Function *F,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000246 ArrayRef<GenericValue> ArgVals) {
Chris Lattner15157b82001-10-27 04:15:57 +0000247 TheInterpreter = this;
248
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000249 unique_lock<sys::Mutex> Guard(*FunctionsLock);
Owen Andersonda19a132009-06-22 22:30:56 +0000250
Chris Lattner62b7fd12002-04-07 20:49:59 +0000251 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmanaa7d26c2003-10-10 17:42:19 +0000252 // deferred annotation!
Nick Lewyckya89ec992009-02-04 06:26:47 +0000253 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
254 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonda19a132009-06-22 22:30:56 +0000255 : FI->second) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000256 Guard.unlock();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000257 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonda19a132009-06-22 22:30:56 +0000258 }
Nick Lewyckya89ec992009-02-04 06:26:47 +0000259
Nick Lewyckye54da992009-04-13 04:26:06 +0000260#ifdef USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000261 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
262 RawFunc RawFn;
263 if (RF == RawFunctions->end()) {
264 RawFn = (RawFunc)(intptr_t)
265 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
Torok Edwin921e80b2010-03-30 20:15:13 +0000266 if (!RawFn)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000267 RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000268 if (RawFn != 0)
269 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
270 } else {
271 RawFn = RF->second;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000272 }
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000273
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000274 Guard.unlock();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000275
Nick Lewyckya89ec992009-02-04 06:26:47 +0000276 GenericValue Result;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000277 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
Nick Lewyckya89ec992009-02-04 06:26:47 +0000278 return Result;
Nick Lewyckye54da992009-04-13 04:26:06 +0000279#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000280
Torok Edwinccb29cd2009-07-11 13:10:19 +0000281 if (F->getName() == "__main")
David Greene1df14c42010-01-05 01:53:59 +0000282 errs() << "Tried to execute an unknown external function: "
Chris Lattner0f214eb2011-06-18 21:18:23 +0000283 << *F->getType() << " __main\n";
Torok Edwinccb29cd2009-07-11 13:10:19 +0000284 else
Chris Lattner2104b8d2010-04-07 22:58:41 +0000285 report_fatal_error("Tried to execute an unknown external function: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +0000286 F->getName());
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000287#ifndef USE_LIBFFI
David Greene1df14c42010-01-05 01:53:59 +0000288 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000289#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +0000290 return GenericValue();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000291}
292
293
294//===----------------------------------------------------------------------===//
Chris Lattnerf94811a2002-03-29 03:57:15 +0000295// Functions "exported" to the running application...
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000296//
Daniel Dunbar86ec7ba2009-08-07 20:50:09 +0000297
Chris Lattner4a5bb952003-05-14 14:21:30 +0000298// void atexit(Function*)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000299static GenericValue lle_X_atexit(FunctionType *FT,
300 ArrayRef<GenericValue> Args) {
Chris Lattner4a5bb952003-05-14 14:21:30 +0000301 assert(Args.size() == 1);
302 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
303 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000304 GV.IntVal = 0;
Chris Lattner4a5bb952003-05-14 14:21:30 +0000305 return GV;
Chris Lattnerd299dba2001-10-18 21:55:32 +0000306}
307
Chris Lattner0313db62002-10-02 21:12:13 +0000308// void exit(int)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000309static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
Chris Lattner15157b82001-10-27 04:15:57 +0000310 TheInterpreter->exitCalled(Args[0]);
311 return GenericValue();
312}
313
Chris Lattner0313db62002-10-02 21:12:13 +0000314// void abort(void)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000315static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000316 //FIXME: should we report or raise here?
Chris Lattner2104b8d2010-04-07 22:58:41 +0000317 //report_fatal_error("Interpreted program raised SIGABRT");
Brian Gaeke4e106f02003-11-05 01:18:49 +0000318 raise (SIGABRT);
Chris Lattner13194292002-05-20 21:17:16 +0000319 return GenericValue();
320}
321
Nick Lewyckya89ec992009-02-04 06:26:47 +0000322// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattner60a9a232001-12-13 00:43:47 +0000323// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000324static GenericValue lle_X_sprintf(FunctionType *FT,
325 ArrayRef<GenericValue> Args) {
Chris Lattnerd49518c2003-01-13 00:59:47 +0000326 char *OutputBuffer = (char *)GVTOP(Args[0]);
327 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattner60a9a232001-12-13 00:43:47 +0000328 unsigned ArgNo = 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000329
330 // printf should return # chars printed. This is completely incorrect, but
331 // close enough for now.
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000332 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000333 GV.IntVal = APInt(32, strlen(FmtStr));
Chris Lattner490d2a82001-10-29 20:27:45 +0000334 while (1) {
335 switch (*FmtStr) {
336 case 0: return GV; // Null terminator...
337 default: // Normal nonspecial character
Chris Lattner60a9a232001-12-13 00:43:47 +0000338 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner490d2a82001-10-29 20:27:45 +0000339 break;
340 case '\\': { // Handle escape codes
Chris Lattner60a9a232001-12-13 00:43:47 +0000341 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
342 FmtStr += 2; OutputBuffer += 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000343 break;
344 }
345 case '%': { // Handle format specifiers
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000346 char FmtBuf[100] = "", Buffer[1000] = "";
347 char *FB = FmtBuf;
348 *FB++ = *FmtStr++;
349 char Last = *FB++ = *FmtStr++;
350 unsigned HowLong = 0;
351 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
352 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
353 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
354 Last != 'p' && Last != 's' && Last != '%') {
355 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
356 Last = *FB++ = *FmtStr++;
Chris Lattner490d2a82001-10-29 20:27:45 +0000357 }
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000358 *FB = 0;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000359
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000360 switch (Last) {
361 case '%':
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000362 memcpy(Buffer, "%", 2); break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000363 case 'c':
Reid Spencerc45e1042007-03-06 03:08:12 +0000364 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
365 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000366 case 'd': case 'i':
367 case 'u': case 'o':
368 case 'x': case 'X':
Chris Lattner33b3b962002-08-02 23:08:32 +0000369 if (HowLong >= 1) {
Chris Lattner47985402003-08-24 14:02:47 +0000370 if (HowLong == 1 &&
Mehdi Aminif2643f42015-07-16 06:17:14 +0000371 TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
Reid Spencer6e641802006-05-24 19:21:13 +0000372 sizeof(long) < sizeof(int64_t)) {
Chris Lattner33b3b962002-08-02 23:08:32 +0000373 // Make sure we use %lld with a 64 bit argument because we might be
374 // compiling LLI on a 32 bit compiler.
375 unsigned Size = strlen(FmtBuf);
376 FmtBuf[Size] = FmtBuf[Size-1];
377 FmtBuf[Size+1] = 0;
378 FmtBuf[Size-1] = 'l';
379 }
Reid Spencerc45e1042007-03-06 03:08:12 +0000380 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner33b3b962002-08-02 23:08:32 +0000381 } else
Reid Spencerc45e1042007-03-06 03:08:12 +0000382 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
383 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000384 case 'e': case 'E': case 'g': case 'G': case 'f':
385 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
386 case 'p':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000387 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000388 case 's':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000389 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattner471ba482009-08-23 08:43:55 +0000390 default:
David Greene1df14c42010-01-05 01:53:59 +0000391 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000392 ArgNo++; break;
Chris Lattner490d2a82001-10-29 20:27:45 +0000393 }
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000394 size_t Len = strlen(Buffer);
395 memcpy(OutputBuffer, Buffer, Len + 1);
396 OutputBuffer += Len;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000397 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000398 break;
399 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000400 }
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000401 return GV;
Chris Lattner490d2a82001-10-29 20:27:45 +0000402}
403
Nick Lewyckya89ec992009-02-04 06:26:47 +0000404// int printf(const char *, ...) - a very rough implementation to make output
405// useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000406static GenericValue lle_X_printf(FunctionType *FT,
407 ArrayRef<GenericValue> Args) {
Chris Lattner60a9a232001-12-13 00:43:47 +0000408 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000409 std::vector<GenericValue> NewArgs;
Reid Spencera68c3742007-04-21 17:11:45 +0000410 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattner60a9a232001-12-13 00:43:47 +0000411 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000412 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattner471ba482009-08-23 08:43:55 +0000413 outs() << Buffer;
Chris Lattner60a9a232001-12-13 00:43:47 +0000414 return GV;
415}
416
Chris Lattner5dec4602002-03-08 22:51:07 +0000417// int sscanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000418static GenericValue lle_X_sscanf(FunctionType *FT,
419 ArrayRef<GenericValue> args) {
Chris Lattner5dec4602002-03-08 22:51:07 +0000420 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
421
Chris Lattnerd3183712003-03-31 22:12:37 +0000422 char *Args[10];
Chris Lattner5dec4602002-03-08 22:51:07 +0000423 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerd3183712003-03-31 22:12:37 +0000424 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner5dec4602002-03-08 22:51:07 +0000425
426 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000427 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000428 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerd3183712003-03-31 22:12:37 +0000429 return GV;
430}
431
432// int scanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000433static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
Chris Lattnerd3183712003-03-31 22:12:37 +0000434 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
435
436 char *Args[10];
437 for (unsigned i = 0; i < args.size(); ++i)
438 Args[i] = (char*)GVTOP(args[i]);
439
440 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000441 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000442 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattner5dec4602002-03-08 22:51:07 +0000443 return GV;
444}
445
Nick Lewyckya89ec992009-02-04 06:26:47 +0000446// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
447// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000448static GenericValue lle_X_fprintf(FunctionType *FT,
449 ArrayRef<GenericValue> Args) {
Chris Lattner16106662003-04-21 22:43:20 +0000450 assert(Args.size() >= 2);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000451 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000452 std::vector<GenericValue> NewArgs;
Chris Lattnerd49518c2003-01-13 00:59:47 +0000453 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000454 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000455 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000456
Nick Lewyckya89ec992009-02-04 06:26:47 +0000457 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000458 return GV;
459}
460
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000461static GenericValue lle_X_memset(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000462 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000463 int val = (int)Args[1].IntVal.getSExtValue();
464 size_t len = (size_t)Args[2].IntVal.getZExtValue();
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000465 memset((void *)GVTOP(Args[0]), val, len);
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000466 // llvm.memset.* returns void, lle_X_* returns GenericValue,
467 // so here we return GenericValue with IntVal set to zero
468 GenericValue GV;
469 GV.IntVal = 0;
470 return GV;
471}
472
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000473static GenericValue lle_X_memcpy(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000474 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000475 memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
476 (size_t)(Args[2].IntVal.getLimitedValue()));
477
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000478 // llvm.memcpy* returns void, lle_X_* returns GenericValue,
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000479 // so here we return GenericValue with IntVal set to zero
480 GenericValue GV;
481 GV.IntVal = 0;
482 return GV;
483}
484
Chris Lattner470754e2003-05-08 16:18:31 +0000485void Interpreter::initializeExternalFunctions() {
Owen Anderson5c96ef72009-07-07 18:33:04 +0000486 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000487 (*FuncNames)["lle_X_atexit"] = lle_X_atexit;
488 (*FuncNames)["lle_X_exit"] = lle_X_exit;
489 (*FuncNames)["lle_X_abort"] = lle_X_abort;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000490
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000491 (*FuncNames)["lle_X_printf"] = lle_X_printf;
492 (*FuncNames)["lle_X_sprintf"] = lle_X_sprintf;
493 (*FuncNames)["lle_X_sscanf"] = lle_X_sscanf;
494 (*FuncNames)["lle_X_scanf"] = lle_X_scanf;
495 (*FuncNames)["lle_X_fprintf"] = lle_X_fprintf;
496 (*FuncNames)["lle_X_memset"] = lle_X_memset;
497 (*FuncNames)["lle_X_memcpy"] = lle_X_memcpy;
Chris Lattner7fd51b52001-10-30 20:28:00 +0000498}