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 TypeMapType::iterator I = TypeMap.find(Ty);
33 if (I == TypeMap.end()) return failure(true); // Didn't find type!
36 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
40 const Type *BytecodeParser::getType(unsigned ID) {
41 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
44 //cerr << "Looking up Type ID: " << ID << endl;
46 const Value *D = getValue(Type::TypeTy, ID, false);
47 if (D == 0) return failure<const Type*>(0);
49 assert(D->getType() == Type::TypeTy);
50 return ((const ConstPoolType*)D->castConstantAsserting())->getValue();
53 bool BytecodeParser::insertValue(Value *Def, vector<ValueList> &ValueTab) {
55 if (getTypeSlot(Def->getType(), type)) return failure(true);
57 if (ValueTab.size() <= type)
58 ValueTab.resize(type+1, ValueList());
60 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
61 // << "] = " << Def << endl;
63 if (type == Type::TypeTyID && Def->isConstant()) {
64 const Type *Ty = ((const ConstPoolType*)Def)->getValue();
65 unsigned ValueOffset = FirstDerivedTyID;
67 if (&ValueTab == &Values) // Take into consideration module level types
68 ValueOffset += ModuleValues[type].size();
70 if (TypeMap.find(Ty) == TypeMap.end())
71 TypeMap[Ty] = ValueTab[type].size()+ValueOffset;
74 ValueTab[type].push_back(Def);
79 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
81 unsigned type; // The type plane it lives in...
83 if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
85 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
86 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
87 if (T) return (Value*)T; // Asked for a primitive type...
89 // Otherwise, derived types need offset...
90 Num -= FirstDerivedTyID;
93 if (ModuleValues.size() > type) {
94 if (ModuleValues[type].size() > Num)
95 return ModuleValues[type][Num];
96 Num -= ModuleValues[type].size();
99 if (Values.size() > type && Values[type].size() > Num)
100 return Values[type][Num];
102 if (!Create) return failure<Value*>(0); // Do not create a placeholder?
105 switch (Ty->getPrimitiveID()) {
106 case Type::LabelTyID: d = new BBPHolder(Ty, oNum); break;
107 case Type::MethodTyID:
108 cerr << "Creating method pholder! : " << type << ":" << oNum << " "
109 << Ty->getName() << endl;
110 d = new MethPHolder(Ty, oNum);
111 insertValue(d, LateResolveModuleValues);
113 default: d = new DefPHolder(Ty, oNum); break;
116 assert(d != 0 && "How did we not make something?");
117 if (insertValue(d, LateResolveValues)) return failure<Value*>(0);
121 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
123 for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
124 ValueList &DL = ValTab[ty];
126 while ((Size = DL.size())) {
127 unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
129 Value *D = DL[Size-1];
132 Value *NewDef = getValue(D->getType(), IDNumber, false);
134 Error = true; // Unresolved thinger
135 cerr << "Unresolvable reference found: <" << D->getType()->getName()
136 << ">:" << IDNumber << "!\n";
138 // Fixup all of the uses of this placeholder def...
139 D->replaceAllUsesWith(NewDef);
141 // Now that all the uses are gone, delete the placeholder...
142 // If we couldn't find a def (error case), then leak a little
143 delete D; // memory, 'cause otherwise we can't remove all uses!
151 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
153 BB = new BasicBlock();
155 while (Buf < EndBuf) {
157 if (ParseInstruction(Buf, EndBuf, Def)) {
159 return failure(true);
162 if (Def == 0) { delete BB; return failure(true); }
163 if (insertValue(Def, Values)) { delete BB; return failure(true); }
165 BB->getInstList().push_back(Def);
171 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf) {
172 while (Buf < EndBuf) {
173 // Symtab block header: [num entries][type id number]
174 unsigned NumEntries, Typ;
175 if (read_vbr(Buf, EndBuf, NumEntries) ||
176 read_vbr(Buf, EndBuf, Typ)) return failure(true);
177 const Type *Ty = getType(Typ);
178 if (Ty == 0) return failure(true);
180 for (unsigned i = 0; i < NumEntries; ++i) {
181 // Symtab entry: [def slot #][name]
183 if (read_vbr(Buf, EndBuf, slot)) return failure(true);
185 if (read(Buf, EndBuf, Name, false)) // Not aligned...
186 return failure(true);
188 Value *D = getValue(Ty, slot, false); // Find mapping...
189 if (D == 0) return failure(true);
194 if (Buf > EndBuf) return failure(true);
199 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
201 // Clear out the local values table...
203 if (MethodSignatureList.empty()) return failure(true); // Unexpected method!
205 const MethodType *MTy = MethodSignatureList.front().first;
206 unsigned MethSlot = MethodSignatureList.front().second;
207 MethodSignatureList.pop_front();
208 Method *M = new Method(MTy);
210 const MethodType::ParamTypes &Params = MTy->getParamTypes();
211 for (MethodType::ParamTypes::const_iterator It = Params.begin();
212 It != Params.end(); ++It) {
213 MethodArgument *MA = new MethodArgument(*It);
214 if (insertValue(MA, Values)) { delete M; return failure(true); }
215 M->getArgumentList().push_back(MA);
218 while (Buf < EndBuf) {
220 const uchar *OldBuf = Buf;
221 if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
224 case BytecodeFormat::ConstantPool:
225 if (ParseConstantPool(Buf, Buf+Size, M->getConstantPool(), Values)) {
226 cerr << "Error reading constant pool!\n";
227 delete M; return failure(true);
231 case BytecodeFormat::BasicBlock: {
233 if (ParseBasicBlock(Buf, Buf+Size, BB) ||
234 insertValue(BB, Values)) {
235 cerr << "Error parsing basic block!\n";
236 delete M; return failure(true); // Parse error... :(
239 M->getBasicBlocks().push_back(BB);
243 case BytecodeFormat::SymbolTable:
244 if (ParseSymbolTable(Buf, Buf+Size)) {
245 cerr << "Error reading method symbol table!\n";
246 delete M; return failure(true);
252 if (OldBuf > Buf) return failure(true); // Wrap around!
255 if (align32(Buf, EndBuf)) {
256 delete M; // Malformed bc file, read past end of block.
257 return failure(true);
261 if (postResolveValues(LateResolveValues) ||
262 postResolveValues(LateResolveModuleValues)) {
263 delete M; return failure(true); // Unresolvable references!
266 Value *MethPHolder = getValue(MTy, MethSlot, false);
267 assert(MethPHolder && "Something is broken no placeholder found!");
268 assert(MethPHolder->isMethod() && "Not a method?");
270 unsigned type; // Type slot
271 assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
272 getTypeSlot(MTy, type);
274 C->getMethodList().push_back(M);
276 // Replace placeholder with the real method pointer...
277 ModuleValues[type][MethSlot] = M;
279 // If anyone is using the placeholder make them use the real method instead
280 MethPHolder->replaceAllUsesWith(M);
282 // We don't need the placeholder anymore!
288 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
291 if (!MethodSignatureList.empty())
292 return failure(true); // Two ModuleGlobal blocks?
294 // Read the method signatures for all of the methods that are coming, and
295 // create fillers in the Value tables.
296 unsigned MethSignature;
297 if (read_vbr(Buf, End, MethSignature)) return failure(true);
298 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
299 const Type *Ty = getType(MethSignature);
300 if (!Ty || !Ty->isMethodType()) {
301 cerr << "Method not meth type! ";
302 if (Ty) cerr << Ty->getName(); else cerr << MethSignature; cerr << endl;
303 return failure(true);
306 // When the ModuleGlobalInfo section is read, we load the type of each method
307 // and the 'ModuleValues' slot that it lands in. We then load a placeholder
308 // into its slot to reserve it. When the method is loaded, this placeholder
311 // Insert the placeholder...
312 Value *Def = new MethPHolder(Ty, 0);
313 insertValue(Def, ModuleValues);
315 // Figure out which entry of its typeslot it went into...
317 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
319 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
321 // Keep track of this information in a linked list that is emptied as
322 // methods are loaded...
324 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
325 if (read_vbr(Buf, End, MethSignature)) return failure(true);
328 if (align32(Buf, End)) return failure(true);
330 // This is for future proofing... in the future extra fields may be added that
331 // we don't understand, so we transparently ignore them.
337 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
341 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
342 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
343 return failure(true); // Hrm, not a class?
345 MethodSignatureList.clear(); // Just in case...
347 // Read into instance variables...
348 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
349 if (align32(Buf, EndBuf)) return failure(true);
353 while (Buf < EndBuf) {
354 const uchar *OldBuf = Buf;
355 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
357 case BytecodeFormat::ModuleGlobalInfo:
358 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
359 cerr << "Error reading class global info section!\n";
360 delete C; return failure(true);
364 case BytecodeFormat::ConstantPool:
365 if (ParseConstantPool(Buf, Buf+Size, C->getConstantPool(), ModuleValues)) {
366 cerr << "Error reading class constant pool!\n";
367 delete C; return failure(true);
371 case BytecodeFormat::Method: {
372 if (ParseMethod(Buf, Buf+Size, C)) {
373 delete C; return failure(true); // Error parsing method
378 case BytecodeFormat::SymbolTable:
379 if (ParseSymbolTable(Buf, Buf+Size)) {
380 cerr << "Error reading class symbol table!\n";
381 delete C; return failure(true);
386 cerr << "Unknown class block: " << Type << endl;
388 if (OldBuf > Buf) return failure(true); // Wrap around!
391 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
394 if (!MethodSignatureList.empty()) // Expected more methods!
395 return failure(true);
399 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
400 LateResolveValues.clear();
402 // Read and check signature...
403 if (read(Buf, EndBuf, Sig) ||
404 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
405 return failure<Module*>(0); // Invalid signature!
408 if (ParseModule(Buf, EndBuf, Result)) return 0;
413 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
414 BytecodeParser Parser;
415 return Parser.ParseBytecode(Buffer, Buffer+Length);
418 // Parse and return a class file...
420 Module *ParseBytecodeFile(const string &Filename) {
424 if (Filename != string("-")) { // Read from a file...
425 int FD = open(Filename.c_str(), O_RDONLY);
426 if (FD == -1) return failure<Module*>(0);
428 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
430 int Length = StatBuf.st_size;
431 if (Length == 0) { close(FD); return failure<Module*>(0); }
432 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
434 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
436 BytecodeParser Parser;
437 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
439 munmap((char*)Buffer, Length);
441 } else { // Read from stdin
444 uchar Buffer[4096], *FileData = 0;
445 while ((BlockSize = read(0, Buffer, 4))) {
446 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
448 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
449 memcpy(FileData+FileSize, Buffer, BlockSize);
450 FileSize += BlockSize;
453 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
457 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
458 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
459 assert((Buf != (uchar*)-1) && "mmap returned error!");
461 memcpy(Buf, FileData, FileSize);
463 uchar *Buf = FileData;
466 BytecodeParser Parser;
467 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
470 munmap((char*)Buf, FileSize); // Free mmap'd data area
472 free(FileData); // Free realloc'd block of memory