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/Module.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/ConstPoolVals.h"
19 #include "llvm/iOther.h"
20 #include "ReaderInternals.h"
21 #include <sys/types.h>
28 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
29 if (Ty->isPrimitiveType()) {
30 Slot = Ty->getPrimitiveID();
32 // Check the method level types first...
33 TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
34 MethodTypeValues.end(), Ty);
35 if (I != MethodTypeValues.end()) {
36 Slot = FirstDerivedTyID+ModuleTypeValues.size()+
37 (&*I - &MethodTypeValues[0]);
39 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
40 if (I == ModuleTypeValues.end()) return true; // Didn't find type!
41 Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
44 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
48 const Type *BytecodeParser::getType(unsigned ID) {
49 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
52 //cerr << "Looking up Type ID: " << ID << endl;
54 const Value *D = getValue(Type::TypeTy, ID, false);
55 if (D == 0) return failure<const Type*>(0);
57 return D->castTypeAsserting();
60 bool BytecodeParser::insertValue(Value *Val, vector<ValueList> &ValueTab) {
62 if (getTypeSlot(Val->getType(), type)) return failure(true);
63 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
65 if (ValueTab.size() <= type)
66 ValueTab.resize(type+1, ValueList());
68 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
69 // << "] = " << Val << endl;
70 ValueTab[type].push_back(Val);
75 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
77 unsigned type; // The type plane it lives in...
79 if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
81 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
82 assert(Create == false);
83 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
84 if (T) return (Value*)T; // Asked for a primitive type...
86 // Otherwise, derived types need offset...
87 Num -= FirstDerivedTyID;
89 // Is it a module level type?
90 if (Num < ModuleTypeValues.size())
91 return (Value*)(const Type*)ModuleTypeValues[Num];
93 // Nope, is it a method level type?
94 Num -= ModuleTypeValues.size();
95 if (Num < MethodTypeValues.size())
96 return (Value*)(const Type*)MethodTypeValues[Num];
101 if (type < ModuleValues.size()) {
102 if (Num < ModuleValues[type].size())
103 return ModuleValues[type][Num];
104 Num -= ModuleValues[type].size();
107 if (Values.size() > type && Values[type].size() > Num)
108 return Values[type][Num];
110 if (!Create) return failure<Value*>(0); // Do not create a placeholder?
113 switch (Ty->getPrimitiveID()) {
114 case Type::LabelTyID: d = new BBPHolder(Ty, oNum); break;
115 case Type::MethodTyID:
116 cerr << "Creating method pholder! : " << type << ":" << oNum << " "
117 << Ty->getName() << endl;
118 d = new MethPHolder(Ty, oNum);
119 insertValue(d, LateResolveModuleValues);
121 default: d = new DefPHolder(Ty, oNum); break;
124 assert(d != 0 && "How did we not make something?");
125 if (insertValue(d, LateResolveValues)) return failure<Value*>(0);
129 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
131 for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
132 ValueList &DL = ValTab[ty];
134 while ((Size = DL.size())) {
135 unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
137 Value *D = DL[Size-1];
140 Value *NewDef = getValue(D->getType(), IDNumber, false);
142 Error = true; // Unresolved thinger
143 cerr << "Unresolvable reference found: <" << D->getType()->getName()
144 << ">:" << IDNumber << "!\n";
146 // Fixup all of the uses of this placeholder def...
147 D->replaceAllUsesWith(NewDef);
149 // Now that all the uses are gone, delete the placeholder...
150 // If we couldn't find a def (error case), then leak a little
151 delete D; // memory, 'cause otherwise we can't remove all uses!
159 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
161 BB = new BasicBlock();
163 while (Buf < EndBuf) {
165 if (ParseInstruction(Buf, EndBuf, Inst)) {
167 return failure(true);
170 if (Inst == 0) { delete BB; return failure(true); }
171 if (insertValue(Inst, Values)) { delete BB; return failure(true); }
173 BB->getInstList().push_back(Inst);
181 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
183 while (Buf < EndBuf) {
184 // Symtab block header: [num entries][type id number]
185 unsigned NumEntries, Typ;
186 if (read_vbr(Buf, EndBuf, NumEntries) ||
187 read_vbr(Buf, EndBuf, Typ)) return failure(true);
188 const Type *Ty = getType(Typ);
189 if (Ty == 0) return failure(true);
191 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
194 for (unsigned i = 0; i < NumEntries; ++i) {
195 // Symtab entry: [def slot #][name]
197 if (read_vbr(Buf, EndBuf, slot)) return failure(true);
199 if (read(Buf, EndBuf, Name, false)) // Not aligned...
200 return failure(true);
202 Value *D = getValue(Ty, slot, false); // Find mapping...
204 BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << endl);
205 return failure(true);
207 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
208 if (!D->isInstruction()) cerr << endl);
210 D->setName(Name, ST);
214 if (Buf > EndBuf) return failure(true);
219 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
221 // Clear out the local values table...
223 if (MethodSignatureList.empty()) return failure(true); // Unexpected method!
225 const MethodType *MTy = MethodSignatureList.front().first;
226 unsigned MethSlot = MethodSignatureList.front().second;
227 MethodSignatureList.pop_front();
228 Method *M = new Method(MTy);
230 BCR_TRACE(2, "METHOD TYPE: " << MTy << endl);
232 const MethodType::ParamTypes &Params = MTy->getParamTypes();
233 for (MethodType::ParamTypes::const_iterator It = Params.begin();
234 It != Params.end(); ++It) {
235 MethodArgument *MA = new MethodArgument(*It);
236 if (insertValue(MA, Values)) { delete M; return failure(true); }
237 M->getArgumentList().push_back(MA);
240 while (Buf < EndBuf) {
242 const uchar *OldBuf = Buf;
243 if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
246 case BytecodeFormat::ConstantPool:
247 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
248 if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
249 delete M; return failure(true);
253 case BytecodeFormat::BasicBlock: {
254 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
256 if (ParseBasicBlock(Buf, Buf+Size, BB) ||
257 insertValue(BB, Values)) {
258 delete M; return failure(true); // Parse error... :(
261 M->getBasicBlocks().push_back(BB);
265 case BytecodeFormat::SymbolTable:
266 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
267 if (ParseSymbolTable(Buf, Buf+Size, M->getSymbolTableSure())) {
268 delete M; return failure(true);
273 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
275 if (OldBuf > Buf) return failure(true); // Wrap around!
278 BCR_TRACE(2, "} end block\n");
280 if (align32(Buf, EndBuf)) {
281 delete M; // Malformed bc file, read past end of block.
282 return failure(true);
286 if (postResolveValues(LateResolveValues) ||
287 postResolveValues(LateResolveModuleValues)) {
288 delete M; return failure(true); // Unresolvable references!
291 Value *MethPHolder = getValue(MTy, MethSlot, false);
292 assert(MethPHolder && "Something is broken no placeholder found!");
293 assert(MethPHolder->isMethod() && "Not a method?");
295 unsigned type; // Type slot
296 assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
297 getTypeSlot(MTy, type);
299 C->getMethodList().push_back(M);
301 // Replace placeholder with the real method pointer...
302 ModuleValues[type][MethSlot] = M;
304 // If anyone is using the placeholder make them use the real method instead
305 MethPHolder->replaceAllUsesWith(M);
307 // We don't need the placeholder anymore!
313 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
316 if (!MethodSignatureList.empty())
317 return failure(true); // Two ModuleGlobal blocks?
319 // Read the method signatures for all of the methods that are coming, and
320 // create fillers in the Value tables.
321 unsigned MethSignature;
322 if (read_vbr(Buf, End, MethSignature)) return failure(true);
323 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
324 const Type *Ty = getType(MethSignature);
325 if (!Ty || !Ty->isMethodType()) {
326 cerr << "Method not meth type! Ty = " << Ty << endl;
327 if (Ty) cerr << Ty->getName(); else cerr << MethSignature; cerr << endl;
328 return failure(true);
331 // When the ModuleGlobalInfo section is read, we load the type of each
332 // method and the 'ModuleValues' slot that it lands in. We then load a
333 // placeholder into its slot to reserve it. When the method is loaded, this
334 // placeholder is replaced.
336 // Insert the placeholder...
337 Value *Def = new MethPHolder(Ty, 0);
338 insertValue(Def, ModuleValues);
340 // Figure out which entry of its typeslot it went into...
342 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
344 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
346 // Keep track of this information in a linked list that is emptied as
347 // methods are loaded...
349 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
350 if (read_vbr(Buf, End, MethSignature)) return failure(true);
351 BCR_TRACE(2, "Method of type: " << Ty << endl);
354 if (align32(Buf, End)) return failure(true);
356 // This is for future proofing... in the future extra fields may be added that
357 // we don't understand, so we transparently ignore them.
363 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
367 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
368 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
369 return failure(true); // Hrm, not a class?
371 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
372 MethodSignatureList.clear(); // Just in case...
374 // Read into instance variables...
375 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
376 if (align32(Buf, EndBuf)) return failure(true);
377 BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
380 while (Buf < EndBuf) {
381 const uchar *OldBuf = Buf;
382 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
384 case BytecodeFormat::ConstantPool:
385 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
386 if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
387 delete C; return failure(true);
391 case BytecodeFormat::ModuleGlobalInfo:
392 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
394 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
395 delete C; return failure(true);
399 case BytecodeFormat::Method: {
400 BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
401 if (ParseMethod(Buf, Buf+Size, C)) {
402 delete C; return failure(true); // Error parsing method
407 case BytecodeFormat::SymbolTable:
408 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
409 if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
410 delete C; return failure(true);
415 cerr << " Unknown class block: " << Type << endl;
417 if (OldBuf > Buf) return failure(true); // Wrap around!
420 BCR_TRACE(1, "} end block\n");
421 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
424 if (!MethodSignatureList.empty()) // Expected more methods!
425 return failure(true);
427 BCR_TRACE(0, "} end block\n\n");
431 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
432 LateResolveValues.clear();
434 // Read and check signature...
435 if (read(Buf, EndBuf, Sig) ||
436 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
437 return failure<Module*>(0); // Invalid signature!
440 if (ParseModule(Buf, EndBuf, Result)) return 0;
445 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
446 BytecodeParser Parser;
447 return Parser.ParseBytecode(Buffer, Buffer+Length);
450 // Parse and return a class file...
452 Module *ParseBytecodeFile(const string &Filename) {
456 if (Filename != string("-")) { // Read from a file...
457 int FD = open(Filename.c_str(), O_RDONLY);
458 if (FD == -1) return failure<Module*>(0);
460 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
462 int Length = StatBuf.st_size;
463 if (Length == 0) { close(FD); return failure<Module*>(0); }
464 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
466 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
468 BytecodeParser Parser;
469 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
471 munmap((char*)Buffer, Length);
473 } else { // Read from stdin
476 uchar Buffer[4096], *FileData = 0;
477 while ((BlockSize = read(0, Buffer, 4))) {
478 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
480 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
481 memcpy(FileData+FileSize, Buffer, BlockSize);
482 FileSize += BlockSize;
485 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
489 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
490 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
491 assert((Buf != (uchar*)-1) && "mmap returned error!");
493 memcpy(Buf, FileData, FileSize);
495 uchar *Buf = FileData;
498 BytecodeParser Parser;
499 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
502 munmap((char*)Buf, FileSize); // Free mmap'd data area
504 free(FileData); // Free realloc'd block of memory