xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file contains both code to deal with invoking "external" functions, but
100b57cec5SDimitry Andric //  also contains code that implements "exported" external functions.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //  There are currently two mechanisms for handling external functions in the
130b57cec5SDimitry Andric //  Interpreter.  The first is to implement lle_* wrapper functions that are
140b57cec5SDimitry Andric //  specific to well-known library functions which manually translate the
150b57cec5SDimitry Andric //  arguments from GenericValues and make the call.  If such a wrapper does
160b57cec5SDimitry Andric //  not exist, and libffi is available, then the Interpreter will attempt to
170b57cec5SDimitry Andric //  invoke the function using libffi, after finding its address.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric #include "Interpreter.h"
220b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
230b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
240b57cec5SDimitry Andric #include "llvm/Config/config.h" // Detect libffi
250b57cec5SDimitry Andric #include "llvm/ExecutionEngine/GenericValue.h"
260b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
270b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
280b57cec5SDimitry Andric #include "llvm/IR/Function.h"
290b57cec5SDimitry Andric #include "llvm/IR/Type.h"
300b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
310b57cec5SDimitry Andric #include "llvm/Support/DynamicLibrary.h"
320b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
330b57cec5SDimitry Andric #include "llvm/Support/Mutex.h"
340b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
350b57cec5SDimitry Andric #include <cassert>
360b57cec5SDimitry Andric #include <cmath>
370b57cec5SDimitry Andric #include <csignal>
380b57cec5SDimitry Andric #include <cstdint>
390b57cec5SDimitry Andric #include <cstdio>
400b57cec5SDimitry Andric #include <cstring>
410b57cec5SDimitry Andric #include <map>
428bcb0991SDimitry Andric #include <mutex>
430b57cec5SDimitry Andric #include <string>
440b57cec5SDimitry Andric #include <utility>
450b57cec5SDimitry Andric #include <vector>
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric #ifdef HAVE_FFI_CALL
480b57cec5SDimitry Andric #ifdef HAVE_FFI_H
490b57cec5SDimitry Andric #include <ffi.h>
500b57cec5SDimitry Andric #define USE_LIBFFI
510b57cec5SDimitry Andric #elif HAVE_FFI_FFI_H
520b57cec5SDimitry Andric #include <ffi/ffi.h>
530b57cec5SDimitry Andric #define USE_LIBFFI
540b57cec5SDimitry Andric #endif
550b57cec5SDimitry Andric #endif
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric using namespace llvm;
580b57cec5SDimitry Andric 
59bdd1243dSDimitry Andric namespace {
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
620b57cec5SDimitry Andric typedef void (*RawFunc)();
63bdd1243dSDimitry Andric 
64bdd1243dSDimitry Andric struct Functions {
65bdd1243dSDimitry Andric   sys::Mutex Lock;
66bdd1243dSDimitry Andric   std::map<const Function *, ExFunc> ExportedFunctions;
67bdd1243dSDimitry Andric   std::map<std::string, ExFunc> FuncNames;
68bdd1243dSDimitry Andric #ifdef USE_LIBFFI
69bdd1243dSDimitry Andric   std::map<const Function *, RawFunc> RawFunctions;
700b57cec5SDimitry Andric #endif
71bdd1243dSDimitry Andric };
72bdd1243dSDimitry Andric 
getFunctions()73bdd1243dSDimitry Andric Functions &getFunctions() {
74bdd1243dSDimitry Andric   static Functions F;
75bdd1243dSDimitry Andric   return F;
76bdd1243dSDimitry Andric }
77bdd1243dSDimitry Andric 
78bdd1243dSDimitry Andric } // anonymous namespace
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric static Interpreter *TheInterpreter;
810b57cec5SDimitry Andric 
getTypeID(Type * Ty)820b57cec5SDimitry Andric static char getTypeID(Type *Ty) {
830b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
840b57cec5SDimitry Andric   case Type::VoidTyID:    return 'V';
850b57cec5SDimitry Andric   case Type::IntegerTyID:
860b57cec5SDimitry Andric     switch (cast<IntegerType>(Ty)->getBitWidth()) {
870b57cec5SDimitry Andric       case 1:  return 'o';
880b57cec5SDimitry Andric       case 8:  return 'B';
890b57cec5SDimitry Andric       case 16: return 'S';
900b57cec5SDimitry Andric       case 32: return 'I';
910b57cec5SDimitry Andric       case 64: return 'L';
920b57cec5SDimitry Andric       default: return 'N';
930b57cec5SDimitry Andric     }
940b57cec5SDimitry Andric   case Type::FloatTyID:   return 'F';
950b57cec5SDimitry Andric   case Type::DoubleTyID:  return 'D';
960b57cec5SDimitry Andric   case Type::PointerTyID: return 'P';
970b57cec5SDimitry Andric   case Type::FunctionTyID:return 'M';
980b57cec5SDimitry Andric   case Type::StructTyID:  return 'T';
990b57cec5SDimitry Andric   case Type::ArrayTyID:   return 'A';
1000b57cec5SDimitry Andric   default: return 'U';
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric // Try to find address of external function given a Function object.
1050b57cec5SDimitry Andric // Please note, that interpreter doesn't know how to assemble a
1060b57cec5SDimitry Andric // real call in general case (this is JIT job), that's why it assumes,
1070b57cec5SDimitry Andric // that all external functions has the same (and pretty "general") signature.
1080b57cec5SDimitry Andric // The typical example of such functions are "lle_X_" ones.
lookupFunction(const Function * F)1090b57cec5SDimitry Andric static ExFunc lookupFunction(const Function *F) {
1100b57cec5SDimitry Andric   // Function not found, look it up... start by figuring out what the
1110b57cec5SDimitry Andric   // composite function name should be.
1120b57cec5SDimitry Andric   std::string ExtName = "lle_";
1130b57cec5SDimitry Andric   FunctionType *FT = F->getFunctionType();
1140b57cec5SDimitry Andric   ExtName += getTypeID(FT->getReturnType());
1150b57cec5SDimitry Andric   for (Type *T : FT->params())
1160b57cec5SDimitry Andric     ExtName += getTypeID(T);
1170b57cec5SDimitry Andric   ExtName += ("_" + F->getName()).str();
1180b57cec5SDimitry Andric 
119bdd1243dSDimitry Andric   auto &Fns = getFunctions();
120bdd1243dSDimitry Andric   sys::ScopedLock Writer(Fns.Lock);
121bdd1243dSDimitry Andric   ExFunc FnPtr = Fns.FuncNames[ExtName];
1220b57cec5SDimitry Andric   if (!FnPtr)
123bdd1243dSDimitry Andric     FnPtr = Fns.FuncNames[("lle_X_" + F->getName()).str()];
1240b57cec5SDimitry Andric   if (!FnPtr)  // Try calling a generic function... if it exists...
1250b57cec5SDimitry Andric     FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
1260b57cec5SDimitry Andric         ("lle_X_" + F->getName()).str());
1270b57cec5SDimitry Andric   if (FnPtr)
128bdd1243dSDimitry Andric     Fns.ExportedFunctions.insert(std::make_pair(F, FnPtr)); // Cache for later
1290b57cec5SDimitry Andric   return FnPtr;
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric #ifdef USE_LIBFFI
ffiTypeFor(Type * Ty)1330b57cec5SDimitry Andric static ffi_type *ffiTypeFor(Type *Ty) {
1340b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
1350b57cec5SDimitry Andric     case Type::VoidTyID: return &ffi_type_void;
1360b57cec5SDimitry Andric     case Type::IntegerTyID:
1370b57cec5SDimitry Andric       switch (cast<IntegerType>(Ty)->getBitWidth()) {
1380b57cec5SDimitry Andric         case 8:  return &ffi_type_sint8;
1390b57cec5SDimitry Andric         case 16: return &ffi_type_sint16;
1400b57cec5SDimitry Andric         case 32: return &ffi_type_sint32;
1410b57cec5SDimitry Andric         case 64: return &ffi_type_sint64;
1420b57cec5SDimitry Andric       }
143fe6060f1SDimitry Andric       llvm_unreachable("Unhandled integer type bitwidth");
1440b57cec5SDimitry Andric     case Type::FloatTyID:   return &ffi_type_float;
1450b57cec5SDimitry Andric     case Type::DoubleTyID:  return &ffi_type_double;
1460b57cec5SDimitry Andric     case Type::PointerTyID: return &ffi_type_pointer;
1470b57cec5SDimitry Andric     default: break;
1480b57cec5SDimitry Andric   }
1490b57cec5SDimitry Andric   // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
1500b57cec5SDimitry Andric   report_fatal_error("Type could not be mapped for use with libffi.");
1510b57cec5SDimitry Andric   return NULL;
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
ffiValueFor(Type * Ty,const GenericValue & AV,void * ArgDataPtr)1540b57cec5SDimitry Andric static void *ffiValueFor(Type *Ty, const GenericValue &AV,
1550b57cec5SDimitry Andric                          void *ArgDataPtr) {
1560b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
1570b57cec5SDimitry Andric     case Type::IntegerTyID:
1580b57cec5SDimitry Andric       switch (cast<IntegerType>(Ty)->getBitWidth()) {
1590b57cec5SDimitry Andric         case 8: {
1600b57cec5SDimitry Andric           int8_t *I8Ptr = (int8_t *) ArgDataPtr;
1610b57cec5SDimitry Andric           *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
1620b57cec5SDimitry Andric           return ArgDataPtr;
1630b57cec5SDimitry Andric         }
1640b57cec5SDimitry Andric         case 16: {
1650b57cec5SDimitry Andric           int16_t *I16Ptr = (int16_t *) ArgDataPtr;
1660b57cec5SDimitry Andric           *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
1670b57cec5SDimitry Andric           return ArgDataPtr;
1680b57cec5SDimitry Andric         }
1690b57cec5SDimitry Andric         case 32: {
1700b57cec5SDimitry Andric           int32_t *I32Ptr = (int32_t *) ArgDataPtr;
1710b57cec5SDimitry Andric           *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
1720b57cec5SDimitry Andric           return ArgDataPtr;
1730b57cec5SDimitry Andric         }
1740b57cec5SDimitry Andric         case 64: {
1750b57cec5SDimitry Andric           int64_t *I64Ptr = (int64_t *) ArgDataPtr;
1760b57cec5SDimitry Andric           *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
1770b57cec5SDimitry Andric           return ArgDataPtr;
1780b57cec5SDimitry Andric         }
1790b57cec5SDimitry Andric       }
180fe6060f1SDimitry Andric       llvm_unreachable("Unhandled integer type bitwidth");
1810b57cec5SDimitry Andric     case Type::FloatTyID: {
1820b57cec5SDimitry Andric       float *FloatPtr = (float *) ArgDataPtr;
1830b57cec5SDimitry Andric       *FloatPtr = AV.FloatVal;
1840b57cec5SDimitry Andric       return ArgDataPtr;
1850b57cec5SDimitry Andric     }
1860b57cec5SDimitry Andric     case Type::DoubleTyID: {
1870b57cec5SDimitry Andric       double *DoublePtr = (double *) ArgDataPtr;
1880b57cec5SDimitry Andric       *DoublePtr = AV.DoubleVal;
1890b57cec5SDimitry Andric       return ArgDataPtr;
1900b57cec5SDimitry Andric     }
1910b57cec5SDimitry Andric     case Type::PointerTyID: {
1920b57cec5SDimitry Andric       void **PtrPtr = (void **) ArgDataPtr;
1930b57cec5SDimitry Andric       *PtrPtr = GVTOP(AV);
1940b57cec5SDimitry Andric       return ArgDataPtr;
1950b57cec5SDimitry Andric     }
1960b57cec5SDimitry Andric     default: break;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric   // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
1990b57cec5SDimitry Andric   report_fatal_error("Type value could not be mapped for use with libffi.");
2000b57cec5SDimitry Andric   return NULL;
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
ffiInvoke(RawFunc Fn,Function * F,ArrayRef<GenericValue> ArgVals,const DataLayout & TD,GenericValue & Result)2030b57cec5SDimitry Andric static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
2040b57cec5SDimitry Andric                       const DataLayout &TD, GenericValue &Result) {
2050b57cec5SDimitry Andric   ffi_cif cif;
2060b57cec5SDimitry Andric   FunctionType *FTy = F->getFunctionType();
2070b57cec5SDimitry Andric   const unsigned NumArgs = F->arg_size();
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // TODO: We don't have type information about the remaining arguments, because
2100b57cec5SDimitry Andric   // this information is never passed into ExecutionEngine::runFunction().
2110b57cec5SDimitry Andric   if (ArgVals.size() > NumArgs && F->isVarArg()) {
2120b57cec5SDimitry Andric     report_fatal_error("Calling external var arg function '" + F->getName()
2130b57cec5SDimitry Andric                       + "' is not supported by the Interpreter.");
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   unsigned ArgBytes = 0;
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   std::vector<ffi_type*> args(NumArgs);
2190b57cec5SDimitry Andric   for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
2200b57cec5SDimitry Andric        A != E; ++A) {
2210b57cec5SDimitry Andric     const unsigned ArgNo = A->getArgNo();
2220b57cec5SDimitry Andric     Type *ArgTy = FTy->getParamType(ArgNo);
2230b57cec5SDimitry Andric     args[ArgNo] = ffiTypeFor(ArgTy);
2240b57cec5SDimitry Andric     ArgBytes += TD.getTypeStoreSize(ArgTy);
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   SmallVector<uint8_t, 128> ArgData;
2280b57cec5SDimitry Andric   ArgData.resize(ArgBytes);
2290b57cec5SDimitry Andric   uint8_t *ArgDataPtr = ArgData.data();
2300b57cec5SDimitry Andric   SmallVector<void*, 16> values(NumArgs);
2310b57cec5SDimitry Andric   for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
2320b57cec5SDimitry Andric        A != E; ++A) {
2330b57cec5SDimitry Andric     const unsigned ArgNo = A->getArgNo();
2340b57cec5SDimitry Andric     Type *ArgTy = FTy->getParamType(ArgNo);
2350b57cec5SDimitry Andric     values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
2360b57cec5SDimitry Andric     ArgDataPtr += TD.getTypeStoreSize(ArgTy);
2370b57cec5SDimitry Andric   }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   Type *RetTy = FTy->getReturnType();
2400b57cec5SDimitry Andric   ffi_type *rtype = ffiTypeFor(RetTy);
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, args.data()) ==
2430b57cec5SDimitry Andric       FFI_OK) {
2440b57cec5SDimitry Andric     SmallVector<uint8_t, 128> ret;
2450b57cec5SDimitry Andric     if (RetTy->getTypeID() != Type::VoidTyID)
2460b57cec5SDimitry Andric       ret.resize(TD.getTypeStoreSize(RetTy));
2470b57cec5SDimitry Andric     ffi_call(&cif, Fn, ret.data(), values.data());
2480b57cec5SDimitry Andric     switch (RetTy->getTypeID()) {
2490b57cec5SDimitry Andric       case Type::IntegerTyID:
2500b57cec5SDimitry Andric         switch (cast<IntegerType>(RetTy)->getBitWidth()) {
2510b57cec5SDimitry Andric           case 8:  Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
2520b57cec5SDimitry Andric           case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
2530b57cec5SDimitry Andric           case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
2540b57cec5SDimitry Andric           case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
2550b57cec5SDimitry Andric         }
2560b57cec5SDimitry Andric         break;
2570b57cec5SDimitry Andric       case Type::FloatTyID:   Result.FloatVal   = *(float *) ret.data(); break;
2580b57cec5SDimitry Andric       case Type::DoubleTyID:  Result.DoubleVal  = *(double*) ret.data(); break;
2590b57cec5SDimitry Andric       case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
2600b57cec5SDimitry Andric       default: break;
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric     return true;
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   return false;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric #endif // USE_LIBFFI
2680b57cec5SDimitry Andric 
callExternalFunction(Function * F,ArrayRef<GenericValue> ArgVals)2690b57cec5SDimitry Andric GenericValue Interpreter::callExternalFunction(Function *F,
2700b57cec5SDimitry Andric                                                ArrayRef<GenericValue> ArgVals) {
2710b57cec5SDimitry Andric   TheInterpreter = this;
2720b57cec5SDimitry Andric 
273bdd1243dSDimitry Andric   auto &Fns = getFunctions();
274bdd1243dSDimitry Andric   std::unique_lock<sys::Mutex> Guard(Fns.Lock);
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   // Do a lookup to see if the function is in our cache... this should just be a
2770b57cec5SDimitry Andric   // deferred annotation!
278bdd1243dSDimitry Andric   std::map<const Function *, ExFunc>::iterator FI =
279bdd1243dSDimitry Andric       Fns.ExportedFunctions.find(F);
280bdd1243dSDimitry Andric   if (ExFunc Fn = (FI == Fns.ExportedFunctions.end()) ? lookupFunction(F)
2810b57cec5SDimitry Andric                                                       : FI->second) {
2820b57cec5SDimitry Andric     Guard.unlock();
2830b57cec5SDimitry Andric     return Fn(F->getFunctionType(), ArgVals);
2840b57cec5SDimitry Andric   }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric #ifdef USE_LIBFFI
287bdd1243dSDimitry Andric   std::map<const Function *, RawFunc>::iterator RF = Fns.RawFunctions.find(F);
2880b57cec5SDimitry Andric   RawFunc RawFn;
289bdd1243dSDimitry Andric   if (RF == Fns.RawFunctions.end()) {
2900b57cec5SDimitry Andric     RawFn = (RawFunc)(intptr_t)
2915ffd83dbSDimitry Andric       sys::DynamicLibrary::SearchForAddressOfSymbol(std::string(F->getName()));
2920b57cec5SDimitry Andric     if (!RawFn)
2930b57cec5SDimitry Andric       RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
2940b57cec5SDimitry Andric     if (RawFn != 0)
295bdd1243dSDimitry Andric       Fns.RawFunctions.insert(std::make_pair(F, RawFn)); // Cache for later
2960b57cec5SDimitry Andric   } else {
2970b57cec5SDimitry Andric     RawFn = RF->second;
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   Guard.unlock();
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   GenericValue Result;
3030b57cec5SDimitry Andric   if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
3040b57cec5SDimitry Andric     return Result;
3050b57cec5SDimitry Andric #endif // USE_LIBFFI
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   if (F->getName() == "__main")
3080b57cec5SDimitry Andric     errs() << "Tried to execute an unknown external function: "
3090b57cec5SDimitry Andric       << *F->getType() << " __main\n";
3100b57cec5SDimitry Andric   else
3110b57cec5SDimitry Andric     report_fatal_error("Tried to execute an unknown external function: " +
3120b57cec5SDimitry Andric                        F->getName());
3130b57cec5SDimitry Andric #ifndef USE_LIBFFI
3140b57cec5SDimitry Andric   errs() << "Recompiling LLVM with --enable-libffi might help.\n";
3150b57cec5SDimitry Andric #endif
3160b57cec5SDimitry Andric   return GenericValue();
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3200b57cec5SDimitry Andric //  Functions "exported" to the running application...
3210b57cec5SDimitry Andric //
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric // void atexit(Function*)
lle_X_atexit(FunctionType * FT,ArrayRef<GenericValue> Args)3240b57cec5SDimitry Andric static GenericValue lle_X_atexit(FunctionType *FT,
3250b57cec5SDimitry Andric                                  ArrayRef<GenericValue> Args) {
3260b57cec5SDimitry Andric   assert(Args.size() == 1);
3270b57cec5SDimitry Andric   TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
3280b57cec5SDimitry Andric   GenericValue GV;
3290b57cec5SDimitry Andric   GV.IntVal = 0;
3300b57cec5SDimitry Andric   return GV;
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric // void exit(int)
lle_X_exit(FunctionType * FT,ArrayRef<GenericValue> Args)3340b57cec5SDimitry Andric static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {
3350b57cec5SDimitry Andric   TheInterpreter->exitCalled(Args[0]);
3360b57cec5SDimitry Andric   return GenericValue();
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric // void abort(void)
lle_X_abort(FunctionType * FT,ArrayRef<GenericValue> Args)3400b57cec5SDimitry Andric static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {
3410b57cec5SDimitry Andric   //FIXME: should we report or raise here?
3420b57cec5SDimitry Andric   //report_fatal_error("Interpreted program raised SIGABRT");
3430b57cec5SDimitry Andric   raise (SIGABRT);
3440b57cec5SDimitry Andric   return GenericValue();
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric 
347*06c3fb27SDimitry Andric // Silence warnings about sprintf. (See also
348*06c3fb27SDimitry Andric // https://github.com/llvm/llvm-project/issues/58086)
349*06c3fb27SDimitry Andric #if defined(__clang__)
350*06c3fb27SDimitry Andric #pragma clang diagnostic push
351*06c3fb27SDimitry Andric #pragma clang diagnostic ignored "-Wdeprecated-declarations"
352*06c3fb27SDimitry Andric #endif
3530b57cec5SDimitry Andric // int sprintf(char *, const char *, ...) - a very rough implementation to make
3540b57cec5SDimitry Andric // output useful.
lle_X_sprintf(FunctionType * FT,ArrayRef<GenericValue> Args)3550b57cec5SDimitry Andric static GenericValue lle_X_sprintf(FunctionType *FT,
3560b57cec5SDimitry Andric                                   ArrayRef<GenericValue> Args) {
3570b57cec5SDimitry Andric   char *OutputBuffer = (char *)GVTOP(Args[0]);
3580b57cec5SDimitry Andric   const char *FmtStr = (const char *)GVTOP(Args[1]);
3590b57cec5SDimitry Andric   unsigned ArgNo = 2;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // printf should return # chars printed.  This is completely incorrect, but
3620b57cec5SDimitry Andric   // close enough for now.
3630b57cec5SDimitry Andric   GenericValue GV;
3640b57cec5SDimitry Andric   GV.IntVal = APInt(32, strlen(FmtStr));
3650b57cec5SDimitry Andric   while (true) {
3660b57cec5SDimitry Andric     switch (*FmtStr) {
3670b57cec5SDimitry Andric     case 0: return GV;             // Null terminator...
3680b57cec5SDimitry Andric     default:                       // Normal nonspecial character
3690b57cec5SDimitry Andric       sprintf(OutputBuffer++, "%c", *FmtStr++);
3700b57cec5SDimitry Andric       break;
3710b57cec5SDimitry Andric     case '\\': {                   // Handle escape codes
3720b57cec5SDimitry Andric       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
3730b57cec5SDimitry Andric       FmtStr += 2; OutputBuffer += 2;
3740b57cec5SDimitry Andric       break;
3750b57cec5SDimitry Andric     }
3760b57cec5SDimitry Andric     case '%': {                    // Handle format specifiers
3770b57cec5SDimitry Andric       char FmtBuf[100] = "", Buffer[1000] = "";
3780b57cec5SDimitry Andric       char *FB = FmtBuf;
3790b57cec5SDimitry Andric       *FB++ = *FmtStr++;
3800b57cec5SDimitry Andric       char Last = *FB++ = *FmtStr++;
3810b57cec5SDimitry Andric       unsigned HowLong = 0;
3820b57cec5SDimitry Andric       while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
3830b57cec5SDimitry Andric              Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
3840b57cec5SDimitry Andric              Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
3850b57cec5SDimitry Andric              Last != 'p' && Last != 's' && Last != '%') {
3860b57cec5SDimitry Andric         if (Last == 'l' || Last == 'L') HowLong++;  // Keep track of l's
3870b57cec5SDimitry Andric         Last = *FB++ = *FmtStr++;
3880b57cec5SDimitry Andric       }
3890b57cec5SDimitry Andric       *FB = 0;
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric       switch (Last) {
3920b57cec5SDimitry Andric       case '%':
3930b57cec5SDimitry Andric         memcpy(Buffer, "%", 2); break;
3940b57cec5SDimitry Andric       case 'c':
3950b57cec5SDimitry Andric         sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
3960b57cec5SDimitry Andric         break;
3970b57cec5SDimitry Andric       case 'd': case 'i':
3980b57cec5SDimitry Andric       case 'u': case 'o':
3990b57cec5SDimitry Andric       case 'x': case 'X':
4000b57cec5SDimitry Andric         if (HowLong >= 1) {
4010b57cec5SDimitry Andric           if (HowLong == 1 &&
4020b57cec5SDimitry Andric               TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&
4030b57cec5SDimitry Andric               sizeof(long) < sizeof(int64_t)) {
4040b57cec5SDimitry Andric             // Make sure we use %lld with a 64 bit argument because we might be
4050b57cec5SDimitry Andric             // compiling LLI on a 32 bit compiler.
4060b57cec5SDimitry Andric             unsigned Size = strlen(FmtBuf);
4070b57cec5SDimitry Andric             FmtBuf[Size] = FmtBuf[Size-1];
4080b57cec5SDimitry Andric             FmtBuf[Size+1] = 0;
4090b57cec5SDimitry Andric             FmtBuf[Size-1] = 'l';
4100b57cec5SDimitry Andric           }
4110b57cec5SDimitry Andric           sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
4120b57cec5SDimitry Andric         } else
4130b57cec5SDimitry Andric           sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
4140b57cec5SDimitry Andric         break;
4150b57cec5SDimitry Andric       case 'e': case 'E': case 'g': case 'G': case 'f':
4160b57cec5SDimitry Andric         sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
4170b57cec5SDimitry Andric       case 'p':
4180b57cec5SDimitry Andric         sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
4190b57cec5SDimitry Andric       case 's':
4200b57cec5SDimitry Andric         sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
4210b57cec5SDimitry Andric       default:
4220b57cec5SDimitry Andric         errs() << "<unknown printf code '" << *FmtStr << "'!>";
4230b57cec5SDimitry Andric         ArgNo++; break;
4240b57cec5SDimitry Andric       }
4250b57cec5SDimitry Andric       size_t Len = strlen(Buffer);
4260b57cec5SDimitry Andric       memcpy(OutputBuffer, Buffer, Len + 1);
4270b57cec5SDimitry Andric       OutputBuffer += Len;
4280b57cec5SDimitry Andric       }
4290b57cec5SDimitry Andric       break;
4300b57cec5SDimitry Andric     }
4310b57cec5SDimitry Andric   }
4320b57cec5SDimitry Andric   return GV;
4330b57cec5SDimitry Andric }
434*06c3fb27SDimitry Andric #if defined(__clang__)
435*06c3fb27SDimitry Andric #pragma clang diagnostic pop
436*06c3fb27SDimitry Andric #endif
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric // int printf(const char *, ...) - a very rough implementation to make output
4390b57cec5SDimitry Andric // useful.
lle_X_printf(FunctionType * FT,ArrayRef<GenericValue> Args)4400b57cec5SDimitry Andric static GenericValue lle_X_printf(FunctionType *FT,
4410b57cec5SDimitry Andric                                  ArrayRef<GenericValue> Args) {
4420b57cec5SDimitry Andric   char Buffer[10000];
4430b57cec5SDimitry Andric   std::vector<GenericValue> NewArgs;
4440b57cec5SDimitry Andric   NewArgs.push_back(PTOGV((void*)&Buffer[0]));
445e8d8bef9SDimitry Andric   llvm::append_range(NewArgs, Args);
4460b57cec5SDimitry Andric   GenericValue GV = lle_X_sprintf(FT, NewArgs);
4470b57cec5SDimitry Andric   outs() << Buffer;
4480b57cec5SDimitry Andric   return GV;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric // int sscanf(const char *format, ...);
lle_X_sscanf(FunctionType * FT,ArrayRef<GenericValue> args)4520b57cec5SDimitry Andric static GenericValue lle_X_sscanf(FunctionType *FT,
4530b57cec5SDimitry Andric                                  ArrayRef<GenericValue> args) {
4540b57cec5SDimitry Andric   assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   char *Args[10];
4570b57cec5SDimitry Andric   for (unsigned i = 0; i < args.size(); ++i)
4580b57cec5SDimitry Andric     Args[i] = (char*)GVTOP(args[i]);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   GenericValue GV;
4610b57cec5SDimitry Andric   GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
4620b57cec5SDimitry Andric                     Args[5], Args[6], Args[7], Args[8], Args[9]));
4630b57cec5SDimitry Andric   return GV;
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric // int scanf(const char *format, ...);
lle_X_scanf(FunctionType * FT,ArrayRef<GenericValue> args)4670b57cec5SDimitry Andric static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {
4680b57cec5SDimitry Andric   assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   char *Args[10];
4710b57cec5SDimitry Andric   for (unsigned i = 0; i < args.size(); ++i)
4720b57cec5SDimitry Andric     Args[i] = (char*)GVTOP(args[i]);
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   GenericValue GV;
4750b57cec5SDimitry Andric   GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
4760b57cec5SDimitry Andric                     Args[5], Args[6], Args[7], Args[8], Args[9]));
4770b57cec5SDimitry Andric   return GV;
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric // int fprintf(FILE *, const char *, ...) - a very rough implementation to make
4810b57cec5SDimitry Andric // output useful.
lle_X_fprintf(FunctionType * FT,ArrayRef<GenericValue> Args)4820b57cec5SDimitry Andric static GenericValue lle_X_fprintf(FunctionType *FT,
4830b57cec5SDimitry Andric                                   ArrayRef<GenericValue> Args) {
4840b57cec5SDimitry Andric   assert(Args.size() >= 2);
4850b57cec5SDimitry Andric   char Buffer[10000];
4860b57cec5SDimitry Andric   std::vector<GenericValue> NewArgs;
4870b57cec5SDimitry Andric   NewArgs.push_back(PTOGV(Buffer));
4880b57cec5SDimitry Andric   NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
4890b57cec5SDimitry Andric   GenericValue GV = lle_X_sprintf(FT, NewArgs);
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   fputs(Buffer, (FILE *) GVTOP(Args[0]));
4920b57cec5SDimitry Andric   return GV;
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric 
lle_X_memset(FunctionType * FT,ArrayRef<GenericValue> Args)4950b57cec5SDimitry Andric static GenericValue lle_X_memset(FunctionType *FT,
4960b57cec5SDimitry Andric                                  ArrayRef<GenericValue> Args) {
4970b57cec5SDimitry Andric   int val = (int)Args[1].IntVal.getSExtValue();
4980b57cec5SDimitry Andric   size_t len = (size_t)Args[2].IntVal.getZExtValue();
4990b57cec5SDimitry Andric   memset((void *)GVTOP(Args[0]), val, len);
5000b57cec5SDimitry Andric   // llvm.memset.* returns void, lle_X_* returns GenericValue,
5010b57cec5SDimitry Andric   // so here we return GenericValue with IntVal set to zero
5020b57cec5SDimitry Andric   GenericValue GV;
5030b57cec5SDimitry Andric   GV.IntVal = 0;
5040b57cec5SDimitry Andric   return GV;
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric 
lle_X_memcpy(FunctionType * FT,ArrayRef<GenericValue> Args)5070b57cec5SDimitry Andric static GenericValue lle_X_memcpy(FunctionType *FT,
5080b57cec5SDimitry Andric                                  ArrayRef<GenericValue> Args) {
5090b57cec5SDimitry Andric   memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
5100b57cec5SDimitry Andric          (size_t)(Args[2].IntVal.getLimitedValue()));
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // llvm.memcpy* returns void, lle_X_* returns GenericValue,
5130b57cec5SDimitry Andric   // so here we return GenericValue with IntVal set to zero
5140b57cec5SDimitry Andric   GenericValue GV;
5150b57cec5SDimitry Andric   GV.IntVal = 0;
5160b57cec5SDimitry Andric   return GV;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
initializeExternalFunctions()5190b57cec5SDimitry Andric void Interpreter::initializeExternalFunctions() {
520bdd1243dSDimitry Andric   auto &Fns = getFunctions();
521bdd1243dSDimitry Andric   sys::ScopedLock Writer(Fns.Lock);
522bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_atexit"]       = lle_X_atexit;
523bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_exit"]         = lle_X_exit;
524bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_abort"]        = lle_X_abort;
5250b57cec5SDimitry Andric 
526bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_printf"]       = lle_X_printf;
527bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_sprintf"]      = lle_X_sprintf;
528bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_sscanf"]       = lle_X_sscanf;
529bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_scanf"]        = lle_X_scanf;
530bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_fprintf"]      = lle_X_fprintf;
531bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_memset"]       = lle_X_memset;
532bdd1243dSDimitry Andric   Fns.FuncNames["lle_X_memcpy"]       = lle_X_memcpy;
5330b57cec5SDimitry Andric }
534