Don't reject an empty archive.
[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 *Magic = "!<arch>\n";
25
26 static bool isInternalMember(const ArchiveMemberHeader &amh) {
27   static const char *const internals[] = {
28     "/",
29     "//"
30   };
31
32   StringRef name = amh.getName();
33   for (std::size_t i = 0; i < sizeof(internals) / sizeof(*internals); ++i) {
34     if (name == internals[i])
35       return true;
36   }
37   return false;
38 }
39
40 void Archive::anchor() { }
41
42 StringRef ArchiveMemberHeader::getName() const {
43   char EndCond;
44   if (Name[0] == '/' || Name[0] == '#')
45     EndCond = ' ';
46   else
47     EndCond = '/';
48   llvm::StringRef::size_type end =
49       llvm::StringRef(Name, sizeof(Name)).find(EndCond);
50   if (end == llvm::StringRef::npos)
51     end = sizeof(Name);
52   assert(end <= sizeof(Name) && end > 0);
53   // Don't include the EndCond if there is one.
54   return llvm::StringRef(Name, end);
55 }
56
57 uint32_t ArchiveMemberHeader::getSize() const {
58   uint32_t Ret;
59   if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
60     llvm_unreachable("Size is not a decimal number.");
61   return Ret;
62 }
63
64 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
65   unsigned Ret;
66   if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
67     llvm_unreachable("Access mode is not an octal number.");
68   return static_cast<sys::fs::perms>(Ret);
69 }
70
71 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
72   unsigned Seconds;
73   if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
74           .getAsInteger(10, Seconds))
75     llvm_unreachable("Last modified time not a decimal number.");
76
77   sys::TimeValue Ret;
78   Ret.fromEpochTime(Seconds);
79   return Ret;
80 }
81
82 unsigned ArchiveMemberHeader::getUID() const {
83   unsigned Ret;
84   if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
85     llvm_unreachable("UID time not a decimal number.");
86   return Ret;
87 }
88
89 unsigned ArchiveMemberHeader::getGID() const {
90   unsigned Ret;
91   if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
92     llvm_unreachable("GID time not a decimal number.");
93   return Ret;
94 }
95
96 static const ArchiveMemberHeader *toHeader(const char *base) {
97   return reinterpret_cast<const ArchiveMemberHeader *>(base);
98 }
99
100 Archive::Child::Child(const Archive *Parent, const char *Start)
101     : Parent(Parent) {
102   if (!Start)
103     return;
104
105   const ArchiveMemberHeader *Header = toHeader(Start);
106   Data = StringRef(Start, sizeof(ArchiveMemberHeader) + Header->getSize());
107
108   // Setup StartOfFile and PaddingBytes.
109   StartOfFile = sizeof(ArchiveMemberHeader);
110   // Don't include attached name.
111   StringRef Name = Header->getName();
112   if (Name.startswith("#1/")) {
113     uint64_t NameSize;
114     if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
115       llvm_unreachable("Long name length is not an integer");
116     StartOfFile += NameSize;
117   }
118 }
119
120 Archive::Child Archive::Child::getNext() const {
121   size_t SpaceToSkip = Data.size();
122   // If it's odd, add 1 to make it even.
123   if (SpaceToSkip & 1)
124     ++SpaceToSkip;
125
126   const char *NextLoc = Data.data() + SpaceToSkip;
127
128   // Check to see if this is past the end of the archive.
129   if (NextLoc >= Parent->Data->getBufferEnd())
130     return Child(Parent, NULL);
131
132   return Child(Parent, NextLoc);
133 }
134
135 error_code Archive::Child::getName(StringRef &Result) const {
136   StringRef name = getRawName();
137   // Check if it's a special name.
138   if (name[0] == '/') {
139     if (name.size() == 1) { // Linker member.
140       Result = name;
141       return object_error::success;
142     }
143     if (name.size() == 2 && name[1] == '/') { // String table.
144       Result = name;
145       return object_error::success;
146     }
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->end_children()
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) {
166       StringRef::size_type End = StringRef(addr).find('/');
167       Result = StringRef(addr, End);
168     } else {
169       Result = addr;
170     }
171     return object_error::success;
172   } else if (name.startswith("#1/")) {
173     uint64_t name_size;
174     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
175       llvm_unreachable("Long name length is not an ingeter");
176     Result = Data.substr(sizeof(ArchiveMemberHeader), name_size);
177     return object_error::success;
178   }
179   // It's a simple name.
180   if (name[name.size() - 1] == '/')
181     Result = name.substr(0, name.size() - 1);
182   else
183     Result = name;
184   return object_error::success;
185 }
186
187 error_code Archive::Child::getMemoryBuffer(OwningPtr<MemoryBuffer> &Result,
188                                            bool FullPath) const {
189   StringRef Name;
190   if (error_code ec = getName(Name))
191     return ec;
192   SmallString<128> Path;
193   Result.reset(MemoryBuffer::getMemBuffer(
194       getBuffer(), FullPath ? (Twine(Parent->getFileName()) + "(" + Name + ")")
195                                   .toStringRef(Path)
196                             : Name,
197       false));
198   return error_code::success();
199 }
200
201 error_code Archive::Child::getAsBinary(OwningPtr<Binary> &Result) const {
202   OwningPtr<Binary> ret;
203   OwningPtr<MemoryBuffer> Buff;
204   if (error_code ec = getMemoryBuffer(Buff))
205     return ec;
206   if (error_code ec = createBinary(Buff.take(), ret))
207     return ec;
208   Result.swap(ret);
209   return object_error::success;
210 }
211
212 Archive::Archive(MemoryBuffer *source, error_code &ec)
213   : Binary(Binary::ID_Archive, source), SymbolTable(end_children()) {
214   // Check for sufficient magic.
215   assert(source);
216   if (source->getBufferSize() < 8 ||
217       StringRef(source->getBufferStart(), 8) != Magic) {
218     ec = object_error::invalid_file_type;
219     return;
220   }
221
222   // Get the special members.
223   child_iterator i = begin_children(false);
224   child_iterator e = end_children();
225
226   if (i == e) {
227     ec = object_error::success;
228     return;
229   }
230
231   StringRef Name = i->getRawName();
232
233   // Below is the pattern that is used to figure out the archive format
234   // GNU archive format
235   //  First member : / (may exist, if it exists, points to the symbol table )
236   //  Second member : // (may exist, if it exists, points to the string table)
237   //  Note : The string table is used if the filename exceeds 15 characters
238   // BSD archive format
239   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
240   //  There is no string table, if the filename exceeds 15 characters or has a
241   //  embedded space, the filename has #1/<size>, The size represents the size
242   //  of the filename that needs to be read after the archive header
243   // COFF archive format
244   //  First member : /
245   //  Second member : / (provides a directory of symbols)
246   //  Third member : // (may exist, if it exists, contains the string table)
247   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
248   //  even if the string table is empty. However, lib.exe does not in fact
249   //  seem to create the third member if there's no member whose filename
250   //  exceeds 15 characters. So the third member is optional.
251
252   if (Name == "__.SYMDEF") {
253     Format = K_BSD;
254     SymbolTable = i;
255     ec = object_error::success;
256     return;
257   }
258
259   if (Name.startswith("#1/")) {
260     Format = K_BSD;
261     // We know this is BSD, so getName will work since there is no string table.
262     ec = i->getName(Name);
263     if (ec)
264       return;
265     if (Name == StringRef("__.SYMDEF SORTED\0\0\0", 20))
266       SymbolTable = 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     ec = object_error::success;
285     return;
286   }
287
288   if (Name[0] != '/') {
289     Format = K_GNU;
290     ec = object_error::success;
291     return;
292   }
293
294   if (Name != "/") {
295     ec = object_error::parse_failed;
296     return;
297   }
298
299   Format = K_COFF;
300   SymbolTable = i;
301
302   ++i;
303   if (i == e) {
304     ec = object_error::success;
305     return;
306   }
307
308   Name = i->getRawName();
309
310   if (Name == "//")
311     StringTable = i;
312
313   ec = object_error::success;
314 }
315
316 Archive::child_iterator Archive::begin_children(bool skip_internal) const {
317   if (Data->getBufferSize() == 8) // empty archive.
318     return end_children();
319   const char *Loc = Data->getBufferStart() + strlen(Magic);
320   Child c(this, Loc);
321   // Skip internals at the beginning of an archive.
322   if (skip_internal && isInternalMember(*toHeader(Loc)))
323     return c.getNext();
324   return c;
325 }
326
327 Archive::child_iterator Archive::end_children() const {
328   return Child(this, NULL);
329 }
330
331 error_code Archive::Symbol::getName(StringRef &Result) const {
332   Result = StringRef(Parent->SymbolTable->getBuffer().begin() + StringIndex);
333   return object_error::success;
334 }
335
336 error_code Archive::Symbol::getMember(child_iterator &Result) const {
337   const char *Buf = Parent->SymbolTable->getBuffer().begin();
338   const char *Offsets = Buf + 4;
339   uint32_t Offset = 0;
340   if (Parent->kind() == K_GNU) {
341     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
342                + SymbolIndex);
343   } else if (Parent->kind() == K_BSD) {
344     llvm_unreachable("BSD format is not supported");
345   } else {
346     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
347     
348     // Skip offsets.
349     Buf += sizeof(support::ulittle32_t)
350            + (MemberCount * sizeof(support::ulittle32_t));
351
352     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
353
354     if (SymbolIndex >= SymbolCount)
355       return object_error::parse_failed;
356
357     // Skip SymbolCount to get to the indices table.
358     const char *Indices = Buf + sizeof(support::ulittle32_t);
359
360     // Get the index of the offset in the file member offset table for this
361     // symbol.
362     uint16_t OffsetIndex =
363       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
364         + SymbolIndex);
365     // Subtract 1 since OffsetIndex is 1 based.
366     --OffsetIndex;
367
368     if (OffsetIndex >= MemberCount)
369       return object_error::parse_failed;
370
371     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
372                + OffsetIndex);
373   }
374
375   const char *Loc = Parent->getData().begin() + Offset;
376   Result = Child(Parent, Loc);
377
378   return object_error::success;
379 }
380
381 Archive::Symbol Archive::Symbol::getNext() const {
382   Symbol t(*this);
383   // Go to one past next null.
384   t.StringIndex =
385       Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
386   ++t.SymbolIndex;
387   return t;
388 }
389
390 Archive::symbol_iterator Archive::begin_symbols() const {
391   if (SymbolTable == end_children())
392     return symbol_iterator(Symbol(this, 0, 0));
393
394   const char *buf = SymbolTable->getBuffer().begin();
395   if (kind() == K_GNU) {
396     uint32_t symbol_count = 0;
397     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
398     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
399   } else if (kind() == K_BSD) {
400     llvm_unreachable("BSD archive format is not supported");
401   } else {
402     uint32_t member_count = 0;
403     uint32_t symbol_count = 0;
404     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
405     buf += 4 + (member_count * 4); // Skip offsets.
406     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
407     buf += 4 + (symbol_count * 2); // Skip indices.
408   }
409   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
410   return symbol_iterator(Symbol(this, 0, string_start_offset));
411 }
412
413 Archive::symbol_iterator Archive::end_symbols() const {
414   if (SymbolTable == end_children())
415     return symbol_iterator(Symbol(this, 0, 0));
416
417   const char *buf = SymbolTable->getBuffer().begin();
418   uint32_t symbol_count = 0;
419   if (kind() == K_GNU) {
420     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
421   } else if (kind() == K_BSD) {
422     llvm_unreachable("BSD archive format is not supported");
423   } else {
424     uint32_t member_count = 0;
425     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
426     buf += 4 + (member_count * 4); // Skip offsets.
427     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
428   }
429   return symbol_iterator(
430     Symbol(this, symbol_count, 0));
431 }
432
433 Archive::child_iterator Archive::findSym(StringRef name) const {
434   Archive::symbol_iterator bs = begin_symbols();
435   Archive::symbol_iterator es = end_symbols();
436   Archive::child_iterator result;
437   
438   StringRef symname;
439   for (; bs != es; ++bs) {
440     if (bs->getName(symname))
441         return end_children();
442     if (symname == name) {
443       if (bs->getMember(result))
444         return end_children();
445       return result;
446     }
447   }
448   return end_children();
449 }