be023538e18e5813de740b212c3ca3413d7a78f9
[oota-llvm.git] / lib / Archive / ArchiveReader.cpp
1 //===- ArchiveReader.cpp - Code to read LLVM bytecode from .a files -------===//
2 //
3 // This file implements the ReadArchiveFile interface, which allows a linker to
4 // read all of the LLVM bytecode files contained in a .a file.  This file
5 // understands the standard system .a file format.  This can only handle the .a
6 // variant prevalent on Linux systems so far, but may be extended.  See
7 // information in this source file for more information:
8 //   http://sources.redhat.com/cgi-bin/cvsweb.cgi/src/bfd/archive.c?cvsroot=src
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Bytecode/Reader.h"
13 #include "llvm/Module.h"
14 #include "Config/sys/stat.h"
15 #include "Config/sys/mman.h"
16 #include "Config/fcntl.h"
17
18 namespace {
19   struct ar_hdr {
20     char name[16];
21     char date[12];
22     char uid[6];
23     char gid[6];
24     char mode[8];
25     char size[10];
26     char fmag[2];          // Always equal to '`\n'
27   };
28
29   enum ObjectType {
30     UserObject,            // A user .o/.bc file
31     Unknown,               // Unknown file, just ignore it
32     SVR4LongFilename,      // a "//" section used for long file names
33   };
34 }
35
36
37 // getObjectType - Determine the type of object that this header represents.
38 // This is capable of parsing the variety of special sections used for various
39 // purposes.
40 static enum ObjectType getObjectType(ar_hdr *H, unsigned Size) {
41   // Check for sections with special names...
42   if (!memcmp(H->name, "//              ", 16))
43     return SVR4LongFilename;
44
45   // Check to see if it looks like an llvm object file...
46   if (Size >= 4 && !memcmp(H+1, "llvm", 4))
47     return UserObject;
48
49   return Unknown;
50 }
51
52
53 static inline bool Error(std::string *ErrorStr, const char *Message) {
54   if (ErrorStr) *ErrorStr = Message;
55   return true;
56 }
57
58 static bool ParseLongFilenameSection(unsigned char *Buffer, unsigned Size,
59                                      std::vector<std::string> &LongFilenames,
60                                      std::string *S) {
61   if (!LongFilenames.empty())
62     return Error(S, "archive file contains multiple long filename entries");
63                  
64   while (Size) {
65     // Long filename entries are newline delimited to keep the archive readable.
66     unsigned char *Ptr = (unsigned char*)memchr(Buffer, '\n', Size);
67     if (Ptr == 0)
68       return Error(S, "archive long filename entry doesn't end with newline!");
69     assert(*Ptr == '\n');
70
71     if (Ptr == Buffer) break;  // Last entry contains just a newline.
72
73     unsigned char *End = Ptr;
74     if (End[-1] == '/') --End; // Remove trailing / from name
75     
76     LongFilenames.push_back(std::string(Buffer, End));
77     Size -= Ptr-Buffer+1;
78     Buffer = Ptr+1;
79   }
80   
81   return false;
82 }
83
84
85 static bool ReadArchiveBuffer(const std::string &Filename,
86                               unsigned char *Buffer, unsigned Length,
87                               std::vector<Module*> &Objects,
88                               std::string *ErrorStr) {
89   if (Length < 8 || memcmp(Buffer, "!<arch>\n", 8))
90     return Error(ErrorStr, "signature incorrect for an archive file!");
91   Buffer += 8;  Length -= 8; // Skip the magic string.
92
93   std::vector<std::string> LongFilenames;
94
95   while (Length >= sizeof(ar_hdr)) {
96     ar_hdr *Hdr = (ar_hdr*)Buffer;
97     unsigned Size = atoi(Hdr->size);
98     if (Size+sizeof(ar_hdr) > Length)
99       return Error(ErrorStr, "invalid record length in archive file!");
100
101     switch (getObjectType(Hdr, Size)) {
102     case SVR4LongFilename:
103       // If this is a long filename section, read all of the file names into the
104       // LongFilenames vector.
105       //
106       if (ParseLongFilenameSection(Buffer+sizeof(ar_hdr), Size,
107                                    LongFilenames, ErrorStr))
108         return true;
109       break;
110     case UserObject: {
111       Module *M = ParseBytecodeBuffer(Buffer+sizeof(ar_hdr), Size,
112                                       Filename+":somefile", ErrorStr);
113       if (!M) return true;
114       Objects.push_back(M);
115       break;
116     }
117     case Unknown:
118       std::cerr << "ReadArchiveBuffer: WARNING: Skipping unknown file: ";
119       std::cerr << std::string(Hdr->name, Hdr->name+sizeof(Hdr->name+1)) <<"\n";
120       break;   // Just ignore unknown files.
121     }
122
123     // Round Size up to an even number...
124     Size = (Size+1)/2*2;
125     Buffer += sizeof(ar_hdr)+Size;   // Move to the next entry
126     Length -= sizeof(ar_hdr)+Size;
127   }
128
129   return Length != 0;
130 }
131
132
133 // ReadArchiveFile - Read bytecode files from the specified .a file, returning
134 // true on error, or false on success.  This does not support reading files from
135 // standard input.
136 //
137 bool ReadArchiveFile(const std::string &Filename, std::vector<Module*> &Objects,
138                      std::string *ErrorStr) {
139   int FD = open(Filename.c_str(), O_RDONLY);
140   if (FD == -1)
141     return Error(ErrorStr, "Error opening file!");
142   
143   // Stat the file to get its length...
144   struct stat StatBuf;
145   if (fstat(FD, &StatBuf) == -1 || StatBuf.st_size == 0)
146     return Error(ErrorStr, "Error stat'ing file!");
147   
148     // mmap in the file all at once...
149   int Length = StatBuf.st_size;
150   unsigned char *Buffer = (unsigned char*)mmap(0, Length, PROT_READ, 
151                                                MAP_PRIVATE, FD, 0);
152   if (Buffer == (unsigned char*)MAP_FAILED)
153     return Error(ErrorStr, "Error mmapping file!");
154   
155   // Parse the archive files we mmap'ped in
156   bool Result = ReadArchiveBuffer(Filename, Buffer, Length, Objects, ErrorStr);
157   
158   // Unmmap the archive...
159   munmap((char*)Buffer, Length);
160
161   if (Result)    // Free any loaded objects
162     while (!Objects.empty()) {
163       delete Objects.back();
164       Objects.pop_back();
165     }
166   
167   return Result;
168 }