blob: cb1b35d62388b25f6764d1d2269e8d50939835fb [file] [log] [blame]
Chris Lattner62b7fd12002-04-07 20:49:59 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
Misha Brukman91fb9ab2005-04-21 22:43:08 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukman91fb9ab2005-04-21 22:43:08 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Misha Brukman91fb9ab2005-04-21 22:43:08 +00008//
Chris Lattner62b7fd12002-04-07 20:49:59 +00009// This file contains both code to deal with invoking "external" functions, but
10// also contains code that implements "exported" external functions.
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000011//
Nick Lewyckya89ec992009-02-04 06:26:47 +000012// There are currently two mechanisms for handling external functions in the
13// Interpreter. The first is to implement lle_* wrapper functions that are
14// specific to well-known library functions which manually translate the
15// arguments from GenericValues and make the call. If such a wrapper does
16// not exist, and libffi is available, then the Interpreter will attempt to
17// invoke the function using libffi, after finding its address.
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000018//
19//===----------------------------------------------------------------------===//
20
21#include "Interpreter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/Config/config.h" // Detect libffi
Eugene Zelenko33d7b762016-08-23 17:14:32 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000028#include "llvm/IR/Function.h"
29#include "llvm/IR/Type.h"
30#include "llvm/Support/Casting.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000031#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/ErrorHandling.h"
Chuck Rose III1a39a2d12007-07-27 18:26:35 +000033#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000034#include "llvm/Support/Mutex.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000035#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include <cassert>
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include <cmath>
Brian Gaeke4e106f02003-11-05 01:18:49 +000038#include <csignal>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000039#include <cstdint>
Duncan Sands26ff6f92008-10-08 07:23:46 +000040#include <cstdio>
Anton Korobeynikov579f0712008-02-20 11:08:44 +000041#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include <map>
Benjamin Kramer3d5360a2019-08-07 10:57:25 +000043#include <mutex>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000044#include <string>
45#include <utility>
46#include <vector>
Zhou Sheng3115ba32007-12-12 06:16:47 +000047
Nick Lewyckye54da992009-04-13 04:26:06 +000048#ifdef HAVE_FFI_CALL
Nick Lewyckya89ec992009-02-04 06:26:47 +000049#ifdef HAVE_FFI_H
50#include <ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000051#define USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +000052#elif HAVE_FFI_FFI_H
53#include <ffi/ffi.h>
Nick Lewyckye54da992009-04-13 04:26:06 +000054#define USE_LIBFFI
Zhou Sheng3115ba32007-12-12 06:16:47 +000055#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +000056#endif
Tanya Lattner9a8602c2009-01-22 20:09:20 +000057
Chris Lattner18099662003-12-14 23:25:48 +000058using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000059
Owen Andersonda19a132009-06-22 22:30:56 +000060static ManagedStatic<sys::Mutex> FunctionsLock;
61
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +000062typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
Nick Lewyckya89ec992009-02-04 06:26:47 +000063static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Bieneman3b1fd572014-09-19 21:07:01 +000064static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000065
Nick Lewyckye54da992009-04-13 04:26:06 +000066#ifdef USE_LIBFFI
Dan Gohman1432ef82009-08-12 22:10:57 +000067typedef void (*RawFunc)();
Nick Lewyckya89ec992009-02-04 06:26:47 +000068static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
69#endif
70
Chris Lattner15157b82001-10-27 04:15:57 +000071static Interpreter *TheInterpreter;
72
Chris Lattner229907c2011-07-18 04:54:35 +000073static char getTypeID(Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000074 switch (Ty->getTypeID()) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000075 case Type::VoidTyID: return 'V';
Reid Spencer7a9c62b2007-01-12 07:05:14 +000076 case Type::IntegerTyID:
77 switch (cast<IntegerType>(Ty)->getBitWidth()) {
78 case 1: return 'o';
79 case 8: return 'B';
80 case 16: return 'S';
81 case 32: return 'I';
82 case 64: return 'L';
83 default: return 'N';
84 }
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000085 case Type::FloatTyID: return 'F';
86 case Type::DoubleTyID: return 'D';
87 case Type::PointerTyID: return 'P';
Reid Spencer0d54e782006-12-31 05:51:36 +000088 case Type::FunctionTyID:return 'M';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000089 case Type::StructTyID: return 'T';
90 case Type::ArrayTyID: return 'A';
Chris Lattnerbaf08eb2001-09-10 04:50:17 +000091 default: return 'U';
92 }
93}
94
Anton Korobeynikov187bf732007-07-30 23:03:25 +000095// Try to find address of external function given a Function object.
96// Please note, that interpreter doesn't know how to assemble a
97// real call in general case (this is JIT job), that's why it assumes,
98// that all external functions has the same (and pretty "general") signature.
99// The typical example of such functions are "lle_X_" ones.
Brian Gaeke6cc20de2003-10-10 17:03:10 +0000100static ExFunc lookupFunction(const Function *F) {
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000101 // Function not found, look it up... start by figuring out what the
102 // composite function name should be.
Chris Lattner7f74a562002-01-20 22:54:45 +0000103 std::string ExtName = "lle_";
Chris Lattner229907c2011-07-18 04:54:35 +0000104 FunctionType *FT = F->getFunctionType();
James Y Knight62df5ee2019-01-10 16:07:20 +0000105 ExtName += getTypeID(FT->getReturnType());
106 for (Type *T : FT->params())
107 ExtName += getTypeID(T);
Yaron Keren075759a2015-03-30 15:42:36 +0000108 ExtName += ("_" + F->getName()).str();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000109
Owen Anderson5c96ef72009-07-07 18:33:04 +0000110 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000111 ExFunc FnPtr = (*FuncNames)[ExtName];
Craig Topper353eda42014-04-24 06:44:33 +0000112 if (!FnPtr)
Yaron Keren075759a2015-03-30 15:42:36 +0000113 FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
Craig Topper353eda42014-04-24 06:44:33 +0000114 if (!FnPtr) // Try calling a generic function... if it exists...
Yaron Keren075759a2015-03-30 15:42:36 +0000115 FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
116 ("lle_X_" + F->getName()).str());
Craig Topper353eda42014-04-24 06:44:33 +0000117 if (FnPtr)
Nick Lewyckya89ec992009-02-04 06:26:47 +0000118 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000119 return FnPtr;
120}
121
Nick Lewyckye54da992009-04-13 04:26:06 +0000122#ifdef USE_LIBFFI
Chris Lattner229907c2011-07-18 04:54:35 +0000123static ffi_type *ffiTypeFor(Type *Ty) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000124 switch (Ty->getTypeID()) {
125 case Type::VoidTyID: return &ffi_type_void;
126 case Type::IntegerTyID:
127 switch (cast<IntegerType>(Ty)->getBitWidth()) {
128 case 8: return &ffi_type_sint8;
129 case 16: return &ffi_type_sint16;
130 case 32: return &ffi_type_sint32;
131 case 64: return &ffi_type_sint64;
132 }
133 case Type::FloatTyID: return &ffi_type_float;
134 case Type::DoubleTyID: return &ffi_type_double;
135 case Type::PointerTyID: return &ffi_type_pointer;
136 default: break;
137 }
138 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000139 report_fatal_error("Type could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000140 return NULL;
141}
142
Chris Lattner229907c2011-07-18 04:54:35 +0000143static void *ffiValueFor(Type *Ty, const GenericValue &AV,
Nick Lewyckya89ec992009-02-04 06:26:47 +0000144 void *ArgDataPtr) {
145 switch (Ty->getTypeID()) {
146 case Type::IntegerTyID:
147 switch (cast<IntegerType>(Ty)->getBitWidth()) {
148 case 8: {
149 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
150 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
151 return ArgDataPtr;
152 }
153 case 16: {
154 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
155 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
156 return ArgDataPtr;
157 }
158 case 32: {
159 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
160 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
161 return ArgDataPtr;
162 }
163 case 64: {
164 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
165 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
166 return ArgDataPtr;
167 }
168 }
169 case Type::FloatTyID: {
170 float *FloatPtr = (float *) ArgDataPtr;
Nick Lewycky41ee7922009-11-18 05:43:15 +0000171 *FloatPtr = AV.FloatVal;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000172 return ArgDataPtr;
173 }
174 case Type::DoubleTyID: {
175 double *DoublePtr = (double *) ArgDataPtr;
176 *DoublePtr = AV.DoubleVal;
177 return ArgDataPtr;
178 }
179 case Type::PointerTyID: {
180 void **PtrPtr = (void **) ArgDataPtr;
181 *PtrPtr = GVTOP(AV);
182 return ArgDataPtr;
183 }
184 default: break;
185 }
186 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner2104b8d2010-04-07 22:58:41 +0000187 report_fatal_error("Type value could not be mapped for use with libffi.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000188 return NULL;
189}
190
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000191static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000192 const DataLayout &TD, GenericValue &Result) {
Nick Lewyckya89ec992009-02-04 06:26:47 +0000193 ffi_cif cif;
Chris Lattner229907c2011-07-18 04:54:35 +0000194 FunctionType *FTy = F->getFunctionType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000195 const unsigned NumArgs = F->arg_size();
196
197 // TODO: We don't have type information about the remaining arguments, because
198 // this information is never passed into ExecutionEngine::runFunction().
199 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000200 report_fatal_error("Calling external var arg function '" + F->getName()
Torok Edwinccb29cd2009-07-11 13:10:19 +0000201 + "' is not supported by the Interpreter.");
Nick Lewyckya89ec992009-02-04 06:26:47 +0000202 }
203
204 unsigned ArgBytes = 0;
205
206 std::vector<ffi_type*> args(NumArgs);
207 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
208 A != E; ++A) {
209 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000210 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000211 args[ArgNo] = ffiTypeFor(ArgTy);
Mehdi Amini731ad622015-07-16 22:23:09 +0000212 ArgBytes += TD.getTypeStoreSize(ArgTy);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000213 }
214
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000215 SmallVector<uint8_t, 128> ArgData;
216 ArgData.resize(ArgBytes);
217 uint8_t *ArgDataPtr = ArgData.data();
218 SmallVector<void*, 16> values(NumArgs);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000219 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
220 A != E; ++A) {
221 const unsigned ArgNo = A->getArgNo();
Chris Lattner229907c2011-07-18 04:54:35 +0000222 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000223 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
Mehdi Amini731ad622015-07-16 22:23:09 +0000224 ArgDataPtr += TD.getTypeStoreSize(ArgTy);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000225 }
226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *RetTy = FTy->getReturnType();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000228 ffi_type *rtype = ffiTypeFor(RetTy);
229
Lang Hamesa4d5b342018-11-20 01:01:26 +0000230 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, args.data()) ==
231 FFI_OK) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000232 SmallVector<uint8_t, 128> ret;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000233 if (RetTy->getTypeID() != Type::VoidTyID)
Mehdi Amini731ad622015-07-16 22:23:09 +0000234 ret.resize(TD.getTypeStoreSize(RetTy));
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000235 ffi_call(&cif, Fn, ret.data(), values.data());
Nick Lewyckya89ec992009-02-04 06:26:47 +0000236 switch (RetTy->getTypeID()) {
237 case Type::IntegerTyID:
238 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000239 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
240 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
241 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
242 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000243 }
244 break;
Nick Lewyckybf4c56d2009-09-18 16:46:16 +0000245 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
246 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
247 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000248 default: break;
249 }
250 return true;
251 }
252
253 return false;
254}
Nick Lewyckye54da992009-04-13 04:26:06 +0000255#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000256
Chris Lattner28edd692005-01-21 19:59:37 +0000257GenericValue Interpreter::callExternalFunction(Function *F,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000258 ArrayRef<GenericValue> ArgVals) {
Chris Lattner15157b82001-10-27 04:15:57 +0000259 TheInterpreter = this;
260
Benjamin Kramer3d5360a2019-08-07 10:57:25 +0000261 std::unique_lock<sys::Mutex> Guard(*FunctionsLock);
Owen Andersonda19a132009-06-22 22:30:56 +0000262
Chris Lattner62b7fd12002-04-07 20:49:59 +0000263 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmanaa7d26c2003-10-10 17:42:19 +0000264 // deferred annotation!
Nick Lewyckya89ec992009-02-04 06:26:47 +0000265 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
266 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonda19a132009-06-22 22:30:56 +0000267 : FI->second) {
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000268 Guard.unlock();
Nick Lewyckya89ec992009-02-04 06:26:47 +0000269 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonda19a132009-06-22 22:30:56 +0000270 }
Nick Lewyckya89ec992009-02-04 06:26:47 +0000271
Nick Lewyckye54da992009-04-13 04:26:06 +0000272#ifdef USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000273 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
274 RawFunc RawFn;
275 if (RF == RawFunctions->end()) {
276 RawFn = (RawFunc)(intptr_t)
Sylvestre Ledru2eb80a992020-02-01 15:36:51 +0100277 sys::DynamicLibrary::SearchForAddressOfSymbol(std::string(F->getName()));
Torok Edwin921e80b2010-03-30 20:15:13 +0000278 if (!RawFn)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000279 RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
Nick Lewyckya89ec992009-02-04 06:26:47 +0000280 if (RawFn != 0)
281 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
282 } else {
283 RawFn = RF->second;
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000284 }
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000285
Dylan Noblesmithc4c51802014-08-23 23:07:14 +0000286 Guard.unlock();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000287
Nick Lewyckya89ec992009-02-04 06:26:47 +0000288 GenericValue Result;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000289 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
Nick Lewyckya89ec992009-02-04 06:26:47 +0000290 return Result;
Nick Lewyckye54da992009-04-13 04:26:06 +0000291#endif // USE_LIBFFI
Nick Lewyckya89ec992009-02-04 06:26:47 +0000292
Torok Edwinccb29cd2009-07-11 13:10:19 +0000293 if (F->getName() == "__main")
David Greene1df14c42010-01-05 01:53:59 +0000294 errs() << "Tried to execute an unknown external function: "
Chris Lattner0f214eb2011-06-18 21:18:23 +0000295 << *F->getType() << " __main\n";
Torok Edwinccb29cd2009-07-11 13:10:19 +0000296 else
Chris Lattner2104b8d2010-04-07 22:58:41 +0000297 report_fatal_error("Tried to execute an unknown external function: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +0000298 F->getName());
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000299#ifndef USE_LIBFFI
David Greene1df14c42010-01-05 01:53:59 +0000300 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
Nick Lewycky7efd07f2009-11-17 07:52:09 +0000301#endif
Nick Lewyckya89ec992009-02-04 06:26:47 +0000302 return GenericValue();
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000303}
304
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000305//===----------------------------------------------------------------------===//
Chris Lattnerf94811a2002-03-29 03:57:15 +0000306// Functions "exported" to the running application...
Chris Lattnerbaf08eb2001-09-10 04:50:17 +0000307//
Daniel Dunbar86ec7ba2009-08-07 20:50:09 +0000308
Chris Lattner4a5bb952003-05-14 14:21:30 +0000309// void atexit(Function*)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000310static GenericValue lle_X_atexit(FunctionType *FT,
311 ArrayRef<GenericValue> Args) {
Chris Lattner4a5bb952003-05-14 14:21:30 +0000312 assert(Args.size() == 1);
313 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
314 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000315 GV.IntVal = 0;
Chris Lattner4a5bb952003-05-14 14:21:30 +0000316 return GV;
Chris Lattnerd299dba2001-10-18 21:55:32 +0000317}
318
Chris Lattner0313db62002-10-02 21:12:13 +0000319// void exit(int)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000320static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
Chris Lattner15157b82001-10-27 04:15:57 +0000321 TheInterpreter->exitCalled(Args[0]);
322 return GenericValue();
323}
324
Chris Lattner0313db62002-10-02 21:12:13 +0000325// void abort(void)
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000326static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000327 //FIXME: should we report or raise here?
Chris Lattner2104b8d2010-04-07 22:58:41 +0000328 //report_fatal_error("Interpreted program raised SIGABRT");
Brian Gaeke4e106f02003-11-05 01:18:49 +0000329 raise (SIGABRT);
Chris Lattner13194292002-05-20 21:17:16 +0000330 return GenericValue();
331}
332
Nick Lewyckya89ec992009-02-04 06:26:47 +0000333// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattner60a9a232001-12-13 00:43:47 +0000334// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000335static GenericValue lle_X_sprintf(FunctionType *FT,
336 ArrayRef<GenericValue> Args) {
Chris Lattnerd49518c2003-01-13 00:59:47 +0000337 char *OutputBuffer = (char *)GVTOP(Args[0]);
338 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattner60a9a232001-12-13 00:43:47 +0000339 unsigned ArgNo = 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000340
341 // printf should return # chars printed. This is completely incorrect, but
342 // close enough for now.
Daniel Dunbarc7012fa2009-09-17 00:14:44 +0000343 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000344 GV.IntVal = APInt(32, strlen(FmtStr));
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000345 while (true) {
Chris Lattner490d2a82001-10-29 20:27:45 +0000346 switch (*FmtStr) {
347 case 0: return GV; // Null terminator...
348 default: // Normal nonspecial character
Chris Lattner60a9a232001-12-13 00:43:47 +0000349 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner490d2a82001-10-29 20:27:45 +0000350 break;
351 case '\\': { // Handle escape codes
Chris Lattner60a9a232001-12-13 00:43:47 +0000352 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
353 FmtStr += 2; OutputBuffer += 2;
Chris Lattner490d2a82001-10-29 20:27:45 +0000354 break;
355 }
356 case '%': { // Handle format specifiers
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000357 char FmtBuf[100] = "", Buffer[1000] = "";
358 char *FB = FmtBuf;
359 *FB++ = *FmtStr++;
360 char Last = *FB++ = *FmtStr++;
361 unsigned HowLong = 0;
362 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
363 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
364 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
365 Last != 'p' && Last != 's' && Last != '%') {
366 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
367 Last = *FB++ = *FmtStr++;
Chris Lattner490d2a82001-10-29 20:27:45 +0000368 }
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000369 *FB = 0;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000370
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000371 switch (Last) {
372 case '%':
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000373 memcpy(Buffer, "%", 2); break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000374 case 'c':
Reid Spencerc45e1042007-03-06 03:08:12 +0000375 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
376 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000377 case 'd': case 'i':
378 case 'u': case 'o':
379 case 'x': case 'X':
Chris Lattner33b3b962002-08-02 23:08:32 +0000380 if (HowLong >= 1) {
Chris Lattner47985402003-08-24 14:02:47 +0000381 if (HowLong == 1 &&
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000382 TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
Reid Spencer6e641802006-05-24 19:21:13 +0000383 sizeof(long) < sizeof(int64_t)) {
Chris Lattner33b3b962002-08-02 23:08:32 +0000384 // Make sure we use %lld with a 64 bit argument because we might be
385 // compiling LLI on a 32 bit compiler.
386 unsigned Size = strlen(FmtBuf);
387 FmtBuf[Size] = FmtBuf[Size-1];
388 FmtBuf[Size+1] = 0;
389 FmtBuf[Size-1] = 'l';
390 }
Reid Spencerc45e1042007-03-06 03:08:12 +0000391 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner33b3b962002-08-02 23:08:32 +0000392 } else
Reid Spencerc45e1042007-03-06 03:08:12 +0000393 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
394 break;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000395 case 'e': case 'E': case 'g': case 'G': case 'f':
396 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
397 case 'p':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000398 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukman91fb9ab2005-04-21 22:43:08 +0000399 case 's':
Chris Lattnerd49518c2003-01-13 00:59:47 +0000400 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattner471ba482009-08-23 08:43:55 +0000401 default:
David Greene1df14c42010-01-05 01:53:59 +0000402 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000403 ArgNo++; break;
Chris Lattner490d2a82001-10-29 20:27:45 +0000404 }
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000405 size_t Len = strlen(Buffer);
406 memcpy(OutputBuffer, Buffer, Len + 1);
407 OutputBuffer += Len;
Chris Lattner31e9e4d2001-11-07 19:46:27 +0000408 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000409 break;
410 }
Chris Lattner490d2a82001-10-29 20:27:45 +0000411 }
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000412 return GV;
Chris Lattner490d2a82001-10-29 20:27:45 +0000413}
414
Nick Lewyckya89ec992009-02-04 06:26:47 +0000415// int printf(const char *, ...) - a very rough implementation to make output
416// useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000417static GenericValue lle_X_printf(FunctionType *FT,
418 ArrayRef<GenericValue> Args) {
Chris Lattner60a9a232001-12-13 00:43:47 +0000419 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000420 std::vector<GenericValue> NewArgs;
Reid Spencera68c3742007-04-21 17:11:45 +0000421 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattner60a9a232001-12-13 00:43:47 +0000422 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000423 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattner471ba482009-08-23 08:43:55 +0000424 outs() << Buffer;
Chris Lattner60a9a232001-12-13 00:43:47 +0000425 return GV;
426}
427
Chris Lattner5dec4602002-03-08 22:51:07 +0000428// int sscanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000429static GenericValue lle_X_sscanf(FunctionType *FT,
430 ArrayRef<GenericValue> args) {
Chris Lattner5dec4602002-03-08 22:51:07 +0000431 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
432
Chris Lattnerd3183712003-03-31 22:12:37 +0000433 char *Args[10];
Chris Lattner5dec4602002-03-08 22:51:07 +0000434 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerd3183712003-03-31 22:12:37 +0000435 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner5dec4602002-03-08 22:51:07 +0000436
437 GenericValue GV;
Reid Spencerc45e1042007-03-06 03:08:12 +0000438 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000439 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerd3183712003-03-31 22:12:37 +0000440 return GV;
441}
442
443// int scanf(const char *format, ...);
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000444static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
Chris Lattnerd3183712003-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 Spencerc45e1042007-03-06 03:08:12 +0000452 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000453 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattner5dec4602002-03-08 22:51:07 +0000454 return GV;
455}
456
Nick Lewyckya89ec992009-02-04 06:26:47 +0000457// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
458// output useful.
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000459static GenericValue lle_X_fprintf(FunctionType *FT,
460 ArrayRef<GenericValue> Args) {
Chris Lattner16106662003-04-21 22:43:20 +0000461 assert(Args.size() >= 2);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000462 char Buffer[10000];
Nick Lewyckya89ec992009-02-04 06:26:47 +0000463 std::vector<GenericValue> NewArgs;
Chris Lattnerd49518c2003-01-13 00:59:47 +0000464 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000465 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer8c3d3dc2007-03-30 16:41:50 +0000466 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerc3a84092002-11-06 23:05:03 +0000467
Nick Lewyckya89ec992009-02-04 06:26:47 +0000468 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnerc3a84092002-11-06 23:05:03 +0000469 return GV;
470}
471
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000472static GenericValue lle_X_memset(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000473 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000474 int val = (int)Args[1].IntVal.getSExtValue();
475 size_t len = (size_t)Args[2].IntVal.getZExtValue();
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000476 memset((void *)GVTOP(Args[0]), val, len);
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000477 // llvm.memset.* returns void, lle_X_* returns GenericValue,
478 // so here we return GenericValue with IntVal set to zero
479 GenericValue GV;
480 GV.IntVal = 0;
481 return GV;
482}
483
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000484static GenericValue lle_X_memcpy(FunctionType *FT,
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000485 ArrayRef<GenericValue> Args) {
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000486 memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
487 (size_t)(Args[2].IntVal.getLimitedValue()));
488
Benjamin Kramerfcb71662013-09-11 12:42:39 +0000489 // llvm.memcpy* returns void, lle_X_* returns GenericValue,
Elena Demikhovsky843657c2013-09-02 06:40:09 +0000490 // so here we return GenericValue with IntVal set to zero
491 GenericValue GV;
492 GV.IntVal = 0;
493 return GV;
494}
495
Chris Lattner470754e2003-05-08 16:18:31 +0000496void Interpreter::initializeExternalFunctions() {
Owen Anderson5c96ef72009-07-07 18:33:04 +0000497 sys::ScopedLock Writer(*FunctionsLock);
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000498 (*FuncNames)["lle_X_atexit"] = lle_X_atexit;
499 (*FuncNames)["lle_X_exit"] = lle_X_exit;
500 (*FuncNames)["lle_X_abort"] = lle_X_abort;
Nick Lewyckya89ec992009-02-04 06:26:47 +0000501
Chris Bieneman3b1fd572014-09-19 21:07:01 +0000502 (*FuncNames)["lle_X_printf"] = lle_X_printf;
503 (*FuncNames)["lle_X_sprintf"] = lle_X_sprintf;
504 (*FuncNames)["lle_X_sscanf"] = lle_X_sscanf;
505 (*FuncNames)["lle_X_scanf"] = lle_X_scanf;
506 (*FuncNames)["lle_X_fprintf"] = lle_X_fprintf;
507 (*FuncNames)["lle_X_memset"] = lle_X_memset;
508 (*FuncNames)["lle_X_memcpy"] = lle_X_memcpy;
Chris Lattner7fd51b52001-10-30 20:28:00 +0000509}