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);
58 return D->castTypeAsserting();
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 (!D->isInstruction()) 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(MethPHolder->isMethod() && "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 const Type *Ty = getType(VarType);
327 if (!Ty || !Ty->isPointerType()) {
328 cerr << "Global not pointer type! Ty = " << Ty << endl;
329 return failure(true);
332 // Create the global variable...
333 GlobalVariable *GV = new GlobalVariable(Ty);
334 insertValue(GV, ModuleValues);
335 C->getGlobalList().push_back(GV);
337 if (read_vbr(Buf, End, VarType)) return failure(true);
338 BCR_TRACE(2, "Global Variable of type: " << Ty->getDescription() << endl);
341 // Read the method signatures for all of the methods that are coming, and
342 // create fillers in the Value tables.
343 unsigned MethSignature;
344 if (read_vbr(Buf, End, MethSignature)) return failure(true);
345 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
346 const Type *Ty = getType(MethSignature);
347 if (!Ty || !Ty->isMethodType()) {
348 cerr << "Method not meth type! Ty = " << Ty << endl;
349 return failure(true);
352 // When the ModuleGlobalInfo section is read, we load the type of each
353 // method and the 'ModuleValues' slot that it lands in. We then load a
354 // placeholder into its slot to reserve it. When the method is loaded, this
355 // placeholder is replaced.
357 // Insert the placeholder...
358 Value *Def = new MethPHolder(Ty, 0);
359 insertValue(Def, ModuleValues);
361 // Figure out which entry of its typeslot it went into...
363 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
365 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
367 // Keep track of this information in a linked list that is emptied as
368 // methods are loaded...
370 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
371 if (read_vbr(Buf, End, MethSignature)) return failure(true);
372 BCR_TRACE(2, "Method of type: " << Ty << endl);
375 if (align32(Buf, End)) return failure(true);
377 // This is for future proofing... in the future extra fields may be added that
378 // we don't understand, so we transparently ignore them.
384 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
388 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
389 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
390 return failure(true); // Hrm, not a class?
392 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
393 MethodSignatureList.clear(); // Just in case...
395 // Read into instance variables...
396 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
397 if (align32(Buf, EndBuf)) return failure(true);
398 BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
401 while (Buf < EndBuf) {
402 const uchar *OldBuf = Buf;
403 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
405 case BytecodeFormat::ConstantPool:
406 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
407 if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
408 delete C; return failure(true);
412 case BytecodeFormat::ModuleGlobalInfo:
413 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
415 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
416 delete C; return failure(true);
420 case BytecodeFormat::Method: {
421 BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
422 if (ParseMethod(Buf, Buf+Size, C)) {
423 delete C; return failure(true); // Error parsing method
428 case BytecodeFormat::SymbolTable:
429 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
430 if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
431 delete C; return failure(true);
436 cerr << " Unknown class block: " << Type << endl;
438 if (OldBuf > Buf) return failure(true); // Wrap around!
441 BCR_TRACE(1, "} end block\n");
442 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
445 if (!MethodSignatureList.empty()) // Expected more methods!
446 return failure(true);
448 BCR_TRACE(0, "} end block\n\n");
452 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
453 LateResolveValues.clear();
455 // Read and check signature...
456 if (read(Buf, EndBuf, Sig) ||
457 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
458 return failure<Module*>(0); // Invalid signature!
461 if (ParseModule(Buf, EndBuf, Result)) return 0;
466 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
467 BytecodeParser Parser;
468 return Parser.ParseBytecode(Buffer, Buffer+Length);
471 // Parse and return a class file...
473 Module *ParseBytecodeFile(const string &Filename) {
477 if (Filename != string("-")) { // Read from a file...
478 int FD = open(Filename.c_str(), O_RDONLY);
479 if (FD == -1) return failure<Module*>(0);
481 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
483 int Length = StatBuf.st_size;
484 if (Length == 0) { close(FD); return failure<Module*>(0); }
485 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
487 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
489 BytecodeParser Parser;
490 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
492 munmap((char*)Buffer, Length);
494 } else { // Read from stdin
497 uchar Buffer[4096], *FileData = 0;
498 while ((BlockSize = read(0, Buffer, 4))) {
499 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
501 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
502 memcpy(FileData+FileSize, Buffer, BlockSize);
503 FileSize += BlockSize;
506 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
510 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
511 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
512 assert((Buf != (uchar*)-1) && "mmap returned error!");
514 memcpy(Buf, FileData, FileSize);
516 uchar *Buf = FileData;
519 BytecodeParser Parser;
520 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
523 munmap((char*)Buf, FileSize); // Free mmap'd data area
525 free(FileData); // Free realloc'd block of memory