* Bug fixes:
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
2 //
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
4 //
5 // Note that this library should be as fast as possible, reentrant, and 
6 // threadsafe!!
7 //
8 // TODO: Return error messages to caller instead of printing them out directly.
9 // TODO: Allow passing in an option to ignore the symbol table
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "ReaderInternals.h"
14 #include "llvm/Bytecode/Reader.h"
15 #include "llvm/Bytecode/Format.h"
16 #include "llvm/Module.h"
17 #include "llvm/Constants.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/iOther.h"
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/mman.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <algorithm>
26
27 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
28   if (Ty->isPrimitiveType()) {
29     Slot = Ty->getPrimitiveID();
30   } else {
31     // Check the function level types first...
32     TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
33                                         FunctionTypeValues.end(), Ty);
34     if (I != FunctionTypeValues.end()) {
35       Slot = FirstDerivedTyID+ModuleTypeValues.size()+
36              (&*I - &FunctionTypeValues[0]);
37     } else {
38       I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
39       if (I == ModuleTypeValues.end()) return true;   // Didn't find type!
40       Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
41     }
42   }
43   //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << "\n";
44   return false;
45 }
46
47 const Type *BytecodeParser::getType(unsigned ID) {
48   if (ID < Type::NumPrimitiveIDs) {
49     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
50     if (T) return T;
51   }
52   
53   //cerr << "Looking up Type ID: " << ID << "\n";
54   const Value *V = getValue(Type::TypeTy, ID, false);
55   return cast_or_null<Type>(V);
56 }
57
58 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
59   assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
60           Val->getType()->isPrimitiveType() ||
61           !cast<Constant>(Val)->isNullValue()) &&
62          "Cannot read null values from bytecode!");
63   unsigned type;
64   if (getTypeSlot(Val->getType(), type)) return -1;
65   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
66  
67   if (ValueTab.size() <= type) {
68     unsigned OldSize = ValueTab.size();
69     ValueTab.resize(type+1);
70     while (OldSize != type+1)
71       ValueTab[OldSize++] = new ValueList();
72   }
73
74   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
75   //     << "] = " << Val << "\n";
76   ValueTab[type]->push_back(Val);
77
78   bool HasOffset = HasImplicitZeroInitializer &&
79                        !Val->getType()->isPrimitiveType();
80
81   return ValueTab[type]->size()-1 + HasOffset;
82 }
83
84
85 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
86                                 Value *Val) {
87   assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
88   unsigned type;
89   if (getTypeSlot(Val->getType(), type))
90     assert(0 && "getTypeSlot failed!");
91   
92   assert((!HasImplicitZeroInitializer || Slot != 0) &&
93          "Cannot change zero init");
94   assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
95   ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
96 }
97
98 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
99   unsigned Num = oNum;
100   unsigned type;   // The type plane it lives in...
101
102   if (getTypeSlot(Ty, type)) return 0;
103
104   if (type == Type::TypeTyID) {  // The 'type' plane has implicit values
105     assert(Create == false);
106     if (Num < Type::NumPrimitiveIDs) {
107       const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
108       if (T) return (Value*)T;   // Asked for a primitive type...
109     }
110
111     // Otherwise, derived types need offset...
112     Num -= FirstDerivedTyID;
113
114     // Is it a module level type?
115     if (Num < ModuleTypeValues.size())
116       return (Value*)ModuleTypeValues[Num].get();
117
118     // Nope, is it a function level type?
119     Num -= ModuleTypeValues.size();
120     if (Num < FunctionTypeValues.size())
121       return (Value*)FunctionTypeValues[Num].get();
122
123     return 0;
124   }
125
126   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
127     if (Num == 0)
128       return Constant::getNullValue(Ty);
129     --Num;
130   }
131
132   if (type < ModuleValues.size()) {
133     if (Num < ModuleValues[type]->size())
134       return ModuleValues[type]->getOperand(Num);
135     Num -= ModuleValues[type]->size();
136   }
137
138   if (Values.size() > type && Values[type]->size() > Num)
139     return Values[type]->getOperand(Num);
140
141   if (!Create) return 0;  // Do not create a placeholder?
142
143   Value *d = 0;
144   switch (Ty->getPrimitiveID()) {
145   case Type::LabelTyID:
146     d = new BBPHolder(Ty, oNum);
147     break;
148   default:
149     d = new ValPHolder(Ty, oNum);
150     break;
151   }
152
153   assert(d != 0 && "How did we not make something?");
154   if (insertValue(d, LateResolveValues) == -1) return 0;
155   return d;
156 }
157
158 /// getConstantValue - Just like getValue, except that it returns a null pointer
159 /// only on error.  It always returns a constant (meaning that if the value is
160 /// defined, but is not a constant, that is an error).  If the specified
161 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
162 /// after the real value is parsed, the placeholder is eliminated.
163 ///
164 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
165   if (Value *V = getValue(Ty, Slot, false))
166     return dyn_cast<Constant>(V);      // If we already have the value parsed...
167
168   std::pair<const Type*, unsigned> Key(Ty, Slot);
169   GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
170
171   if (I != GlobalRefs.end() && I->first == Key) {
172     BCR_TRACE(5, "Previous forward ref found!\n");
173     return cast<Constant>(I->second);
174   } else {
175     // Create a placeholder for the constant reference and
176     // keep track of the fact that we have a forward ref to recycle it
177     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
178     Constant *C = new ConstPHolder(Ty, Slot);
179     
180     // Keep track of the fact that we have a forward ref to recycle it
181     GlobalRefs.insert(I, std::make_pair(Key, C));
182     return C;
183   }
184 }
185
186
187 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
188   bool Error = false;
189   while (!ValTab.empty()) {
190     ValueList &DL = *ValTab.back();
191     ValTab.pop_back();    
192
193     while (!DL.empty()) {
194       Value *D = DL.back();
195       unsigned IDNumber = getValueIDNumberFromPlaceHolder(D);
196       DL.pop_back();
197
198       Value *NewDef = getValue(D->getType(), IDNumber, false);
199       if (NewDef == 0) {
200         Error = true;  // Unresolved thinger
201         std::cerr << "Unresolvable reference found: <"
202                   << *D->getType() << ">:" << IDNumber <<"!\n";
203       } else {
204         // Fixup all of the uses of this placeholder def...
205         D->replaceAllUsesWith(NewDef);
206
207         // Now that all the uses are gone, delete the placeholder...
208         // If we couldn't find a def (error case), then leak a little
209         delete D;  // memory, 'cause otherwise we can't remove all uses!
210       }
211     }
212     delete &DL;
213   }
214
215   return Error;
216 }
217
218 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf, 
219                                      BasicBlock *&BB) {
220   BB = new BasicBlock();
221
222   while (Buf < EndBuf) {
223     Instruction *Inst;
224     if (ParseInstruction(Buf, EndBuf, Inst, /*HACK*/BB)) {
225       delete BB;
226       return true;
227     }
228
229     if (Inst == 0) { delete BB; return true; }
230     if (insertValue(Inst, Values) == -1) { delete BB; return true; }
231
232     BB->getInstList().push_back(Inst);
233
234     BCR_TRACE(4, Inst);
235   }
236
237   return false;
238 }
239
240 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
241                                       SymbolTable *ST) {
242   while (Buf < EndBuf) {
243     // Symtab block header: [num entries][type id number]
244     unsigned NumEntries, Typ;
245     if (read_vbr(Buf, EndBuf, NumEntries) ||
246         read_vbr(Buf, EndBuf, Typ)) return true;
247     const Type *Ty = getType(Typ);
248     if (Ty == 0) return true;
249
250     BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
251               " entries\n");
252
253     for (unsigned i = 0; i < NumEntries; ++i) {
254       // Symtab entry: [def slot #][name]
255       unsigned slot;
256       if (read_vbr(Buf, EndBuf, slot)) return true;
257       std::string Name;
258       if (read(Buf, EndBuf, Name, false))  // Not aligned...
259         return true;
260
261       Value *V = getValue(Ty, slot, false); // Find mapping...
262       if (V == 0) {
263         BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
264         return true;
265       }
266       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
267                 if (!isa<Instruction>(V)) std::cerr << "\n");
268
269       V->setName(Name, ST);
270     }
271   }
272
273   if (Buf > EndBuf) return true;
274   return false;
275 }
276
277 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
278   GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
279                                                               Slot));
280   if (I == GlobalRefs.end()) return;   // Never forward referenced?
281
282   BCR_TRACE(3, "Mutating forward refs!\n");
283   Value *VPH = I->second;   // Get the placeholder...
284
285   VPH->replaceAllUsesWith(NewV);
286
287   // If this is a global variable being resolved, remove the placeholder from
288   // the module...
289   if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
290     GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
291
292   delete VPH;                         // Delete the old placeholder
293   GlobalRefs.erase(I);                // Remove the map entry for it
294 }
295
296
297 bool BytecodeParser::ParseFunction(const uchar *&Buf, const uchar *EndBuf) {
298   // Clear out the local values table...
299   if (FunctionSignatureList.empty()) {
300     Error = "Function found, but FunctionSignatureList empty!";
301     return true;  // Unexpected function!
302   }
303
304   unsigned isInternal;
305   if (read_vbr(Buf, EndBuf, isInternal)) return true;
306
307   Function *F = FunctionSignatureList.back().first;
308   unsigned FunctionSlot = FunctionSignatureList.back().second;
309   FunctionSignatureList.pop_back();
310   F->setInternalLinkage(isInternal != 0);
311
312   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
313   Function::aiterator AI = F->abegin();
314   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
315        It != Params.end(); ++It, ++AI) {
316     if (insertValue(AI, Values) == -1) {
317       Error = "Error reading function arguments!\n";
318       return true; 
319     }
320   }
321
322   while (Buf < EndBuf) {
323     unsigned Type, Size;
324     const unsigned char *OldBuf = Buf;
325     if (readBlock(Buf, EndBuf, Type, Size)) {
326       Error = "Error reading Function level block!";
327       return true; 
328     }
329
330     switch (Type) {
331     case BytecodeFormat::ConstantPool:
332       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
333       if (ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues))
334         return true;
335       break;
336
337     case BytecodeFormat::BasicBlock: {
338       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
339       BasicBlock *BB;
340       if (ParseBasicBlock(Buf, Buf+Size, BB) ||
341           insertValue(BB, Values) == -1)
342         return true;                // Parse error... :(
343
344       F->getBasicBlockList().push_back(BB);
345       break;
346     }
347
348     case BytecodeFormat::SymbolTable:
349       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
350       if (ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable()))
351         return true;
352       break;
353
354     default:
355       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
356       Buf += Size;
357       if (OldBuf > Buf) return true; // Wrap around!
358       break;
359     }
360     BCR_TRACE(2, "} end block\n");
361
362     if (align32(Buf, EndBuf)) {
363       Error = "Error aligning Function level block!";
364       return true;   // Malformed bc file, read past end of block.
365     }
366   }
367
368   if (postResolveValues(LateResolveValues)) {
369     Error = "Error resolving function values!";
370     return true;     // Unresolvable references!
371   }
372
373   ResolveReferencesToValue(F, FunctionSlot);
374
375   // Clear out function level types...
376   FunctionTypeValues.clear();
377
378   freeTable(Values);
379   return false;
380 }
381
382 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End){
383   if (!FunctionSignatureList.empty()) {
384     Error = "Two ModuleGlobalInfo packets found!";
385     return true;  // Two ModuleGlobal blocks?
386   }
387
388   // Read global variables...
389   unsigned VarType;
390   if (read_vbr(Buf, End, VarType)) return true;
391   while (VarType != Type::VoidTyID) { // List is terminated by Void
392     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
393     // bit2 = isInternal, bit3+ = slot#
394     const Type *Ty = getType(VarType >> 3);
395     if (!Ty || !isa<PointerType>(Ty)) { 
396       Error = "Global not pointer type!  Ty = " + Ty->getDescription();
397       return true; 
398     }
399
400     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
401
402     // Create the global variable...
403     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, VarType & 4,
404                                             0, "", TheModule);
405     int DestSlot = insertValue(GV, ModuleValues);
406     if (DestSlot == -1) return true;
407     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
408     ResolveReferencesToValue(GV, (unsigned)DestSlot);
409
410     if (VarType & 2) { // Does it have an initalizer?
411       unsigned InitSlot;
412       if (read_vbr(Buf, End, InitSlot)) return true;
413       GlobalInits.push_back(std::make_pair(GV, InitSlot));
414     }
415     if (read_vbr(Buf, End, VarType)) return true;
416   }
417
418   // Read the function objects for all of the functions that are coming
419   unsigned FnSignature;
420   if (read_vbr(Buf, End, FnSignature)) return true;
421   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
422     const Type *Ty = getType(FnSignature);
423     if (!Ty || !isa<PointerType>(Ty) ||
424         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) { 
425       Error = "Function not ptr to func type!  Ty = " + Ty->getDescription();
426       return true; 
427     }
428
429     // We create functions by passing the underlying FunctionType to create...
430     Ty = cast<PointerType>(Ty)->getElementType();
431
432     // When the ModuleGlobalInfo section is read, we load the type of each
433     // function and the 'ModuleValues' slot that it lands in.  We then load a
434     // placeholder into its slot to reserve it.  When the function is loaded,
435     // this placeholder is replaced.
436
437     // Insert the placeholder...
438     Function *Func = new Function(cast<FunctionType>(Ty), false, "", TheModule);
439     int DestSlot = insertValue(Func, ModuleValues);
440     if (DestSlot == -1) return true;
441     ResolveReferencesToValue(Func, (unsigned)DestSlot);
442
443     // Keep track of this information in a list that is emptied as functions are
444     // loaded...
445     //
446     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
447
448     if (read_vbr(Buf, End, FnSignature)) return true;
449     BCR_TRACE(2, "Function of type: " << Ty << "\n");
450   }
451
452   if (align32(Buf, End)) return true;
453
454   // Now that the function signature list is set up, reverse it so that we can 
455   // remove elements efficiently from the back of the vector.
456   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
457
458   // This is for future proofing... in the future extra fields may be added that
459   // we don't understand, so we transparently ignore them.
460   //
461   Buf = End;
462   return false;
463 }
464
465 bool BytecodeParser::ParseVersionInfo(const uchar *&Buf, const uchar *EndBuf) {
466   unsigned Version;
467   if (read_vbr(Buf, EndBuf, Version)) return true;
468
469   // Unpack version number: low four bits are for flags, top bits = version
470   isBigEndian     = Version & 1;
471   hasLongPointers = Version & 2;
472   RevisionNum     = Version >> 4;
473   HasImplicitZeroInitializer = true;
474
475   switch (RevisionNum) {
476   case 0:                  // Initial revision
477     // Version #0 didn't have any of the flags stored correctly, and in fact as
478     // only valid with a 14 in the flags values.  Also, it does not support
479     // encoding zero initializers for arrays compactly.
480     //
481     if (Version != 14) return true;  // Unknown revision 0 flags?
482     FirstDerivedTyID = 14;
483     HasImplicitZeroInitializer = false;
484     isBigEndian = hasLongPointers = true;
485     break;
486   case 1:
487     // Version #1 has two bit fields: isBigEndian and hasLongPointers
488     FirstDerivedTyID = 14;
489     break;
490   default:
491     Error = "Unknown bytecode version number!";
492     return true;
493   }
494
495   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
496   BCR_TRACE(1, "BigEndian/LongPointers = " << isBigEndian << ","
497                << hasLongPointers << "\n");
498   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
499   return false;
500 }
501
502 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf) {
503   unsigned Type, Size;
504   if (readBlock(Buf, EndBuf, Type, Size)) return true;
505   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf) {
506     Error = "Expected Module packet!";
507     return true;                      // Hrm, not a class?
508   }
509
510   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
511   FunctionSignatureList.clear();                 // Just in case...
512
513   // Read into instance variables...
514   if (ParseVersionInfo(Buf, EndBuf)) return true;
515   if (align32(Buf, EndBuf)) return true;
516
517   while (Buf < EndBuf) {
518     const unsigned char *OldBuf = Buf;
519     if (readBlock(Buf, EndBuf, Type, Size)) return true;
520     switch (Type) {
521     case BytecodeFormat::GlobalTypePlane:
522       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
523       if (ParseGlobalTypes(Buf, Buf+Size)) return true;
524       break;
525
526     case BytecodeFormat::ModuleGlobalInfo:
527       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
528       if (ParseModuleGlobalInfo(Buf, Buf+Size)) return true;
529       break;
530
531     case BytecodeFormat::ConstantPool:
532       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
533       if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues))
534         return true;
535       break;
536
537     case BytecodeFormat::Function: {
538       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
539       if (ParseFunction(Buf, Buf+Size))
540         return true;  // Error parsing function
541       break;
542     }
543
544     case BytecodeFormat::SymbolTable:
545       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
546       if (ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable()))
547         return true;
548       break;
549
550     default:
551       Error = "Expected Module Block!";
552       Buf += Size;
553       if (OldBuf > Buf) return true; // Wrap around!
554       break;
555     }
556     BCR_TRACE(1, "} end block\n");
557     if (align32(Buf, EndBuf)) return true;
558   }
559
560   // After the module constant pool has been read, we can safely initialize
561   // global variables...
562   while (!GlobalInits.empty()) {
563     GlobalVariable *GV = GlobalInits.back().first;
564     unsigned Slot = GlobalInits.back().second;
565     GlobalInits.pop_back();
566
567     // Look up the initializer value...
568     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
569       if (GV->hasInitializer()) return true;
570       GV->setInitializer(cast<Constant>(V));
571     } else
572       return true;
573   }
574
575   if (!FunctionSignatureList.empty()) {     // Expected more functions!
576     Error = "Function expected, but bytecode stream at end!";
577     return true;
578   }
579
580   BCR_TRACE(0, "} end block\n\n");
581   return false;
582 }
583
584 static inline Module *Error(std::string *ErrorStr, const char *Message) {
585   if (ErrorStr) *ErrorStr = Message;
586   return 0;
587 }
588
589 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
590   unsigned Sig;
591   // Read and check signature...
592   if (read(Buf, EndBuf, Sig) ||
593       Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
594     return ::Error(&Error, "Invalid bytecode signature!");
595
596   TheModule = new Module();
597   if (ParseModule(Buf, EndBuf)) {
598     delete TheModule;
599     TheModule = 0;
600   }
601   return TheModule;
602 }
603
604
605 Module *ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
606                             std::string *ErrorStr) {
607   BytecodeParser Parser;
608   Module *R = Parser.ParseBytecode(Buffer, Buffer+Length);
609   if (ErrorStr) *ErrorStr = Parser.getError();
610   return R;
611 }
612
613
614 /// FDHandle - Simple handle class to make sure a file descriptor gets closed
615 /// when the object is destroyed.
616 class FDHandle {
617   int FD;
618 public:
619   FDHandle(int fd) : FD(fd) {}
620   operator int() const { return FD; }
621   ~FDHandle() {
622     if (FD != -1) close(FD);
623   }
624 };
625
626 // Parse and return a class file...
627 //
628 Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
629   Module *Result = 0;
630
631   if (Filename != std::string("-")) {        // Read from a file...
632     FDHandle FD = open(Filename.c_str(), O_RDONLY);
633     if (FD == -1)
634       return Error(ErrorStr, "Error opening file!");
635
636     // Stat the file to get its length...
637     struct stat StatBuf;
638     if (fstat(FD, &StatBuf) == -1 || StatBuf.st_size == 0)
639       return Error(ErrorStr, "Error stat'ing file!");
640
641     // mmap in the file all at once...
642     int Length = StatBuf.st_size;
643     unsigned char *Buffer = (unsigned char*)mmap(0, Length, PROT_READ, 
644                                                  MAP_PRIVATE, FD, 0);
645     if (Buffer == (unsigned char*)MAP_FAILED)
646       return Error(ErrorStr, "Error mmapping file!");
647
648     // Parse the bytecode we mmapped in
649     Result = ParseBytecodeBuffer(Buffer, Length, ErrorStr);
650
651     // Unmmap the bytecode...
652     munmap((char*)Buffer, Length);
653   } else {                              // Read from stdin
654     int BlockSize;
655     uchar Buffer[4096*4];
656     std::vector<unsigned char> FileData;
657
658     // Read in all of the data from stdin, we cannot mmap stdin...
659     while ((BlockSize = read(0 /*stdin*/, Buffer, 4096*4))) {
660       if (BlockSize == -1)
661         return Error(ErrorStr, "Error reading from stdin!");
662
663       FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
664     }
665
666     if (FileData.empty())
667       return Error(ErrorStr, "Standard Input empty!");
668
669 #define ALIGN_PTRS 0
670 #if ALIGN_PTRS
671     uchar *Buf = (uchar*)mmap(0, FileData.size(), PROT_READ|PROT_WRITE, 
672                               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
673     assert((Buf != (uchar*)-1) && "mmap returned error!");
674     memcpy(Buf, &FileData[0], FileData.size());
675 #else
676     unsigned char *Buf = &FileData[0];
677 #endif
678
679     Result = ParseBytecodeBuffer(Buf, FileData.size(), ErrorStr);
680
681 #if ALIGN_PTRS
682     munmap((char*)Buf, FileData.size());   // Free mmap'd data area
683 #endif
684   }
685
686   return Result;
687 }