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