8671c422a1ecb615b05316dea5149d39fc594e7f
[oota-llvm.git] / lib / Archive / ArchiveReader.cpp
1 //===- ArchiveReader.cpp - Code to read LLVM bytecode from .a files -------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ReadArchiveFile interface, which allows a linker to
11 // read all of the LLVM bytecode files contained in a .a file.  This file
12 // understands the standard system .a file format.  This can only handle the .a
13 // variant prevalent on Linux systems so far, but may be extended.  See
14 // information in this source file for more information:
15 //   http://sources.redhat.com/cgi-bin/cvsweb.cgi/src/bfd/archive.c?cvsroot=src
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Module.h"
21 #include "Support/FileUtilities.h"
22 #include "Config/sys/mman.h"
23 #include "Config/fcntl.h"
24 #include <cstdlib>
25 using namespace llvm;
26
27 namespace {
28   struct ar_hdr {
29     char name[16];
30     char date[12];
31     char uid[6];
32     char gid[6];
33     char mode[8];
34     char size[10];
35     char fmag[2];          // Always equal to '`\n'
36   };
37
38   enum ObjectType {
39     UserObject,            // A user .o/.bc file
40     Unknown,               // Unknown file, just ignore it
41     SVR4LongFilename,      // a "//" section used for long file names
42     ArchiveSymbolTable,    // Symbol table produced by ranlib.
43   };
44 }
45
46 /// getObjectType - Determine the type of object that this header represents.
47 /// This is capable of parsing the variety of special sections used for various
48 /// purposes.
49 ///
50 static enum ObjectType getObjectType(ar_hdr *H, std::string MemberName,
51                                      unsigned char *MemberData, unsigned Size) {
52   // Check for sections with special names...
53   if (MemberName == "__.SYMDEF       " || MemberName == "__.SYMDEF SORTED")
54     return ArchiveSymbolTable;
55   else if (MemberName == "//              ")
56     return SVR4LongFilename;
57
58   // Check to see if it looks like an llvm object file...
59   if (Size >= 4 && !memcmp(MemberData, "llvm", 4))
60     return UserObject;
61
62   return Unknown;
63 }
64
65 static inline bool Error(std::string *ErrorStr, const char *Message) {
66   if (ErrorStr) *ErrorStr = Message;
67   return true;
68 }
69
70 static bool ParseSymbolTableSection(unsigned char *Buffer, unsigned Size,
71                                     std::string *S) {
72   // Currently not supported (succeeds without doing anything)
73   return false;
74 }
75
76 static bool ReadArchiveBuffer(const std::string &ArchiveName,
77                               unsigned char *Buffer, unsigned Length,
78                               std::vector<Module*> &Objects,
79                               std::string *ErrorStr) {
80   if (Length < 8 || memcmp(Buffer, "!<arch>\n", 8))
81     return Error(ErrorStr, "signature incorrect for an archive file!");
82   Buffer += 8;  Length -= 8; // Skip the magic string.
83
84   std::vector<char> LongFilenames;
85
86   while (Length >= sizeof(ar_hdr)) {
87     ar_hdr *Hdr = (ar_hdr*)Buffer;
88     unsigned SizeFromHeader = atoi(Hdr->size);
89     if (SizeFromHeader + sizeof(ar_hdr) > Length)
90       return Error(ErrorStr, "invalid record length in archive file!");
91
92     unsigned char *MemberData = Buffer + sizeof(ar_hdr);
93     unsigned MemberSize = SizeFromHeader;
94     // Get name of archive member.
95     char *startp = Hdr->name;
96     char *endp = (char *) memchr (startp, '/', sizeof(ar_hdr));
97     if (memcmp (Hdr->name, "#1/", 3) == 0) {
98       // 4.4BSD/MacOSX long filenames are abbreviated as "#1/L", where L is an
99       // ASCII-coded decimal number representing the length of the name buffer,
100       // which is prepended to the archive member's contents.
101       unsigned NameLength = atoi (&Hdr->name[3]);
102       startp = (char *) MemberData;
103       endp = startp + NameLength;
104       MemberData += NameLength;
105       MemberSize -= NameLength;
106     } else if (startp == endp && isdigit (Hdr->name[1])) {
107       // SVR4 long filenames are abbreviated as "/I", where I is
108       // an ASCII-coded decimal index into the LongFilenames vector.
109       unsigned NameIndex = atoi (&Hdr->name[1]);
110       assert (LongFilenames.size () > NameIndex
111               && "SVR4-style long filename for archive member not found");
112       startp = &LongFilenames[NameIndex];
113       endp = strchr (startp, '/');
114     } else if (startp == endp && Hdr->name[1] == '/') {
115       // This is for the SVR4 long filename table (there might be other
116       // names starting with // but I don't know about them). Make sure that
117       // getObjectType sees it.
118       endp = &Hdr->name[sizeof (Hdr->name)];
119     }
120     if (!endp) {
121       // 4.4BSD/MacOSX *short* filenames are not guaranteed to have a
122       // terminator. Start at the end of the field and backtrack over spaces.
123       endp = startp + sizeof(Hdr->name);
124       while (endp[-1] == ' ')
125         --endp;
126     }
127     std::string MemberName (startp, endp);
128     std::string FullMemberName = ArchiveName + "(" + MemberName + ")";
129
130     switch (getObjectType(Hdr, MemberName, MemberData, MemberSize)) {
131     case SVR4LongFilename:
132       // If this is a long filename section, read all of the file names into the
133       // LongFilenames vector.
134       LongFilenames.assign (MemberData, MemberData + MemberSize);
135       break;
136     case UserObject: {
137       Module *M = ParseBytecodeBuffer(MemberData, MemberSize,
138                                       FullMemberName, ErrorStr);
139       if (!M) return true;
140       Objects.push_back(M);
141       break;
142     }
143     case ArchiveSymbolTable:
144       if (ParseSymbolTableSection(MemberData, MemberSize, ErrorStr))
145         return true;
146       break;
147     default:
148       std::cerr << "ReadArchiveBuffer: WARNING: Skipping unknown file: "
149                 << FullMemberName << "\n";
150       break;   // Just ignore unknown files.
151     }
152
153     // Round SizeFromHeader up to an even number...
154     SizeFromHeader = (SizeFromHeader+1)/2*2;
155     Buffer += sizeof(ar_hdr)+SizeFromHeader;   // Move to the next entry
156     Length -= sizeof(ar_hdr)+SizeFromHeader;
157   }
158
159   return Length != 0;
160 }
161
162
163 // ReadArchiveFile - Read bytecode files from the specified .a file, returning
164 // true on error, or false on success.  This does not support reading files from
165 // standard input.
166 //
167 bool llvm::ReadArchiveFile(const std::string &Filename,
168                            std::vector<Module*> &Objects,std::string *ErrorStr){
169   int Length = getFileSize(Filename);
170   if (Length == -1)
171     return Error(ErrorStr, "Error getting file length!");
172
173   int FD = open(Filename.c_str(), O_RDONLY);
174   if (FD == -1)
175     return Error(ErrorStr, "Error opening file!");
176   
177     // mmap in the file all at once...
178   unsigned char *Buffer = (unsigned char*)mmap(0, Length, PROT_READ, 
179                                                MAP_PRIVATE, FD, 0);
180   if (Buffer == (unsigned char*)MAP_FAILED)
181     return Error(ErrorStr, "Error mmapping file!");
182   
183   // Parse the archive files we mmap'ped in
184   bool Result = ReadArchiveBuffer(Filename, Buffer, Length, Objects, ErrorStr);
185   
186   // Unmmap the archive...
187   munmap((char*)Buffer, Length);
188
189   if (Result)    // Free any loaded objects
190     while (!Objects.empty()) {
191       delete Objects.back();
192       Objects.pop_back();
193     }
194   
195   return Result;
196 }