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 // If anyone is using the placeholder make them use the real method instead
306 MethPHolder->replaceAllUsesWith(M);
308 // We don't need the placeholder anymore!
314 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
316 if (!MethodSignatureList.empty())
317 return failure(true); // Two ModuleGlobal blocks?
319 // Read global variables...
321 if (read_vbr(Buf, End, VarType)) return failure(true);
322 while (VarType != Type::VoidTyID) { // List is terminated by Void
323 const Type *Ty = getType(VarType);
324 if (!Ty || !Ty->isPointerType()) {
325 cerr << "Global not pointer type! Ty = " << Ty << endl;
326 return failure(true);
329 // Create the global variable...
330 GlobalVariable *GV = new GlobalVariable(Ty);
331 insertValue(GV, ModuleValues);
332 C->getGlobalList().push_back(GV);
334 if (read_vbr(Buf, End, VarType)) return failure(true);
335 BCR_TRACE(2, "Global Variable of type: " << Ty->getDescription() << endl);
338 // Read the method signatures for all of the methods that are coming, and
339 // create fillers in the Value tables.
340 unsigned MethSignature;
341 if (read_vbr(Buf, End, MethSignature)) return failure(true);
342 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
343 const Type *Ty = getType(MethSignature);
344 if (!Ty || !Ty->isMethodType()) {
345 cerr << "Method not meth type! Ty = " << Ty << endl;
346 return failure(true);
349 // When the ModuleGlobalInfo section is read, we load the type of each
350 // method and the 'ModuleValues' slot that it lands in. We then load a
351 // placeholder into its slot to reserve it. When the method is loaded, this
352 // placeholder is replaced.
354 // Insert the placeholder...
355 Value *Def = new MethPHolder(Ty, 0);
356 insertValue(Def, ModuleValues);
358 // Figure out which entry of its typeslot it went into...
360 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
362 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
364 // Keep track of this information in a linked list that is emptied as
365 // methods are loaded...
367 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
368 if (read_vbr(Buf, End, MethSignature)) return failure(true);
369 BCR_TRACE(2, "Method of type: " << Ty << endl);
372 if (align32(Buf, End)) return failure(true);
374 // This is for future proofing... in the future extra fields may be added that
375 // we don't understand, so we transparently ignore them.
381 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
385 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
386 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
387 return failure(true); // Hrm, not a class?
389 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
390 MethodSignatureList.clear(); // Just in case...
392 // Read into instance variables...
393 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
394 if (align32(Buf, EndBuf)) return failure(true);
395 BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
398 while (Buf < EndBuf) {
399 const uchar *OldBuf = Buf;
400 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
402 case BytecodeFormat::ConstantPool:
403 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
404 if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
405 delete C; return failure(true);
409 case BytecodeFormat::ModuleGlobalInfo:
410 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
412 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
413 delete C; return failure(true);
417 case BytecodeFormat::Method: {
418 BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
419 if (ParseMethod(Buf, Buf+Size, C)) {
420 delete C; return failure(true); // Error parsing method
425 case BytecodeFormat::SymbolTable:
426 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
427 if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
428 delete C; return failure(true);
433 cerr << " Unknown class block: " << Type << endl;
435 if (OldBuf > Buf) return failure(true); // Wrap around!
438 BCR_TRACE(1, "} end block\n");
439 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
442 if (!MethodSignatureList.empty()) // Expected more methods!
443 return failure(true);
445 BCR_TRACE(0, "} end block\n\n");
449 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
450 LateResolveValues.clear();
452 // Read and check signature...
453 if (read(Buf, EndBuf, Sig) ||
454 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
455 return failure<Module*>(0); // Invalid signature!
458 if (ParseModule(Buf, EndBuf, Result)) return 0;
463 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
464 BytecodeParser Parser;
465 return Parser.ParseBytecode(Buffer, Buffer+Length);
468 // Parse and return a class file...
470 Module *ParseBytecodeFile(const string &Filename) {
474 if (Filename != string("-")) { // Read from a file...
475 int FD = open(Filename.c_str(), O_RDONLY);
476 if (FD == -1) return failure<Module*>(0);
478 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
480 int Length = StatBuf.st_size;
481 if (Length == 0) { close(FD); return failure<Module*>(0); }
482 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
484 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
486 BytecodeParser Parser;
487 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
489 munmap((char*)Buffer, Length);
491 } else { // Read from stdin
494 uchar Buffer[4096], *FileData = 0;
495 while ((BlockSize = read(0, Buffer, 4))) {
496 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
498 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
499 memcpy(FileData+FileSize, Buffer, BlockSize);
500 FileSize += BlockSize;
503 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
507 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
508 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
509 assert((Buf != (uchar*)-1) && "mmap returned error!");
511 memcpy(Buf, FileData, FileSize);
513 uchar *Buf = FileData;
516 BytecodeParser Parser;
517 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
520 munmap((char*)Buf, FileSize); // Free mmap'd data area
522 free(FileData); // Free realloc'd block of memory