[Object] Support reading 64-bit MIPS ELF archives
[oota-llvm.git] / lib / Object / Archive.cpp
1 //===- Archive.cpp - ar File Format implementation --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ArchiveObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/Archive.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Support/Endian.h"
19 #include "llvm/Support/MemoryBuffer.h"
20
21 using namespace llvm;
22 using namespace object;
23
24 static const char *const Magic = "!<arch>\n";
25 static const char *const ThinMagic = "!<thin>\n";
26
27 void Archive::anchor() { }
28
29 StringRef ArchiveMemberHeader::getName() const {
30   char EndCond;
31   if (Name[0] == '/' || Name[0] == '#')
32     EndCond = ' ';
33   else
34     EndCond = '/';
35   llvm::StringRef::size_type end =
36       llvm::StringRef(Name, sizeof(Name)).find(EndCond);
37   if (end == llvm::StringRef::npos)
38     end = sizeof(Name);
39   assert(end <= sizeof(Name) && end > 0);
40   // Don't include the EndCond if there is one.
41   return llvm::StringRef(Name, end);
42 }
43
44 uint32_t ArchiveMemberHeader::getSize() const {
45   uint32_t Ret;
46   if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
47     llvm_unreachable("Size is not a decimal number.");
48   return Ret;
49 }
50
51 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
52   unsigned Ret;
53   if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
54     llvm_unreachable("Access mode is not an octal number.");
55   return static_cast<sys::fs::perms>(Ret);
56 }
57
58 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
59   unsigned Seconds;
60   if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
61           .getAsInteger(10, Seconds))
62     llvm_unreachable("Last modified time not a decimal number.");
63
64   sys::TimeValue Ret;
65   Ret.fromEpochTime(Seconds);
66   return Ret;
67 }
68
69 unsigned ArchiveMemberHeader::getUID() const {
70   unsigned Ret;
71   if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
72     llvm_unreachable("UID time not a decimal number.");
73   return Ret;
74 }
75
76 unsigned ArchiveMemberHeader::getGID() const {
77   unsigned Ret;
78   if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
79     llvm_unreachable("GID time not a decimal number.");
80   return Ret;
81 }
82
83 Archive::Child::Child(const Archive *Parent, const char *Start)
84     : Parent(Parent) {
85   if (!Start)
86     return;
87
88   const ArchiveMemberHeader *Header =
89       reinterpret_cast<const ArchiveMemberHeader *>(Start);
90   uint64_t Size = sizeof(ArchiveMemberHeader);
91   if (!Parent->IsThin || Header->getName() == "/" || Header->getName() == "//")
92     Size += Header->getSize();
93   Data = StringRef(Start, Size);
94
95   // Setup StartOfFile and PaddingBytes.
96   StartOfFile = sizeof(ArchiveMemberHeader);
97   // Don't include attached name.
98   StringRef Name = Header->getName();
99   if (Name.startswith("#1/")) {
100     uint64_t NameSize;
101     if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
102       llvm_unreachable("Long name length is not an integer");
103     StartOfFile += NameSize;
104   }
105 }
106
107 uint64_t Archive::Child::getSize() const {
108   if (Parent->IsThin)
109     return getHeader()->getSize();
110   return Data.size() - StartOfFile;
111 }
112
113 uint64_t Archive::Child::getRawSize() const {
114   return getHeader()->getSize();
115 }
116
117 Archive::Child Archive::Child::getNext() const {
118   size_t SpaceToSkip = Data.size();
119   // If it's odd, add 1 to make it even.
120   if (SpaceToSkip & 1)
121     ++SpaceToSkip;
122
123   const char *NextLoc = Data.data() + SpaceToSkip;
124
125   // Check to see if this is past the end of the archive.
126   if (NextLoc >= Parent->Data.getBufferEnd())
127     return Child(Parent, nullptr);
128
129   return Child(Parent, NextLoc);
130 }
131
132 uint64_t Archive::Child::getChildOffset() const {
133   const char *a = Parent->Data.getBuffer().data();
134   const char *c = Data.data();
135   uint64_t offset = c - a;
136   return offset;
137 }
138
139 ErrorOr<StringRef> Archive::Child::getName() const {
140   StringRef name = getRawName();
141   // Check if it's a special name.
142   if (name[0] == '/') {
143     if (name.size() == 1) // Linker member.
144       return name;
145     if (name.size() == 2 && name[1] == '/') // String table.
146       return name;
147     // It's a long name.
148     // Get the offset.
149     std::size_t offset;
150     if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
151       llvm_unreachable("Long name offset is not an integer");
152     const char *addr = Parent->StringTable->Data.begin()
153                        + sizeof(ArchiveMemberHeader)
154                        + offset;
155     // Verify it.
156     if (Parent->StringTable == Parent->child_end()
157         || addr < (Parent->StringTable->Data.begin()
158                    + sizeof(ArchiveMemberHeader))
159         || addr > (Parent->StringTable->Data.begin()
160                    + sizeof(ArchiveMemberHeader)
161                    + Parent->StringTable->getSize()))
162       return object_error::parse_failed;
163
164     // GNU long file names end with a /.
165     if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
166       StringRef::size_type End = StringRef(addr).find('/');
167       return StringRef(addr, End);
168     }
169     return StringRef(addr);
170   } else if (name.startswith("#1/")) {
171     uint64_t name_size;
172     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
173       llvm_unreachable("Long name length is not an ingeter");
174     return Data.substr(sizeof(ArchiveMemberHeader), name_size)
175         .rtrim(StringRef("\0", 1));
176   }
177   // It's a simple name.
178   if (name[name.size() - 1] == '/')
179     return name.substr(0, name.size() - 1);
180   return name;
181 }
182
183 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
184   ErrorOr<StringRef> NameOrErr = getName();
185   if (std::error_code EC = NameOrErr.getError())
186     return EC;
187   StringRef Name = NameOrErr.get();
188   return MemoryBufferRef(getBuffer(), Name);
189 }
190
191 ErrorOr<std::unique_ptr<Binary>>
192 Archive::Child::getAsBinary(LLVMContext *Context) const {
193   ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
194   if (std::error_code EC = BuffOrErr.getError())
195     return EC;
196
197   return createBinary(BuffOrErr.get(), Context);
198 }
199
200 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
201   std::error_code EC;
202   std::unique_ptr<Archive> Ret(new Archive(Source, EC));
203   if (EC)
204     return EC;
205   return std::move(Ret);
206 }
207
208 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
209     : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()) {
210   StringRef Buffer = Data.getBuffer();
211   // Check for sufficient magic.
212   if (Buffer.startswith(ThinMagic)) {
213     IsThin = true;
214   } else if (Buffer.startswith(Magic)) {
215     IsThin = false;
216   } else {
217     ec = object_error::invalid_file_type;
218     return;
219   }
220
221   // Get the special members.
222   child_iterator i = child_begin(false);
223   child_iterator e = child_end();
224
225   if (i == e) {
226     ec = object_error::success;
227     return;
228   }
229
230   StringRef Name = i->getRawName();
231
232   // Below is the pattern that is used to figure out the archive format
233   // GNU archive format
234   //  First member : / (may exist, if it exists, points to the symbol table )
235   //  Second member : // (may exist, if it exists, points to the string table)
236   //  Note : The string table is used if the filename exceeds 15 characters
237   // BSD archive format
238   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
239   //  There is no string table, if the filename exceeds 15 characters or has a
240   //  embedded space, the filename has #1/<size>, The size represents the size
241   //  of the filename that needs to be read after the archive header
242   // COFF archive format
243   //  First member : /
244   //  Second member : / (provides a directory of symbols)
245   //  Third member : // (may exist, if it exists, contains the string table)
246   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
247   //  even if the string table is empty. However, lib.exe does not in fact
248   //  seem to create the third member if there's no member whose filename
249   //  exceeds 15 characters. So the third member is optional.
250
251   if (Name == "__.SYMDEF") {
252     Format = K_BSD;
253     SymbolTable = i;
254     ++i;
255     FirstRegular = i;
256     ec = object_error::success;
257     return;
258   }
259
260   if (Name.startswith("#1/")) {
261     Format = K_BSD;
262     // We know this is BSD, so getName will work since there is no string table.
263     ErrorOr<StringRef> NameOrErr = i->getName();
264     ec = NameOrErr.getError();
265     if (ec)
266       return;
267     Name = NameOrErr.get();
268     if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
269       SymbolTable = i;
270       ++i;
271     }
272     FirstRegular = i;
273     return;
274   }
275
276   // MIPS 64-bit ELF archives use a special format of a symbol table.
277   // This format is marked by `ar_name` field equals to "/SYM64/".
278   // For detailed description see page 96 in the following document:
279   // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
280
281   bool has64SymTable = false;
282   if (Name == "/" || Name == "/SYM64/") {
283     SymbolTable = i;
284     if (Name == "/SYM64/")
285       has64SymTable = true;
286
287     ++i;
288     if (i == e) {
289       ec = object_error::parse_failed;
290       return;
291     }
292     Name = i->getRawName();
293   }
294
295   if (Name == "//") {
296     Format = has64SymTable ? K_MIPS64 : K_GNU;
297     StringTable = i;
298     ++i;
299     FirstRegular = i;
300     ec = object_error::success;
301     return;
302   }
303
304   if (Name[0] != '/') {
305     Format = has64SymTable ? K_MIPS64 : K_GNU;
306     FirstRegular = i;
307     ec = object_error::success;
308     return;
309   }
310
311   if (Name != "/") {
312     ec = object_error::parse_failed;
313     return;
314   }
315
316   Format = K_COFF;
317   SymbolTable = i;
318
319   ++i;
320   if (i == e) {
321     FirstRegular = i;
322     ec = object_error::success;
323     return;
324   }
325
326   Name = i->getRawName();
327
328   if (Name == "//") {
329     StringTable = i;
330     ++i;
331   }
332
333   FirstRegular = i;
334   ec = object_error::success;
335 }
336
337 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
338   if (Data.getBufferSize() == 8) // empty archive.
339     return child_end();
340
341   if (SkipInternal)
342     return FirstRegular;
343
344   const char *Loc = Data.getBufferStart() + strlen(Magic);
345   Child c(this, Loc);
346   return c;
347 }
348
349 Archive::child_iterator Archive::child_end() const {
350   return Child(this, nullptr);
351 }
352
353 StringRef Archive::Symbol::getName() const {
354   return Parent->SymbolTable->getBuffer().begin() + StringIndex;
355 }
356
357 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
358   const char *Buf = Parent->SymbolTable->getBuffer().begin();
359   const char *Offsets = Buf;
360   if (Parent->kind() == K_MIPS64)
361     Offsets += sizeof(uint64_t);
362   else
363     Offsets += sizeof(uint32_t);
364   uint32_t Offset = 0;
365   if (Parent->kind() == K_GNU) {
366     Offset =
367         *(reinterpret_cast<const support::ubig32_t *>(Offsets) + SymbolIndex);
368   } else if (Parent->kind() == K_MIPS64) {
369     Offset =
370         *(reinterpret_cast<const support::ubig64_t *>(Offsets) + SymbolIndex);
371   } else if (Parent->kind() == K_BSD) {
372     // The SymbolIndex is an index into the ranlib structs that start at
373     // Offsets (the first uint32_t is the number of bytes of the ranlib
374     // structs).  The ranlib structs are a pair of uint32_t's the first
375     // being a string table offset and the second being the offset into
376     // the archive of the member that defines the symbol.  Which is what
377     // is needed here.
378     Offset = *(reinterpret_cast<const support::ulittle32_t *>(Offsets) +
379                (SymbolIndex * 2) + 1);
380   } else {
381     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
382     
383     // Skip offsets.
384     Buf += sizeof(support::ulittle32_t) +
385            (MemberCount * sizeof(support::ulittle32_t));
386
387     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
388
389     if (SymbolIndex >= SymbolCount)
390       return object_error::parse_failed;
391
392     // Skip SymbolCount to get to the indices table.
393     const char *Indices = Buf + sizeof(support::ulittle32_t);
394
395     // Get the index of the offset in the file member offset table for this
396     // symbol.
397     uint16_t OffsetIndex =
398       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
399         + SymbolIndex);
400     // Subtract 1 since OffsetIndex is 1 based.
401     --OffsetIndex;
402
403     if (OffsetIndex >= MemberCount)
404       return object_error::parse_failed;
405
406     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
407                + OffsetIndex);
408   }
409
410   const char *Loc = Parent->getData().begin() + Offset;
411   child_iterator Iter(Child(Parent, Loc));
412   return Iter;
413 }
414
415 Archive::Symbol Archive::Symbol::getNext() const {
416   Symbol t(*this);
417   if (Parent->kind() == K_BSD) {
418     // t.StringIndex is an offset from the start of the __.SYMDEF or
419     // "__.SYMDEF SORTED" member into the string table for the ranlib
420     // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
421     // offset in the string table for t.SymbolIndex+1 we subtract the
422     // its offset from the start of the string table for t.SymbolIndex
423     // and add the offset of the string table for t.SymbolIndex+1.
424
425     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
426     // which is the number of bytes of ranlib structs that follow.  The ranlib
427     // structs are a pair of uint32_t's the first being a string table offset
428     // and the second being the offset into the archive of the member that
429     // define the symbol. After that the next uint32_t is the byte count of
430     // the string table followed by the string table.
431     const char *Buf = Parent->SymbolTable->getBuffer().begin();
432     uint32_t RanlibCount = 0;
433     RanlibCount = (*reinterpret_cast<const support::ulittle32_t *>(Buf)) /
434                   (sizeof(uint32_t) * 2);
435     // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
436     // don't change the t.StringIndex as we don't want to reference a ranlib
437     // past RanlibCount.
438     if (t.SymbolIndex + 1 < RanlibCount) {
439       const char *Ranlibs = Buf + 4;
440       uint32_t CurRanStrx = 0;
441       uint32_t NextRanStrx = 0;
442       CurRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
443                      (t.SymbolIndex * 2));
444       NextRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
445                       ((t.SymbolIndex + 1) * 2));
446       t.StringIndex -= CurRanStrx;
447       t.StringIndex += NextRanStrx;
448     }
449   } else {
450     // Go to one past next null.
451     t.StringIndex =
452         Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
453   }
454   ++t.SymbolIndex;
455   return t;
456 }
457
458 Archive::symbol_iterator Archive::symbol_begin() const {
459   if (!hasSymbolTable())
460     return symbol_iterator(Symbol(this, 0, 0));
461
462   const char *buf = SymbolTable->getBuffer().begin();
463   if (kind() == K_GNU) {
464     uint32_t symbol_count = 0;
465     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
466     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
467   } else if (kind() == K_MIPS64) {
468     uint64_t symbol_count = *reinterpret_cast<const support::ubig64_t *>(buf);
469     buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
470   } else if (kind() == K_BSD) {
471     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
472     // which is the number of bytes of ranlib structs that follow.  The ranlib
473     // structs are a pair of uint32_t's the first being a string table offset
474     // and the second being the offset into the archive of the member that
475     // define the symbol. After that the next uint32_t is the byte count of
476     // the string table followed by the string table.
477     uint32_t ranlib_count = 0;
478     ranlib_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
479                    (sizeof(uint32_t) * 2);
480     const char *ranlibs = buf + 4;
481     uint32_t ran_strx = 0;
482     ran_strx = *(reinterpret_cast<const support::ulittle32_t *>(ranlibs));
483     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
484     // Skip the byte count of the string table.
485     buf += sizeof(uint32_t);
486     buf += ran_strx;
487   } else {
488     uint32_t member_count = 0;
489     uint32_t symbol_count = 0;
490     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
491     buf += 4 + (member_count * 4); // Skip offsets.
492     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
493     buf += 4 + (symbol_count * 2); // Skip indices.
494   }
495   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
496   return symbol_iterator(Symbol(this, 0, string_start_offset));
497 }
498
499 Archive::symbol_iterator Archive::symbol_end() const {
500   if (!hasSymbolTable())
501     return symbol_iterator(Symbol(this, 0, 0));
502
503   const char *buf = SymbolTable->getBuffer().begin();
504   uint32_t symbol_count = 0;
505   if (kind() == K_GNU) {
506     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
507   } else if (kind() == K_MIPS64) {
508     symbol_count = *reinterpret_cast<const support::ubig64_t*>(buf);
509   } else if (kind() == K_BSD) {
510     symbol_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
511                    (sizeof(uint32_t) * 2);
512   } else {
513     uint32_t member_count = 0;
514     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
515     buf += 4 + (member_count * 4); // Skip offsets.
516     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
517   }
518   return symbol_iterator(Symbol(this, symbol_count, 0));
519 }
520
521 Archive::child_iterator Archive::findSym(StringRef name) const {
522   Archive::symbol_iterator bs = symbol_begin();
523   Archive::symbol_iterator es = symbol_end();
524
525   for (; bs != es; ++bs) {
526     StringRef SymName = bs->getName();
527     if (SymName == name) {
528       ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
529       // FIXME: Should we really eat the error?
530       if (ResultOrErr.getError())
531         return child_end();
532       return ResultOrErr.get();
533     }
534   }
535   return child_end();
536 }
537
538 bool Archive::hasSymbolTable() const {
539   return SymbolTable != child_end();
540 }