Use the raw member names in Archive::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/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 static bool isInternalMember(const ArchiveMemberHeader &amh) {
25   static const char *const internals[] = {
26     "/",
27     "//"
28   };
29
30   StringRef name = amh.getName();
31   for (std::size_t i = 0; i < sizeof(internals) / sizeof(*internals); ++i) {
32     if (name == internals[i])
33       return true;
34   }
35   return false;
36 }
37
38 void Archive::anchor() { }
39
40 error_code Archive::Child::getName(StringRef &Result) const {
41   StringRef name = getRawName();
42   // Check if it's a special name.
43   if (name[0] == '/') {
44     if (name.size() == 1) { // Linker member.
45       Result = name;
46       return object_error::success;
47     }
48     if (name.size() == 2 && name[1] == '/') { // String table.
49       Result = name;
50       return object_error::success;
51     }
52     // It's a long name.
53     // Get the offset.
54     std::size_t offset;
55     if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
56       llvm_unreachable("Long name offset is not an integer");
57     const char *addr = Parent->StringTable->Data.begin()
58                        + sizeof(ArchiveMemberHeader)
59                        + offset;
60     // Verify it.
61     if (Parent->StringTable == Parent->end_children()
62         || addr < (Parent->StringTable->Data.begin()
63                    + sizeof(ArchiveMemberHeader))
64         || addr > (Parent->StringTable->Data.begin()
65                    + sizeof(ArchiveMemberHeader)
66                    + Parent->StringTable->getSize()))
67       return object_error::parse_failed;
68
69     // GNU long file names end with a /.
70     if (Parent->kind() == K_GNU) {
71       StringRef::size_type End = StringRef(addr).find('/');
72       Result = StringRef(addr, End);
73     } else {
74       Result = addr;
75     }
76     return object_error::success;
77   } else if (name.startswith("#1/")) {
78     uint64_t name_size;
79     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
80       llvm_unreachable("Long name length is not an ingeter");
81     Result = Data.substr(sizeof(ArchiveMemberHeader), name_size);
82     return object_error::success;
83   }
84   // It's a simple name.
85   if (name[name.size() - 1] == '/')
86     Result = name.substr(0, name.size() - 1);
87   else
88     Result = name;
89   return object_error::success;
90 }
91
92 error_code Archive::Child::getAsBinary(OwningPtr<Binary> &Result) const {
93   OwningPtr<Binary> ret;
94   OwningPtr<MemoryBuffer> Buff;
95   if (error_code ec = getMemoryBuffer(Buff))
96     return ec;
97   if (error_code ec = createBinary(Buff.take(), ret))
98     return ec;
99   Result.swap(ret);
100   return object_error::success;
101 }
102
103 Archive::Archive(MemoryBuffer *source, error_code &ec)
104   : Binary(Binary::ID_Archive, source) {
105   // Check for sufficient magic.
106   if (!source || source->getBufferSize()
107                  < (8 + sizeof(ArchiveMemberHeader)) // Smallest archive.
108               || StringRef(source->getBufferStart(), 8) != Magic) {
109     ec = object_error::invalid_file_type;
110     return;
111   }
112
113   // Get the special members.
114   child_iterator i = begin_children(false);
115   child_iterator e = end_children();
116
117   if (i == e) {
118     ec = object_error::parse_failed;
119     return;
120   }
121
122   StringRef Name = i->getRawName();
123
124   // Below is the pattern that is used to figure out the archive format
125   // GNU archive format
126   //  First member : / (may exist, if it exists, points to the symbol table )
127   //  Second member : // (may exist, if it exists, points to the string table)
128   //  Note : The string table is used if the filename exceeds 15 characters
129   // BSD archive format
130   //  First member : __.SYMDEF (points to the symbol table)
131   //  There is no string table, if the filename exceeds 15 characters or has a 
132   //  embedded space, the filename has #1/<size>, The size represents the size 
133   //  of the filename that needs to be read after the archive header
134   // COFF archive format
135   //  First member : /
136   //  Second member : / (provides a directory of symbols)
137   //  Third member : // (may exist, if it exists, contains the string table)
138   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
139   //  even if the string table is empty. However, lib.exe does not in fact
140   //  seem to create the third member if there's no member whose filename
141   //  exceeds 15 characters. So the third member is optional.
142
143   if (Name == "__.SYMDEF") {
144     Format = K_BSD;
145     SymbolTable = i;
146     ec = object_error::success;
147     return;
148   }
149
150   if (Name == "/") {
151     SymbolTable = i;
152
153     ++i;
154     if (i == e) {
155       ec = object_error::parse_failed;
156       return;
157     }
158     Name = i->getRawName();
159   }
160
161   if (Name == "//") {
162     Format = K_GNU;
163     StringTable = i;
164     ec = object_error::success;
165     return;
166   }
167
168   if (Name[0] != '/') {
169     Format = K_GNU;
170     ec = object_error::success;
171     return;
172   }
173
174   if (Name != "/") {
175     ec = object_error::parse_failed;
176     return;
177   }
178
179   Format = K_COFF;
180   SymbolTable = i;
181
182   ++i;
183   if (i == e) {
184     ec = object_error::success;
185     return;
186   }
187
188   Name = i->getRawName();
189
190   if (Name == "//")
191     StringTable = i;
192
193   ec = object_error::success;
194 }
195
196 Archive::child_iterator Archive::begin_children(bool skip_internal) const {
197   const char *Loc = Data->getBufferStart() + strlen(Magic);
198   size_t Size = sizeof(ArchiveMemberHeader) +
199     ToHeader(Loc)->getSize();
200   Child c(this, StringRef(Loc, Size));
201   // Skip internals at the beginning of an archive.
202   if (skip_internal && isInternalMember(*ToHeader(Loc)))
203     return c.getNext();
204   return c;
205 }
206
207 Archive::child_iterator Archive::end_children() const {
208   return Child(this, StringRef(0, 0));
209 }
210
211 error_code Archive::Symbol::getName(StringRef &Result) const {
212   Result = StringRef(Parent->SymbolTable->getBuffer().begin() + StringIndex);
213   return object_error::success;
214 }
215
216 error_code Archive::Symbol::getMember(child_iterator &Result) const {
217   const char *Buf = Parent->SymbolTable->getBuffer().begin();
218   const char *Offsets = Buf + 4;
219   uint32_t Offset = 0;
220   if (Parent->kind() == K_GNU) {
221     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
222                + SymbolIndex);
223   } else if (Parent->kind() == K_BSD) {
224     llvm_unreachable("BSD format is not supported");
225   } else {
226     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
227     
228     // Skip offsets.
229     Buf += sizeof(support::ulittle32_t)
230            + (MemberCount * sizeof(support::ulittle32_t));
231
232     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
233
234     if (SymbolIndex >= SymbolCount)
235       return object_error::parse_failed;
236
237     // Skip SymbolCount to get to the indices table.
238     const char *Indices = Buf + sizeof(support::ulittle32_t);
239
240     // Get the index of the offset in the file member offset table for this
241     // symbol.
242     uint16_t OffsetIndex =
243       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
244         + SymbolIndex);
245     // Subtract 1 since OffsetIndex is 1 based.
246     --OffsetIndex;
247
248     if (OffsetIndex >= MemberCount)
249       return object_error::parse_failed;
250
251     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
252                + OffsetIndex);
253   }
254
255   const char *Loc = Parent->getData().begin() + Offset;
256   size_t Size = sizeof(ArchiveMemberHeader) +
257     ToHeader(Loc)->getSize();
258   Result = Child(Parent, StringRef(Loc, Size));
259
260   return object_error::success;
261 }
262
263 Archive::Symbol Archive::Symbol::getNext() const {
264   Symbol t(*this);
265   // Go to one past next null.
266   t.StringIndex =
267       Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
268   ++t.SymbolIndex;
269   return t;
270 }
271
272 Archive::symbol_iterator Archive::begin_symbols() const {
273   const char *buf = SymbolTable->getBuffer().begin();
274   if (kind() == K_GNU) {
275     uint32_t symbol_count = 0;
276     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
277     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
278   } else if (kind() == K_BSD) {
279     llvm_unreachable("BSD archive format is not supported");
280   } else {
281     uint32_t member_count = 0;
282     uint32_t symbol_count = 0;
283     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
284     buf += 4 + (member_count * 4); // Skip offsets.
285     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
286     buf += 4 + (symbol_count * 2); // Skip indices.
287   }
288   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
289   return symbol_iterator(Symbol(this, 0, string_start_offset));
290 }
291
292 Archive::symbol_iterator Archive::end_symbols() const {
293   const char *buf = SymbolTable->getBuffer().begin();
294   uint32_t symbol_count = 0;
295   if (kind() == K_GNU) {
296     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
297     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
298   } else if (kind() == K_BSD) {
299     llvm_unreachable("BSD archive format is not supported");
300   } else {
301     uint32_t member_count = 0;
302     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
303     buf += 4 + (member_count * 4); // Skip offsets.
304     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
305   }
306   return symbol_iterator(
307     Symbol(this, symbol_count, 0));
308 }
309
310 Archive::child_iterator Archive::findSym(StringRef name) const {
311   Archive::symbol_iterator bs = begin_symbols();
312   Archive::symbol_iterator es = end_symbols();
313   Archive::child_iterator result;
314   
315   StringRef symname;
316   for (; bs != es; ++bs) {
317     if (bs->getName(symname))
318         return end_children();
319     if (symname == name) {
320       if (bs->getMember(result))
321         return end_children();
322       return result;
323     }
324   }
325   return end_children();
326 }