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