blob: 37f6ef07f6de666a84cf39d8b4ba0aaf53277c9d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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//
Nick Lewycky63254ee2009-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
Nick Lewycky63254ee2009-02-04 06:26:47 +000025#include "llvm/Config/config.h" // Detect libffi
Edwin Törökced9ff82009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Support/Streams.h"
28#include "llvm/System/DynamicLibrary.h"
29#include "llvm/Target/TargetData.h"
Chuck Rose III9a2da442007-07-27 18:26:35 +000030#include "llvm/Support/ManagedStatic.h"
Owen Anderson7c9c0682009-06-22 22:30:56 +000031#include "llvm/System/Mutex.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include <csignal>
Duncan Sands05f68372008-10-08 07:23:46 +000033#include <cstdio>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include <map>
35#include <cmath>
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000036#include <cstring>
Zhou Shenga80aaba2007-12-12 06:16:47 +000037
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000038#ifdef HAVE_FFI_CALL
Nick Lewycky63254ee2009-02-04 06:26:47 +000039#ifdef HAVE_FFI_H
40#include <ffi.h>
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000041#define USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +000042#elif HAVE_FFI_FFI_H
43#include <ffi/ffi.h>
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000044#define USE_LIBFFI
Zhou Shenga80aaba2007-12-12 06:16:47 +000045#endif
Nick Lewycky63254ee2009-02-04 06:26:47 +000046#endif
Tanya Lattner295e3772009-01-22 20:09:20 +000047
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048using namespace llvm;
49
Owen Anderson7c9c0682009-06-22 22:30:56 +000050static ManagedStatic<sys::Mutex> FunctionsLock;
51
Nick Lewycky63254ee2009-02-04 06:26:47 +000052typedef GenericValue (*ExFunc)(const FunctionType *,
53 const std::vector<GenericValue> &);
54static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055static std::map<std::string, ExFunc> FuncNames;
56
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000057#ifdef USE_LIBFFI
Dan Gohman3dbe9442009-08-12 22:10:57 +000058typedef void (*RawFunc)();
Nick Lewycky63254ee2009-02-04 06:26:47 +000059static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
60#endif
61
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062static Interpreter *TheInterpreter;
63
64static char getTypeID(const Type *Ty) {
65 switch (Ty->getTypeID()) {
66 case Type::VoidTyID: return 'V';
67 case Type::IntegerTyID:
68 switch (cast<IntegerType>(Ty)->getBitWidth()) {
69 case 1: return 'o';
70 case 8: return 'B';
71 case 16: return 'S';
72 case 32: return 'I';
73 case 64: return 'L';
74 default: return 'N';
75 }
76 case Type::FloatTyID: return 'F';
77 case Type::DoubleTyID: return 'D';
78 case Type::PointerTyID: return 'P';
79 case Type::FunctionTyID:return 'M';
80 case Type::StructTyID: return 'T';
81 case Type::ArrayTyID: return 'A';
82 case Type::OpaqueTyID: return 'O';
83 default: return 'U';
84 }
85}
86
Anton Korobeynikov85a94032007-07-30 23:03:25 +000087// Try to find address of external function given a Function object.
88// Please note, that interpreter doesn't know how to assemble a
89// real call in general case (this is JIT job), that's why it assumes,
90// that all external functions has the same (and pretty "general") signature.
91// The typical example of such functions are "lle_X_" ones.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092static ExFunc lookupFunction(const Function *F) {
93 // Function not found, look it up... start by figuring out what the
94 // composite function name should be.
95 std::string ExtName = "lle_";
96 const FunctionType *FT = F->getFunctionType();
97 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
98 ExtName += getTypeID(FT->getContainedType(i));
Daniel Dunbar1e13b972009-07-24 08:24:36 +000099 ExtName + "_" + F->getNameStr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100
Owen Andersonbe44bed2009-07-07 18:33:04 +0000101 sys::ScopedLock Writer(*FunctionsLock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102 ExFunc FnPtr = FuncNames[ExtName];
103 if (FnPtr == 0)
Daniel Dunbar1e13b972009-07-24 08:24:36 +0000104 FnPtr = FuncNames["lle_X_" + F->getNameStr()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 if (FnPtr == 0) // Try calling a generic function... if it exists...
Daniel Dunbar936763a2009-07-22 21:10:12 +0000106 FnPtr = (ExFunc)(intptr_t)
Daniel Dunbar1e13b972009-07-24 08:24:36 +0000107 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 if (FnPtr != 0)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000109 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110 return FnPtr;
111}
112
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000113#ifdef USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000114static ffi_type *ffiTypeFor(const Type *Ty) {
115 switch (Ty->getTypeID()) {
116 case Type::VoidTyID: return &ffi_type_void;
117 case Type::IntegerTyID:
118 switch (cast<IntegerType>(Ty)->getBitWidth()) {
119 case 8: return &ffi_type_sint8;
120 case 16: return &ffi_type_sint16;
121 case 32: return &ffi_type_sint32;
122 case 64: return &ffi_type_sint64;
123 }
124 case Type::FloatTyID: return &ffi_type_float;
125 case Type::DoubleTyID: return &ffi_type_double;
126 case Type::PointerTyID: return &ffi_type_pointer;
127 default: break;
128 }
129 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Edwin Törökced9ff82009-07-11 13:10:19 +0000130 llvm_report_error("Type could not be mapped for use with libffi.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000131 return NULL;
132}
133
134static void *ffiValueFor(const Type *Ty, const GenericValue &AV,
135 void *ArgDataPtr) {
136 switch (Ty->getTypeID()) {
137 case Type::IntegerTyID:
138 switch (cast<IntegerType>(Ty)->getBitWidth()) {
139 case 8: {
140 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
141 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
142 return ArgDataPtr;
143 }
144 case 16: {
145 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
146 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
147 return ArgDataPtr;
148 }
149 case 32: {
150 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
151 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
152 return ArgDataPtr;
153 }
154 case 64: {
155 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
156 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
157 return ArgDataPtr;
158 }
159 }
160 case Type::FloatTyID: {
161 float *FloatPtr = (float *) ArgDataPtr;
162 *FloatPtr = AV.DoubleVal;
163 return ArgDataPtr;
164 }
165 case Type::DoubleTyID: {
166 double *DoublePtr = (double *) ArgDataPtr;
167 *DoublePtr = AV.DoubleVal;
168 return ArgDataPtr;
169 }
170 case Type::PointerTyID: {
171 void **PtrPtr = (void **) ArgDataPtr;
172 *PtrPtr = GVTOP(AV);
173 return ArgDataPtr;
174 }
175 default: break;
176 }
177 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Edwin Törökced9ff82009-07-11 13:10:19 +0000178 llvm_report_error("Type value could not be mapped for use with libffi.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000179 return NULL;
180}
181
182static bool ffiInvoke(RawFunc Fn, Function *F,
183 const std::vector<GenericValue> &ArgVals,
184 const TargetData *TD, GenericValue &Result) {
185 ffi_cif cif;
186 const FunctionType *FTy = F->getFunctionType();
187 const unsigned NumArgs = F->arg_size();
188
189 // TODO: We don't have type information about the remaining arguments, because
190 // this information is never passed into ExecutionEngine::runFunction().
191 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000192 llvm_report_error("Calling external var arg function '" + F->getName()
193 + "' is not supported by the Interpreter.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000194 }
195
196 unsigned ArgBytes = 0;
197
198 std::vector<ffi_type*> args(NumArgs);
199 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
200 A != E; ++A) {
201 const unsigned ArgNo = A->getArgNo();
202 const Type *ArgTy = FTy->getParamType(ArgNo);
203 args[ArgNo] = ffiTypeFor(ArgTy);
204 ArgBytes += TD->getTypeStoreSize(ArgTy);
205 }
206
207 uint8_t *ArgData = (uint8_t*) alloca(ArgBytes);
208 uint8_t *ArgDataPtr = ArgData;
209 std::vector<void*> values(NumArgs);
210 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
211 A != E; ++A) {
212 const unsigned ArgNo = A->getArgNo();
213 const Type *ArgTy = FTy->getParamType(ArgNo);
214 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
215 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
216 }
217
218 const Type *RetTy = FTy->getReturnType();
219 ffi_type *rtype = ffiTypeFor(RetTy);
220
221 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
222 void *ret = NULL;
223 if (RetTy->getTypeID() != Type::VoidTyID)
224 ret = alloca(TD->getTypeStoreSize(RetTy));
225 ffi_call(&cif, Fn, ret, &values[0]);
226 switch (RetTy->getTypeID()) {
227 case Type::IntegerTyID:
228 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
229 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret); break;
230 case 16: Result.IntVal = APInt(16, *(int16_t*) ret); break;
231 case 32: Result.IntVal = APInt(32, *(int32_t*) ret); break;
232 case 64: Result.IntVal = APInt(64, *(int64_t*) ret); break;
233 }
234 break;
235 case Type::FloatTyID: Result.FloatVal = *(float *) ret; break;
236 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret; break;
237 case Type::PointerTyID: Result.PointerVal = *(void **) ret; break;
238 default: break;
239 }
240 return true;
241 }
242
243 return false;
244}
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000245#endif // USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000246
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247GenericValue Interpreter::callExternalFunction(Function *F,
248 const std::vector<GenericValue> &ArgVals) {
249 TheInterpreter = this;
250
Owen Anderson7c9c0682009-06-22 22:30:56 +0000251 FunctionsLock->acquire();
252
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 // Do a lookup to see if the function is in our cache... this should just be a
254 // deferred annotation!
Nick Lewycky63254ee2009-02-04 06:26:47 +0000255 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
256 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Anderson7c9c0682009-06-22 22:30:56 +0000257 : FI->second) {
258 FunctionsLock->release();
Nick Lewycky63254ee2009-02-04 06:26:47 +0000259 return Fn(F->getFunctionType(), ArgVals);
Owen Anderson7c9c0682009-06-22 22:30:56 +0000260 }
Nick Lewycky63254ee2009-02-04 06:26:47 +0000261
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000262#ifdef USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000263 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
264 RawFunc RawFn;
265 if (RF == RawFunctions->end()) {
266 RawFn = (RawFunc)(intptr_t)
267 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
268 if (RawFn != 0)
269 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
270 } else {
271 RawFn = RF->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 }
Owen Anderson7c9c0682009-06-22 22:30:56 +0000273
274 FunctionsLock->release();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275
Nick Lewycky63254ee2009-02-04 06:26:47 +0000276 GenericValue Result;
277 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result))
278 return Result;
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000279#endif // USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000280
Edwin Törökced9ff82009-07-11 13:10:19 +0000281 if (F->getName() == "__main")
282 cerr << "Tried to execute an unknown external function: "
283 << F->getType()->getDescription() << " __main\n";
284 else
285 llvm_report_error("Tried to execute an unknown external function: " +
286 F->getType()->getDescription() + " " +F->getName());
Nick Lewycky63254ee2009-02-04 06:26:47 +0000287 return GenericValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288}
289
290
291//===----------------------------------------------------------------------===//
292// Functions "exported" to the running application...
293//
Daniel Dunbar04de3242009-08-07 20:50:09 +0000294
295// Visual Studio warns about returning GenericValue in extern "C" linkage
296#ifdef _MSC_VER
297 #pragma warning(disable : 4190)
298#endif
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300extern "C" { // Don't add C++ manglings to llvm mangling :)
301
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302// void atexit(Function*)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000303GenericValue lle_X_atexit(const FunctionType *FT,
304 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 assert(Args.size() == 1);
306 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
307 GenericValue GV;
308 GV.IntVal = 0;
309 return GV;
310}
311
312// void exit(int)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000313GenericValue lle_X_exit(const FunctionType *FT,
314 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 TheInterpreter->exitCalled(Args[0]);
316 return GenericValue();
317}
318
319// void abort(void)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000320GenericValue lle_X_abort(const FunctionType *FT,
321 const std::vector<GenericValue> &Args) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000322 //FIXME: should we report or raise here?
323 //llvm_report_error("Interpreted program raised SIGABRT");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 raise (SIGABRT);
325 return GenericValue();
326}
327
Nick Lewycky63254ee2009-02-04 06:26:47 +0000328// int sprintf(char *, const char *, ...) - a very rough implementation to make
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329// output useful.
Nick Lewycky63254ee2009-02-04 06:26:47 +0000330GenericValue lle_X_sprintf(const FunctionType *FT,
331 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332 char *OutputBuffer = (char *)GVTOP(Args[0]);
333 const char *FmtStr = (const char *)GVTOP(Args[1]);
334 unsigned ArgNo = 2;
335
336 // printf should return # chars printed. This is completely incorrect, but
337 // close enough for now.
338 GenericValue GV;
339 GV.IntVal = APInt(32, strlen(FmtStr));
340 while (1) {
341 switch (*FmtStr) {
342 case 0: return GV; // Null terminator...
343 default: // Normal nonspecial character
344 sprintf(OutputBuffer++, "%c", *FmtStr++);
345 break;
346 case '\\': { // Handle escape codes
347 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
348 FmtStr += 2; OutputBuffer += 2;
349 break;
350 }
351 case '%': { // Handle format specifiers
352 char FmtBuf[100] = "", Buffer[1000] = "";
353 char *FB = FmtBuf;
354 *FB++ = *FmtStr++;
355 char Last = *FB++ = *FmtStr++;
356 unsigned HowLong = 0;
357 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
358 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
359 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
360 Last != 'p' && Last != 's' && Last != '%') {
361 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
362 Last = *FB++ = *FmtStr++;
363 }
364 *FB = 0;
365
366 switch (Last) {
367 case '%':
Dan Gohmane5dce982008-08-05 23:36:35 +0000368 strcpy(Buffer, "%"); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 case 'c':
370 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
371 break;
372 case 'd': case 'i':
373 case 'u': case 'o':
374 case 'x': case 'X':
375 if (HowLong >= 1) {
376 if (HowLong == 1 &&
377 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 &&
378 sizeof(long) < sizeof(int64_t)) {
379 // Make sure we use %lld with a 64 bit argument because we might be
380 // compiling LLI on a 32 bit compiler.
381 unsigned Size = strlen(FmtBuf);
382 FmtBuf[Size] = FmtBuf[Size-1];
383 FmtBuf[Size+1] = 0;
384 FmtBuf[Size-1] = 'l';
385 }
386 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
387 } else
388 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
389 break;
390 case 'e': case 'E': case 'g': case 'G': case 'f':
391 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
392 case 'p':
393 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
394 case 's':
395 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
396 default: cerr << "<unknown printf code '" << *FmtStr << "'!>";
397 ArgNo++; break;
398 }
399 strcpy(OutputBuffer, Buffer);
400 OutputBuffer += strlen(Buffer);
401 }
402 break;
403 }
404 }
405 return GV;
406}
407
Nick Lewycky63254ee2009-02-04 06:26:47 +0000408// int printf(const char *, ...) - a very rough implementation to make output
409// useful.
410GenericValue lle_X_printf(const FunctionType *FT,
411 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 char Buffer[10000];
Nick Lewycky63254ee2009-02-04 06:26:47 +0000413 std::vector<GenericValue> NewArgs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
415 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
416 GenericValue GV = lle_X_sprintf(FT, NewArgs);
417 cout << Buffer;
418 return GV;
419}
420
421static void ByteswapSCANFResults(const char *Fmt, void *Arg0, void *Arg1,
422 void *Arg2, void *Arg3, void *Arg4, void *Arg5,
423 void *Arg6, void *Arg7, void *Arg8) {
424 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
425
426 // Loop over the format string, munging read values as appropriate (performs
427 // byteswaps as necessary).
428 unsigned ArgNo = 0;
429 while (*Fmt) {
430 if (*Fmt++ == '%') {
431 // Read any flag characters that may be present...
432 bool Suppress = false;
433 bool Half = false;
434 bool Long = false;
435 bool LongLong = false; // long long or long double
436
437 while (1) {
438 switch (*Fmt++) {
439 case '*': Suppress = true; break;
440 case 'a': /*Allocate = true;*/ break; // We don't need to track this
441 case 'h': Half = true; break;
442 case 'l': Long = true; break;
443 case 'q':
444 case 'L': LongLong = true; break;
445 default:
446 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs
447 goto Out;
448 }
449 }
450 Out:
451
452 // Read the conversion character
453 if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
454 unsigned Size = 0;
455 const Type *Ty = 0;
456
457 switch (Fmt[-1]) {
458 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
459 case 'd':
460 if (Long || LongLong) {
461 Size = 8; Ty = Type::Int64Ty;
462 } else if (Half) {
463 Size = 4; Ty = Type::Int16Ty;
464 } else {
465 Size = 4; Ty = Type::Int32Ty;
466 }
467 break;
468
469 case 'e': case 'g': case 'E':
470 case 'f':
471 if (Long || LongLong) {
472 Size = 8; Ty = Type::DoubleTy;
473 } else {
474 Size = 4; Ty = Type::FloatTy;
475 }
476 break;
477
478 case 's': case 'c': case '[': // No byteswap needed
479 Size = 1;
480 Ty = Type::Int8Ty;
481 break;
482
483 default: break;
484 }
485
486 if (Size) {
487 GenericValue GV;
488 void *Arg = Args[ArgNo++];
489 memcpy(&GV, Arg, Size);
490 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
491 }
492 }
493 }
494 }
495}
496
497// int sscanf(const char *format, ...);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000498GenericValue lle_X_sscanf(const FunctionType *FT,
499 const std::vector<GenericValue> &args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
501
502 char *Args[10];
503 for (unsigned i = 0; i < args.size(); ++i)
504 Args[i] = (char*)GVTOP(args[i]);
505
506 GenericValue GV;
507 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
508 Args[5], Args[6], Args[7], Args[8], Args[9]));
509 ByteswapSCANFResults(Args[1], Args[2], Args[3], Args[4],
510 Args[5], Args[6], Args[7], Args[8], Args[9], 0);
511 return GV;
512}
513
514// int scanf(const char *format, ...);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000515GenericValue lle_X_scanf(const FunctionType *FT,
516 const std::vector<GenericValue> &args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
518
519 char *Args[10];
520 for (unsigned i = 0; i < args.size(); ++i)
521 Args[i] = (char*)GVTOP(args[i]);
522
523 GenericValue GV;
524 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
525 Args[5], Args[6], Args[7], Args[8], Args[9]));
526 ByteswapSCANFResults(Args[0], Args[1], Args[2], Args[3], Args[4],
527 Args[5], Args[6], Args[7], Args[8], Args[9]);
528 return GV;
529}
530
Nick Lewycky63254ee2009-02-04 06:26:47 +0000531// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
532// output useful.
533GenericValue lle_X_fprintf(const FunctionType *FT,
534 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 assert(Args.size() >= 2);
536 char Buffer[10000];
Nick Lewycky63254ee2009-02-04 06:26:47 +0000537 std::vector<GenericValue> NewArgs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 NewArgs.push_back(PTOGV(Buffer));
539 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
540 GenericValue GV = lle_X_sprintf(FT, NewArgs);
541
Nick Lewycky63254ee2009-02-04 06:26:47 +0000542 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 return GV;
544}
545
546} // End extern "C"
547
Daniel Dunbar04de3242009-08-07 20:50:09 +0000548// Done with externals; turn the warning back on
549#ifdef _MSC_VER
550 #pragma warning(default: 4190)
551#endif
552
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553
554void Interpreter::initializeExternalFunctions() {
Owen Andersonbe44bed2009-07-07 18:33:04 +0000555 sys::ScopedLock Writer(*FunctionsLock);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000556 FuncNames["lle_X_atexit"] = lle_X_atexit;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 FuncNames["lle_X_exit"] = lle_X_exit;
558 FuncNames["lle_X_abort"] = lle_X_abort;
Nick Lewycky63254ee2009-02-04 06:26:47 +0000559
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000560 FuncNames["lle_X_printf"] = lle_X_printf;
561 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
562 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
563 FuncNames["lle_X_scanf"] = lle_X_scanf;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565}
566