1 //===-- 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 //===----------------------------------------------------------------------===//
10 // Builds up standard unix archive files (.a) containing LLVM bytecode.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/Bytecode/Reader.h"
16 #include "Support/CommandLine.h"
17 #include "Support/FileUtilities.h"
22 #include <sys/types.h>
31 #define ARFMAG "\n" /* header trailer string */
32 #define ARMAG "!<arch>\n" /* magic string */
33 #define SARMAG 8 /* length of magic string */
34 #define VERSION "llvm-ar is a part of the LLVM compiler infrastructure.\nPlease see http://llvm.cs.uiuc.edu for more information.\n";
37 // Each file member is preceded by a file member header. Which is
38 // of the following format:
40 // char ar_name[16] - '/' terminated file member name.
41 // If the file name does not fit, a dummy name is used.
42 // char ar_date[12] - file date in decimal
43 // char ar_uid[6] - User id of file owner in decimal.
44 // char ar_gid[6] - Group ID file belongs to in decimal.
45 // char ar_mode[8] - File mode in octal.
46 // char ar_size[10] - Size of file in decimal.
47 // char ar_fmag[2] - Trailer of header file, a newline.
68 //Option for X32_64, not used but must allow it to be present.
69 cl::opt<bool> X32Option ("X32_64", cl::desc("Ignored option spelt -X32_64, for compatibility with AIX"), cl::Optional);
72 cl::opt<string> Options(cl::Positional, cl::desc("{dmpqrstx}[abcfilNoPsSuvV] "), cl::Required);
75 cl::list<string> RestofArgs(cl::Positional, cl::desc("[relpos] [count]] <archive-file> [members..]"), cl::Optional);
77 //booleans to represent Operation, only one can be preformed at a time
78 bool Print, Delete, Move, QuickAppend, InsertWithReplacement, DisplayTable;
81 //Modifiers to follow operation to vary behavior
82 bool AddAfter, AddBefore, Create, TruncateNames, InsertBefore, UseCount;
83 bool OriginalDates, FullPath, SymTable, OnlyUpdate, Verbose;
88 //Count, use for multiple entries in the archive with the same name
95 std::vector<string> Members;
98 // WriteSymbolTable - Writes symbol table to ArchiveFile, return false
99 // on errors. Also returns by reference size of symbol table.
101 // Overview of method:
102 // 1) Generate the header for the symbol table. This is a normal
103 // archive member header, but it has a zero length name.
104 // 2) For each archive member file, stat the file and parse the bytecode
105 // Store cumulative offset (file size + header size).
106 // 3) Loop over all the symbols for the current member file,
107 // add offset entry to offset vector, and add symbol name to its vector.
108 // Note: The symbol name vector is a vector of chars to speed up calculating
109 // the total size of the symbol table.
110 // 4) Update offset vector once we know the total size of symbol table. This is
111 // because the symbol table appears before all archive member file contents.
112 // We add the size of magic string, and size of symbol table to each offset.
113 // 5) If the new updated offset it not even, we add 1 byte to offset because
114 // a newline will be inserted when writing member files. This adjustment is
115 // cummulative (ie. each time we have an odd offset we add 1 to total adjustment).
116 // 6) Lastly, write symbol table to file.
118 bool WriteSymbolTable(std::ofstream &ArchiveFile) {
120 //Create header for symbol table. This is essentially an empty header with the
121 //name set to a '/' to indicate its a symbol table.
125 //Name of symbol table is '/'
129 //Set the header trailer to a newline
130 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
133 //Write header to archive file
134 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
137 unsigned memoff = 0; //Keep Track of total size of files added to archive
138 std::vector<unsigned> offsets; //Vector of offsets into archive file
139 std::vector<char> names; //Vector of characters that are the symbol names.
141 //Loop over archive member files, parse bytecode, and generate symbol table.
142 for(unsigned i=0; i<Members.size(); ++i) {
144 //Open Member file for reading and copy to buffer
145 int FD = open(Members[i].c_str(),O_RDONLY);
147 //Check for errors opening the file.
149 std::cerr << "Error opening file!\n";
154 unsigned Length = getFileSize(Members[i]);
155 if (Length == (unsigned)-1) {
156 std::cerr << "Error stating file\n";
160 //Read in file into a buffer.
161 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
164 //Check if mmap failed.
165 if (buf == (unsigned char*)MAP_FAILED) {
166 std::cerr << "Error mmapping file!\n";
170 //Parse the bytecode file and get all the symbols.
172 Module *M = ParseBytecodeBuffer(buf,Length,Members[i],&ErrorStr);
174 //Check for errors parsing bytecode.
176 //std::cerr << "Error Parsing Bytecode\n";
180 //Loop over function names and global vars and add to symbol maps
181 for(Module::iterator I = M->begin(), E=M->end(); I != E; ++I) {
184 string NM = ((Function*)I)->getName();
186 //Loop over the characters in the name and add to symbol name vector
187 for(unsigned i=0; i<NM.size(); ++i)
188 names.push_back(NM[i]);
190 //Each symbol is null terminated.
191 names.push_back('\0');
193 //Add offset to vector of offsets
194 offsets.push_back(memoff);
197 memoff += Length + sizeof(Hdr);
200 //Determine how large our symbol table is.
201 unsigned symbolTableSize = sizeof(Hdr) + 4 + 4*(offsets.size()) + names.size();
202 std::cout << "Symbol Table Size: " << symbolTableSize << "\n";
204 //Number of symbols should be in network byte order as well
206 unsigned temp = offsets.size();
207 num[0] = (temp >> 24) & 255;
208 num[1] = (temp >> 16) & 255;
209 num[2] = (temp >> 8) & 255;
212 //Write number of symbols to archive file
213 ArchiveFile.write(num,4);
215 //Adjustment to offset to start files on even byte boundaries
218 //Update offsets write symbol table to archive.
219 for(unsigned i=0; i<offsets.size(); ++i) {
221 offsets[i] = offsets[i] + symbolTableSize + SARMAG;
222 offsets[i] += adjust;
223 if((offsets[i] % 2 != 0)) {
225 offsets[i] += adjust;
228 std::cout << "Offset: " << offsets[i] << "\n";
229 output[0] = (offsets[i] >> 24) & 255;
230 output[1] = (offsets[i] >> 16) & 255;
231 output[2] = (offsets[i] >> 8) & 255;
232 output[3] = offsets[i] & 255;
233 ArchiveFile.write(output,4);
237 //Write out symbol name vector.
238 for(unsigned i=0; i<names.size(); ++i)
239 ArchiveFile << names[i];
244 // AddMemberToArchive - Writes member file to archive. Returns false on errors.
246 // Overview of method:
247 // 1) Open file, and stat it.
248 // 2) Fill out header using stat information. If name is longer then 15
249 // characters, use "dummy" name.
250 // 3) Write header and file contents to disk.
251 // 4) Keep track of total offset into file, and insert a newline if it is odd.
253 bool AddMemberToArchive(string Member, std::ofstream &ArchiveFile) {
255 std::cout << "Member File Start: " << ArchiveFile.tellp() << "\n";
257 ar_hdr Hdr; //Header for archive member file.
259 //stat the file to get info
261 if (stat(Member.c_str(), &StatBuf) == -1 || StatBuf.st_size == 0)
266 //set name to white spaces
267 memset(Hdr.name,' ', sizeof(Hdr.name));
269 //check the size of the name, if less than 15, we can copy it directly
270 //otherwise we give it a dummy name for now
271 if(Member.length() < 16)
272 memcpy(Hdr.name,Member.c_str(),Member.length());
274 memcpy(Hdr.name, "Dummy", 5);
276 //terminate name with forward slash
279 //file member size in decimal
280 unsigned Length = StatBuf.st_size;
281 sprintf(Hdr.size,"%d", Length);
282 std::cout << "Size: " << Length << "\n";
284 //file member user id in decimal
285 sprintf(Hdr.uid, "%d", StatBuf.st_uid);
287 //file member group id in decimal
288 sprintf(Hdr.gid, "%d", StatBuf.st_gid);
290 //file member date in decimal
291 sprintf(Hdr.date,"%d", (int)StatBuf.st_mtime);
293 //file member mode in OCTAL
294 sprintf(Hdr.mode,"%d", StatBuf.st_mode);
296 //add our header trailer
297 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
299 //write header to archive file
300 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
302 //open Member file for reading and copy to buffer
303 int FD = open(Member.c_str(),O_RDONLY);
305 std::cerr << "Error opening file!\n";
309 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
312 //check if mmap failed
313 if (buf == (unsigned char*)MAP_FAILED) {
314 std::cerr << "Error mmapping file!\n";
318 //write to archive file
319 ArchiveFile.write((char*)buf,Length);
321 // Unmmap the memberfile
322 munmap((char*)buf, Length);
324 std::cout << "Member File End: " << ArchiveFile.tellp() << "\n";
330 // CreateArchive - Generates archive with or without symbol table.
332 void CreateArchive() {
334 std::cerr << "Archive File: " << Archive << "\n";
336 //Create archive file for output.
337 std::ofstream ArchiveFile(Archive.c_str());
339 //Check for errors opening or creating archive file.
340 if(!ArchiveFile.is_open() || ArchiveFile.bad() ) {
341 std::cerr << "Error opening Archive File\n";
345 //Write magic string to archive.
346 ArchiveFile << ARMAG;
348 //If the '-s' option was specified, generate symbol table.
350 std::cout << "Symbol Table Start: " << ArchiveFile.tellp() << "\n";
351 if(!WriteSymbolTable(ArchiveFile)) {
352 std::cerr << "Error creating symbol table. Exiting program.";
355 std::cout << "Symbol Table End: " << ArchiveFile.tellp() << "\n";
357 //Loop over all member files, and add to the archive.
358 for(unsigned i=0; i < Members.size(); ++i) {
359 if(ArchiveFile.tellp() % 2 != 0)
360 ArchiveFile << ARFMAG;
361 if(AddMemberToArchive(Members[i],ArchiveFile) != true) {
362 std::cerr << "Error adding " << Members[i] << "to archive. Exiting program.\n";
367 //Close archive file.
371 //Print out usage for errors in command line
373 std::cout << "USAGE: ar [-X32_64] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] [count] archive-file [files..]\n\n";
375 std::cout << "commands:\n" <<
376 "d - delete file(s) from the archive\n"
377 << "m[ab] - move file(s) in the archive\n"
378 << "p - print file(s) found in the archive\n"
379 << "q[f] - quick append file(s) to the archive\n"
380 << "r[ab][f][u] - replace existing or insert new file(s) into the archive\n"
381 << "t - display contents of archive\n"
382 << "x[o] - extract file(s) from the archive\n";
384 std::cout << "\ncommand specific modifiers:\n"
385 << "[a] - put file(s) after [member-name]\n"
386 << "[b] - put file(s) before [member-name] (same as [i])\n"
387 << "[N] - use instance [count] of name\n"
388 << "[f] - truncate inserted file names\n"
389 << "[P] - use full path names when matching\n"
390 << "[o] - preserve original dates\n"
391 << "[u] - only replace files that are newer than current archive contents\n";
393 std::cout << "generic modifiers:\n"
394 << "[c] - do not warn if the library had to be created\n"
395 << "[s] - create an archive index (cf. ranlib)\n"
396 << "[S] - do not build a symbol table\n"
397 << "[v] - be verbose\n"
398 << "[V] - display the version number\n";
404 void printVersion() {
405 std::cout << VERSION;
409 //Extract the memberfile name from the command line
411 if(RestofArgs.size() > 0) {
412 RelPos = RestofArgs[0];
413 RestofArgs.erase(RestofArgs.begin());
415 //Throw error if needed and not present
420 //Extract count from the command line
422 if(RestofArgs.size() > 0) {
423 Count = atoi(RestofArgs[0].c_str());
424 RestofArgs.erase(RestofArgs.begin());
426 //Throw error if needed and not present
431 //Get the Archive File Name from the command line
433 std::cerr << RestofArgs.size() << "\n";
434 if(RestofArgs.size() > 0) {
435 Archive = RestofArgs[0];
436 RestofArgs.erase(RestofArgs.begin());
438 //Throw error if needed and not present
444 //Copy over remaining items in RestofArgs to our Member File vector.
445 //This is just for clarity.
447 std::cerr << RestofArgs.size() << "\n";
448 if(RestofArgs.size() > 0)
449 Members = std::vector<string>(RestofArgs);
452 // Parse the operations and operation modifiers
453 // FIXME: Not all of these options has been implemented, but we still
454 // do all the command line parsing for them.
457 //Keep track of number of operations. We can only specify one
459 unsigned NumOperations = 0;
461 for(unsigned i=0; i<Options.size(); ++i) {
477 InsertWithReplacement = true;
499 TruncateNames = true;
512 OriginalDates = true;
537 //Check that only one operation has been specified
538 if(NumOperations > 1)
546 int main(int argc, char **argv) {
548 //Parse Command line options
549 cl::ParseCommandLineOptions(argc, argv);