Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp
35271 views
//===-- ExternalFunctions.cpp - Implement External Functions --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains both code to deal with invoking "external" functions, but9// also contains code that implements "exported" external functions.10//11// There are currently two mechanisms for handling external functions in the12// Interpreter. The first is to implement lle_* wrapper functions that are13// specific to well-known library functions which manually translate the14// arguments from GenericValues and make the call. If such a wrapper does15// not exist, and libffi is available, then the Interpreter will attempt to16// invoke the function using libffi, after finding its address.17//18//===----------------------------------------------------------------------===//1920#include "Interpreter.h"21#include "llvm/ADT/APInt.h"22#include "llvm/ADT/ArrayRef.h"23#include "llvm/Config/config.h" // Detect libffi24#include "llvm/ExecutionEngine/GenericValue.h"25#include "llvm/IR/DataLayout.h"26#include "llvm/IR/DerivedTypes.h"27#include "llvm/IR/Function.h"28#include "llvm/IR/Type.h"29#include "llvm/Support/Casting.h"30#include "llvm/Support/DynamicLibrary.h"31#include "llvm/Support/ErrorHandling.h"32#include "llvm/Support/Mutex.h"33#include "llvm/Support/raw_ostream.h"34#include <cassert>35#include <cmath>36#include <csignal>37#include <cstdint>38#include <cstdio>39#include <cstring>40#include <map>41#include <mutex>42#include <string>43#include <utility>44#include <vector>4546#ifdef HAVE_FFI_CALL47#ifdef HAVE_FFI_H48#include <ffi.h>49#define USE_LIBFFI50#elif HAVE_FFI_FFI_H51#include <ffi/ffi.h>52#define USE_LIBFFI53#endif54#endif5556using namespace llvm;5758namespace {5960typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);61typedef void (*RawFunc)();6263struct Functions {64sys::Mutex Lock;65std::map<const Function *, ExFunc> ExportedFunctions;66std::map<std::string, ExFunc> FuncNames;67#ifdef USE_LIBFFI68std::map<const Function *, RawFunc> RawFunctions;69#endif70};7172Functions &getFunctions() {73static Functions F;74return F;75}7677} // anonymous namespace7879static Interpreter *TheInterpreter;8081static char getTypeID(Type *Ty) {82switch (Ty->getTypeID()) {83case Type::VoidTyID: return 'V';84case Type::IntegerTyID:85switch (cast<IntegerType>(Ty)->getBitWidth()) {86case 1: return 'o';87case 8: return 'B';88case 16: return 'S';89case 32: return 'I';90case 64: return 'L';91default: return 'N';92}93case Type::FloatTyID: return 'F';94case Type::DoubleTyID: return 'D';95case Type::PointerTyID: return 'P';96case Type::FunctionTyID:return 'M';97case Type::StructTyID: return 'T';98case Type::ArrayTyID: return 'A';99default: return 'U';100}101}102103// Try to find address of external function given a Function object.104// Please note, that interpreter doesn't know how to assemble a105// real call in general case (this is JIT job), that's why it assumes,106// that all external functions has the same (and pretty "general") signature.107// The typical example of such functions are "lle_X_" ones.108static ExFunc lookupFunction(const Function *F) {109// Function not found, look it up... start by figuring out what the110// composite function name should be.111std::string ExtName = "lle_";112FunctionType *FT = F->getFunctionType();113ExtName += getTypeID(FT->getReturnType());114for (Type *T : FT->params())115ExtName += getTypeID(T);116ExtName += ("_" + F->getName()).str();117118auto &Fns = getFunctions();119sys::ScopedLock Writer(Fns.Lock);120ExFunc FnPtr = Fns.FuncNames[ExtName];121if (!FnPtr)122FnPtr = Fns.FuncNames[("lle_X_" + F->getName()).str()];123if (!FnPtr) // Try calling a generic function... if it exists...124FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(125("lle_X_" + F->getName()).str());126if (FnPtr)127Fns.ExportedFunctions.insert(std::make_pair(F, FnPtr)); // Cache for later128return FnPtr;129}130131#ifdef USE_LIBFFI132static ffi_type *ffiTypeFor(Type *Ty) {133switch (Ty->getTypeID()) {134case Type::VoidTyID: return &ffi_type_void;135case Type::IntegerTyID:136switch (cast<IntegerType>(Ty)->getBitWidth()) {137case 8: return &ffi_type_sint8;138case 16: return &ffi_type_sint16;139case 32: return &ffi_type_sint32;140case 64: return &ffi_type_sint64;141}142llvm_unreachable("Unhandled integer type bitwidth");143case Type::FloatTyID: return &ffi_type_float;144case Type::DoubleTyID: return &ffi_type_double;145case Type::PointerTyID: return &ffi_type_pointer;146default: break;147}148// TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.149report_fatal_error("Type could not be mapped for use with libffi.");150return NULL;151}152153static void *ffiValueFor(Type *Ty, const GenericValue &AV,154void *ArgDataPtr) {155switch (Ty->getTypeID()) {156case Type::IntegerTyID:157switch (cast<IntegerType>(Ty)->getBitWidth()) {158case 8: {159int8_t *I8Ptr = (int8_t *) ArgDataPtr;160*I8Ptr = (int8_t) AV.IntVal.getZExtValue();161return ArgDataPtr;162}163case 16: {164int16_t *I16Ptr = (int16_t *) ArgDataPtr;165*I16Ptr = (int16_t) AV.IntVal.getZExtValue();166return ArgDataPtr;167}168case 32: {169int32_t *I32Ptr = (int32_t *) ArgDataPtr;170*I32Ptr = (int32_t) AV.IntVal.getZExtValue();171return ArgDataPtr;172}173case 64: {174int64_t *I64Ptr = (int64_t *) ArgDataPtr;175*I64Ptr = (int64_t) AV.IntVal.getZExtValue();176return ArgDataPtr;177}178}179llvm_unreachable("Unhandled integer type bitwidth");180case Type::FloatTyID: {181float *FloatPtr = (float *) ArgDataPtr;182*FloatPtr = AV.FloatVal;183return ArgDataPtr;184}185case Type::DoubleTyID: {186double *DoublePtr = (double *) ArgDataPtr;187*DoublePtr = AV.DoubleVal;188return ArgDataPtr;189}190case Type::PointerTyID: {191void **PtrPtr = (void **) ArgDataPtr;192*PtrPtr = GVTOP(AV);193return ArgDataPtr;194}195default: break;196}197// TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.198report_fatal_error("Type value could not be mapped for use with libffi.");199return NULL;200}201202static bool ffiInvoke(RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,203const DataLayout &TD, GenericValue &Result) {204ffi_cif cif;205FunctionType *FTy = F->getFunctionType();206const unsigned NumArgs = F->arg_size();207208// TODO: We don't have type information about the remaining arguments, because209// this information is never passed into ExecutionEngine::runFunction().210if (ArgVals.size() > NumArgs && F->isVarArg()) {211report_fatal_error("Calling external var arg function '" + F->getName()212+ "' is not supported by the Interpreter.");213}214215unsigned ArgBytes = 0;216217std::vector<ffi_type*> args(NumArgs);218for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();219A != E; ++A) {220const unsigned ArgNo = A->getArgNo();221Type *ArgTy = FTy->getParamType(ArgNo);222args[ArgNo] = ffiTypeFor(ArgTy);223ArgBytes += TD.getTypeStoreSize(ArgTy);224}225226SmallVector<uint8_t, 128> ArgData;227ArgData.resize(ArgBytes);228uint8_t *ArgDataPtr = ArgData.data();229SmallVector<void*, 16> values(NumArgs);230for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();231A != E; ++A) {232const unsigned ArgNo = A->getArgNo();233Type *ArgTy = FTy->getParamType(ArgNo);234values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);235ArgDataPtr += TD.getTypeStoreSize(ArgTy);236}237238Type *RetTy = FTy->getReturnType();239ffi_type *rtype = ffiTypeFor(RetTy);240241if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, args.data()) ==242FFI_OK) {243SmallVector<uint8_t, 128> ret;244if (RetTy->getTypeID() != Type::VoidTyID)245ret.resize(TD.getTypeStoreSize(RetTy));246ffi_call(&cif, Fn, ret.data(), values.data());247switch (RetTy->getTypeID()) {248case Type::IntegerTyID:249switch (cast<IntegerType>(RetTy)->getBitWidth()) {250case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;251case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;252case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;253case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;254}255break;256case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;257case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;258case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;259default: break;260}261return true;262}263264return false;265}266#endif // USE_LIBFFI267268GenericValue Interpreter::callExternalFunction(Function *F,269ArrayRef<GenericValue> ArgVals) {270TheInterpreter = this;271272auto &Fns = getFunctions();273std::unique_lock<sys::Mutex> Guard(Fns.Lock);274275// Do a lookup to see if the function is in our cache... this should just be a276// deferred annotation!277std::map<const Function *, ExFunc>::iterator FI =278Fns.ExportedFunctions.find(F);279if (ExFunc Fn = (FI == Fns.ExportedFunctions.end()) ? lookupFunction(F)280: FI->second) {281Guard.unlock();282return Fn(F->getFunctionType(), ArgVals);283}284285#ifdef USE_LIBFFI286std::map<const Function *, RawFunc>::iterator RF = Fns.RawFunctions.find(F);287RawFunc RawFn;288if (RF == Fns.RawFunctions.end()) {289RawFn = (RawFunc)(intptr_t)290sys::DynamicLibrary::SearchForAddressOfSymbol(std::string(F->getName()));291if (!RawFn)292RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);293if (RawFn != 0)294Fns.RawFunctions.insert(std::make_pair(F, RawFn)); // Cache for later295} else {296RawFn = RF->second;297}298299Guard.unlock();300301GenericValue Result;302if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))303return Result;304#endif // USE_LIBFFI305306if (F->getName() == "__main")307errs() << "Tried to execute an unknown external function: "308<< *F->getType() << " __main\n";309else310report_fatal_error("Tried to execute an unknown external function: " +311F->getName());312#ifndef USE_LIBFFI313errs() << "Recompiling LLVM with --enable-libffi might help.\n";314#endif315return GenericValue();316}317318//===----------------------------------------------------------------------===//319// Functions "exported" to the running application...320//321322// void atexit(Function*)323static GenericValue lle_X_atexit(FunctionType *FT,324ArrayRef<GenericValue> Args) {325assert(Args.size() == 1);326TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));327GenericValue GV;328GV.IntVal = 0;329return GV;330}331332// void exit(int)333static GenericValue lle_X_exit(FunctionType *FT, ArrayRef<GenericValue> Args) {334TheInterpreter->exitCalled(Args[0]);335return GenericValue();336}337338// void abort(void)339static GenericValue lle_X_abort(FunctionType *FT, ArrayRef<GenericValue> Args) {340//FIXME: should we report or raise here?341//report_fatal_error("Interpreted program raised SIGABRT");342raise (SIGABRT);343return GenericValue();344}345346// Silence warnings about sprintf. (See also347// https://github.com/llvm/llvm-project/issues/58086)348#if defined(__clang__)349#pragma clang diagnostic push350#pragma clang diagnostic ignored "-Wdeprecated-declarations"351#endif352// int sprintf(char *, const char *, ...) - a very rough implementation to make353// output useful.354static GenericValue lle_X_sprintf(FunctionType *FT,355ArrayRef<GenericValue> Args) {356char *OutputBuffer = (char *)GVTOP(Args[0]);357const char *FmtStr = (const char *)GVTOP(Args[1]);358unsigned ArgNo = 2;359360// printf should return # chars printed. This is completely incorrect, but361// close enough for now.362GenericValue GV;363GV.IntVal = APInt(32, strlen(FmtStr));364while (true) {365switch (*FmtStr) {366case 0: return GV; // Null terminator...367default: // Normal nonspecial character368sprintf(OutputBuffer++, "%c", *FmtStr++);369break;370case '\\': { // Handle escape codes371sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));372FmtStr += 2; OutputBuffer += 2;373break;374}375case '%': { // Handle format specifiers376char FmtBuf[100] = "", Buffer[1000] = "";377char *FB = FmtBuf;378*FB++ = *FmtStr++;379char Last = *FB++ = *FmtStr++;380unsigned HowLong = 0;381while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&382Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&383Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&384Last != 'p' && Last != 's' && Last != '%') {385if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's386Last = *FB++ = *FmtStr++;387}388*FB = 0;389390switch (Last) {391case '%':392memcpy(Buffer, "%", 2); break;393case 'c':394sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));395break;396case 'd': case 'i':397case 'u': case 'o':398case 'x': case 'X':399if (HowLong >= 1) {400if (HowLong == 1 &&401TheInterpreter->getDataLayout().getPointerSizeInBits() == 64 &&402sizeof(long) < sizeof(int64_t)) {403// Make sure we use %lld with a 64 bit argument because we might be404// compiling LLI on a 32 bit compiler.405unsigned Size = strlen(FmtBuf);406FmtBuf[Size] = FmtBuf[Size-1];407FmtBuf[Size+1] = 0;408FmtBuf[Size-1] = 'l';409}410sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());411} else412sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));413break;414case 'e': case 'E': case 'g': case 'G': case 'f':415sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;416case 'p':417sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;418case 's':419sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;420default:421errs() << "<unknown printf code '" << *FmtStr << "'!>";422ArgNo++; break;423}424size_t Len = strlen(Buffer);425memcpy(OutputBuffer, Buffer, Len + 1);426OutputBuffer += Len;427}428break;429}430}431return GV;432}433#if defined(__clang__)434#pragma clang diagnostic pop435#endif436437// int printf(const char *, ...) - a very rough implementation to make output438// useful.439static GenericValue lle_X_printf(FunctionType *FT,440ArrayRef<GenericValue> Args) {441char Buffer[10000];442std::vector<GenericValue> NewArgs;443NewArgs.push_back(PTOGV((void*)&Buffer[0]));444llvm::append_range(NewArgs, Args);445GenericValue GV = lle_X_sprintf(FT, NewArgs);446outs() << Buffer;447return GV;448}449450// int sscanf(const char *format, ...);451static GenericValue lle_X_sscanf(FunctionType *FT,452ArrayRef<GenericValue> args) {453assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");454455char *Args[10];456for (unsigned i = 0; i < args.size(); ++i)457Args[i] = (char*)GVTOP(args[i]);458459GenericValue GV;460GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],461Args[5], Args[6], Args[7], Args[8], Args[9]));462return GV;463}464465// int scanf(const char *format, ...);466static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef<GenericValue> args) {467assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");468469char *Args[10];470for (unsigned i = 0; i < args.size(); ++i)471Args[i] = (char*)GVTOP(args[i]);472473GenericValue GV;474GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],475Args[5], Args[6], Args[7], Args[8], Args[9]));476return GV;477}478479// int fprintf(FILE *, const char *, ...) - a very rough implementation to make480// output useful.481static GenericValue lle_X_fprintf(FunctionType *FT,482ArrayRef<GenericValue> Args) {483assert(Args.size() >= 2);484char Buffer[10000];485std::vector<GenericValue> NewArgs;486NewArgs.push_back(PTOGV(Buffer));487NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());488GenericValue GV = lle_X_sprintf(FT, NewArgs);489490fputs(Buffer, (FILE *) GVTOP(Args[0]));491return GV;492}493494static GenericValue lle_X_memset(FunctionType *FT,495ArrayRef<GenericValue> Args) {496int val = (int)Args[1].IntVal.getSExtValue();497size_t len = (size_t)Args[2].IntVal.getZExtValue();498memset((void *)GVTOP(Args[0]), val, len);499// llvm.memset.* returns void, lle_X_* returns GenericValue,500// so here we return GenericValue with IntVal set to zero501GenericValue GV;502GV.IntVal = 0;503return GV;504}505506static GenericValue lle_X_memcpy(FunctionType *FT,507ArrayRef<GenericValue> Args) {508memcpy(GVTOP(Args[0]), GVTOP(Args[1]),509(size_t)(Args[2].IntVal.getLimitedValue()));510511// llvm.memcpy* returns void, lle_X_* returns GenericValue,512// so here we return GenericValue with IntVal set to zero513GenericValue GV;514GV.IntVal = 0;515return GV;516}517518void Interpreter::initializeExternalFunctions() {519auto &Fns = getFunctions();520sys::ScopedLock Writer(Fns.Lock);521Fns.FuncNames["lle_X_atexit"] = lle_X_atexit;522Fns.FuncNames["lle_X_exit"] = lle_X_exit;523Fns.FuncNames["lle_X_abort"] = lle_X_abort;524525Fns.FuncNames["lle_X_printf"] = lle_X_printf;526Fns.FuncNames["lle_X_sprintf"] = lle_X_sprintf;527Fns.FuncNames["lle_X_sscanf"] = lle_X_sscanf;528Fns.FuncNames["lle_X_scanf"] = lle_X_scanf;529Fns.FuncNames["lle_X_fprintf"] = lle_X_fprintf;530Fns.FuncNames["lle_X_memset"] = lle_X_memset;531Fns.FuncNames["lle_X_memcpy"] = lle_X_memcpy;532}533534535