1 //===-- tools/llvm-ar/llvm-ar.cpp - LLVM archive librarian utility --------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
11 // Builds up standard unix archive files (.a) containing LLVM bytecode.
13 //===----------------------------------------------------------------------===//
15 #include "Support/CommandLine.h"
16 #include "llvm/Bytecode/Reader.h"
17 #include "llvm/Module.h"
24 #include <sys/types.h>
34 #define ARFMAG "\n" /* header trailer string */
35 #define ARMAG "!<arch>\n" /* magic string */
36 #define SARMAG 8 /* length of magic string */
40 // Each file member is preceded by a file member header. Which is
41 // of the following format:
43 // char ar_name[16] - '/' terminated file member name.
44 // If the file name does not fit, a dummy name is used.
45 // char ar_date[12] - file date in decimal
46 // char ar_uid[6] - User id of file owner in decimal.
47 // char ar_gid[6] - Group ID file belongs to in decimal.
48 // char ar_mode[8] - File mode in octal.
49 // char ar_size[10] - Size of file in decimal.
50 // char ar_fmag[2] - Trailer of header file, a newline.
71 //Option to generate symbol table or not
72 //running llvm-ar -s is the same as ranlib
73 cl::opt<bool> SymbolTable ("s", cl::desc("Generate an archive symbol table"));
76 cl::opt<string> Archive (cl::Positional, cl::desc("<archive file>"),
79 //For now we require one or more member files, this should change so
80 //we can just run llvm-ar -s on an archive to generate the symbol
82 cl::list<string> Members(cl::ConsumeAfter, cl::desc("<archive members>..."));
85 static inline bool Error(std::string *ErrorStr, const char *Message) {
86 if (ErrorStr) *ErrorStr = Message;
91 // WriteSymbolTable - Writes symbol table to ArchiveFile, return false
92 // on errors. Also returns by reference size of symbol table.
94 // Overview of method:
95 // 1) Generate the header for the symbol table. This is a normal
96 // archive member header, but it has a zero length name.
97 // 2) For each archive member file, stat the file and parse the bytecode
98 // Store cumulative offset (file size + header size).
99 // 3) Loop over all the symbols for the current member file,
100 // add offset entry to offset vector, and add symbol name to its vector.
101 // Note: The symbol name vector is a vector of chars to speed up calculating
102 // the total size of the symbol table.
103 // 4) Update offset vector once we know the total size of symbol table. This is
104 // because the symbol table appears before all archive member file contents.
105 // We add the size of magic string, and size of symbol table to each offset.
106 // 5) If the new updated offset it not even, we add 1 byte to offset because
107 // a newline will be inserted when writing member files. This adjustment is
108 // cummulative (ie. each time we have an odd offset we add 1 to total adjustment).
109 // 6) Lastly, write symbol table to file.
111 bool WriteSymbolTable(std::ofstream &ArchiveFile) {
113 //Create header for symbol table. This is essentially an empty header with the
114 //name set to a '/' to indicate its a symbol table.
118 //Name of symbol table is '/'
122 //Set the header trailer to a newline
123 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
126 //Write header to archive file
127 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
130 unsigned memoff = 0; //Keep Track of total size of files added to archive
131 vector<unsigned> offsets; //Vector of offsets into archive file
132 vector<char> names; //Vector of characters that are the symbol names.
134 //Loop over archive member files, parse bytecode, and generate symbol table.
135 for(unsigned i=0; i<Members.size(); ++i) {
137 //Open Member file for reading and copy to buffer
138 int FD = open(Members[i].c_str(),O_RDONLY);
140 //Check for errors opening the file.
142 std::cerr << "Error opening file!\n";
146 //Stat the file to get its size.
148 if (stat(Members[i].c_str(), &StatBuf) == -1 || StatBuf.st_size == 0) {
149 std::cerr << "Error stating file\n";
154 unsigned Length = StatBuf.st_size;
156 //Read in file into a buffer.
157 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
160 //Check if mmap failed.
161 if (buf == (unsigned char*)MAP_FAILED) {
162 std::cerr << "Error mmapping file!\n";
166 //Parse the bytecode file and get all the symbols.
168 Module *M = ParseBytecodeBuffer(buf,Length,Members[i],&ErrorStr);
170 //Check for errors parsing bytecode.
172 //std::cerr << "Error Parsing Bytecode\n";
176 //Loop over function names and global vars and add to symbol maps
177 for(Module::iterator I = M->begin(), E=M->end(); I != E; ++I) {
180 string NM = ((Function*)I)->getName();
182 //Loop over the characters in the name and add to symbol name vector
183 for(unsigned i=0; i<NM.size(); ++i)
184 names.push_back(NM[i]);
186 //Each symbol is null terminated.
187 names.push_back('\0');
189 //Add offset to vector of offsets
190 offsets.push_back(memoff);
193 memoff += Length + sizeof(Hdr);
196 //Determine how large our symbol table is.
197 unsigned symbolTableSize = sizeof(Hdr) + 4 + 4*(offsets.size()) + names.size();
198 cout << "Symbol Table Size: " << symbolTableSize << "\n";
200 //Number of symbols should be in network byte order as well
202 unsigned temp = offsets.size();
203 num[0] = (temp >> 24) & 255;
204 num[1] = (temp >> 16) & 255;
205 num[2] = (temp >> 8) & 255;
208 //Write number of symbols to archive file
209 ArchiveFile.write(num,4);
211 //Adjustment to offset to start files on even byte boundaries
214 //Update offsets write symbol table to archive.
215 for(unsigned i=0; i<offsets.size(); ++i) {
217 offsets[i] = offsets[i] + symbolTableSize + SARMAG;
218 offsets[i] += adjust;
219 if((offsets[i] % 2 != 0)) {
221 offsets[i] += adjust;
224 cout << "Offset: " << offsets[i] << "\n";
225 output[0] = (offsets[i] >> 24) & 255;
226 output[1] = (offsets[i] >> 16) & 255;
227 output[2] = (offsets[i] >> 8) & 255;
228 output[3] = offsets[i] & 255;
229 ArchiveFile.write(output,4);
233 //Write out symbol name vector.
234 for(unsigned i=0; i<names.size(); ++i)
235 ArchiveFile << names[i];
240 // AddMemberToArchive - Writes member file to archive. Returns false on errors.
242 // Overview of method:
243 // 1) Open file, and stat it.
244 // 2) Fill out header using stat information. If name is longer then 15
245 // characters, use "dummy" name.
246 // 3) Write header and file contents to disk.
247 // 4) Keep track of total offset into file, and insert a newline if it is odd.
249 bool AddMemberToArchive(string Member, std::ofstream &ArchiveFile) {
251 ar_hdr Hdr; //Header for archive member file.
253 //stat the file to get info
255 if (stat(Member.c_str(), &StatBuf) == -1 || StatBuf.st_size == 0)
260 //set name to white spaces
261 memset(Hdr.name,' ', sizeof(Hdr.name));
263 //check the size of the name, if less than 15, we can copy it directly
264 //otherwise we give it a dummy name for now
265 if(Member.length() < 16)
266 memcpy(Hdr.name,Member.c_str(),Member.length());
268 memcpy(Hdr.name, "Dummy", 5);
270 //terminate name with forward slash
273 //file member size in decimal
274 unsigned Length = StatBuf.st_size;
275 sprintf(Hdr.size,"%d", Length);
276 cout << "Size: " << Length << "\n";
278 //file member user id in decimal
279 sprintf(Hdr.uid, "%d", StatBuf.st_uid);
281 //file member group id in decimal
282 sprintf(Hdr.gid, "%d", StatBuf.st_gid);
284 //file member date in decimal
285 sprintf(Hdr.date,"%d", (int)StatBuf.st_mtime);
287 //file member mode in OCTAL
288 sprintf(Hdr.mode,"%d", StatBuf.st_mode);
290 //add our header trailer
291 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
293 //write header to archive file
294 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
296 //open Member file for reading and copy to buffer
297 int FD = open(Member.c_str(),O_RDONLY);
299 std::cerr << "Error opening file!\n";
303 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
306 //check if mmap failed
307 if (buf == (unsigned char*)MAP_FAILED) {
308 std::cerr << "Error mmapping file!\n";
312 //write to archive file
313 ArchiveFile.write((char*)buf,Length);
315 // Unmmap the memberfile
316 munmap((char*)buf, Length);
322 // CreateArchive - Generates archive with or without symbol table.
324 void CreateArchive() {
326 //Create archive file for output.
327 std::ofstream ArchiveFile(Archive.c_str());
329 //Check for errors opening or creating archive file.
330 if(!ArchiveFile.is_open() || ArchiveFile.bad() ) {
331 std::cerr << "Error opening Archive File\n";
335 //Write magic string to archive.
336 ArchiveFile << ARMAG;
338 //If the '-s' option was specified, generate symbol table.
340 cout << "Symbol Table Start: " << ArchiveFile.tellp() << "\n";
341 if(!WriteSymbolTable(ArchiveFile)) {
342 std::cerr << "Error creating symbol table. Exiting program.";
345 cout << "Symbol Table End: " << ArchiveFile.tellp() << "\n";
347 //Loop over all member files, and add to the archive.
348 for(unsigned i=0; i<Members.size(); ++i) {
349 if(ArchiveFile.tellp() % 2 != 0)
350 ArchiveFile << ARFMAG;
352 cout << "Member File Start: " << ArchiveFile.tellp() << "\n";
354 if(AddMemberToArchive(Members[i],ArchiveFile) != true) {
355 std::cerr << "Error adding file to archive. Exiting program.";
358 cout << "Member File End: " << ArchiveFile.tellp() << "\n";
361 //Close archive file.
366 int main(int argc, char **argv) {
368 //Parse Command line options
369 cl::ParseCommandLineOptions(argc, argv, " llvm-ar\n");