blob: 055875c9456a2e12d63c81fa536ef49a6afeeb01 [file] [log] [blame]
Chris Lattner2fbfdcf2002-04-07 20:49:59 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmand1c881a2005-04-21 22:43:08 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00009//
Chris Lattner2fbfdcf2002-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 Lattner7720c8e2001-09-10 04:50:17 +000012//
Nick Lewyckyf9c5c5c2009-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 Lattner7720c8e2001-09-10 04:50:17 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
23#include "llvm/DerivedTypes.h"
Misha Brukmanb8d15b22003-10-14 21:42:11 +000024#include "llvm/Module.h"
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000025#include "llvm/Config/config.h" // Detect libffi
Torok Edwin7d696d82009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000027#include "llvm/Support/DynamicLibrary.h"
Chris Lattner005cbce2002-10-02 21:12:13 +000028#include "llvm/Target/TargetData.h"
Chuck Rose III936baaa2007-07-27 18:26:35 +000029#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000030#include "llvm/Support/Mutex.h"
Brian Gaekeb56a6bc2003-11-05 01:18:49 +000031#include <csignal>
Duncan Sands4520dd22008-10-08 07:23:46 +000032#include <cstdio>
Misha Brukmanb8d15b22003-10-14 21:42:11 +000033#include <map>
Jeff Cohen97af7512006-12-02 02:22:01 +000034#include <cmath>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000035#include <cstring>
Zhou Sheng621dead2007-12-12 06:16:47 +000036
Nick Lewycky93f70fc2009-04-13 04:26:06 +000037#ifdef HAVE_FFI_CALL
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000038#ifdef HAVE_FFI_H
39#include <ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000040#define USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000041#elif HAVE_FFI_FFI_H
42#include <ffi/ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000043#define USE_LIBFFI
Zhou Sheng621dead2007-12-12 06:16:47 +000044#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000045#endif
Tanya Lattner32aaee62009-01-22 20:09:20 +000046
Chris Lattnerf7a743d2003-12-14 23:25:48 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Owen Andersonc2265702009-06-22 22:30:56 +000049static ManagedStatic<sys::Mutex> FunctionsLock;
50
Chris Lattnerdb125cf2011-07-18 04:54:35 +000051typedef GenericValue (*ExFunc)(FunctionType *,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000052 const std::vector<GenericValue> &);
53static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Lattner697954c2002-01-20 22:54:45 +000054static std::map<std::string, ExFunc> FuncNames;
Chris Lattner7720c8e2001-09-10 04:50:17 +000055
Nick Lewycky93f70fc2009-04-13 04:26:06 +000056#ifdef USE_LIBFFI
Dan Gohmana9ad0412009-08-12 22:10:57 +000057typedef void (*RawFunc)();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000058static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
59#endif
60
Chris Lattnere43db882001-10-27 04:15:57 +000061static Interpreter *TheInterpreter;
62
Chris Lattnerdb125cf2011-07-18 04:54:35 +000063static char getTypeID(Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000064 switch (Ty->getTypeID()) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000065 case Type::VoidTyID: return 'V';
Reid Spencera54b7cb2007-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 Lattner7720c8e2001-09-10 04:50:17 +000075 case Type::FloatTyID: return 'F';
76 case Type::DoubleTyID: return 'D';
77 case Type::PointerTyID: return 'P';
Reid Spencere49661b2006-12-31 05:51:36 +000078 case Type::FunctionTyID:return 'M';
Chris Lattner7720c8e2001-09-10 04:50:17 +000079 case Type::StructTyID: return 'T';
80 case Type::ArrayTyID: return 'A';
Chris Lattner7720c8e2001-09-10 04:50:17 +000081 default: return 'U';
82 }
83}
84
Anton Korobeynikov42346f52007-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 Gaeke58a6faa2003-10-10 17:03:10 +000090static ExFunc lookupFunction(const Function *F) {
Chris Lattner7720c8e2001-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 Lattner697954c2002-01-20 22:54:45 +000093 std::string ExtName = "lle_";
Chris Lattnerdb125cf2011-07-18 04:54:35 +000094 FunctionType *FT = F->getFunctionType();
Brian Gaeke58a6faa2003-10-10 17:03:10 +000095 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
96 ExtName += getTypeID(FT->getContainedType(i));
Daniel Dunbarf6ccee52009-07-24 08:24:36 +000097 ExtName + "_" + F->getNameStr();
Chris Lattner7720c8e2001-09-10 04:50:17 +000098
Owen Andersona9d1f2c2009-07-07 18:33:04 +000099 sys::ScopedLock Writer(*FunctionsLock);
Chris Lattner4721f132001-10-30 20:28:00 +0000100 ExFunc FnPtr = FuncNames[ExtName];
101 if (FnPtr == 0)
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000102 FnPtr = FuncNames["lle_X_" + F->getNameStr()];
Chris Lattner7720c8e2001-09-10 04:50:17 +0000103 if (FnPtr == 0) // Try calling a generic function... if it exists...
Daniel Dunbar8f603022009-07-22 21:10:12 +0000104 FnPtr = (ExFunc)(intptr_t)
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000105 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr());
Chris Lattner7720c8e2001-09-10 04:50:17 +0000106 if (FnPtr != 0)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000107 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattner7720c8e2001-09-10 04:50:17 +0000108 return FnPtr;
109}
110
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000111#ifdef USE_LIBFFI
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000112static ffi_type *ffiTypeFor(Type *Ty) {
Nick Lewyckyf9c5c5c2009-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 Lattner75361b62010-04-07 22:58:41 +0000128 report_fatal_error("Type could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000129 return NULL;
130}
131
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000132static void *ffiValueFor(Type *Ty, const GenericValue &AV,
Nick Lewyckyf9c5c5c2009-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 Lewyckyb5106f52009-11-18 05:43:15 +0000160 *FloatPtr = AV.FloatVal;
Nick Lewyckyf9c5c5c2009-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 Lattner75361b62010-04-07 22:58:41 +0000176 report_fatal_error("Type value could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000177 return NULL;
178}
179
180static bool ffiInvoke(RawFunc Fn, Function *F,
181 const std::vector<GenericValue> &ArgVals,
182 const TargetData *TD, GenericValue &Result) {
183 ffi_cif cif;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000184 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000185 const unsigned NumArgs = F->arg_size();
186
187 // TODO: We don't have type information about the remaining arguments, because
188 // this information is never passed into ExecutionEngine::runFunction().
189 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000190 report_fatal_error("Calling external var arg function '" + F->getName()
Torok Edwin7d696d82009-07-11 13:10:19 +0000191 + "' is not supported by the Interpreter.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000192 }
193
194 unsigned ArgBytes = 0;
195
196 std::vector<ffi_type*> args(NumArgs);
197 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
198 A != E; ++A) {
199 const unsigned ArgNo = A->getArgNo();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000200 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000201 args[ArgNo] = ffiTypeFor(ArgTy);
202 ArgBytes += TD->getTypeStoreSize(ArgTy);
203 }
204
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000205 SmallVector<uint8_t, 128> ArgData;
206 ArgData.resize(ArgBytes);
207 uint8_t *ArgDataPtr = ArgData.data();
208 SmallVector<void*, 16> values(NumArgs);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000209 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
210 A != E; ++A) {
211 const unsigned ArgNo = A->getArgNo();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000212 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000213 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
214 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
215 }
216
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000217 Type *RetTy = FTy->getReturnType();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000218 ffi_type *rtype = ffiTypeFor(RetTy);
219
220 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000221 SmallVector<uint8_t, 128> ret;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000222 if (RetTy->getTypeID() != Type::VoidTyID)
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000223 ret.resize(TD->getTypeStoreSize(RetTy));
224 ffi_call(&cif, Fn, ret.data(), values.data());
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000225 switch (RetTy->getTypeID()) {
226 case Type::IntegerTyID:
227 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000228 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
229 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
230 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
231 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000232 }
233 break;
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000234 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
235 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
236 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000237 default: break;
238 }
239 return true;
240 }
241
242 return false;
243}
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000244#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000245
Chris Lattner4e7dd8f2005-01-21 19:59:37 +0000246GenericValue Interpreter::callExternalFunction(Function *F,
Chris Lattner44edb6b2003-05-14 14:21:30 +0000247 const std::vector<GenericValue> &ArgVals) {
Chris Lattnere43db882001-10-27 04:15:57 +0000248 TheInterpreter = this;
249
Owen Andersonc2265702009-06-22 22:30:56 +0000250 FunctionsLock->acquire();
251
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000252 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmand5d96b92003-10-10 17:42:19 +0000253 // deferred annotation!
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000254 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
255 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonc2265702009-06-22 22:30:56 +0000256 : FI->second) {
257 FunctionsLock->release();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000258 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonc2265702009-06-22 22:30:56 +0000259 }
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000260
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000261#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000262 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
263 RawFunc RawFn;
264 if (RF == RawFunctions->end()) {
265 RawFn = (RawFunc)(intptr_t)
266 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
Torok Edwin820580d2010-03-30 20:15:13 +0000267 if (!RawFn)
Duncan Sands34727662010-07-12 08:16:59 +0000268 RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000269 if (RawFn != 0)
270 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
271 } else {
272 RawFn = RF->second;
Chris Lattner7720c8e2001-09-10 04:50:17 +0000273 }
Daniel Dunbare4a57432009-09-17 00:14:44 +0000274
Owen Andersonc2265702009-06-22 22:30:56 +0000275 FunctionsLock->release();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000276
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000277 GenericValue Result;
278 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result))
279 return Result;
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000280#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000281
Torok Edwin7d696d82009-07-11 13:10:19 +0000282 if (F->getName() == "__main")
David Greenec74fe782010-01-05 01:53:59 +0000283 errs() << "Tried to execute an unknown external function: "
Chris Lattner0cd0d882011-06-18 21:18:23 +0000284 << *F->getType() << " __main\n";
Torok Edwin7d696d82009-07-11 13:10:19 +0000285 else
Chris Lattner75361b62010-04-07 22:58:41 +0000286 report_fatal_error("Tried to execute an unknown external function: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000287 F->getName());
Nick Lewycky0e49fe82009-11-17 07:52:09 +0000288#ifndef USE_LIBFFI
David Greenec74fe782010-01-05 01:53:59 +0000289 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
Nick Lewycky0e49fe82009-11-17 07:52:09 +0000290#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000291 return GenericValue();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000292}
293
294
295//===----------------------------------------------------------------------===//
Chris Lattnerb408b122002-03-29 03:57:15 +0000296// Functions "exported" to the running application...
Chris Lattner7720c8e2001-09-10 04:50:17 +0000297//
Daniel Dunbar482cccd2009-08-07 20:50:09 +0000298
299// Visual Studio warns about returning GenericValue in extern "C" linkage
300#ifdef _MSC_VER
301 #pragma warning(disable : 4190)
302#endif
303
Chris Lattner7720c8e2001-09-10 04:50:17 +0000304extern "C" { // Don't add C++ manglings to llvm mangling :)
305
Chris Lattner44edb6b2003-05-14 14:21:30 +0000306// void atexit(Function*)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000307GenericValue lle_X_atexit(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000308 const std::vector<GenericValue> &Args) {
Chris Lattner44edb6b2003-05-14 14:21:30 +0000309 assert(Args.size() == 1);
310 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
311 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000312 GV.IntVal = 0;
Chris Lattner44edb6b2003-05-14 14:21:30 +0000313 return GV;
Chris Lattnerf8f2afb2001-10-18 21:55:32 +0000314}
315
Chris Lattner005cbce2002-10-02 21:12:13 +0000316// void exit(int)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000317GenericValue lle_X_exit(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000318 const std::vector<GenericValue> &Args) {
Chris Lattnere43db882001-10-27 04:15:57 +0000319 TheInterpreter->exitCalled(Args[0]);
320 return GenericValue();
321}
322
Chris Lattner005cbce2002-10-02 21:12:13 +0000323// void abort(void)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000324GenericValue lle_X_abort(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000325 const std::vector<GenericValue> &Args) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000326 //FIXME: should we report or raise here?
Chris Lattner75361b62010-04-07 22:58:41 +0000327 //report_fatal_error("Interpreted program raised SIGABRT");
Brian Gaekeb56a6bc2003-11-05 01:18:49 +0000328 raise (SIGABRT);
Chris Lattner1ee34a52002-05-20 21:17:16 +0000329 return GenericValue();
330}
331
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000332// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattnere7c6f722001-12-13 00:43:47 +0000333// output useful.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000334GenericValue lle_X_sprintf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000335 const std::vector<GenericValue> &Args) {
Chris Lattnerb1118742003-01-13 00:59:47 +0000336 char *OutputBuffer = (char *)GVTOP(Args[0]);
337 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattnere7c6f722001-12-13 00:43:47 +0000338 unsigned ArgNo = 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000339
340 // printf should return # chars printed. This is completely incorrect, but
341 // close enough for now.
Daniel Dunbare4a57432009-09-17 00:14:44 +0000342 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000343 GV.IntVal = APInt(32, strlen(FmtStr));
Chris Lattner08845a22001-10-29 20:27:45 +0000344 while (1) {
345 switch (*FmtStr) {
346 case 0: return GV; // Null terminator...
347 default: // Normal nonspecial character
Chris Lattnere7c6f722001-12-13 00:43:47 +0000348 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner08845a22001-10-29 20:27:45 +0000349 break;
350 case '\\': { // Handle escape codes
Chris Lattnere7c6f722001-12-13 00:43:47 +0000351 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
352 FmtStr += 2; OutputBuffer += 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000353 break;
354 }
355 case '%': { // Handle format specifiers
Chris Lattnerea38c0e2001-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 Lattner08845a22001-10-29 20:27:45 +0000367 }
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000368 *FB = 0;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000369
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000370 switch (Last) {
371 case '%':
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000372 memcpy(Buffer, "%", 2); break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000373 case 'c':
Reid Spencerbfcd5992007-03-06 03:08:12 +0000374 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
375 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000376 case 'd': case 'i':
377 case 'u': case 'o':
378 case 'x': case 'X':
Chris Lattner69ab7a82002-08-02 23:08:32 +0000379 if (HowLong >= 1) {
Chris Lattner1543e402003-08-24 14:02:47 +0000380 if (HowLong == 1 &&
Chris Lattnerfe854032006-08-16 01:24:12 +0000381 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 &&
Reid Spencer19b7e0e2006-05-24 19:21:13 +0000382 sizeof(long) < sizeof(int64_t)) {
Chris Lattner69ab7a82002-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 Spencerbfcd5992007-03-06 03:08:12 +0000390 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner69ab7a82002-08-02 23:08:32 +0000391 } else
Reid Spencerbfcd5992007-03-06 03:08:12 +0000392 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
393 break;
Chris Lattnerea38c0e2001-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 Lattnerb1118742003-01-13 00:59:47 +0000397 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000398 case 's':
Chris Lattnerb1118742003-01-13 00:59:47 +0000399 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000400 default:
David Greenec74fe782010-01-05 01:53:59 +0000401 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000402 ArgNo++; break;
Chris Lattner08845a22001-10-29 20:27:45 +0000403 }
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000404 size_t Len = strlen(Buffer);
405 memcpy(OutputBuffer, Buffer, Len + 1);
406 OutputBuffer += Len;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000407 }
Chris Lattner08845a22001-10-29 20:27:45 +0000408 break;
409 }
Chris Lattner08845a22001-10-29 20:27:45 +0000410 }
Reid Spencerb3b07272007-04-21 17:11:45 +0000411 return GV;
Chris Lattner08845a22001-10-29 20:27:45 +0000412}
413
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000414// int printf(const char *, ...) - a very rough implementation to make output
415// useful.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000416GenericValue lle_X_printf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000417 const std::vector<GenericValue> &Args) {
Chris Lattnere7c6f722001-12-13 00:43:47 +0000418 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000419 std::vector<GenericValue> NewArgs;
Reid Spencerb3b07272007-04-21 17:11:45 +0000420 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattnere7c6f722001-12-13 00:43:47 +0000421 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000422 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000423 outs() << Buffer;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000424 return GV;
425}
426
Chris Lattner665ee882002-03-08 22:51:07 +0000427// int sscanf(const char *format, ...);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000428GenericValue lle_X_sscanf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000429 const std::vector<GenericValue> &args) {
Chris Lattner665ee882002-03-08 22:51:07 +0000430 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
431
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000432 char *Args[10];
Chris Lattner665ee882002-03-08 22:51:07 +0000433 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000434 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner665ee882002-03-08 22:51:07 +0000435
436 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000437 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
438 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000439 return GV;
440}
441
442// int scanf(const char *format, ...);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000443GenericValue lle_X_scanf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000444 const std::vector<GenericValue> &args) {
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000445 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
446
447 char *Args[10];
448 for (unsigned i = 0; i < args.size(); ++i)
449 Args[i] = (char*)GVTOP(args[i]);
450
451 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000452 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
453 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattner665ee882002-03-08 22:51:07 +0000454 return GV;
455}
456
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000457// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
458// output useful.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000459GenericValue lle_X_fprintf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000460 const std::vector<GenericValue> &Args) {
Chris Lattner9dbf6dd2003-04-21 22:43:20 +0000461 assert(Args.size() >= 2);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000462 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000463 std::vector<GenericValue> NewArgs;
Chris Lattnerb1118742003-01-13 00:59:47 +0000464 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000465 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000466 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000467
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000468 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000469 return GV;
470}
471
Chris Lattner7720c8e2001-09-10 04:50:17 +0000472} // End extern "C"
Chris Lattner4721f132001-10-30 20:28:00 +0000473
Daniel Dunbar482cccd2009-08-07 20:50:09 +0000474// Done with externals; turn the warning back on
475#ifdef _MSC_VER
476 #pragma warning(default: 4190)
477#endif
478
Chris Lattner4721f132001-10-30 20:28:00 +0000479
Chris Lattnerda82ed52003-05-08 16:18:31 +0000480void Interpreter::initializeExternalFunctions() {
Owen Andersona9d1f2c2009-07-07 18:33:04 +0000481 sys::ScopedLock Writer(*FunctionsLock);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000482 FuncNames["lle_X_atexit"] = lle_X_atexit;
Chris Lattner0f279b22001-11-03 10:15:32 +0000483 FuncNames["lle_X_exit"] = lle_X_exit;
Chris Lattner1ee34a52002-05-20 21:17:16 +0000484 FuncNames["lle_X_abort"] = lle_X_abort;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000485
Chris Lattner0f279b22001-11-03 10:15:32 +0000486 FuncNames["lle_X_printf"] = lle_X_printf;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000487 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
Chris Lattner665ee882002-03-08 22:51:07 +0000488 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000489 FuncNames["lle_X_scanf"] = lle_X_scanf;
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000490 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
Chris Lattner4721f132001-10-30 20:28:00 +0000491}