Pass a std::unique_ptr& to the create??? methods is lib/Object.
[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 *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   std::unique_ptr<Binary> ret;
181   ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = getMemoryBuffer();
182   if (std::error_code EC = BuffOrErr.getError())
183     return EC;
184
185   std::unique_ptr<MemoryBuffer> Buff(BuffOrErr.get().release());
186   return createBinary(Buff, Context);
187 }
188
189 ErrorOr<Archive*> Archive::create(MemoryBuffer *Source) {
190   std::error_code EC;
191   std::unique_ptr<Archive> Ret(new Archive(Source, EC));
192   if (EC)
193     return EC;
194   return Ret.release();
195 }
196
197 Archive::Archive(MemoryBuffer *source, std::error_code &ec)
198     : Binary(Binary::ID_Archive, source), SymbolTable(child_end()) {
199   // Check for sufficient magic.
200   assert(source);
201   if (source->getBufferSize() < 8 ||
202       StringRef(source->getBufferStart(), 8) != Magic) {
203     ec = object_error::invalid_file_type;
204     return;
205   }
206
207   // Get the special members.
208   child_iterator i = child_begin(false);
209   child_iterator e = child_end();
210
211   if (i == e) {
212     ec = object_error::success;
213     return;
214   }
215
216   StringRef Name = i->getRawName();
217
218   // Below is the pattern that is used to figure out the archive format
219   // GNU archive format
220   //  First member : / (may exist, if it exists, points to the symbol table )
221   //  Second member : // (may exist, if it exists, points to the string table)
222   //  Note : The string table is used if the filename exceeds 15 characters
223   // BSD archive format
224   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
225   //  There is no string table, if the filename exceeds 15 characters or has a
226   //  embedded space, the filename has #1/<size>, The size represents the size
227   //  of the filename that needs to be read after the archive header
228   // COFF archive format
229   //  First member : /
230   //  Second member : / (provides a directory of symbols)
231   //  Third member : // (may exist, if it exists, contains the string table)
232   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
233   //  even if the string table is empty. However, lib.exe does not in fact
234   //  seem to create the third member if there's no member whose filename
235   //  exceeds 15 characters. So the third member is optional.
236
237   if (Name == "__.SYMDEF") {
238     Format = K_BSD;
239     SymbolTable = i;
240     ++i;
241     FirstRegular = i;
242     ec = object_error::success;
243     return;
244   }
245
246   if (Name.startswith("#1/")) {
247     Format = K_BSD;
248     // We know this is BSD, so getName will work since there is no string table.
249     ErrorOr<StringRef> NameOrErr = i->getName();
250     ec = NameOrErr.getError();
251     if (ec)
252       return;
253     Name = NameOrErr.get();
254     if (Name == "__.SYMDEF SORTED") {
255       SymbolTable = i;
256       ++i;
257     }
258     FirstRegular = i;
259     return;
260   }
261
262   if (Name == "/") {
263     SymbolTable = i;
264
265     ++i;
266     if (i == e) {
267       ec = object_error::parse_failed;
268       return;
269     }
270     Name = i->getRawName();
271   }
272
273   if (Name == "//") {
274     Format = K_GNU;
275     StringTable = i;
276     ++i;
277     FirstRegular = i;
278     ec = object_error::success;
279     return;
280   }
281
282   if (Name[0] != '/') {
283     Format = K_GNU;
284     FirstRegular = i;
285     ec = object_error::success;
286     return;
287   }
288
289   if (Name != "/") {
290     ec = object_error::parse_failed;
291     return;
292   }
293
294   Format = K_COFF;
295   SymbolTable = i;
296
297   ++i;
298   if (i == e) {
299     FirstRegular = i;
300     ec = object_error::success;
301     return;
302   }
303
304   Name = i->getRawName();
305
306   if (Name == "//") {
307     StringTable = i;
308     ++i;
309   }
310
311   FirstRegular = i;
312   ec = object_error::success;
313 }
314
315 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
316   if (Data->getBufferSize() == 8) // empty archive.
317     return child_end();
318
319   if (SkipInternal)
320     return FirstRegular;
321
322   const char *Loc = Data->getBufferStart() + strlen(Magic);
323   Child c(this, Loc);
324   return c;
325 }
326
327 Archive::child_iterator Archive::child_end() const {
328   return Child(this, nullptr);
329 }
330
331 StringRef Archive::Symbol::getName() const {
332   return Parent->SymbolTable->getBuffer().begin() + StringIndex;
333 }
334
335 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
336   const char *Buf = Parent->SymbolTable->getBuffer().begin();
337   const char *Offsets = Buf + 4;
338   uint32_t Offset = 0;
339   if (Parent->kind() == K_GNU) {
340     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
341                + SymbolIndex);
342   } else if (Parent->kind() == K_BSD) {
343     llvm_unreachable("BSD format is not supported");
344   } else {
345     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
346     
347     // Skip offsets.
348     Buf += sizeof(support::ulittle32_t)
349            + (MemberCount * sizeof(support::ulittle32_t));
350
351     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
352
353     if (SymbolIndex >= SymbolCount)
354       return object_error::parse_failed;
355
356     // Skip SymbolCount to get to the indices table.
357     const char *Indices = Buf + sizeof(support::ulittle32_t);
358
359     // Get the index of the offset in the file member offset table for this
360     // symbol.
361     uint16_t OffsetIndex =
362       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
363         + SymbolIndex);
364     // Subtract 1 since OffsetIndex is 1 based.
365     --OffsetIndex;
366
367     if (OffsetIndex >= MemberCount)
368       return object_error::parse_failed;
369
370     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
371                + OffsetIndex);
372   }
373
374   const char *Loc = Parent->getData().begin() + Offset;
375   child_iterator Iter(Child(Parent, Loc));
376   return Iter;
377 }
378
379 Archive::Symbol Archive::Symbol::getNext() const {
380   Symbol t(*this);
381   // Go to one past next null.
382   t.StringIndex =
383       Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
384   ++t.SymbolIndex;
385   return t;
386 }
387
388 Archive::symbol_iterator Archive::symbol_begin() const {
389   if (!hasSymbolTable())
390     return symbol_iterator(Symbol(this, 0, 0));
391
392   const char *buf = SymbolTable->getBuffer().begin();
393   if (kind() == K_GNU) {
394     uint32_t symbol_count = 0;
395     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
396     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
397   } else if (kind() == K_BSD) {
398     llvm_unreachable("BSD archive format is not supported");
399   } else {
400     uint32_t member_count = 0;
401     uint32_t symbol_count = 0;
402     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
403     buf += 4 + (member_count * 4); // Skip offsets.
404     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
405     buf += 4 + (symbol_count * 2); // Skip indices.
406   }
407   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
408   return symbol_iterator(Symbol(this, 0, string_start_offset));
409 }
410
411 Archive::symbol_iterator Archive::symbol_end() const {
412   if (!hasSymbolTable())
413     return symbol_iterator(Symbol(this, 0, 0));
414
415   const char *buf = SymbolTable->getBuffer().begin();
416   uint32_t symbol_count = 0;
417   if (kind() == K_GNU) {
418     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
419   } else if (kind() == K_BSD) {
420     llvm_unreachable("BSD archive format is not supported");
421   } else {
422     uint32_t member_count = 0;
423     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
424     buf += 4 + (member_count * 4); // Skip offsets.
425     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
426   }
427   return symbol_iterator(
428     Symbol(this, symbol_count, 0));
429 }
430
431 Archive::child_iterator Archive::findSym(StringRef name) const {
432   Archive::symbol_iterator bs = symbol_begin();
433   Archive::symbol_iterator es = symbol_end();
434
435   for (; bs != es; ++bs) {
436     StringRef SymName = bs->getName();
437     if (SymName == name) {
438       ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
439       // FIXME: Should we really eat the error?
440       if (ResultOrErr.getError())
441         return child_end();
442       return ResultOrErr.get();
443     }
444   }
445   return child_end();
446 }
447
448 bool Archive::hasSymbolTable() const {
449   return SymbolTable != child_end();
450 }