blob: e7e2b488c935c88afa370e37b3187823e17bbe66 [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===- Reader.cpp - Code to read bytecode files -----------------------------===
2//
3// This library implements the functionality defined in llvm/Bytecode/Reader.h
4//
5// Note that this library should be as fast as possible, reentrant, and
6// threadsafe!!
7//
8// TODO: Make error message outputs be configurable depending on an option?
9// TODO: Allow passing in an option to ignore the symbol table
10//
11//===------------------------------------------------------------------------===
12
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>
22#include <sys/mman.h>
23#include <sys/stat.h>
24#include <fcntl.h>
25#include <unistd.h>
26#include <algorithm>
27
28bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
29 if (Ty->isPrimitiveType()) {
30 Slot = Ty->getPrimitiveID();
31 } else {
32 TypeMapType::iterator I = TypeMap.find(Ty);
Chris Lattner3d3f2892001-07-28 17:50:18 +000033 if (I == TypeMap.end()) return failure(true); // Didn't find type!
Chris Lattner00950542001-06-06 20:29:01 +000034 Slot = I->second;
35 }
36 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
37 return false;
38}
39
40const Type *BytecodeParser::getType(unsigned ID) {
41 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
42 if (T) return T;
43
44 //cerr << "Looking up Type ID: " << ID << endl;
45
46 const Value *D = getValue(Type::TypeTy, ID, false);
Chris Lattner3d3f2892001-07-28 17:50:18 +000047 if (D == 0) return failure<const Type*>(0);
Chris Lattner00950542001-06-06 20:29:01 +000048
Chris Lattner7fc9fe32001-06-27 23:41:11 +000049 assert(D->getType() == Type::TypeTy);
50 return ((const ConstPoolType*)D->castConstantAsserting())->getValue();
Chris Lattner00950542001-06-06 20:29:01 +000051}
52
53bool BytecodeParser::insertValue(Value *Def, vector<ValueList> &ValueTab) {
54 unsigned type;
Chris Lattner3d3f2892001-07-28 17:50:18 +000055 if (getTypeSlot(Def->getType(), type)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +000056
57 if (ValueTab.size() <= type)
58 ValueTab.resize(type+1, ValueList());
59
60 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
61 // << "] = " << Def << endl;
62
Chris Lattner7fc9fe32001-06-27 23:41:11 +000063 if (type == Type::TypeTyID && Def->isConstant()) {
Chris Lattner00950542001-06-06 20:29:01 +000064 const Type *Ty = ((const ConstPoolType*)Def)->getValue();
65 unsigned ValueOffset = FirstDerivedTyID;
66
67 if (&ValueTab == &Values) // Take into consideration module level types
68 ValueOffset += ModuleValues[type].size();
69
70 if (TypeMap.find(Ty) == TypeMap.end())
71 TypeMap[Ty] = ValueTab[type].size()+ValueOffset;
72 }
73
74 ValueTab[type].push_back(Def);
75
76 return false;
77}
78
79Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
80 unsigned Num = oNum;
81 unsigned type; // The type plane it lives in...
82
Chris Lattner3d3f2892001-07-28 17:50:18 +000083 if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
Chris Lattner00950542001-06-06 20:29:01 +000084
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...
88
89 // Otherwise, derived types need offset...
90 Num -= FirstDerivedTyID;
91 }
92
93 if (ModuleValues.size() > type) {
94 if (ModuleValues[type].size() > Num)
95 return ModuleValues[type][Num];
96 Num -= ModuleValues[type].size();
97 }
98
99 if (Values.size() > type && Values[type].size() > Num)
100 return Values[type][Num];
101
Chris Lattner3d3f2892001-07-28 17:50:18 +0000102 if (!Create) return failure<Value*>(0); // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000103
104 Value *d = 0;
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);
112 return d;
113 default: d = new DefPHolder(Ty, oNum); break;
114 }
115
116 assert(d != 0 && "How did we not make something?");
Chris Lattner3d3f2892001-07-28 17:50:18 +0000117 if (insertValue(d, LateResolveValues)) return failure<Value*>(0);
Chris Lattner00950542001-06-06 20:29:01 +0000118 return d;
119}
120
121bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
122 bool Error = false;
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000123 for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
Chris Lattner00950542001-06-06 20:29:01 +0000124 ValueList &DL = ValTab[ty];
125 unsigned Size;
126 while ((Size = DL.size())) {
127 unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
128
129 Value *D = DL[Size-1];
130 DL.pop_back();
131
132 Value *NewDef = getValue(D->getType(), IDNumber, false);
133 if (NewDef == 0) {
134 Error = true; // Unresolved thinger
135 cerr << "Unresolvable reference found: <" << D->getType()->getName()
136 << ">:" << IDNumber << "!\n";
137 } else {
138 // Fixup all of the uses of this placeholder def...
139 D->replaceAllUsesWith(NewDef);
140
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!
144 }
145 }
146 }
147
148 return Error;
149}
150
151bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
152 BasicBlock *&BB) {
153 BB = new BasicBlock();
154
155 while (Buf < EndBuf) {
156 Instruction *Def;
157 if (ParseInstruction(Buf, EndBuf, Def)) {
158 delete BB;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000159 return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000160 }
161
Chris Lattner3d3f2892001-07-28 17:50:18 +0000162 if (Def == 0) { delete BB; return failure(true); }
163 if (insertValue(Def, Values)) { delete BB; return failure(true); }
Chris Lattner00950542001-06-06 20:29:01 +0000164
165 BB->getInstList().push_back(Def);
166 }
167
168 return false;
169}
170
171bool 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) ||
Chris Lattner3d3f2892001-07-28 17:50:18 +0000176 read_vbr(Buf, EndBuf, Typ)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000177 const Type *Ty = getType(Typ);
Chris Lattner3d3f2892001-07-28 17:50:18 +0000178 if (Ty == 0) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000179
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000180 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000181 // Symtab entry: [def slot #][name]
182 unsigned slot;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000183 if (read_vbr(Buf, EndBuf, slot)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000184 string Name;
185 if (read(Buf, EndBuf, Name, false)) // Not aligned...
Chris Lattner3d3f2892001-07-28 17:50:18 +0000186 return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000187
188 Value *D = getValue(Ty, slot, false); // Find mapping...
Chris Lattner3d3f2892001-07-28 17:50:18 +0000189 if (D == 0) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000190 D->setName(Name);
191 }
192 }
193
Chris Lattner3d3f2892001-07-28 17:50:18 +0000194 if (Buf > EndBuf) return failure(true);
195 return false;
Chris Lattner00950542001-06-06 20:29:01 +0000196}
197
198
199bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
200 Module *C) {
201 // Clear out the local values table...
202 Values.clear();
Chris Lattner3d3f2892001-07-28 17:50:18 +0000203 if (MethodSignatureList.empty()) return failure(true); // Unexpected method!
Chris Lattner00950542001-06-06 20:29:01 +0000204
205 const MethodType *MTy = MethodSignatureList.front().first;
206 unsigned MethSlot = MethodSignatureList.front().second;
207 MethodSignatureList.pop_front();
208 Method *M = new Method(MTy);
209
210 const MethodType::ParamTypes &Params = MTy->getParamTypes();
211 for (MethodType::ParamTypes::const_iterator It = Params.begin();
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000212 It != Params.end(); ++It) {
Chris Lattner00950542001-06-06 20:29:01 +0000213 MethodArgument *MA = new MethodArgument(*It);
Chris Lattner3d3f2892001-07-28 17:50:18 +0000214 if (insertValue(MA, Values)) { delete M; return failure(true); }
Chris Lattner00950542001-06-06 20:29:01 +0000215 M->getArgumentList().push_back(MA);
216 }
217
218 while (Buf < EndBuf) {
219 unsigned Type, Size;
220 const uchar *OldBuf = Buf;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000221 if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
Chris Lattner00950542001-06-06 20:29:01 +0000222
223 switch (Type) {
224 case BytecodeFormat::ConstantPool:
225 if (ParseConstantPool(Buf, Buf+Size, M->getConstantPool(), Values)) {
226 cerr << "Error reading constant pool!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000227 delete M; return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000228 }
229 break;
230
231 case BytecodeFormat::BasicBlock: {
232 BasicBlock *BB;
233 if (ParseBasicBlock(Buf, Buf+Size, BB) ||
234 insertValue(BB, Values)) {
235 cerr << "Error parsing basic block!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000236 delete M; return failure(true); // Parse error... :(
Chris Lattner00950542001-06-06 20:29:01 +0000237 }
238
239 M->getBasicBlocks().push_back(BB);
240 break;
241 }
242
243 case BytecodeFormat::SymbolTable:
244 if (ParseSymbolTable(Buf, Buf+Size)) {
245 cerr << "Error reading method symbol table!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000246 delete M; return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000247 }
248 break;
249
250 default:
251 Buf += Size;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000252 if (OldBuf > Buf) return failure(true); // Wrap around!
Chris Lattner00950542001-06-06 20:29:01 +0000253 break;
254 }
255 if (align32(Buf, EndBuf)) {
256 delete M; // Malformed bc file, read past end of block.
Chris Lattner3d3f2892001-07-28 17:50:18 +0000257 return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000258 }
259 }
260
261 if (postResolveValues(LateResolveValues) ||
262 postResolveValues(LateResolveModuleValues)) {
Chris Lattner3d3f2892001-07-28 17:50:18 +0000263 delete M; return failure(true); // Unresolvable references!
Chris Lattner00950542001-06-06 20:29:01 +0000264 }
265
266 Value *MethPHolder = getValue(MTy, MethSlot, false);
267 assert(MethPHolder && "Something is broken no placeholder found!");
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000268 assert(MethPHolder->isMethod() && "Not a method?");
Chris Lattner00950542001-06-06 20:29:01 +0000269
270 unsigned type; // Type slot
271 assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
272 getTypeSlot(MTy, type);
273
274 C->getMethodList().push_back(M);
275
276 // Replace placeholder with the real method pointer...
277 ModuleValues[type][MethSlot] = M;
278
279 // If anyone is using the placeholder make them use the real method instead
280 MethPHolder->replaceAllUsesWith(M);
281
282 // We don't need the placeholder anymore!
283 delete MethPHolder;
284
285 return false;
286}
287
288bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
289 Module *C) {
290
Chris Lattner3d3f2892001-07-28 17:50:18 +0000291 if (!MethodSignatureList.empty())
292 return failure(true); // Two ModuleGlobal blocks?
Chris Lattner00950542001-06-06 20:29:01 +0000293
294 // Read the method signatures for all of the methods that are coming, and
295 // create fillers in the Value tables.
296 unsigned MethSignature;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000297 if (read_vbr(Buf, End, MethSignature)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000298 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;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000303 return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000304 }
305
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
309 // is replaced.
310
311 // Insert the placeholder...
312 Value *Def = new MethPHolder(Ty, 0);
313 insertValue(Def, ModuleValues);
314
315 // Figure out which entry of its typeslot it went into...
316 unsigned TypeSlot;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000317 if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000318
319 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
320
321 // Keep track of this information in a linked list that is emptied as
322 // methods are loaded...
323 //
324 MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
Chris Lattner3d3f2892001-07-28 17:50:18 +0000325 if (read_vbr(Buf, End, MethSignature)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000326 }
327
Chris Lattner3d3f2892001-07-28 17:50:18 +0000328 if (align32(Buf, End)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000329
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.
332 //
333 Buf = End;
334 return false;
335}
336
337bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
338 Module *&C) {
339
340 unsigned Type, Size;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000341 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000342 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
Chris Lattner3d3f2892001-07-28 17:50:18 +0000343 return failure(true); // Hrm, not a class?
Chris Lattner00950542001-06-06 20:29:01 +0000344
345 MethodSignatureList.clear(); // Just in case...
346
347 // Read into instance variables...
Chris Lattner3d3f2892001-07-28 17:50:18 +0000348 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
349 if (align32(Buf, EndBuf)) return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000350
351 C = new Module();
352
353 while (Buf < EndBuf) {
354 const uchar *OldBuf = Buf;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000355 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
Chris Lattner00950542001-06-06 20:29:01 +0000356 switch (Type) {
357 case BytecodeFormat::ModuleGlobalInfo:
358 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
359 cerr << "Error reading class global info section!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000360 delete C; return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000361 }
362 break;
363
364 case BytecodeFormat::ConstantPool:
365 if (ParseConstantPool(Buf, Buf+Size, C->getConstantPool(), ModuleValues)) {
366 cerr << "Error reading class constant pool!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000367 delete C; return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000368 }
369 break;
370
371 case BytecodeFormat::Method: {
372 if (ParseMethod(Buf, Buf+Size, C)) {
Chris Lattner3d3f2892001-07-28 17:50:18 +0000373 delete C; return failure(true); // Error parsing method
Chris Lattner00950542001-06-06 20:29:01 +0000374 }
375 break;
376 }
377
378 case BytecodeFormat::SymbolTable:
379 if (ParseSymbolTable(Buf, Buf+Size)) {
380 cerr << "Error reading class symbol table!\n";
Chris Lattner3d3f2892001-07-28 17:50:18 +0000381 delete C; return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000382 }
383 break;
384
385 default:
386 cerr << "Unknown class block: " << Type << endl;
387 Buf += Size;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000388 if (OldBuf > Buf) return failure(true); // Wrap around!
Chris Lattner00950542001-06-06 20:29:01 +0000389 break;
390 }
Chris Lattner3d3f2892001-07-28 17:50:18 +0000391 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
Chris Lattner00950542001-06-06 20:29:01 +0000392 }
393
394 if (!MethodSignatureList.empty()) // Expected more methods!
Chris Lattner3d3f2892001-07-28 17:50:18 +0000395 return failure(true);
Chris Lattner00950542001-06-06 20:29:01 +0000396 return false;
397}
398
399Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
400 LateResolveValues.clear();
401 unsigned Sig;
402 // Read and check signature...
403 if (read(Buf, EndBuf, Sig) ||
404 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
Chris Lattner3d3f2892001-07-28 17:50:18 +0000405 return failure<Module*>(0); // Invalid signature!
Chris Lattner00950542001-06-06 20:29:01 +0000406
407 Module *Result;
408 if (ParseModule(Buf, EndBuf, Result)) return 0;
409 return Result;
410}
411
412
413Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
414 BytecodeParser Parser;
415 return Parser.ParseBytecode(Buffer, Buffer+Length);
416}
417
418// Parse and return a class file...
419//
420Module *ParseBytecodeFile(const string &Filename) {
421 struct stat StatBuf;
422 Module *Result = 0;
423
424 if (Filename != string("-")) { // Read from a file...
Chris Lattnerb49ff5c2001-07-23 18:51:23 +0000425 int FD = open(Filename.c_str(), O_RDONLY);
Chris Lattner3d3f2892001-07-28 17:50:18 +0000426 if (FD == -1) return failure<Module*>(0);
Chris Lattner00950542001-06-06 20:29:01 +0000427
Chris Lattner3d3f2892001-07-28 17:50:18 +0000428 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
Chris Lattner00950542001-06-06 20:29:01 +0000429
430 int Length = StatBuf.st_size;
Chris Lattner3d3f2892001-07-28 17:50:18 +0000431 if (Length == 0) { close(FD); return failure<Module*>(0); }
Chris Lattner00950542001-06-06 20:29:01 +0000432 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
433 MAP_PRIVATE, FD, 0);
Chris Lattner3d3f2892001-07-28 17:50:18 +0000434 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
Chris Lattner00950542001-06-06 20:29:01 +0000435
436 BytecodeParser Parser;
437 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
438
439 munmap((char*)Buffer, Length);
440 close(FD);
441 } else { // Read from stdin
442 size_t FileSize = 0;
443 int BlockSize;
444 uchar Buffer[4096], *FileData = 0;
445 while ((BlockSize = read(0, Buffer, 4))) {
Chris Lattner3d3f2892001-07-28 17:50:18 +0000446 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
Chris Lattner00950542001-06-06 20:29:01 +0000447
448 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
449 memcpy(FileData+FileSize, Buffer, BlockSize);
450 FileSize += BlockSize;
451 }
452
Chris Lattner3d3f2892001-07-28 17:50:18 +0000453 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
Chris Lattner00950542001-06-06 20:29:01 +0000454
455#define ALIGN_PTRS 1
456#if ALIGN_PTRS
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!");
460 free(FileData);
461 memcpy(Buf, FileData, FileSize);
462#else
463 uchar *Buf = FileData;
464#endif
465
466 BytecodeParser Parser;
467 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
468
469#if ALIGN_PTRS
470 munmap((char*)Buf, FileSize); // Free mmap'd data area
471#else
472 free(FileData); // Free realloc'd block of memory
473#endif
474 }
475
476 return Result;
477}