1 //===- Reader.cpp - Code to read bytecode files -----------------------------===
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
5 // Note that this library should be as fast as possible, reentrant, and
8 // TODO: Make error message outputs be configurable depending on an option?
9 // TODO: Allow passing in an option to ignore the symbol table
11 //===------------------------------------------------------------------------===
13 #include "llvm/Bytecode/Reader.h"
14 #include "llvm/Bytecode/Format.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/Module.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/ConstPoolVals.h"
20 #include "llvm/iOther.h"
21 #include "ReaderInternals.h"
22 #include <sys/types.h>
29 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
30 if (Ty->isPrimitiveType()) {
31 Slot = Ty->getPrimitiveID();
33 // Check the method level types first...
34 TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
35 MethodTypeValues.end(), Ty);
36 if (I != MethodTypeValues.end()) {
37 Slot = FirstDerivedTyID+ModuleTypeValues.size()+
38 (&*I - &MethodTypeValues[0]);
40 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
41 if (I == ModuleTypeValues.end()) return true; // Didn't find type!
42 Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
45 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
49 const Type *BytecodeParser::getType(unsigned ID) {
50 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
53 //cerr << "Looking up Type ID: " << ID << endl;
55 const Value *D = getValue(Type::TypeTy, ID, false);
56 if (D == 0) return failure<const Type*>(0);
61 bool BytecodeParser::insertValue(Value *Val, vector<ValueList> &ValueTab) {
63 if (getTypeSlot(Val->getType(), type)) return failure(true);
64 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
66 if (ValueTab.size() <= type)
67 ValueTab.resize(type+1, ValueList());
69 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
70 // << "] = " << Val << endl;
71 ValueTab[type].push_back(Val);
76 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
78 unsigned type; // The type plane it lives in...
80 if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
82 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
83 assert(Create == false);
84 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
85 if (T) return (Value*)T; // Asked for a primitive type...
87 // Otherwise, derived types need offset...
88 Num -= FirstDerivedTyID;
90 // Is it a module level type?
91 if (Num < ModuleTypeValues.size())
92 return (Value*)(const Type*)ModuleTypeValues[Num];
94 // Nope, is it a method level type?
95 Num -= ModuleTypeValues.size();
96 if (Num < MethodTypeValues.size())
97 return (Value*)(const Type*)MethodTypeValues[Num];
102 if (type < ModuleValues.size()) {
103 if (Num < ModuleValues[type].size())
104 return ModuleValues[type][Num];
105 Num -= ModuleValues[type].size();
108 if (Values.size() > type && Values[type].size() > Num)
109 return Values[type][Num];
111 if (!Create) return failure<Value*>(0); // Do not create a placeholder?
114 switch (Ty->getPrimitiveID()) {
115 case Type::LabelTyID: d = new BBPHolder(Ty, oNum); break;
116 case Type::MethodTyID:
117 cerr << "Creating method pholder! : " << type << ":" << oNum << " "
118 << Ty->getName() << endl;
119 d = new MethPHolder(Ty, oNum);
120 insertValue(d, LateResolveModuleValues);
122 default: d = new DefPHolder(Ty, oNum); break;
125 assert(d != 0 && "How did we not make something?");
126 if (insertValue(d, LateResolveValues)) return failure<Value*>(0);
130 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
132 for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
133 ValueList &DL = ValTab[ty];
135 while ((Size = DL.size())) {
136 unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
138 Value *D = DL[Size-1];
141 Value *NewDef = getValue(D->getType(), IDNumber, false);
143 Error = true; // Unresolved thinger
144 cerr << "Unresolvable reference found: <" << D->getType()->getName()
145 << ">:" << IDNumber << "!\n";
147 // Fixup all of the uses of this placeholder def...
148 D->replaceAllUsesWith(NewDef);
150 // Now that all the uses are gone, delete the placeholder...
151 // If we couldn't find a def (error case), then leak a little
152 delete D; // memory, 'cause otherwise we can't remove all uses!
160 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
162 BB = new BasicBlock();
164 while (Buf < EndBuf) {
166 if (ParseInstruction(Buf, EndBuf, Inst)) {
168 return failure(true);
171 if (Inst == 0) { delete BB; return failure(true); }
172 if (insertValue(Inst, Values)) { delete BB; return failure(true); }
174 BB->getInstList().push_back(Inst);
182 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
184 while (Buf < EndBuf) {
185 // Symtab block header: [num entries][type id number]
186 unsigned NumEntries, Typ;
187 if (read_vbr(Buf, EndBuf, NumEntries) ||
188 read_vbr(Buf, EndBuf, Typ)) return failure(true);
189 const Type *Ty = getType(Typ);
190 if (Ty == 0) return failure(true);
192 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
195 for (unsigned i = 0; i < NumEntries; ++i) {
196 // Symtab entry: [def slot #][name]
198 if (read_vbr(Buf, EndBuf, slot)) return failure(true);
200 if (read(Buf, EndBuf, Name, false)) // Not aligned...
201 return failure(true);
203 Value *D = getValue(Ty, slot, false); // Find mapping...
205 BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << endl);
206 return failure(true);
208 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
209 if (!isa<Instruction>(D)) cerr << endl);
211 D->setName(Name, ST);
215 if (Buf > EndBuf) return failure(true);
220 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
222 // Clear out the local values table...
224 if (MethodSignatureList.empty()) return failure(true); // Unexpected method!
226 const MethodType *MTy = MethodSignatureList.front().first;
227 unsigned MethSlot = MethodSignatureList.front().second;
228 MethodSignatureList.pop_front();
229 Method *M = new Method(MTy);
231 BCR_TRACE(2, "METHOD TYPE: " << MTy << endl);
233 const MethodType::ParamTypes &Params = MTy->getParamTypes();
234 for (MethodType::ParamTypes::const_iterator It = Params.begin();
235 It != Params.end(); ++It) {
236 MethodArgument *MA = new MethodArgument(*It);
237 if (insertValue(MA, Values)) { delete M; return failure(true); }
238 M->getArgumentList().push_back(MA);
241 while (Buf < EndBuf) {
243 const uchar *OldBuf = Buf;
244 if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
247 case BytecodeFormat::ConstantPool:
248 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
249 if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
250 delete M; return failure(true);
254 case BytecodeFormat::BasicBlock: {
255 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
257 if (ParseBasicBlock(Buf, Buf+Size, BB) ||
258 insertValue(BB, Values)) {
259 delete M; return failure(true); // Parse error... :(
262 M->getBasicBlocks().push_back(BB);
266 case BytecodeFormat::SymbolTable:
267 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
268 if (ParseSymbolTable(Buf, Buf+Size, M->getSymbolTableSure())) {
269 delete M; return failure(true);
274 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
276 if (OldBuf > Buf) return failure(true); // Wrap around!
279 BCR_TRACE(2, "} end block\n");
281 if (align32(Buf, EndBuf)) {
282 delete M; // Malformed bc file, read past end of block.
283 return failure(true);
287 if (postResolveValues(LateResolveValues) ||
288 postResolveValues(LateResolveModuleValues)) {
289 delete M; return failure(true); // Unresolvable references!
292 Value *MethPHolder = getValue(MTy, MethSlot, false);
293 assert(MethPHolder && "Something is broken no placeholder found!");
294 assert(isa<Method>(MethPHolder) && "Not a method?");
296 unsigned type; // Type slot
297 assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
298 getTypeSlot(MTy, type);
300 C->getMethodList().push_back(M);
302 // Replace placeholder with the real method pointer...
303 ModuleValues[type][MethSlot] = M;
305 // Clear out method level types...
306 MethodTypeValues.clear();
308 // If anyone is using the placeholder make them use the real method instead
309 MethPHolder->replaceAllUsesWith(M);
311 // We don't need the placeholder anymore!
317 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
319 if (!MethodSignatureList.empty())
320 return failure(true); // Two ModuleGlobal blocks?
322 // Read global variables...
324 if (read_vbr(Buf, End, VarType)) return failure(true);
325 while (VarType != Type::VoidTyID) { // List is terminated by Void
326 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2+ = slot#
327 const Type *Ty = getType(VarType >> 2);
328 if (!Ty || !Ty->isPointerType()) {
329 cerr << "Global not pointer type! Ty = " << Ty << endl;
330 return failure(true);
333 ConstPoolVal *Initializer = 0;
334 if (VarType & 2) { // Does it have an initalizer?
335 // Do not improvise... values must have been stored in the constant pool,
336 // which should have been read before now.
339 if (read_vbr(Buf, End, InitSlot)) return failure(true);
341 Value *V = getValue(Ty->castPointerType()->getValueType(),
343 if (V == 0) return failure(true);
344 Initializer = cast<ConstPoolVal>(V);
347 // Create the global variable...
348 GlobalVariable *GV = new GlobalVariable(Ty, VarType & 1, Initializer);
349 insertValue(GV, ModuleValues);
350 C->getGlobalList().push_back(GV);
352 if (read_vbr(Buf, End, VarType)) return failure(true);
353 BCR_TRACE(2, "Global Variable of type: " << Ty->getDescription() << endl);
356 // Read the method signatures for all of the methods that are coming, and
357 // create fillers in the Value tables.
358 unsigned MethSignature;
359 if (read_vbr(Buf, End, MethSignature)) return failure(true);
360 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
361 const Type *Ty = getType(MethSignature);
362 if (!Ty || !isa<MethodType>(Ty)) {
363 cerr << "Method not meth type! Ty = " << Ty << endl;
364 return failure(true);
367 // When the ModuleGlobalInfo section is read, we load the type of each
368 // method and the 'ModuleValues' slot that it lands in. We then load a
369 // placeholder into its slot to reserve it. When the method is loaded, this
370 // placeholder is replaced.
372 // Insert the placeholder...
373 Value *Def = new MethPHolder(Ty, 0);
374 insertValue(Def, ModuleValues);
376 // Figure out which entry of its typeslot it went into...
378 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
380 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
382 // Keep track of this information in a linked list that is emptied as
383 // methods are loaded...
385 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
386 if (read_vbr(Buf, End, MethSignature)) return failure(true);
387 BCR_TRACE(2, "Method of type: " << Ty << endl);
390 if (align32(Buf, End)) return failure(true);
392 // This is for future proofing... in the future extra fields may be added that
393 // we don't understand, so we transparently ignore them.
399 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
403 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
404 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
405 return failure(true); // Hrm, not a class?
407 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
408 MethodSignatureList.clear(); // Just in case...
410 // Read into instance variables...
411 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
412 if (align32(Buf, EndBuf)) return failure(true);
413 BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
416 while (Buf < EndBuf) {
417 const uchar *OldBuf = Buf;
418 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
420 case BytecodeFormat::ConstantPool:
421 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
422 if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
423 delete C; return failure(true);
427 case BytecodeFormat::ModuleGlobalInfo:
428 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
430 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
431 delete C; return failure(true);
435 case BytecodeFormat::Method: {
436 BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
437 if (ParseMethod(Buf, Buf+Size, C)) {
438 delete C; return failure(true); // Error parsing method
443 case BytecodeFormat::SymbolTable:
444 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
445 if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
446 delete C; return failure(true);
451 cerr << " Unknown class block: " << Type << endl;
453 if (OldBuf > Buf) return failure(true); // Wrap around!
456 BCR_TRACE(1, "} end block\n");
457 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
460 if (!MethodSignatureList.empty()) // Expected more methods!
461 return failure(true);
463 BCR_TRACE(0, "} end block\n\n");
467 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
468 LateResolveValues.clear();
470 // Read and check signature...
471 if (read(Buf, EndBuf, Sig) ||
472 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
473 return failure<Module*>(0); // Invalid signature!
476 if (ParseModule(Buf, EndBuf, Result)) return 0;
481 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
482 BytecodeParser Parser;
483 return Parser.ParseBytecode(Buffer, Buffer+Length);
486 // Parse and return a class file...
488 Module *ParseBytecodeFile(const string &Filename) {
492 if (Filename != string("-")) { // Read from a file...
493 int FD = open(Filename.c_str(), O_RDONLY);
494 if (FD == -1) return failure<Module*>(0);
496 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
498 int Length = StatBuf.st_size;
499 if (Length == 0) { close(FD); return failure<Module*>(0); }
500 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
502 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
504 BytecodeParser Parser;
505 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
507 munmap((char*)Buffer, Length);
509 } else { // Read from stdin
512 uchar Buffer[4096], *FileData = 0;
513 while ((BlockSize = read(0, Buffer, 4))) {
514 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
516 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
517 memcpy(FileData+FileSize, Buffer, BlockSize);
518 FileSize += BlockSize;
521 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
525 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
526 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
527 assert((Buf != (uchar*)-1) && "mmap returned error!");
529 memcpy(Buf, FileData, FileSize);
531 uchar *Buf = FileData;
534 BytecodeParser Parser;
535 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
538 munmap((char*)Buf, FileSize); // Free mmap'd data area
540 free(FileData); // Free realloc'd block of memory