28d052e12da0f4c762e39f7884f44c06c338205d
[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/Support/Endian.h"
17 #include "llvm/Support/MemoryBuffer.h"
18
19 using namespace llvm;
20 using namespace object;
21
22 static const char *Magic = "!<arch>\n";
23
24 namespace {
25 struct ArchiveMemberHeader {
26   char Name[16];
27   char LastModified[12];
28   char UID[6];
29   char GID[6];
30   char AccessMode[8];
31   char Size[10]; ///< Size of data, not including header or padding.
32   char Terminator[2];
33
34   ///! Get the name without looking up long names.
35   StringRef getName() const {
36     char EndCond;
37     if (Name[0] == '/' || Name[0] == '#')
38       EndCond = ' ';
39     else
40       EndCond = '/';
41     StringRef::size_type end = StringRef(Name, sizeof(Name)).find(EndCond);
42     if (end == StringRef::npos)
43       end = sizeof(Name);
44     assert(end <= sizeof(Name) && end > 0);
45     // Don't include the EndCond if there is one.
46     return StringRef(Name, end);
47   }
48
49   uint64_t getSize() const {
50     APInt ret;
51     StringRef(Size, sizeof(Size)).getAsInteger(10, ret);
52     return ret.getZExtValue();
53   }
54 };
55 }
56
57 static const ArchiveMemberHeader *ToHeader(const char *base) {
58   return reinterpret_cast<const ArchiveMemberHeader *>(base);
59 }
60
61
62 static bool isInternalMember(const ArchiveMemberHeader &amh) {
63   static const char *const internals[] = {
64     "/",
65     "//",
66     "#_LLVM_SYM_TAB_#"
67   };
68
69   StringRef name = amh.getName();
70   for (std::size_t i = 0; i < sizeof(internals) / sizeof(*internals); ++i) {
71     if (name == internals[i])
72       return true;
73   }
74   return false;
75 }
76
77 void Archive::anchor() { }
78
79 Archive::Child Archive::Child::getNext() const {
80   size_t SpaceToSkip = sizeof(ArchiveMemberHeader) +
81     ToHeader(Data.data())->getSize();
82   // If it's odd, add 1 to make it even.
83   if (SpaceToSkip & 1)
84     ++SpaceToSkip;
85
86   const char *NextLoc = Data.data() + SpaceToSkip;
87
88   // Check to see if this is past the end of the archive.
89   if (NextLoc >= Parent->Data->getBufferEnd())
90     return Child(Parent, StringRef(0, 0));
91
92   size_t NextSize = sizeof(ArchiveMemberHeader) +
93     ToHeader(NextLoc)->getSize();
94
95   return Child(Parent, StringRef(NextLoc, NextSize));
96 }
97
98 error_code Archive::Child::getName(StringRef &Result) const {
99   StringRef name = ToHeader(Data.data())->getName();
100   // Check if it's a special name.
101   if (name[0] == '/') {
102     if (name.size() == 1) { // Linker member.
103       Result = name;
104       return object_error::success;
105     }
106     if (name.size() == 2 && name[1] == '/') { // String table.
107       Result = name;
108       return object_error::success;
109     }
110     // It's a long name.
111     // Get the offset.
112     APInt offset;
113     name.substr(1).getAsInteger(10, offset);
114     const char *addr = Parent->StringTable->Data.begin()
115                        + sizeof(ArchiveMemberHeader)
116                        + offset.getZExtValue();
117     // Verify it.
118     if (Parent->StringTable == Parent->end_children()
119         || addr < (Parent->StringTable->Data.begin()
120                    + sizeof(ArchiveMemberHeader))
121         || addr > (Parent->StringTable->Data.begin()
122                    + sizeof(ArchiveMemberHeader)
123                    + Parent->StringTable->getSize()))
124       return object_error::parse_failed;
125
126     // GNU long file names end with a /.
127     if (Parent->kind() == K_GNU) {
128       StringRef::size_type End = StringRef(addr).find('/');
129       Result = StringRef(addr, End);
130     } else {
131       Result = addr;
132     }
133     return object_error::success;
134   } else if (name.startswith("#1/")) {
135     APInt name_size;
136     name.substr(3).getAsInteger(10, name_size);
137     Result = Data.substr(0, name_size.getZExtValue());
138     return object_error::success;
139   }
140   // It's a simple name.
141   if (name[name.size() - 1] == '/')
142     Result = name.substr(0, name.size() - 1);
143   else
144     Result = name;
145   return object_error::success;
146 }
147
148 uint64_t Archive::Child::getSize() const {
149   uint64_t size = ToHeader(Data.data())->getSize();
150   // Don't include attached name.
151   StringRef name =  ToHeader(Data.data())->getName();
152   if (name.startswith("#1/")) {
153     APInt name_size;
154     name.substr(3).getAsInteger(10, name_size);
155     size -= name_size.getZExtValue();
156   }
157   return size;
158 }
159
160 MemoryBuffer *Archive::Child::getBuffer() const {
161   StringRef name;
162   if (getName(name)) return NULL;
163   int size = sizeof(ArchiveMemberHeader);
164   if (name.startswith("#1/")) {
165     APInt name_size;
166     name.substr(3).getAsInteger(10, name_size);
167     size += name_size.getZExtValue();
168   }
169   return MemoryBuffer::getMemBuffer(Data.substr(size, getSize()),
170                                     name,
171                                     false);
172 }
173
174 error_code Archive::Child::getAsBinary(OwningPtr<Binary> &Result) const {
175   OwningPtr<Binary> ret;
176   if (error_code ec =
177     createBinary(getBuffer(), ret))
178     return ec;
179   Result.swap(ret);
180   return object_error::success;
181 }
182
183 Archive::Archive(MemoryBuffer *source, error_code &ec)
184   : Binary(Binary::ID_Archive, source) {
185   // Check for sufficient magic.
186   if (!source || source->getBufferSize()
187                  < (8 + sizeof(ArchiveMemberHeader) + 2) // Smallest archive.
188               || StringRef(source->getBufferStart(), 8) != Magic) {
189     ec = object_error::invalid_file_type;
190     return;
191   }
192
193   // Get the special members.
194   child_iterator i = begin_children(false);
195   child_iterator e = end_children();
196
197   StringRef name;
198   if ((ec = i->getName(name)))
199     return;
200
201   // Below is the pattern that is used to figure out the archive format
202   // GNU archive format
203   //  First member : / (points to the symbol table )
204   //  Second member : // (may exist, if it exists, points to the string table)
205   //  Note : The string table is used if the filename exceeds 15 characters
206   // BSD archive format
207   //  First member : __.SYMDEF (points to the symbol table)
208   //  There is no string table, if the filename exceeds 15 characters or has a 
209   //  embedded space, the filename has #1/<size>, The size represents the size 
210   //  of the filename that needs to be read after the archive header
211   // COFF archive format
212   //  First member : /
213   //  Second member : / (provides a directory of symbols)
214   //  Third member : // contains the string table, this is present even if the
215   //                    string table is empty
216   if (name == "/") {
217     SymbolTable = i;
218     StringTable = e;
219     if (i != e) ++i;
220     if ((ec = i->getName(name)))
221       return;
222     if (name[0] != '/') {
223       Format = K_GNU;
224     } else if ((name.size() > 1) && (name == "//")) { 
225       Format = K_GNU;
226       StringTable = i;
227       ++i;
228     } else  { 
229       Format = K_COFF;
230       if (i != e) {
231         SymbolTable = i;
232         ++i;
233       }
234       if (i != e) {
235         StringTable = i;
236       }
237     }
238   } else if (name == "__.SYMDEF") {
239     Format = K_BSD;
240     SymbolTable = i;
241     StringTable = e;
242   } 
243   ec = object_error::success;
244 }
245
246 Archive::child_iterator Archive::begin_children(bool skip_internal) const {
247   const char *Loc = Data->getBufferStart() + strlen(Magic);
248   size_t Size = sizeof(ArchiveMemberHeader) +
249     ToHeader(Loc)->getSize();
250   Child c(this, StringRef(Loc, Size));
251   // Skip internals at the beginning of an archive.
252   if (skip_internal && isInternalMember(*ToHeader(Loc)))
253     return c.getNext();
254   return c;
255 }
256
257 Archive::child_iterator Archive::end_children() const {
258   return Child(this, StringRef(0, 0));
259 }
260
261 error_code Archive::Symbol::getName(StringRef &Result) const {
262   Result =
263     StringRef(Parent->SymbolTable->getBuffer()->getBufferStart() + StringIndex);
264   return object_error::success;
265 }
266
267 error_code Archive::Symbol::getMember(child_iterator &Result) const {
268   const char *Buf = Parent->SymbolTable->getBuffer()->getBufferStart();
269   const char *Offsets = Buf + 4;
270   uint32_t Offset = 0;
271   if (Parent->kind() == K_GNU) {
272     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
273                + SymbolIndex);
274   } else if (Parent->kind() == K_BSD) {
275     assert("BSD format is not supported");
276   } else {
277     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
278     
279     // Skip offsets.
280     Buf += sizeof(support::ulittle32_t)
281            + (MemberCount * sizeof(support::ulittle32_t));
282
283     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
284
285     if (SymbolIndex >= SymbolCount)
286       return object_error::parse_failed;
287
288     // Skip SymbolCount to get to the indicies table.
289     const char *Indicies = Buf + sizeof(support::ulittle32_t);
290
291     // Get the index of the offset in the file member offset table for this
292     // symbol.
293     uint16_t OffsetIndex =
294       *(reinterpret_cast<const support::ulittle16_t*>(Indicies)
295         + SymbolIndex);
296     // Subtract 1 since OffsetIndex is 1 based.
297     --OffsetIndex;
298
299     if (OffsetIndex >= MemberCount)
300       return object_error::parse_failed;
301
302     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
303                + OffsetIndex);
304   }
305
306   const char *Loc = Parent->getData().begin() + Offset;
307   size_t Size = sizeof(ArchiveMemberHeader) +
308     ToHeader(Loc)->getSize();
309   Result = Child(Parent, StringRef(Loc, Size));
310
311   return object_error::success;
312 }
313
314 Archive::Symbol Archive::Symbol::getNext() const {
315   Symbol t(*this);
316   // Go to one past next null.
317   t.StringIndex =
318     Parent->SymbolTable->getBuffer()->getBuffer().find('\0', t.StringIndex) + 1;
319   ++t.SymbolIndex;
320   return t;
321 }
322
323 Archive::symbol_iterator Archive::begin_symbols() const {
324   const char *buf = SymbolTable->getBuffer()->getBufferStart();
325   if (kind() == K_GNU) {
326     uint32_t symbol_count = 0;
327     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
328     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
329   } else if (kind() == K_BSD) {
330     assert("BSD archive format is not supported");
331   } else {
332     uint32_t member_count = 0;
333     uint32_t symbol_count = 0;
334     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
335     buf += 4 + (member_count * 4); // Skip offsets.
336     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
337     buf += 4 + (symbol_count * 2); // Skip indices.
338   }
339   uint32_t string_start_offset =
340     buf - SymbolTable->getBuffer()->getBufferStart();
341   return symbol_iterator(Symbol(this, 0, string_start_offset));
342 }
343
344 Archive::symbol_iterator Archive::end_symbols() const {
345   const char *buf = SymbolTable->getBuffer()->getBufferStart();
346   uint32_t symbol_count = 0;
347   if (kind() == K_GNU) {
348     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
349     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
350   } else if (kind() == K_BSD) {
351     assert("BSD archive format is not supported");
352   } else {
353     uint32_t member_count = 0;
354     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
355     buf += 4 + (member_count * 4); // Skip offsets.
356     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
357   }
358   return symbol_iterator(
359     Symbol(this, symbol_count, 0));
360 }
361
362 Archive::child_iterator Archive::findSym(StringRef name) const {
363   Archive::symbol_iterator bs = begin_symbols();
364   Archive::symbol_iterator es = end_symbols();
365   Archive::child_iterator result;
366   
367   StringRef symname;
368   for (; bs != es; ++bs) {
369     if (bs->getName(symname))
370         return end_children();
371     if (symname == name) {
372       if (bs->getMember(result))
373         return end_children();
374       return result;
375     }
376   }
377   return end_children();
378 }