1e66da06392dcf6d3d7cd204820358390b6dc0df
[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 using std::error_code;
24
25 static const char *const Magic = "!<arch>\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   Data = StringRef(Start, sizeof(ArchiveMemberHeader) + Header->getSize());
91
92   // Setup StartOfFile and PaddingBytes.
93   StartOfFile = sizeof(ArchiveMemberHeader);
94   // Don't include attached name.
95   StringRef Name = Header->getName();
96   if (Name.startswith("#1/")) {
97     uint64_t NameSize;
98     if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
99       llvm_unreachable("Long name length is not an integer");
100     StartOfFile += NameSize;
101   }
102 }
103
104 Archive::Child Archive::Child::getNext() const {
105   size_t SpaceToSkip = Data.size();
106   // If it's odd, add 1 to make it even.
107   if (SpaceToSkip & 1)
108     ++SpaceToSkip;
109
110   const char *NextLoc = Data.data() + SpaceToSkip;
111
112   // Check to see if this is past the end of the archive.
113   if (NextLoc >= Parent->Data->getBufferEnd())
114     return Child(Parent, nullptr);
115
116   return Child(Parent, NextLoc);
117 }
118
119 error_code Archive::Child::getName(StringRef &Result) const {
120   StringRef name = getRawName();
121   // Check if it's a special name.
122   if (name[0] == '/') {
123     if (name.size() == 1) { // Linker member.
124       Result = name;
125       return object_error::success;
126     }
127     if (name.size() == 2 && name[1] == '/') { // String table.
128       Result = name;
129       return object_error::success;
130     }
131     // It's a long name.
132     // Get the offset.
133     std::size_t offset;
134     if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
135       llvm_unreachable("Long name offset is not an integer");
136     const char *addr = Parent->StringTable->Data.begin()
137                        + sizeof(ArchiveMemberHeader)
138                        + offset;
139     // Verify it.
140     if (Parent->StringTable == Parent->child_end()
141         || addr < (Parent->StringTable->Data.begin()
142                    + sizeof(ArchiveMemberHeader))
143         || addr > (Parent->StringTable->Data.begin()
144                    + sizeof(ArchiveMemberHeader)
145                    + Parent->StringTable->getSize()))
146       return object_error::parse_failed;
147
148     // GNU long file names end with a /.
149     if (Parent->kind() == K_GNU) {
150       StringRef::size_type End = StringRef(addr).find('/');
151       Result = StringRef(addr, End);
152     } else {
153       Result = addr;
154     }
155     return object_error::success;
156   } else if (name.startswith("#1/")) {
157     uint64_t name_size;
158     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
159       llvm_unreachable("Long name length is not an ingeter");
160     Result = Data.substr(sizeof(ArchiveMemberHeader), name_size)
161         .rtrim(StringRef("\0", 1));
162     return object_error::success;
163   }
164   // It's a simple name.
165   if (name[name.size() - 1] == '/')
166     Result = name.substr(0, name.size() - 1);
167   else
168     Result = name;
169   return object_error::success;
170 }
171
172 error_code Archive::Child::getMemoryBuffer(std::unique_ptr<MemoryBuffer> &Result,
173                                            bool FullPath) const {
174   StringRef Name;
175   if (error_code ec = getName(Name))
176     return ec;
177   SmallString<128> Path;
178   Result.reset(MemoryBuffer::getMemBuffer(
179       getBuffer(), FullPath ? (Twine(Parent->getFileName()) + "(" + Name + ")")
180                                   .toStringRef(Path)
181                             : Name,
182       false));
183   return error_code();
184 }
185
186 error_code Archive::Child::getAsBinary(std::unique_ptr<Binary> &Result,
187                                        LLVMContext *Context) const {
188   std::unique_ptr<Binary> ret;
189   std::unique_ptr<MemoryBuffer> Buff;
190   if (error_code ec = getMemoryBuffer(Buff))
191     return ec;
192   ErrorOr<Binary *> BinaryOrErr = createBinary(Buff.release(), Context);
193   if (error_code EC = BinaryOrErr.getError())
194     return EC;
195   Result.reset(BinaryOrErr.get());
196   return object_error::success;
197 }
198
199 ErrorOr<Archive*> Archive::create(MemoryBuffer *Source) {
200   error_code EC;
201   std::unique_ptr<Archive> Ret(new Archive(Source, EC));
202   if (EC)
203     return EC;
204   return Ret.release();
205 }
206
207 Archive::Archive(MemoryBuffer *source, error_code &ec)
208   : Binary(Binary::ID_Archive, source), SymbolTable(child_end()) {
209   // Check for sufficient magic.
210   assert(source);
211   if (source->getBufferSize() < 8 ||
212       StringRef(source->getBufferStart(), 8) != Magic) {
213     ec = object_error::invalid_file_type;
214     return;
215   }
216
217   // Get the special members.
218   child_iterator i = child_begin(false);
219   child_iterator e = child_end();
220
221   if (i == e) {
222     ec = object_error::success;
223     return;
224   }
225
226   StringRef Name = i->getRawName();
227
228   // Below is the pattern that is used to figure out the archive format
229   // GNU archive format
230   //  First member : / (may exist, if it exists, points to the symbol table )
231   //  Second member : // (may exist, if it exists, points to the string table)
232   //  Note : The string table is used if the filename exceeds 15 characters
233   // BSD archive format
234   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
235   //  There is no string table, if the filename exceeds 15 characters or has a
236   //  embedded space, the filename has #1/<size>, The size represents the size
237   //  of the filename that needs to be read after the archive header
238   // COFF archive format
239   //  First member : /
240   //  Second member : / (provides a directory of symbols)
241   //  Third member : // (may exist, if it exists, contains the string table)
242   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
243   //  even if the string table is empty. However, lib.exe does not in fact
244   //  seem to create the third member if there's no member whose filename
245   //  exceeds 15 characters. So the third member is optional.
246
247   if (Name == "__.SYMDEF") {
248     Format = K_BSD;
249     SymbolTable = i;
250     ++i;
251     FirstRegular = i;
252     ec = object_error::success;
253     return;
254   }
255
256   if (Name.startswith("#1/")) {
257     Format = K_BSD;
258     // We know this is BSD, so getName will work since there is no string table.
259     ec = i->getName(Name);
260     if (ec)
261       return;
262     if (Name == "__.SYMDEF SORTED") {
263       SymbolTable = i;
264       ++i;
265     }
266     FirstRegular = i;
267     return;
268   }
269
270   if (Name == "/") {
271     SymbolTable = i;
272
273     ++i;
274     if (i == e) {
275       ec = object_error::parse_failed;
276       return;
277     }
278     Name = i->getRawName();
279   }
280
281   if (Name == "//") {
282     Format = K_GNU;
283     StringTable = i;
284     ++i;
285     FirstRegular = i;
286     ec = object_error::success;
287     return;
288   }
289
290   if (Name[0] != '/') {
291     Format = K_GNU;
292     FirstRegular = i;
293     ec = object_error::success;
294     return;
295   }
296
297   if (Name != "/") {
298     ec = object_error::parse_failed;
299     return;
300   }
301
302   Format = K_COFF;
303   SymbolTable = i;
304
305   ++i;
306   if (i == e) {
307     FirstRegular = i;
308     ec = object_error::success;
309     return;
310   }
311
312   Name = i->getRawName();
313
314   if (Name == "//") {
315     StringTable = i;
316     ++i;
317   }
318
319   FirstRegular = i;
320   ec = object_error::success;
321 }
322
323 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
324   if (Data->getBufferSize() == 8) // empty archive.
325     return child_end();
326
327   if (SkipInternal)
328     return FirstRegular;
329
330   const char *Loc = Data->getBufferStart() + strlen(Magic);
331   Child c(this, Loc);
332   return c;
333 }
334
335 Archive::child_iterator Archive::child_end() const {
336   return Child(this, nullptr);
337 }
338
339 error_code Archive::Symbol::getName(StringRef &Result) const {
340   Result = StringRef(Parent->SymbolTable->getBuffer().begin() + StringIndex);
341   return object_error::success;
342 }
343
344 error_code Archive::Symbol::getMember(child_iterator &Result) const {
345   const char *Buf = Parent->SymbolTable->getBuffer().begin();
346   const char *Offsets = Buf + 4;
347   uint32_t Offset = 0;
348   if (Parent->kind() == K_GNU) {
349     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
350                + SymbolIndex);
351   } else if (Parent->kind() == K_BSD) {
352     llvm_unreachable("BSD format is not supported");
353   } else {
354     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
355     
356     // Skip offsets.
357     Buf += sizeof(support::ulittle32_t)
358            + (MemberCount * sizeof(support::ulittle32_t));
359
360     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
361
362     if (SymbolIndex >= SymbolCount)
363       return object_error::parse_failed;
364
365     // Skip SymbolCount to get to the indices table.
366     const char *Indices = Buf + sizeof(support::ulittle32_t);
367
368     // Get the index of the offset in the file member offset table for this
369     // symbol.
370     uint16_t OffsetIndex =
371       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
372         + SymbolIndex);
373     // Subtract 1 since OffsetIndex is 1 based.
374     --OffsetIndex;
375
376     if (OffsetIndex >= MemberCount)
377       return object_error::parse_failed;
378
379     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
380                + OffsetIndex);
381   }
382
383   const char *Loc = Parent->getData().begin() + Offset;
384   Result = Child(Parent, Loc);
385
386   return object_error::success;
387 }
388
389 Archive::Symbol Archive::Symbol::getNext() const {
390   Symbol t(*this);
391   // Go to one past next null.
392   t.StringIndex =
393       Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
394   ++t.SymbolIndex;
395   return t;
396 }
397
398 Archive::symbol_iterator Archive::symbol_begin() const {
399   if (!hasSymbolTable())
400     return symbol_iterator(Symbol(this, 0, 0));
401
402   const char *buf = SymbolTable->getBuffer().begin();
403   if (kind() == K_GNU) {
404     uint32_t symbol_count = 0;
405     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
406     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
407   } else if (kind() == K_BSD) {
408     llvm_unreachable("BSD archive format is not supported");
409   } else {
410     uint32_t member_count = 0;
411     uint32_t symbol_count = 0;
412     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
413     buf += 4 + (member_count * 4); // Skip offsets.
414     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
415     buf += 4 + (symbol_count * 2); // Skip indices.
416   }
417   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
418   return symbol_iterator(Symbol(this, 0, string_start_offset));
419 }
420
421 Archive::symbol_iterator Archive::symbol_end() const {
422   if (!hasSymbolTable())
423     return symbol_iterator(Symbol(this, 0, 0));
424
425   const char *buf = SymbolTable->getBuffer().begin();
426   uint32_t symbol_count = 0;
427   if (kind() == K_GNU) {
428     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
429   } else if (kind() == K_BSD) {
430     llvm_unreachable("BSD archive format is not supported");
431   } else {
432     uint32_t member_count = 0;
433     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
434     buf += 4 + (member_count * 4); // Skip offsets.
435     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
436   }
437   return symbol_iterator(
438     Symbol(this, symbol_count, 0));
439 }
440
441 Archive::child_iterator Archive::findSym(StringRef name) const {
442   Archive::symbol_iterator bs = symbol_begin();
443   Archive::symbol_iterator es = symbol_end();
444   Archive::child_iterator result;
445   
446   StringRef symname;
447   for (; bs != es; ++bs) {
448     if (bs->getName(symname))
449         return child_end();
450     if (symname == name) {
451       if (bs->getMember(result))
452         return child_end();
453       return result;
454     }
455   }
456   return child_end();
457 }
458
459 bool Archive::hasSymbolTable() const {
460   return SymbolTable != child_end();
461 }