blob: 160f1ba9f6c514415485ff52a25d4840ab02bbfd [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
Bill Wendling480f0932006-11-27 23:54:50 +000026#include "llvm/Support/Streams.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000027#include "llvm/System/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"
Brian Gaekeb56a6bc2003-11-05 01:18:49 +000030#include <csignal>
Duncan Sands4520dd22008-10-08 07:23:46 +000031#include <cstdio>
Misha Brukmanb8d15b22003-10-14 21:42:11 +000032#include <map>
Jeff Cohen97af7512006-12-02 02:22:01 +000033#include <cmath>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000034#include <cstring>
Zhou Sheng621dead2007-12-12 06:16:47 +000035
Nick Lewycky93f70fc2009-04-13 04:26:06 +000036#ifdef HAVE_FFI_CALL
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000037#ifdef HAVE_FFI_H
38#include <ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000039#define USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000040#elif HAVE_FFI_FFI_H
41#include <ffi/ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000042#define USE_LIBFFI
Zhou Sheng621dead2007-12-12 06:16:47 +000043#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000044#endif
Tanya Lattner32aaee62009-01-22 20:09:20 +000045
Chris Lattnerf7a743d2003-12-14 23:25:48 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000048typedef GenericValue (*ExFunc)(const FunctionType *,
49 const std::vector<GenericValue> &);
50static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Lattner697954c2002-01-20 22:54:45 +000051static std::map<std::string, ExFunc> FuncNames;
Chris Lattner7720c8e2001-09-10 04:50:17 +000052
Nick Lewycky93f70fc2009-04-13 04:26:06 +000053#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000054typedef void (*RawFunc)(void);
55static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
56#endif
57
Chris Lattnere43db882001-10-27 04:15:57 +000058static Interpreter *TheInterpreter;
59
Chris Lattner7720c8e2001-09-10 04:50:17 +000060static char getTypeID(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000061 switch (Ty->getTypeID()) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000062 case Type::VoidTyID: return 'V';
Reid Spencera54b7cb2007-01-12 07:05:14 +000063 case Type::IntegerTyID:
64 switch (cast<IntegerType>(Ty)->getBitWidth()) {
65 case 1: return 'o';
66 case 8: return 'B';
67 case 16: return 'S';
68 case 32: return 'I';
69 case 64: return 'L';
70 default: return 'N';
71 }
Chris Lattner7720c8e2001-09-10 04:50:17 +000072 case Type::FloatTyID: return 'F';
73 case Type::DoubleTyID: return 'D';
74 case Type::PointerTyID: return 'P';
Reid Spencere49661b2006-12-31 05:51:36 +000075 case Type::FunctionTyID:return 'M';
Chris Lattner7720c8e2001-09-10 04:50:17 +000076 case Type::StructTyID: return 'T';
77 case Type::ArrayTyID: return 'A';
78 case Type::OpaqueTyID: return 'O';
79 default: return 'U';
80 }
81}
82
Anton Korobeynikov42346f52007-07-30 23:03:25 +000083// Try to find address of external function given a Function object.
84// Please note, that interpreter doesn't know how to assemble a
85// real call in general case (this is JIT job), that's why it assumes,
86// that all external functions has the same (and pretty "general") signature.
87// The typical example of such functions are "lle_X_" ones.
Brian Gaeke58a6faa2003-10-10 17:03:10 +000088static ExFunc lookupFunction(const Function *F) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000089 // Function not found, look it up... start by figuring out what the
90 // composite function name should be.
Chris Lattner697954c2002-01-20 22:54:45 +000091 std::string ExtName = "lle_";
Brian Gaeke58a6faa2003-10-10 17:03:10 +000092 const FunctionType *FT = F->getFunctionType();
93 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
94 ExtName += getTypeID(FT->getContainedType(i));
95 ExtName += "_" + F->getName();
Chris Lattner7720c8e2001-09-10 04:50:17 +000096
Chris Lattner4721f132001-10-30 20:28:00 +000097 ExFunc FnPtr = FuncNames[ExtName];
98 if (FnPtr == 0)
Brian Gaeke58a6faa2003-10-10 17:03:10 +000099 FnPtr = FuncNames["lle_X_"+F->getName()];
Chris Lattner7720c8e2001-09-10 04:50:17 +0000100 if (FnPtr == 0) // Try calling a generic function... if it exists...
Chris Lattner26e6e102006-06-01 17:27:11 +0000101 FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000102 ("lle_X_"+F->getName()).c_str());
Chris Lattner7720c8e2001-09-10 04:50:17 +0000103 if (FnPtr != 0)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000104 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattner7720c8e2001-09-10 04:50:17 +0000105 return FnPtr;
106}
107
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000108#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000109static ffi_type *ffiTypeFor(const Type *Ty) {
110 switch (Ty->getTypeID()) {
111 case Type::VoidTyID: return &ffi_type_void;
112 case Type::IntegerTyID:
113 switch (cast<IntegerType>(Ty)->getBitWidth()) {
114 case 8: return &ffi_type_sint8;
115 case 16: return &ffi_type_sint16;
116 case 32: return &ffi_type_sint32;
117 case 64: return &ffi_type_sint64;
118 }
119 case Type::FloatTyID: return &ffi_type_float;
120 case Type::DoubleTyID: return &ffi_type_double;
121 case Type::PointerTyID: return &ffi_type_pointer;
122 default: break;
123 }
124 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
125 cerr << "Type could not be mapped for use with libffi.\n";
126 abort();
127 return NULL;
128}
129
130static void *ffiValueFor(const Type *Ty, const GenericValue &AV,
131 void *ArgDataPtr) {
132 switch (Ty->getTypeID()) {
133 case Type::IntegerTyID:
134 switch (cast<IntegerType>(Ty)->getBitWidth()) {
135 case 8: {
136 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
137 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
138 return ArgDataPtr;
139 }
140 case 16: {
141 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
142 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
143 return ArgDataPtr;
144 }
145 case 32: {
146 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
147 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
148 return ArgDataPtr;
149 }
150 case 64: {
151 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
152 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
153 return ArgDataPtr;
154 }
155 }
156 case Type::FloatTyID: {
157 float *FloatPtr = (float *) ArgDataPtr;
158 *FloatPtr = AV.DoubleVal;
159 return ArgDataPtr;
160 }
161 case Type::DoubleTyID: {
162 double *DoublePtr = (double *) ArgDataPtr;
163 *DoublePtr = AV.DoubleVal;
164 return ArgDataPtr;
165 }
166 case Type::PointerTyID: {
167 void **PtrPtr = (void **) ArgDataPtr;
168 *PtrPtr = GVTOP(AV);
169 return ArgDataPtr;
170 }
171 default: break;
172 }
173 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
174 cerr << "Type value could not be mapped for use with libffi.\n";
175 abort();
176 return NULL;
177}
178
179static bool ffiInvoke(RawFunc Fn, Function *F,
180 const std::vector<GenericValue> &ArgVals,
181 const TargetData *TD, GenericValue &Result) {
182 ffi_cif cif;
183 const FunctionType *FTy = F->getFunctionType();
184 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()) {
189 cerr << "Calling external var arg function '" << F->getName()
190 << "' is not supported by the Interpreter.\n";
191 abort();
192 }
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();
200 const Type *ArgTy = FTy->getParamType(ArgNo);
201 args[ArgNo] = ffiTypeFor(ArgTy);
202 ArgBytes += TD->getTypeStoreSize(ArgTy);
203 }
204
205 uint8_t *ArgData = (uint8_t*) alloca(ArgBytes);
206 uint8_t *ArgDataPtr = ArgData;
207 std::vector<void*> values(NumArgs);
208 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
209 A != E; ++A) {
210 const unsigned ArgNo = A->getArgNo();
211 const Type *ArgTy = FTy->getParamType(ArgNo);
212 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
213 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
214 }
215
216 const Type *RetTy = FTy->getReturnType();
217 ffi_type *rtype = ffiTypeFor(RetTy);
218
219 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
220 void *ret = NULL;
221 if (RetTy->getTypeID() != Type::VoidTyID)
222 ret = alloca(TD->getTypeStoreSize(RetTy));
223 ffi_call(&cif, Fn, ret, &values[0]);
224 switch (RetTy->getTypeID()) {
225 case Type::IntegerTyID:
226 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
227 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret); break;
228 case 16: Result.IntVal = APInt(16, *(int16_t*) ret); break;
229 case 32: Result.IntVal = APInt(32, *(int32_t*) ret); break;
230 case 64: Result.IntVal = APInt(64, *(int64_t*) ret); break;
231 }
232 break;
233 case Type::FloatTyID: Result.FloatVal = *(float *) ret; break;
234 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret; break;
235 case Type::PointerTyID: Result.PointerVal = *(void **) ret; break;
236 default: break;
237 }
238 return true;
239 }
240
241 return false;
242}
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000243#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000244
Chris Lattner4e7dd8f2005-01-21 19:59:37 +0000245GenericValue Interpreter::callExternalFunction(Function *F,
Chris Lattner44edb6b2003-05-14 14:21:30 +0000246 const std::vector<GenericValue> &ArgVals) {
Chris Lattnere43db882001-10-27 04:15:57 +0000247 TheInterpreter = this;
248
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000249 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmand5d96b92003-10-10 17:42:19 +0000250 // deferred annotation!
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000251 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
252 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
253 : FI->second)
254 return Fn(F->getFunctionType(), ArgVals);
255
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000256#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000257 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
258 RawFunc RawFn;
259 if (RF == RawFunctions->end()) {
260 RawFn = (RawFunc)(intptr_t)
261 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
262 if (RawFn != 0)
263 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
264 } else {
265 RawFn = RF->second;
Chris Lattner7720c8e2001-09-10 04:50:17 +0000266 }
267
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000268 GenericValue Result;
269 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result))
270 return Result;
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000271#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000272
273 cerr << "Tried to execute an unknown external function: "
274 << F->getType()->getDescription() << " " << F->getName() << "\n";
275 if (F->getName() != "__main")
276 abort();
277 return GenericValue();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000278}
279
280
281//===----------------------------------------------------------------------===//
Chris Lattnerb408b122002-03-29 03:57:15 +0000282// Functions "exported" to the running application...
Chris Lattner7720c8e2001-09-10 04:50:17 +0000283//
284extern "C" { // Don't add C++ manglings to llvm mangling :)
285
Chris Lattner44edb6b2003-05-14 14:21:30 +0000286// void atexit(Function*)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000287GenericValue lle_X_atexit(const FunctionType *FT,
288 const std::vector<GenericValue> &Args) {
Chris Lattner44edb6b2003-05-14 14:21:30 +0000289 assert(Args.size() == 1);
290 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
291 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000292 GV.IntVal = 0;
Chris Lattner44edb6b2003-05-14 14:21:30 +0000293 return GV;
Chris Lattnerf8f2afb2001-10-18 21:55:32 +0000294}
295
Chris Lattner005cbce2002-10-02 21:12:13 +0000296// void exit(int)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000297GenericValue lle_X_exit(const FunctionType *FT,
298 const std::vector<GenericValue> &Args) {
Chris Lattnere43db882001-10-27 04:15:57 +0000299 TheInterpreter->exitCalled(Args[0]);
300 return GenericValue();
301}
302
Chris Lattner005cbce2002-10-02 21:12:13 +0000303// void abort(void)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000304GenericValue lle_X_abort(const FunctionType *FT,
305 const std::vector<GenericValue> &Args) {
Brian Gaekeb56a6bc2003-11-05 01:18:49 +0000306 raise (SIGABRT);
Chris Lattner1ee34a52002-05-20 21:17:16 +0000307 return GenericValue();
308}
309
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000310// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattnere7c6f722001-12-13 00:43:47 +0000311// output useful.
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000312GenericValue lle_X_sprintf(const FunctionType *FT,
313 const std::vector<GenericValue> &Args) {
Chris Lattnerb1118742003-01-13 00:59:47 +0000314 char *OutputBuffer = (char *)GVTOP(Args[0]);
315 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattnere7c6f722001-12-13 00:43:47 +0000316 unsigned ArgNo = 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000317
318 // printf should return # chars printed. This is completely incorrect, but
319 // close enough for now.
Reid Spencerbfcd5992007-03-06 03:08:12 +0000320 GenericValue GV;
321 GV.IntVal = APInt(32, strlen(FmtStr));
Chris Lattner08845a22001-10-29 20:27:45 +0000322 while (1) {
323 switch (*FmtStr) {
324 case 0: return GV; // Null terminator...
325 default: // Normal nonspecial character
Chris Lattnere7c6f722001-12-13 00:43:47 +0000326 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner08845a22001-10-29 20:27:45 +0000327 break;
328 case '\\': { // Handle escape codes
Chris Lattnere7c6f722001-12-13 00:43:47 +0000329 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
330 FmtStr += 2; OutputBuffer += 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000331 break;
332 }
333 case '%': { // Handle format specifiers
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000334 char FmtBuf[100] = "", Buffer[1000] = "";
335 char *FB = FmtBuf;
336 *FB++ = *FmtStr++;
337 char Last = *FB++ = *FmtStr++;
338 unsigned HowLong = 0;
339 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
340 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
341 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
342 Last != 'p' && Last != 's' && Last != '%') {
343 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
344 Last = *FB++ = *FmtStr++;
Chris Lattner08845a22001-10-29 20:27:45 +0000345 }
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000346 *FB = 0;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000347
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000348 switch (Last) {
349 case '%':
Dan Gohman1eac4e02008-08-05 23:36:35 +0000350 strcpy(Buffer, "%"); break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000351 case 'c':
Reid Spencerbfcd5992007-03-06 03:08:12 +0000352 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
353 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000354 case 'd': case 'i':
355 case 'u': case 'o':
356 case 'x': case 'X':
Chris Lattner69ab7a82002-08-02 23:08:32 +0000357 if (HowLong >= 1) {
Chris Lattner1543e402003-08-24 14:02:47 +0000358 if (HowLong == 1 &&
Chris Lattnerfe854032006-08-16 01:24:12 +0000359 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 &&
Reid Spencer19b7e0e2006-05-24 19:21:13 +0000360 sizeof(long) < sizeof(int64_t)) {
Chris Lattner69ab7a82002-08-02 23:08:32 +0000361 // Make sure we use %lld with a 64 bit argument because we might be
362 // compiling LLI on a 32 bit compiler.
363 unsigned Size = strlen(FmtBuf);
364 FmtBuf[Size] = FmtBuf[Size-1];
365 FmtBuf[Size+1] = 0;
366 FmtBuf[Size-1] = 'l';
367 }
Reid Spencerbfcd5992007-03-06 03:08:12 +0000368 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner69ab7a82002-08-02 23:08:32 +0000369 } else
Reid Spencerbfcd5992007-03-06 03:08:12 +0000370 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
371 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000372 case 'e': case 'E': case 'g': case 'G': case 'f':
373 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
374 case 'p':
Chris Lattnerb1118742003-01-13 00:59:47 +0000375 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000376 case 's':
Chris Lattnerb1118742003-01-13 00:59:47 +0000377 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Bill Wendlinge8156192006-12-07 01:30:32 +0000378 default: cerr << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000379 ArgNo++; break;
Chris Lattner08845a22001-10-29 20:27:45 +0000380 }
Chris Lattnere7c6f722001-12-13 00:43:47 +0000381 strcpy(OutputBuffer, Buffer);
382 OutputBuffer += strlen(Buffer);
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000383 }
Chris Lattner08845a22001-10-29 20:27:45 +0000384 break;
385 }
Chris Lattner08845a22001-10-29 20:27:45 +0000386 }
Reid Spencerb3b07272007-04-21 17:11:45 +0000387 return GV;
Chris Lattner08845a22001-10-29 20:27:45 +0000388}
389
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000390// int printf(const char *, ...) - a very rough implementation to make output
391// useful.
392GenericValue lle_X_printf(const FunctionType *FT,
393 const std::vector<GenericValue> &Args) {
Chris Lattnere7c6f722001-12-13 00:43:47 +0000394 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000395 std::vector<GenericValue> NewArgs;
Reid Spencerb3b07272007-04-21 17:11:45 +0000396 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattnere7c6f722001-12-13 00:43:47 +0000397 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000398 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Bill Wendlinge8156192006-12-07 01:30:32 +0000399 cout << Buffer;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000400 return GV;
401}
402
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000403static void ByteswapSCANFResults(const char *Fmt, void *Arg0, void *Arg1,
404 void *Arg2, void *Arg3, void *Arg4, void *Arg5,
405 void *Arg6, void *Arg7, void *Arg8) {
406 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
407
408 // Loop over the format string, munging read values as appropriate (performs
Misha Brukman5560c9d2003-08-18 14:43:39 +0000409 // byteswaps as necessary).
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000410 unsigned ArgNo = 0;
411 while (*Fmt) {
412 if (*Fmt++ == '%') {
413 // Read any flag characters that may be present...
414 bool Suppress = false;
415 bool Half = false;
416 bool Long = false;
417 bool LongLong = false; // long long or long double
418
419 while (1) {
420 switch (*Fmt++) {
421 case '*': Suppress = true; break;
422 case 'a': /*Allocate = true;*/ break; // We don't need to track this
423 case 'h': Half = true; break;
424 case 'l': Long = true; break;
425 case 'q':
426 case 'L': LongLong = true; break;
427 default:
428 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs
429 goto Out;
430 }
431 }
432 Out:
433
434 // Read the conversion character
435 if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
436 unsigned Size = 0;
437 const Type *Ty = 0;
438
439 switch (Fmt[-1]) {
440 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
441 case 'd':
442 if (Long || LongLong) {
Reid Spencere49661b2006-12-31 05:51:36 +0000443 Size = 8; Ty = Type::Int64Ty;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000444 } else if (Half) {
Reid Spencere49661b2006-12-31 05:51:36 +0000445 Size = 4; Ty = Type::Int16Ty;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000446 } else {
Reid Spencere49661b2006-12-31 05:51:36 +0000447 Size = 4; Ty = Type::Int32Ty;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000448 }
449 break;
450
451 case 'e': case 'g': case 'E':
452 case 'f':
453 if (Long || LongLong) {
454 Size = 8; Ty = Type::DoubleTy;
455 } else {
456 Size = 4; Ty = Type::FloatTy;
457 }
458 break;
459
460 case 's': case 'c': case '[': // No byteswap needed
461 Size = 1;
Reid Spencere49661b2006-12-31 05:51:36 +0000462 Ty = Type::Int8Ty;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000463 break;
464
465 default: break;
466 }
467
468 if (Size) {
469 GenericValue GV;
470 void *Arg = Args[ArgNo++];
471 memcpy(&GV, Arg, Size);
472 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
473 }
474 }
475 }
476 }
477}
478
Chris Lattner665ee882002-03-08 22:51:07 +0000479// int sscanf(const char *format, ...);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000480GenericValue lle_X_sscanf(const FunctionType *FT,
481 const std::vector<GenericValue> &args) {
Chris Lattner665ee882002-03-08 22:51:07 +0000482 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
483
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000484 char *Args[10];
Chris Lattner665ee882002-03-08 22:51:07 +0000485 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000486 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner665ee882002-03-08 22:51:07 +0000487
488 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000489 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
490 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000491 ByteswapSCANFResults(Args[1], Args[2], Args[3], Args[4],
492 Args[5], Args[6], Args[7], Args[8], Args[9], 0);
493 return GV;
494}
495
496// int scanf(const char *format, ...);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000497GenericValue lle_X_scanf(const FunctionType *FT,
498 const std::vector<GenericValue> &args) {
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000499 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
500
501 char *Args[10];
502 for (unsigned i = 0; i < args.size(); ++i)
503 Args[i] = (char*)GVTOP(args[i]);
504
505 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000506 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
507 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000508 ByteswapSCANFResults(Args[0], Args[1], Args[2], Args[3], Args[4],
509 Args[5], Args[6], Args[7], Args[8], Args[9]);
Chris Lattner665ee882002-03-08 22:51:07 +0000510 return GV;
511}
512
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000513// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
514// output useful.
515GenericValue lle_X_fprintf(const FunctionType *FT,
516 const std::vector<GenericValue> &Args) {
Chris Lattner9dbf6dd2003-04-21 22:43:20 +0000517 assert(Args.size() >= 2);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000518 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000519 std::vector<GenericValue> NewArgs;
Chris Lattnerb1118742003-01-13 00:59:47 +0000520 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000521 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000522 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000523
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000524 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000525 return GV;
526}
527
Chris Lattner7720c8e2001-09-10 04:50:17 +0000528} // End extern "C"
Chris Lattner4721f132001-10-30 20:28:00 +0000529
530
Chris Lattnerda82ed52003-05-08 16:18:31 +0000531void Interpreter::initializeExternalFunctions() {
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000532 FuncNames["lle_X_atexit"] = lle_X_atexit;
Chris Lattner0f279b22001-11-03 10:15:32 +0000533 FuncNames["lle_X_exit"] = lle_X_exit;
Chris Lattner1ee34a52002-05-20 21:17:16 +0000534 FuncNames["lle_X_abort"] = lle_X_abort;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000535
Chris Lattner0f279b22001-11-03 10:15:32 +0000536 FuncNames["lle_X_printf"] = lle_X_printf;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000537 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
Chris Lattner665ee882002-03-08 22:51:07 +0000538 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000539 FuncNames["lle_X_scanf"] = lle_X_scanf;
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000540 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
Chris Lattner4721f132001-10-30 20:28:00 +0000541}
Brian Gaeked0fde302003-11-11 22:41:34 +0000542