ExternalFunctions.cpp revision 26e6e109d559fb644b59231c14346997290dc9d6
1//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file contains both code to deal with invoking "external" functions, but
11//  also contains code that implements "exported" external functions.
12//
13//  External functions in the interpreter are implemented by
14//  using the system's dynamic loader to look up the address of the function
15//  we want to invoke.  If a function is found, then one of the
16//  many lle_* wrapper functions in this file will translate its arguments from
17//  GenericValues to the types the function is actually expecting, before the
18//  function is called.
19//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
25#include "llvm/System/DynamicLibrary.h"
26#include "llvm/Target/TargetData.h"
27#include <cmath>
28#include <csignal>
29#include <map>
30using std::vector;
31
32using namespace llvm;
33
34typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
35static std::map<const Function *, ExFunc> Functions;
36static std::map<std::string, ExFunc> FuncNames;
37
38static Interpreter *TheInterpreter;
39
40static char getTypeID(const Type *Ty) {
41  switch (Ty->getTypeID()) {
42  case Type::VoidTyID:    return 'V';
43  case Type::BoolTyID:    return 'o';
44  case Type::UByteTyID:   return 'B';
45  case Type::SByteTyID:   return 'b';
46  case Type::UShortTyID:  return 'S';
47  case Type::ShortTyID:   return 's';
48  case Type::UIntTyID:    return 'I';
49  case Type::IntTyID:     return 'i';
50  case Type::ULongTyID:   return 'L';
51  case Type::LongTyID:    return 'l';
52  case Type::FloatTyID:   return 'F';
53  case Type::DoubleTyID:  return 'D';
54  case Type::PointerTyID: return 'P';
55  case Type::FunctionTyID:  return 'M';
56  case Type::StructTyID:  return 'T';
57  case Type::ArrayTyID:   return 'A';
58  case Type::OpaqueTyID:  return 'O';
59  default: return 'U';
60  }
61}
62
63static ExFunc lookupFunction(const Function *F) {
64  // Function not found, look it up... start by figuring out what the
65  // composite function name should be.
66  std::string ExtName = "lle_";
67  const FunctionType *FT = F->getFunctionType();
68  for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
69    ExtName += getTypeID(FT->getContainedType(i));
70  ExtName += "_" + F->getName();
71
72  ExFunc FnPtr = FuncNames[ExtName];
73  if (FnPtr == 0)
74    FnPtr =
75      (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(ExtName);
76  if (FnPtr == 0)
77    FnPtr = FuncNames["lle_X_"+F->getName()];
78  if (FnPtr == 0)  // Try calling a generic function... if it exists...
79    FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
80            ("lle_X_"+F->getName()).c_str());
81  if (FnPtr != 0)
82    Functions.insert(std::make_pair(F, FnPtr));  // Cache for later
83  return FnPtr;
84}
85
86GenericValue Interpreter::callExternalFunction(Function *F,
87                                     const std::vector<GenericValue> &ArgVals) {
88  TheInterpreter = this;
89
90  // Do a lookup to see if the function is in our cache... this should just be a
91  // deferred annotation!
92  std::map<const Function *, ExFunc>::iterator FI = Functions.find(F);
93  ExFunc Fn = (FI == Functions.end()) ? lookupFunction(F) : FI->second;
94  if (Fn == 0) {
95    std::cout << "Tried to execute an unknown external function: "
96              << F->getType()->getDescription() << " " << F->getName() << "\n";
97    if (F->getName() == "__main")
98      return GenericValue();
99    abort();
100  }
101
102  // TODO: FIXME when types are not const!
103  GenericValue Result = Fn(const_cast<FunctionType*>(F->getFunctionType()),
104                           ArgVals);
105  return Result;
106}
107
108
109//===----------------------------------------------------------------------===//
110//  Functions "exported" to the running application...
111//
112extern "C" {  // Don't add C++ manglings to llvm mangling :)
113
114// void putchar(sbyte)
115GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
116  std::cout << Args[0].SByteVal;
117  return GenericValue();
118}
119
120// int putchar(int)
121GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
122  std::cout << ((char)Args[0].IntVal) << std::flush;
123  return Args[0];
124}
125
126// void putchar(ubyte)
127GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
128  std::cout << Args[0].SByteVal << std::flush;
129  return Args[0];
130}
131
132// void atexit(Function*)
133GenericValue lle_X_atexit(FunctionType *M, const vector<GenericValue> &Args) {
134  assert(Args.size() == 1);
135  TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
136  GenericValue GV;
137  GV.IntVal = 0;
138  return GV;
139}
140
141// void exit(int)
142GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
143  TheInterpreter->exitCalled(Args[0]);
144  return GenericValue();
145}
146
147// void abort(void)
148GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
149  raise (SIGABRT);
150  return GenericValue();
151}
152
153// void *malloc(uint)
154GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
155  assert(Args.size() == 1 && "Malloc expects one argument!");
156  return PTOGV(malloc(Args[0].UIntVal));
157}
158
159// void *calloc(uint, uint)
160GenericValue lle_X_calloc(FunctionType *M, const vector<GenericValue> &Args) {
161  assert(Args.size() == 2 && "calloc expects two arguments!");
162  return PTOGV(calloc(Args[0].UIntVal, Args[1].UIntVal));
163}
164
165// void free(void *)
166GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
167  assert(Args.size() == 1);
168  free(GVTOP(Args[0]));
169  return GenericValue();
170}
171
172// int atoi(char *)
173GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
174  assert(Args.size() == 1);
175  GenericValue GV;
176  GV.IntVal = atoi((char*)GVTOP(Args[0]));
177  return GV;
178}
179
180// double pow(double, double)
181GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
182  assert(Args.size() == 2);
183  GenericValue GV;
184  GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
185  return GV;
186}
187
188// double exp(double)
189GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
190  assert(Args.size() == 1);
191  GenericValue GV;
192  GV.DoubleVal = exp(Args[0].DoubleVal);
193  return GV;
194}
195
196// double sqrt(double)
197GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
198  assert(Args.size() == 1);
199  GenericValue GV;
200  GV.DoubleVal = sqrt(Args[0].DoubleVal);
201  return GV;
202}
203
204// double log(double)
205GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
206  assert(Args.size() == 1);
207  GenericValue GV;
208  GV.DoubleVal = log(Args[0].DoubleVal);
209  return GV;
210}
211
212// double floor(double)
213GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
214  assert(Args.size() == 1);
215  GenericValue GV;
216  GV.DoubleVal = floor(Args[0].DoubleVal);
217  return GV;
218}
219
220#ifdef HAVE_RAND48
221
222// double drand48()
223GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
224  assert(Args.size() == 0);
225  GenericValue GV;
226  GV.DoubleVal = drand48();
227  return GV;
228}
229
230// long lrand48()
231GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
232  assert(Args.size() == 0);
233  GenericValue GV;
234  GV.IntVal = lrand48();
235  return GV;
236}
237
238// void srand48(long)
239GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
240  assert(Args.size() == 1);
241  srand48(Args[0].IntVal);
242  return GenericValue();
243}
244
245#endif
246
247// int rand()
248GenericValue lle_X_rand(FunctionType *M, const vector<GenericValue> &Args) {
249  assert(Args.size() == 0);
250  GenericValue GV;
251  GV.IntVal = rand();
252  return GV;
253}
254
255// void srand(uint)
256GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
257  assert(Args.size() == 1);
258  srand(Args[0].UIntVal);
259  return GenericValue();
260}
261
262// int puts(const char*)
263GenericValue lle_X_puts(FunctionType *M, const vector<GenericValue> &Args) {
264  assert(Args.size() == 1);
265  GenericValue GV;
266  GV.IntVal = puts((char*)GVTOP(Args[0]));
267  return GV;
268}
269
270// int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
271// output useful.
272GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
273  char *OutputBuffer = (char *)GVTOP(Args[0]);
274  const char *FmtStr = (const char *)GVTOP(Args[1]);
275  unsigned ArgNo = 2;
276
277  // printf should return # chars printed.  This is completely incorrect, but
278  // close enough for now.
279  GenericValue GV; GV.IntVal = strlen(FmtStr);
280  while (1) {
281    switch (*FmtStr) {
282    case 0: return GV;             // Null terminator...
283    default:                       // Normal nonspecial character
284      sprintf(OutputBuffer++, "%c", *FmtStr++);
285      break;
286    case '\\': {                   // Handle escape codes
287      sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
288      FmtStr += 2; OutputBuffer += 2;
289      break;
290    }
291    case '%': {                    // Handle format specifiers
292      char FmtBuf[100] = "", Buffer[1000] = "";
293      char *FB = FmtBuf;
294      *FB++ = *FmtStr++;
295      char Last = *FB++ = *FmtStr++;
296      unsigned HowLong = 0;
297      while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
298             Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
299             Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
300             Last != 'p' && Last != 's' && Last != '%') {
301        if (Last == 'l' || Last == 'L') HowLong++;  // Keep track of l's
302        Last = *FB++ = *FmtStr++;
303      }
304      *FB = 0;
305
306      switch (Last) {
307      case '%':
308        sprintf(Buffer, FmtBuf); break;
309      case 'c':
310        sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
311      case 'd': case 'i':
312      case 'u': case 'o':
313      case 'x': case 'X':
314        if (HowLong >= 1) {
315          if (HowLong == 1 &&
316              TheInterpreter->getModule().getPointerSize()==Module::Pointer64 &&
317              sizeof(long) < sizeof(int64_t)) {
318            // Make sure we use %lld with a 64 bit argument because we might be
319            // compiling LLI on a 32 bit compiler.
320            unsigned Size = strlen(FmtBuf);
321            FmtBuf[Size] = FmtBuf[Size-1];
322            FmtBuf[Size+1] = 0;
323            FmtBuf[Size-1] = 'l';
324          }
325          sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
326        } else
327          sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
328      case 'e': case 'E': case 'g': case 'G': case 'f':
329        sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
330      case 'p':
331        sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
332      case 's':
333        sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
334      default:  std::cout << "<unknown printf code '" << *FmtStr << "'!>";
335        ArgNo++; break;
336      }
337      strcpy(OutputBuffer, Buffer);
338      OutputBuffer += strlen(Buffer);
339      }
340      break;
341    }
342  }
343}
344
345// int printf(sbyte *, ...) - a very rough implementation to make output useful.
346GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
347  char Buffer[10000];
348  vector<GenericValue> NewArgs;
349  NewArgs.push_back(PTOGV(Buffer));
350  NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
351  GenericValue GV = lle_X_sprintf(M, NewArgs);
352  std::cout << Buffer;
353  return GV;
354}
355
356static void ByteswapSCANFResults(const char *Fmt, void *Arg0, void *Arg1,
357                                 void *Arg2, void *Arg3, void *Arg4, void *Arg5,
358                                 void *Arg6, void *Arg7, void *Arg8) {
359  void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
360
361  // Loop over the format string, munging read values as appropriate (performs
362  // byteswaps as necessary).
363  unsigned ArgNo = 0;
364  while (*Fmt) {
365    if (*Fmt++ == '%') {
366      // Read any flag characters that may be present...
367      bool Suppress = false;
368      bool Half = false;
369      bool Long = false;
370      bool LongLong = false;  // long long or long double
371
372      while (1) {
373        switch (*Fmt++) {
374        case '*': Suppress = true; break;
375        case 'a': /*Allocate = true;*/ break;  // We don't need to track this
376        case 'h': Half = true; break;
377        case 'l': Long = true; break;
378        case 'q':
379        case 'L': LongLong = true; break;
380        default:
381          if (Fmt[-1] > '9' || Fmt[-1] < '0')   // Ignore field width specs
382            goto Out;
383        }
384      }
385    Out:
386
387      // Read the conversion character
388      if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
389        unsigned Size = 0;
390        const Type *Ty = 0;
391
392        switch (Fmt[-1]) {
393        case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
394        case 'd':
395          if (Long || LongLong) {
396            Size = 8; Ty = Type::ULongTy;
397          } else if (Half) {
398            Size = 4; Ty = Type::UShortTy;
399          } else {
400            Size = 4; Ty = Type::UIntTy;
401          }
402          break;
403
404        case 'e': case 'g': case 'E':
405        case 'f':
406          if (Long || LongLong) {
407            Size = 8; Ty = Type::DoubleTy;
408          } else {
409            Size = 4; Ty = Type::FloatTy;
410          }
411          break;
412
413        case 's': case 'c': case '[':  // No byteswap needed
414          Size = 1;
415          Ty = Type::SByteTy;
416          break;
417
418        default: break;
419        }
420
421        if (Size) {
422          GenericValue GV;
423          void *Arg = Args[ArgNo++];
424          memcpy(&GV, Arg, Size);
425          TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
426        }
427      }
428    }
429  }
430}
431
432// int sscanf(const char *format, ...);
433GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
434  assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
435
436  char *Args[10];
437  for (unsigned i = 0; i < args.size(); ++i)
438    Args[i] = (char*)GVTOP(args[i]);
439
440  GenericValue GV;
441  GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
442                     Args[5], Args[6], Args[7], Args[8], Args[9]);
443  ByteswapSCANFResults(Args[1], Args[2], Args[3], Args[4],
444                       Args[5], Args[6], Args[7], Args[8], Args[9], 0);
445  return GV;
446}
447
448// int scanf(const char *format, ...);
449GenericValue lle_X_scanf(FunctionType *M, const vector<GenericValue> &args) {
450  assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
451
452  char *Args[10];
453  for (unsigned i = 0; i < args.size(); ++i)
454    Args[i] = (char*)GVTOP(args[i]);
455
456  GenericValue GV;
457  GV.IntVal = scanf(Args[0], Args[1], Args[2], Args[3], Args[4],
458                    Args[5], Args[6], Args[7], Args[8], Args[9]);
459  ByteswapSCANFResults(Args[0], Args[1], Args[2], Args[3], Args[4],
460                       Args[5], Args[6], Args[7], Args[8], Args[9]);
461  return GV;
462}
463
464
465// int clock(void) - Profiling implementation
466GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
467  extern unsigned int clock(void);
468  GenericValue GV; GV.IntVal = clock();
469  return GV;
470}
471
472
473//===----------------------------------------------------------------------===//
474// String Functions...
475//===----------------------------------------------------------------------===//
476
477// int strcmp(const char *S1, const char *S2);
478GenericValue lle_X_strcmp(FunctionType *M, const vector<GenericValue> &Args) {
479  assert(Args.size() == 2);
480  GenericValue Ret;
481  Ret.IntVal = strcmp((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]));
482  return Ret;
483}
484
485// char *strcat(char *Dest, const char *src);
486GenericValue lle_X_strcat(FunctionType *M, const vector<GenericValue> &Args) {
487  assert(Args.size() == 2);
488  return PTOGV(strcat((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
489}
490
491// char *strcpy(char *Dest, const char *src);
492GenericValue lle_X_strcpy(FunctionType *M, const vector<GenericValue> &Args) {
493  assert(Args.size() == 2);
494  return PTOGV(strcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
495}
496
497static GenericValue size_t_to_GV (size_t n) {
498  GenericValue Ret;
499  if (sizeof (size_t) == sizeof (uint64_t)) {
500    Ret.ULongVal = n;
501  } else {
502    assert (sizeof (size_t) == sizeof (unsigned int));
503    Ret.UIntVal = n;
504  }
505  return Ret;
506}
507
508static size_t GV_to_size_t (GenericValue GV) {
509  size_t count;
510  if (sizeof (size_t) == sizeof (uint64_t)) {
511    count = (size_t)GV.ULongVal;
512  } else {
513    assert (sizeof (size_t) == sizeof (unsigned int));
514    count = (size_t)GV.UIntVal;
515  }
516  return count;
517}
518
519// size_t strlen(const char *src);
520GenericValue lle_X_strlen(FunctionType *M, const vector<GenericValue> &Args) {
521  assert(Args.size() == 1);
522  size_t strlenResult = strlen ((char *) GVTOP (Args[0]));
523  return size_t_to_GV (strlenResult);
524}
525
526// char *strdup(const char *src);
527GenericValue lle_X_strdup(FunctionType *M, const vector<GenericValue> &Args) {
528  assert(Args.size() == 1);
529  return PTOGV(strdup((char*)GVTOP(Args[0])));
530}
531
532// char *__strdup(const char *src);
533GenericValue lle_X___strdup(FunctionType *M, const vector<GenericValue> &Args) {
534  assert(Args.size() == 1);
535  return PTOGV(strdup((char*)GVTOP(Args[0])));
536}
537
538// void *memset(void *S, int C, size_t N)
539GenericValue lle_X_memset(FunctionType *M, const vector<GenericValue> &Args) {
540  assert(Args.size() == 3);
541  size_t count = GV_to_size_t (Args[2]);
542  return PTOGV(memset(GVTOP(Args[0]), Args[1].IntVal, count));
543}
544
545// void *memcpy(void *Dest, void *src, size_t Size);
546GenericValue lle_X_memcpy(FunctionType *M, const vector<GenericValue> &Args) {
547  assert(Args.size() == 3);
548  size_t count = GV_to_size_t (Args[2]);
549  return PTOGV(memcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]), count));
550}
551
552//===----------------------------------------------------------------------===//
553// IO Functions...
554//===----------------------------------------------------------------------===//
555
556// getFILE - Turn a pointer in the host address space into a legit pointer in
557// the interpreter address space.  This is an identity transformation.
558#define getFILE(ptr) ((FILE*)ptr)
559
560// FILE *fopen(const char *filename, const char *mode);
561GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
562  assert(Args.size() == 2);
563  return PTOGV(fopen((const char *)GVTOP(Args[0]),
564                     (const char *)GVTOP(Args[1])));
565}
566
567// int fclose(FILE *F);
568GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
569  assert(Args.size() == 1);
570  GenericValue GV;
571  GV.IntVal = fclose(getFILE(GVTOP(Args[0])));
572  return GV;
573}
574
575// int feof(FILE *stream);
576GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
577  assert(Args.size() == 1);
578  GenericValue GV;
579
580  GV.IntVal = feof(getFILE(GVTOP(Args[0])));
581  return GV;
582}
583
584// size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
585GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
586  assert(Args.size() == 4);
587  size_t result;
588
589  result = fread((void*)GVTOP(Args[0]), GV_to_size_t (Args[1]),
590                 GV_to_size_t (Args[2]), getFILE(GVTOP(Args[3])));
591  return size_t_to_GV (result);
592}
593
594// size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
595GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
596  assert(Args.size() == 4);
597  size_t result;
598
599  result = fwrite((void*)GVTOP(Args[0]), GV_to_size_t (Args[1]),
600                  GV_to_size_t (Args[2]), getFILE(GVTOP(Args[3])));
601  return size_t_to_GV (result);
602}
603
604// char *fgets(char *s, int n, FILE *stream);
605GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
606  assert(Args.size() == 3);
607  return GVTOP(fgets((char*)GVTOP(Args[0]), Args[1].IntVal,
608                     getFILE(GVTOP(Args[2]))));
609}
610
611// FILE *freopen(const char *path, const char *mode, FILE *stream);
612GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
613  assert(Args.size() == 3);
614  return PTOGV(freopen((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]),
615                       getFILE(GVTOP(Args[2]))));
616}
617
618// int fflush(FILE *stream);
619GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
620  assert(Args.size() == 1);
621  GenericValue GV;
622  GV.IntVal = fflush(getFILE(GVTOP(Args[0])));
623  return GV;
624}
625
626// int getc(FILE *stream);
627GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
628  assert(Args.size() == 1);
629  GenericValue GV;
630  GV.IntVal = getc(getFILE(GVTOP(Args[0])));
631  return GV;
632}
633
634// int _IO_getc(FILE *stream);
635GenericValue lle_X__IO_getc(FunctionType *F, const vector<GenericValue> &Args) {
636  return lle_X_getc(F, Args);
637}
638
639// int fputc(int C, FILE *stream);
640GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
641  assert(Args.size() == 2);
642  GenericValue GV;
643  GV.IntVal = fputc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
644  return GV;
645}
646
647// int ungetc(int C, FILE *stream);
648GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
649  assert(Args.size() == 2);
650  GenericValue GV;
651  GV.IntVal = ungetc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
652  return GV;
653}
654
655// int ferror (FILE *stream);
656GenericValue lle_X_ferror(FunctionType *M, const vector<GenericValue> &Args) {
657  assert(Args.size() == 1);
658  GenericValue GV;
659  GV.IntVal = ferror (getFILE(GVTOP(Args[0])));
660  return GV;
661}
662
663// int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
664// useful.
665GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
666  assert(Args.size() >= 2);
667  char Buffer[10000];
668  vector<GenericValue> NewArgs;
669  NewArgs.push_back(PTOGV(Buffer));
670  NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
671  GenericValue GV = lle_X_sprintf(M, NewArgs);
672
673  fputs(Buffer, getFILE(GVTOP(Args[0])));
674  return GV;
675}
676
677} // End extern "C"
678
679
680void Interpreter::initializeExternalFunctions() {
681  FuncNames["lle_Vb_putchar"]     = lle_Vb_putchar;
682  FuncNames["lle_ii_putchar"]     = lle_ii_putchar;
683  FuncNames["lle_VB_putchar"]     = lle_VB_putchar;
684  FuncNames["lle_X_exit"]         = lle_X_exit;
685  FuncNames["lle_X_abort"]        = lle_X_abort;
686  FuncNames["lle_X_malloc"]       = lle_X_malloc;
687  FuncNames["lle_X_calloc"]       = lle_X_calloc;
688  FuncNames["lle_X_free"]         = lle_X_free;
689  FuncNames["lle_X_atoi"]         = lle_X_atoi;
690  FuncNames["lle_X_pow"]          = lle_X_pow;
691  FuncNames["lle_X_exp"]          = lle_X_exp;
692  FuncNames["lle_X_log"]          = lle_X_log;
693  FuncNames["lle_X_floor"]        = lle_X_floor;
694  FuncNames["lle_X_srand"]        = lle_X_srand;
695  FuncNames["lle_X_rand"]         = lle_X_rand;
696#ifdef HAVE_RAND48
697  FuncNames["lle_X_drand48"]      = lle_X_drand48;
698  FuncNames["lle_X_srand48"]      = lle_X_srand48;
699  FuncNames["lle_X_lrand48"]      = lle_X_lrand48;
700#endif
701  FuncNames["lle_X_sqrt"]         = lle_X_sqrt;
702  FuncNames["lle_X_puts"]         = lle_X_puts;
703  FuncNames["lle_X_printf"]       = lle_X_printf;
704  FuncNames["lle_X_sprintf"]      = lle_X_sprintf;
705  FuncNames["lle_X_sscanf"]       = lle_X_sscanf;
706  FuncNames["lle_X_scanf"]        = lle_X_scanf;
707  FuncNames["lle_i_clock"]        = lle_i_clock;
708
709  FuncNames["lle_X_strcmp"]       = lle_X_strcmp;
710  FuncNames["lle_X_strcat"]       = lle_X_strcat;
711  FuncNames["lle_X_strcpy"]       = lle_X_strcpy;
712  FuncNames["lle_X_strlen"]       = lle_X_strlen;
713  FuncNames["lle_X___strdup"]     = lle_X___strdup;
714  FuncNames["lle_X_memset"]       = lle_X_memset;
715  FuncNames["lle_X_memcpy"]       = lle_X_memcpy;
716
717  FuncNames["lle_X_fopen"]        = lle_X_fopen;
718  FuncNames["lle_X_fclose"]       = lle_X_fclose;
719  FuncNames["lle_X_feof"]         = lle_X_feof;
720  FuncNames["lle_X_fread"]        = lle_X_fread;
721  FuncNames["lle_X_fwrite"]       = lle_X_fwrite;
722  FuncNames["lle_X_fgets"]        = lle_X_fgets;
723  FuncNames["lle_X_fflush"]       = lle_X_fflush;
724  FuncNames["lle_X_fgetc"]        = lle_X_getc;
725  FuncNames["lle_X_getc"]         = lle_X_getc;
726  FuncNames["lle_X__IO_getc"]     = lle_X__IO_getc;
727  FuncNames["lle_X_fputc"]        = lle_X_fputc;
728  FuncNames["lle_X_ungetc"]       = lle_X_ungetc;
729  FuncNames["lle_X_fprintf"]      = lle_X_fprintf;
730  FuncNames["lle_X_freopen"]      = lle_X_freopen;
731}
732
733