1193323Sed//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed//  This file contains both code to deal with invoking "external" functions, but
10193323Sed//  also contains code that implements "exported" external functions.
11193323Sed//
12193323Sed//  There are currently two mechanisms for handling external functions in the
13193323Sed//  Interpreter.  The first is to implement lle_* wrapper functions that are
14193323Sed//  specific to well-known library functions which manually translate the
15193323Sed//  arguments from GenericValues and make the call.  If such a wrapper does
16193323Sed//  not exist, and libffi is available, then the Interpreter will attempt to
17193323Sed//  invoke the function using libffi, after finding its address.
18193323Sed//
19193323Sed//===----------------------------------------------------------------------===//
20193323Sed
21193323Sed#include "Interpreter.h"
22314564Sdim#include "llvm/ADT/APInt.h"
23314564Sdim#include "llvm/ADT/ArrayRef.h"
24321369Sdim#include "llvm/Config/config.h" // Detect libffi
25314564Sdim#include "llvm/ExecutionEngine/GenericValue.h"
26249423Sdim#include "llvm/IR/DataLayout.h"
27249423Sdim#include "llvm/IR/DerivedTypes.h"
28314564Sdim#include "llvm/IR/Function.h"
29314564Sdim#include "llvm/IR/Type.h"
30314564Sdim#include "llvm/Support/Casting.h"
31249423Sdim#include "llvm/Support/DynamicLibrary.h"
32198090Srdivacky#include "llvm/Support/ErrorHandling.h"
33193323Sed#include "llvm/Support/ManagedStatic.h"
34218893Sdim#include "llvm/Support/Mutex.h"
35314564Sdim#include "llvm/Support/raw_ostream.h"
36314564Sdim#include <cassert>
37249423Sdim#include <cmath>
38193323Sed#include <csignal>
39314564Sdim#include <cstdint>
40193323Sed#include <cstdio>
41249423Sdim#include <cstring>
42193323Sed#include <map>
43360784Sdim#include <mutex>
44314564Sdim#include <string>
45314564Sdim#include <utility>
46314564Sdim#include <vector>
47193323Sed
48193323Sed#ifdef HAVE_FFI_CALL
49193323Sed#ifdef HAVE_FFI_H
50193323Sed#include <ffi.h>
51193323Sed#define USE_LIBFFI
52193323Sed#elif HAVE_FFI_FFI_H
53193323Sed#include <ffi/ffi.h>
54193323Sed#define USE_LIBFFI
55193323Sed#endif
56193323Sed#endif
57193323Sed
58193323Sedusing namespace llvm;
59193323Sed
60194710Sedstatic ManagedStatic<sys::Mutex> FunctionsLock;
61194710Sed
62288943Sdimtypedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
63193323Sedstatic ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
64280031Sdimstatic ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
65193323Sed
66193323Sed#ifdef USE_LIBFFI
67198090Srdivackytypedef void (*RawFunc)();
68193323Sedstatic ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
69193323Sed#endif
70193323Sed
71193323Sedstatic Interpreter *TheInterpreter;
72193323Sed
73226633Sdimstatic char getTypeID(Type *Ty) {
74193323Sed  switch (Ty->getTypeID()) {
75193323Sed  case Type::VoidTyID:    return 'V';
76193323Sed  case Type::IntegerTyID:
77193323Sed    switch (cast<IntegerType>(Ty)->getBitWidth()) {
78193323Sed      case 1:  return 'o';
79193323Sed      case 8:  return 'B';
80193323Sed      case 16: return 'S';
81193323Sed      case 32: return 'I';
82193323Sed      case 64: return 'L';
83193323Sed      default: return 'N';
84193323Sed    }
85193323Sed  case Type::FloatTyID:   return 'F';
86193323Sed  case Type::DoubleTyID:  return 'D';
87193323Sed  case Type::PointerTyID: return 'P';
88193323Sed  case Type::FunctionTyID:return 'M';
89193323Sed  case Type::StructTyID:  return 'T';
90193323Sed  case Type::ArrayTyID:   return 'A';
91193323Sed  default: return 'U';
92193323Sed  }
93193323Sed}
94193323Sed
95193323Sed// Try to find address of external function given a Function object.
96193323Sed// Please note, that interpreter doesn't know how to assemble a
97193323Sed// real call in general case (this is JIT job), that's why it assumes,
98193323Sed// that all external functions has the same (and pretty "general") signature.
99193323Sed// The typical example of such functions are "lle_X_" ones.
100193323Sedstatic ExFunc lookupFunction(const Function *F) {
101193323Sed  // Function not found, look it up... start by figuring out what the
102193323Sed  // composite function name should be.
103193323Sed  std::string ExtName = "lle_";
104226633Sdim  FunctionType *FT = F->getFunctionType();
105344779Sdim  ExtName += getTypeID(FT->getReturnType());
106344779Sdim  for (Type *T : FT->params())
107344779Sdim    ExtName += getTypeID(T);
108288943Sdim  ExtName += ("_" + F->getName()).str();
109193323Sed
110198090Srdivacky  sys::ScopedLock Writer(*FunctionsLock);
111280031Sdim  ExFunc FnPtr = (*FuncNames)[ExtName];
112276479Sdim  if (!FnPtr)
113288943Sdim    FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
114276479Sdim  if (!FnPtr)  // Try calling a generic function... if it exists...
115288943Sdim    FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
116288943Sdim        ("lle_X_" + F->getName()).str());
117276479Sdim  if (FnPtr)
118193323Sed    ExportedFunctions->insert(std::make_pair(F, FnPtr));  // Cache for later
119193323Sed  return FnPtr;
120193323Sed}
121193323Sed
122193323Sed#ifdef USE_LIBFFI
123226633Sdimstatic ffi_type *ffiTypeFor(Type *Ty) {
124193323Sed  switch (Ty->getTypeID()) {
125193323Sed    case Type::VoidTyID: return &ffi_type_void;
126193323Sed    case Type::IntegerTyID:
127193323Sed      switch (cast<IntegerType>(Ty)->getBitWidth()) {
128193323Sed        case 8:  return &ffi_type_sint8;
129193323Sed        case 16: return &ffi_type_sint16;
130193323Sed        case 32: return &ffi_type_sint32;
131193323Sed        case 64: return &ffi_type_sint64;
132193323Sed      }
133193323Sed    case Type::FloatTyID:   return &ffi_type_float;
134193323Sed    case Type::DoubleTyID:  return &ffi_type_double;
135193323Sed    case Type::PointerTyID: return &ffi_type_pointer;
136193323Sed    default: break;
137193323Sed  }
138193323Sed  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
139207618Srdivacky  report_fatal_error("Type could not be mapped for use with libffi.");
140193323Sed  return NULL;
141193323Sed}
142193323Sed
143226633Sdimstatic void *ffiValueFor(Type *Ty, const GenericValue &AV,
144193323Sed                         void *ArgDataPtr) {
145193323Sed  switch (Ty->getTypeID()) {
146193323Sed    case Type::IntegerTyID:
147193323Sed      switch (cast<IntegerType>(Ty)->getBitWidth()) {
148193323Sed        case 8: {
149193323Sed          int8_t *I8Ptr = (int8_t *) ArgDataPtr;
150193323Sed          *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
151193323Sed          return ArgDataPtr;
152193323Sed        }
153193323Sed        case 16: {
154193323Sed          int16_t *I16Ptr = (int16_t *) ArgDataPtr;
155193323Sed          *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
156193323Sed          return ArgDataPtr;
157193323Sed        }
158193323Sed        case 32: {
159193323Sed          int32_t *I32Ptr = (int32_t *) ArgDataPtr;
160193323Sed          *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
161193323Sed          return ArgDataPtr;
162193323Sed        }
163193323Sed        case 64: {
164193323Sed          int64_t *I64Ptr = (int64_t *) ArgDataPtr;
165193323Sed          *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
166193323Sed          return ArgDataPtr;
167193323Sed        }
168193323Sed      }
169193323Sed    case Type::FloatTyID: {
170193323Sed      float *FloatPtr = (float *) ArgDataPtr;
171199481Srdivacky      *FloatPtr = AV.FloatVal;
172193323Sed      return ArgDataPtr;
173193323Sed    }
174193323Sed    case Type::DoubleTyID: {
175193323Sed      double *DoublePtr = (double *) ArgDataPtr;
176193323Sed      *DoublePtr = AV.DoubleVal;
177193323Sed      return ArgDataPtr;
178193323Sed    }
179193323Sed    case Type::PointerTyID: {
180193323Sed      void **PtrPtr = (void **) ArgDataPtr;
181193323Sed      *PtrPtr = GVTOP(AV);
182193323Sed      return ArgDataPtr;
183193323Sed    }
184193323Sed    default: break;
185193323Sed  }
186193323Sed  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
187207618Srdivacky  report_fatal_error("Type value could not be mapped for use with libffi.");
188193323Sed  return NULL;
189193323Sed}
190193323Sed
191288943Sdimstatic bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
192296417Sdim                      const DataLayout &TD, GenericValue &Result) {
193193323Sed  ffi_cif cif;
194226633Sdim  FunctionType *FTy = F->getFunctionType();
195193323Sed  const unsigned NumArgs = F->arg_size();
196193323Sed
197193323Sed  // TODO: We don't have type information about the remaining arguments, because
198193323Sed  // this information is never passed into ExecutionEngine::runFunction().
199193323Sed  if (ArgVals.size() > NumArgs && F->isVarArg()) {
200207618Srdivacky    report_fatal_error("Calling external var arg function '" + F->getName()
201198090Srdivacky                      + "' is not supported by the Interpreter.");
202193323Sed  }
203193323Sed
204193323Sed  unsigned ArgBytes = 0;
205193323Sed
206193323Sed  std::vector<ffi_type*> args(NumArgs);
207193323Sed  for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
208193323Sed       A != E; ++A) {
209193323Sed    const unsigned ArgNo = A->getArgNo();
210226633Sdim    Type *ArgTy = FTy->getParamType(ArgNo);
211193323Sed    args[ArgNo] = ffiTypeFor(ArgTy);
212296417Sdim    ArgBytes += TD.getTypeStoreSize(ArgTy);
213193323Sed  }
214193323Sed
215198090Srdivacky  SmallVector<uint8_t, 128> ArgData;
216198090Srdivacky  ArgData.resize(ArgBytes);
217198090Srdivacky  uint8_t *ArgDataPtr = ArgData.data();
218198090Srdivacky  SmallVector<void*, 16> values(NumArgs);
219193323Sed  for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
220193323Sed       A != E; ++A) {
221193323Sed    const unsigned ArgNo = A->getArgNo();
222226633Sdim    Type *ArgTy = FTy->getParamType(ArgNo);
223193323Sed    values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
224296417Sdim    ArgDataPtr += TD.getTypeStoreSize(ArgTy);
225193323Sed  }
226193323Sed
227226633Sdim  Type *RetTy = FTy->getReturnType();
228193323Sed  ffi_type *rtype = ffiTypeFor(RetTy);
229193323Sed
230344779Sdim  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, args.data()) ==
231344779Sdim      FFI_OK) {
232198090Srdivacky    SmallVector<uint8_t, 128> ret;
233193323Sed    if (RetTy->getTypeID() != Type::VoidTyID)
234296417Sdim      ret.resize(TD.getTypeStoreSize(RetTy));
235198090Srdivacky    ffi_call(&cif, Fn, ret.data(), values.data());
236193323Sed    switch (RetTy->getTypeID()) {
237193323Sed      case Type::IntegerTyID:
238193323Sed        switch (cast<IntegerType>(RetTy)->getBitWidth()) {
239198090Srdivacky          case 8:  Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
240198090Srdivacky          case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
241198090Srdivacky          case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
242198090Srdivacky          case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
243193323Sed        }
244193323Sed        break;
245198090Srdivacky      case Type::FloatTyID:   Result.FloatVal   = *(float *) ret.data(); break;
246198090Srdivacky      case Type::DoubleTyID:  Result.DoubleVal  = *(double*) ret.data(); break;
247198090Srdivacky      case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
248193323Sed      default: break;
249193323Sed    }
250193323Sed    return true;
251193323Sed  }
252193323Sed
253193323Sed  return false;
254193323Sed}
255193323Sed#endif // USE_LIBFFI
256193323Sed
257193323SedGenericValue Interpreter::callExternalFunction(Function *F,
258288943Sdim                                               ArrayRef<GenericValue> ArgVals) {
259193323Sed  TheInterpreter = this;
260193323Sed
261360784Sdim  std::unique_lock<sys::Mutex> Guard(*FunctionsLock);
262194710Sed
263193323Sed  // Do a lookup to see if the function is in our cache... this should just be a
264193323Sed  // deferred annotation!
265193323Sed  std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
266193323Sed  if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
267194710Sed                                                   : FI->second) {
268280031Sdim    Guard.unlock();
269193323Sed    return Fn(F->getFunctionType(), ArgVals);
270194710Sed  }
271193323Sed
272193323Sed#ifdef USE_LIBFFI
273193323Sed  std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
274193323Sed  RawFunc RawFn;
275193323Sed  if (RF == RawFunctions->end()) {
276193323Sed    RawFn = (RawFunc)(intptr_t)
277193323Sed      sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
278206083Srdivacky    if (!RawFn)
279210299Sed      RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
280193323Sed    if (RawFn != 0)
281193323Sed      RawFunctions->insert(std::make_pair(F, RawFn));  // Cache for later
282193323Sed  } else {
283193323Sed    RawFn = RF->second;
284193323Sed  }
285198090Srdivacky
286280031Sdim  Guard.unlock();
287193323Sed
288193323Sed  GenericValue Result;
289243830Sdim  if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
290193323Sed    return Result;
291193323Sed#endif // USE_LIBFFI
292193323Sed
293198090Srdivacky  if (F->getName() == "__main")
294198090Srdivacky    errs() << "Tried to execute an unknown external function: "
295224145Sdim      << *F->getType() << " __main\n";
296198090Srdivacky  else
297207618Srdivacky    report_fatal_error("Tried to execute an unknown external function: " +
298224145Sdim                       F->getName());
299199481Srdivacky#ifndef USE_LIBFFI
300199481Srdivacky  errs() << "Recompiling LLVM with --enable-libffi might help.\n";
301199481Srdivacky#endif
302193323Sed  return GenericValue();
303193323Sed}
304193323Sed
305193323Sed//===----------------------------------------------------------------------===//
306193323Sed//  Functions "exported" to the running application...
307193323Sed//
308198090Srdivacky
309193323Sed// void atexit(Function*)
310288943Sdimstatic GenericValue lle_X_atexit(FunctionType *FT,
311288943Sdim                                 ArrayRef<GenericValue> Args) {
312193323Sed  assert(Args.size() == 1);
313193323Sed  TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
314193323Sed  GenericValue GV;
315193323Sed  GV.IntVal = 0;
316193323Sed  return GV;
317193323Sed}
318193323Sed
319193323Sed// void exit(int)
320288943Sdimstatic GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
321193323Sed  TheInterpreter->exitCalled(Args[0]);
322193323Sed  return GenericValue();
323193323Sed}
324193323Sed
325193323Sed// void abort(void)
326288943Sdimstatic GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
327198090Srdivacky  //FIXME: should we report or raise here?
328207618Srdivacky  //report_fatal_error("Interpreted program raised SIGABRT");
329193323Sed  raise (SIGABRT);
330193323Sed  return GenericValue();
331193323Sed}
332193323Sed
333193323Sed// int sprintf(char *, const char *, ...) - a very rough implementation to make
334193323Sed// output useful.
335288943Sdimstatic GenericValue lle_X_sprintf(FunctionType *FT,
336288943Sdim                                  ArrayRef<GenericValue> Args) {
337193323Sed  char *OutputBuffer = (char *)GVTOP(Args[0]);
338193323Sed  const char *FmtStr = (const char *)GVTOP(Args[1]);
339193323Sed  unsigned ArgNo = 2;
340193323Sed
341193323Sed  // printf should return # chars printed.  This is completely incorrect, but
342193323Sed  // close enough for now.
343198090Srdivacky  GenericValue GV;
344193323Sed  GV.IntVal = APInt(32, strlen(FmtStr));
345314564Sdim  while (true) {
346193323Sed    switch (*FmtStr) {
347193323Sed    case 0: return GV;             // Null terminator...
348193323Sed    default:                       // Normal nonspecial character
349193323Sed      sprintf(OutputBuffer++, "%c", *FmtStr++);
350193323Sed      break;
351193323Sed    case '\\': {                   // Handle escape codes
352193323Sed      sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
353193323Sed      FmtStr += 2; OutputBuffer += 2;
354193323Sed      break;
355193323Sed    }
356193323Sed    case '%': {                    // Handle format specifiers
357193323Sed      char FmtBuf[100] = "", Buffer[1000] = "";
358193323Sed      char *FB = FmtBuf;
359193323Sed      *FB++ = *FmtStr++;
360193323Sed      char Last = *FB++ = *FmtStr++;
361193323Sed      unsigned HowLong = 0;
362193323Sed      while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
363193323Sed             Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
364193323Sed             Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
365193323Sed             Last != 'p' && Last != 's' && Last != '%') {
366193323Sed        if (Last == 'l' || Last == 'L') HowLong++;  // Keep track of l's
367193323Sed        Last = *FB++ = *FmtStr++;
368193323Sed      }
369193323Sed      *FB = 0;
370193323Sed
371193323Sed      switch (Last) {
372193323Sed      case '%':
373203954Srdivacky        memcpy(Buffer, "%", 2); break;
374193323Sed      case 'c':
375193323Sed        sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
376193323Sed        break;
377193323Sed      case 'd': case 'i':
378193323Sed      case 'u': case 'o':
379193323Sed      case 'x': case 'X':
380193323Sed        if (HowLong >= 1) {
381193323Sed          if (HowLong == 1 &&
382296417Sdim              TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
383193323Sed              sizeof(long) < sizeof(int64_t)) {
384193323Sed            // Make sure we use %lld with a 64 bit argument because we might be
385193323Sed            // compiling LLI on a 32 bit compiler.
386193323Sed            unsigned Size = strlen(FmtBuf);
387193323Sed            FmtBuf[Size] = FmtBuf[Size-1];
388193323Sed            FmtBuf[Size+1] = 0;
389193323Sed            FmtBuf[Size-1] = 'l';
390193323Sed          }
391193323Sed          sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
392193323Sed        } else
393193323Sed          sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
394193323Sed        break;
395193323Sed      case 'e': case 'E': case 'g': case 'G': case 'f':
396193323Sed        sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
397193323Sed      case 'p':
398193323Sed        sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
399193323Sed      case 's':
400193323Sed        sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
401198090Srdivacky      default:
402198090Srdivacky        errs() << "<unknown printf code '" << *FmtStr << "'!>";
403193323Sed        ArgNo++; break;
404193323Sed      }
405203954Srdivacky      size_t Len = strlen(Buffer);
406203954Srdivacky      memcpy(OutputBuffer, Buffer, Len + 1);
407203954Srdivacky      OutputBuffer += Len;
408193323Sed      }
409193323Sed      break;
410193323Sed    }
411193323Sed  }
412261991Sdim  return GV;
413193323Sed}
414193323Sed
415193323Sed// int printf(const char *, ...) - a very rough implementation to make output
416193323Sed// useful.
417288943Sdimstatic GenericValue lle_X_printf(FunctionType *FT,
418288943Sdim                                 ArrayRef<GenericValue> Args) {
419193323Sed  char Buffer[10000];
420193323Sed  std::vector<GenericValue> NewArgs;
421193323Sed  NewArgs.push_back(PTOGV((void*)&Buffer[0]));
422193323Sed  NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
423193323Sed  GenericValue GV = lle_X_sprintf(FT, NewArgs);
424198090Srdivacky  outs() << Buffer;
425193323Sed  return GV;
426193323Sed}
427193323Sed
428193323Sed// int sscanf(const char *format, ...);
429288943Sdimstatic GenericValue lle_X_sscanf(FunctionType *FT,
430288943Sdim                                 ArrayRef<GenericValue> args) {
431193323Sed  assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
432193323Sed
433193323Sed  char *Args[10];
434193323Sed  for (unsigned i = 0; i < args.size(); ++i)
435193323Sed    Args[i] = (char*)GVTOP(args[i]);
436193323Sed
437193323Sed  GenericValue GV;
438193323Sed  GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
439261991Sdim                    Args[5], Args[6], Args[7], Args[8], Args[9]));
440193323Sed  return GV;
441193323Sed}
442193323Sed
443193323Sed// int scanf(const char *format, ...);
444288943Sdimstatic GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
445193323Sed  assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
446193323Sed
447193323Sed  char *Args[10];
448193323Sed  for (unsigned i = 0; i < args.size(); ++i)
449193323Sed    Args[i] = (char*)GVTOP(args[i]);
450193323Sed
451193323Sed  GenericValue GV;
452193323Sed  GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
453261991Sdim                    Args[5], Args[6], Args[7], Args[8], Args[9]));
454193323Sed  return GV;
455193323Sed}
456193323Sed
457193323Sed// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
458193323Sed// output useful.
459288943Sdimstatic GenericValue lle_X_fprintf(FunctionType *FT,
460288943Sdim                                  ArrayRef<GenericValue> Args) {
461193323Sed  assert(Args.size() >= 2);
462193323Sed  char Buffer[10000];
463193323Sed  std::vector<GenericValue> NewArgs;
464193323Sed  NewArgs.push_back(PTOGV(Buffer));
465193323Sed  NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
466193323Sed  GenericValue GV = lle_X_sprintf(FT, NewArgs);
467193323Sed
468193323Sed  fputs(Buffer, (FILE *) GVTOP(Args[0]));
469193323Sed  return GV;
470193323Sed}
471193323Sed
472261991Sdimstatic GenericValue lle_X_memset(FunctionType *FT,
473288943Sdim                                 ArrayRef<GenericValue> Args) {
474261991Sdim  int val = (int)Args[1].IntVal.getSExtValue();
475261991Sdim  size_t len = (size_t)Args[2].IntVal.getZExtValue();
476261991Sdim  memset((void *)GVTOP(Args[0]), val, len);
477261991Sdim  // llvm.memset.* returns void, lle_X_* returns GenericValue,
478261991Sdim  // so here we return GenericValue with IntVal set to zero
479261991Sdim  GenericValue GV;
480261991Sdim  GV.IntVal = 0;
481261991Sdim  return GV;
482261991Sdim}
483261991Sdim
484261991Sdimstatic GenericValue lle_X_memcpy(FunctionType *FT,
485288943Sdim                                 ArrayRef<GenericValue> Args) {
486261991Sdim  memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
487261991Sdim         (size_t)(Args[2].IntVal.getLimitedValue()));
488261991Sdim
489261991Sdim  // llvm.memcpy* returns void, lle_X_* returns GenericValue,
490261991Sdim  // so here we return GenericValue with IntVal set to zero
491261991Sdim  GenericValue GV;
492261991Sdim  GV.IntVal = 0;
493261991Sdim  return GV;
494261991Sdim}
495261991Sdim
496193323Sedvoid Interpreter::initializeExternalFunctions() {
497198090Srdivacky  sys::ScopedLock Writer(*FunctionsLock);
498280031Sdim  (*FuncNames)["lle_X_atexit"]       = lle_X_atexit;
499280031Sdim  (*FuncNames)["lle_X_exit"]         = lle_X_exit;
500280031Sdim  (*FuncNames)["lle_X_abort"]        = lle_X_abort;
501193323Sed
502280031Sdim  (*FuncNames)["lle_X_printf"]       = lle_X_printf;
503280031Sdim  (*FuncNames)["lle_X_sprintf"]      = lle_X_sprintf;
504280031Sdim  (*FuncNames)["lle_X_sscanf"]       = lle_X_sscanf;
505280031Sdim  (*FuncNames)["lle_X_scanf"]        = lle_X_scanf;
506280031Sdim  (*FuncNames)["lle_X_fprintf"]      = lle_X_fprintf;
507280031Sdim  (*FuncNames)["lle_X_memset"]       = lle_X_memset;
508280031Sdim  (*FuncNames)["lle_X_memcpy"]       = lle_X_memcpy;
509193323Sed}
510