Don't treat bitcode files specially in llvm-ar.
[oota-llvm.git] / tools / llvm-ar / ArchiveReader.cpp
1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- 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 // Builds up standard unix archive files (.a) containing LLVM bitcode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Archive.h"
15 #include "ArchiveInternals.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include <cstdio>
23 #include <cstdlib>
24 using namespace llvm;
25
26 /// Read a variable-bit-rate encoded unsigned integer
27 static inline unsigned readInteger(const char*&At, const char*End) {
28   unsigned Shift = 0;
29   unsigned Result = 0;
30
31   do {
32     if (At == End)
33       return Result;
34     Result |= (unsigned)((*At++) & 0x7F) << Shift;
35     Shift += 7;
36   } while (At[-1] & 0x80);
37   return Result;
38 }
39
40 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
41 // by At. The At pointer is updated to the byte just after the header, which
42 // can be variable in size.
43 ArchiveMember*
44 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
45 {
46   if (At + sizeof(ArchiveMemberHeader) >= End) {
47     if (error)
48       *error = "Unexpected end of file";
49     return 0;
50   }
51
52   // Cast archive member header
53   const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
54   At += sizeof(ArchiveMemberHeader);
55
56   int flags = 0;
57   int MemberSize = atoi(Hdr->size);
58   assert(MemberSize >= 0);
59
60   // Check the size of the member for sanity
61   if (At + MemberSize > End) {
62     if (error)
63       *error = "invalid member length in archive file";
64     return 0;
65   }
66
67   // Check the member signature
68   if (!Hdr->checkSignature()) {
69     if (error)
70       *error = "invalid file member signature";
71     return 0;
72   }
73
74   // Convert and check the member name
75   // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
76   // table. The special name "//" and 14 blanks is for a string table, used
77   // for long file names. This library doesn't generate either of those but
78   // it will accept them. If the name starts with #1/ and the remainder is
79   // digits, then those digits specify the length of the name that is
80   // stored immediately following the header. Anything else is a regular, short
81   // filename that is terminated with a '/' and blanks.
82
83   std::string pathname;
84   switch (Hdr->name[0]) {
85     case '#':
86       if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
87         if (isdigit(Hdr->name[3])) {
88           unsigned len = atoi(&Hdr->name[3]);
89           const char *nulp = (const char *)memchr(At, '\0', len);
90           pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - At) : len);
91           At += len;
92           MemberSize -= len;
93           flags |= ArchiveMember::HasLongFilenameFlag;
94         } else {
95           if (error)
96             *error = "invalid long filename";
97           return 0;
98         }
99       }
100       break;
101     case '/':
102       if (Hdr->name[1]== '/') {
103         if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
104           pathname.assign(ARFILE_STRTAB_NAME);
105           flags |= ArchiveMember::StringTableFlag;
106         } else {
107           if (error)
108             *error = "invalid string table name";
109           return 0;
110         }
111       } else if (Hdr->name[1] == ' ') {
112         if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
113           pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
114           flags |= ArchiveMember::SVR4SymbolTableFlag;
115         } else {
116           if (error)
117             *error = "invalid SVR4 symbol table name";
118           return 0;
119         }
120       } else if (isdigit(Hdr->name[1])) {
121         unsigned index = atoi(&Hdr->name[1]);
122         if (index < strtab.length()) {
123           const char* namep = strtab.c_str() + index;
124           const char* endp = strtab.c_str() + strtab.length();
125           const char* p = namep;
126           const char* last_p = p;
127           while (p < endp) {
128             if (*p == '\n' && *last_p == '/') {
129               pathname.assign(namep, last_p - namep);
130               flags |= ArchiveMember::HasLongFilenameFlag;
131               break;
132             }
133             last_p = p;
134             p++;
135           }
136           if (p >= endp) {
137             if (error)
138               *error = "missing name terminator in string table";
139             return 0;
140           }
141         } else {
142           if (error)
143             *error = "name index beyond string table";
144           return 0;
145         }
146       }
147       break;
148     case '_':
149       if (Hdr->name[1] == '_' &&
150           (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
151         pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
152         flags |= ArchiveMember::BSD4SymbolTableFlag;
153         break;
154       }
155       /* FALL THROUGH */
156
157     default:
158       const char* slash = (const char*) memchr(Hdr->name, '/', 16);
159       if (slash == 0)
160         slash = Hdr->name + 16;
161       pathname.assign(Hdr->name, slash - Hdr->name);
162       break;
163   }
164
165   // Instantiate the ArchiveMember to be filled
166   ArchiveMember* member = new ArchiveMember(this);
167
168   // Fill in fields of the ArchiveMember
169   member->parent = this;
170   member->path = pathname;
171   member->Size = MemberSize;
172   member->ModTime.fromEpochTime(atoi(Hdr->date));
173   unsigned int mode;
174   sscanf(Hdr->mode, "%o", &mode);
175   member->Mode = mode;
176   member->User = atoi(Hdr->uid);
177   member->Group = atoi(Hdr->gid);
178   member->flags = flags;
179   member->data = At;
180
181   return member;
182 }
183
184 bool
185 Archive::checkSignature(std::string* error) {
186   // Check the magic string at file's header
187   if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
188     if (error)
189       *error = "invalid signature for an archive file";
190     return false;
191   }
192   return true;
193 }
194
195 // This function loads the entire archive and fully populates its ilist with
196 // the members of the archive file. This is typically used in preparation for
197 // editing the contents of the archive.
198 bool
199 Archive::loadArchive(std::string* error) {
200
201   // Set up parsing
202   members.clear();
203   const char *At = base;
204   const char *End = mapfile->getBufferEnd();
205
206   if (!checkSignature(error))
207     return false;
208
209   At += 8;  // Skip the magic string.
210
211   bool foundFirstFile = false;
212   while (At < End) {
213     // parse the member header
214     const char* Save = At;
215     ArchiveMember* mbr = parseMemberHeader(At, End, error);
216     if (!mbr)
217       return false;
218
219     // check if this is the foreign symbol table
220     if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
221       At += mbr->getSize();
222       if ((intptr_t(At) & 1) == 1)
223         At++;
224     } else if (mbr->isStringTable()) {
225       // Simply suck the entire string table into a string
226       // variable. This will be used to get the names of the
227       // members that use the "/ddd" format for their names
228       // (SVR4 style long names).
229       strtab.assign(At, mbr->getSize());
230       At += mbr->getSize();
231       if ((intptr_t(At) & 1) == 1)
232         At++;
233       delete mbr;
234     } else {
235       // This is just a regular file. If its the first one, save its offset.
236       // Otherwise just push it on the list and move on to the next file.
237       if (!foundFirstFile) {
238         firstFileOffset = Save - base;
239         foundFirstFile = true;
240       }
241       members.push_back(mbr);
242       At += mbr->getSize();
243       if ((intptr_t(At) & 1) == 1)
244         At++;
245     }
246   }
247   return true;
248 }
249
250 // Open and completely load the archive file.
251 Archive*
252 Archive::OpenAndLoad(StringRef File, LLVMContext& C,
253                      std::string* ErrorMessage) {
254   OwningPtr<Archive> result(new Archive(File, C));
255   if (result->mapToMemory(ErrorMessage))
256     return NULL;
257   if (!result->loadArchive(ErrorMessage))
258     return NULL;
259   return result.take();
260 }
261
262 // Load just the symbol table from the archive file
263 bool
264 Archive::loadSymbolTable(std::string* ErrorMsg) {
265
266   // Set up parsing
267   members.clear();
268   const char *At = base;
269   const char *End = mapfile->getBufferEnd();
270
271   // Make sure we're dealing with an archive
272   if (!checkSignature(ErrorMsg))
273     return false;
274
275   At += 8; // Skip signature
276
277   // Parse the first file member header
278   const char* FirstFile = At;
279   ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
280   if (!mbr)
281     return false;
282
283   if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
284     // Skip the foreign symbol table, we don't do anything with it
285     At += mbr->getSize();
286     if ((intptr_t(At) & 1) == 1)
287       At++;
288     delete mbr;
289
290     // Read the next one
291     FirstFile = At;
292     mbr = parseMemberHeader(At, End, ErrorMsg);
293     if (!mbr) {
294       delete mbr;
295       return false;
296     }
297   }
298
299   if (mbr->isStringTable()) {
300     // Process the string table entry
301     strtab.assign((const char*)mbr->getData(), mbr->getSize());
302     At += mbr->getSize();
303     if ((intptr_t(At) & 1) == 1)
304       At++;
305     delete mbr;
306     // Get the next one
307     FirstFile = At;
308     mbr = parseMemberHeader(At, End, ErrorMsg);
309     if (!mbr) {
310       delete mbr;
311       return false;
312     }
313   }
314
315   // There's no symbol table in the file. We have to rebuild it from scratch
316   // because the intent of this method is to get the symbol table loaded so
317   // it can be searched efficiently.
318   // Add the member to the members list
319   members.push_back(mbr);
320
321   firstFileOffset = FirstFile - base;
322   return true;
323 }