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 //===----------------------------------------------------------------------===//
10 // Builds up standard unix archive files (.a) containing LLVM bytecode.
12 //===----------------------------------------------------------------------===//
14 #include "Support/CommandLine.h"
15 #include "llvm/Bytecode/Reader.h"
16 #include "llvm/Module.h"
23 #include <sys/types.h>
35 #define ARFMAG "\n" /* header trailer string */
36 #define ARMAG "!<arch>\n" /* magic string */
37 #define SARMAG 8 /* length of magic string */
38 #define VERSION "llvm-ar is a part of the LLVM compiler infrastructure.\nPlease see http://llvm.cs.uiuc.edu for more information.\n";
41 // Each file member is preceded by a file member header. Which is
42 // of the following format:
44 // char ar_name[16] - '/' terminated file member name.
45 // If the file name does not fit, a dummy name is used.
46 // char ar_date[12] - file date in decimal
47 // char ar_uid[6] - User id of file owner in decimal.
48 // char ar_gid[6] - Group ID file belongs to in decimal.
49 // char ar_mode[8] - File mode in octal.
50 // char ar_size[10] - Size of file in decimal.
51 // char ar_fmag[2] - Trailer of header file, a newline.
72 //Option for X32_64, not used but must allow it to be present.
73 cl::opt<bool> X32Option ("X32_64", cl::desc("Ignored option spelt -X32_64, for compatibility with AIX"), cl::Optional);
76 cl::opt<string> Options(cl::Positional, cl::desc("{dmpqrstx}[abcfilNoPsSuvV] "), cl::Required);
79 cl::list<string> RestofArgs(cl::Positional, cl::desc("[relpos] [count]] <archive-file> [members..]"), cl::Optional);
81 //booleans to represent Operation, only one can be preformed at a time
82 bool Print, Delete, Move, QuickAppend, InsertWithReplacement, DisplayTable;
85 //Modifiers to follow operation to vary behavior
86 bool AddAfter, AddBefore, Create, TruncateNames, InsertBefore, UseCount;
87 bool OriginalDates, FullPath, SymTable, OnlyUpdate, Verbose;
92 //Count, use for multiple entries in the archive with the same name
99 vector<string> Members;
102 // WriteSymbolTable - Writes symbol table to ArchiveFile, return false
103 // on errors. Also returns by reference size of symbol table.
105 // Overview of method:
106 // 1) Generate the header for the symbol table. This is a normal
107 // archive member header, but it has a zero length name.
108 // 2) For each archive member file, stat the file and parse the bytecode
109 // Store cumulative offset (file size + header size).
110 // 3) Loop over all the symbols for the current member file,
111 // add offset entry to offset vector, and add symbol name to its vector.
112 // Note: The symbol name vector is a vector of chars to speed up calculating
113 // the total size of the symbol table.
114 // 4) Update offset vector once we know the total size of symbol table. This is
115 // because the symbol table appears before all archive member file contents.
116 // We add the size of magic string, and size of symbol table to each offset.
117 // 5) If the new updated offset it not even, we add 1 byte to offset because
118 // a newline will be inserted when writing member files. This adjustment is
119 // cummulative (ie. each time we have an odd offset we add 1 to total adjustment).
120 // 6) Lastly, write symbol table to file.
122 bool WriteSymbolTable(std::ofstream &ArchiveFile) {
124 //Create header for symbol table. This is essentially an empty header with the
125 //name set to a '/' to indicate its a symbol table.
129 //Name of symbol table is '/'
133 //Set the header trailer to a newline
134 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
137 //Write header to archive file
138 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
141 unsigned memoff = 0; //Keep Track of total size of files added to archive
142 vector<unsigned> offsets; //Vector of offsets into archive file
143 vector<char> names; //Vector of characters that are the symbol names.
145 //Loop over archive member files, parse bytecode, and generate symbol table.
146 for(unsigned i=0; i<Members.size(); ++i) {
148 //Open Member file for reading and copy to buffer
149 int FD = open(Members[i].c_str(),O_RDONLY);
151 //Check for errors opening the file.
153 std::cerr << "Error opening file!\n";
157 //Stat the file to get its size.
159 if (stat(Members[i].c_str(), &StatBuf) == -1 || StatBuf.st_size == 0) {
160 std::cerr << "Error stating file\n";
165 unsigned Length = StatBuf.st_size;
167 //Read in file into a buffer.
168 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
171 //Check if mmap failed.
172 if (buf == (unsigned char*)MAP_FAILED) {
173 std::cerr << "Error mmapping file!\n";
177 //Parse the bytecode file and get all the symbols.
179 Module *M = ParseBytecodeBuffer(buf,Length,Members[i],&ErrorStr);
181 //Check for errors parsing bytecode.
183 //std::cerr << "Error Parsing Bytecode\n";
187 //Loop over function names and global vars and add to symbol maps
188 for(Module::iterator I = M->begin(), E=M->end(); I != E; ++I) {
191 string NM = ((Function*)I)->getName();
193 //Loop over the characters in the name and add to symbol name vector
194 for(unsigned i=0; i<NM.size(); ++i)
195 names.push_back(NM[i]);
197 //Each symbol is null terminated.
198 names.push_back('\0');
200 //Add offset to vector of offsets
201 offsets.push_back(memoff);
204 memoff += Length + sizeof(Hdr);
207 //Determine how large our symbol table is.
208 unsigned symbolTableSize = sizeof(Hdr) + 4 + 4*(offsets.size()) + names.size();
209 cout << "Symbol Table Size: " << symbolTableSize << "\n";
211 //Number of symbols should be in network byte order as well
213 unsigned temp = offsets.size();
214 num[0] = (temp >> 24) & 255;
215 num[1] = (temp >> 16) & 255;
216 num[2] = (temp >> 8) & 255;
219 //Write number of symbols to archive file
220 ArchiveFile.write(num,4);
222 //Adjustment to offset to start files on even byte boundaries
225 //Update offsets write symbol table to archive.
226 for(unsigned i=0; i<offsets.size(); ++i) {
228 offsets[i] = offsets[i] + symbolTableSize + SARMAG;
229 offsets[i] += adjust;
230 if((offsets[i] % 2 != 0)) {
232 offsets[i] += adjust;
235 cout << "Offset: " << offsets[i] << "\n";
236 output[0] = (offsets[i] >> 24) & 255;
237 output[1] = (offsets[i] >> 16) & 255;
238 output[2] = (offsets[i] >> 8) & 255;
239 output[3] = offsets[i] & 255;
240 ArchiveFile.write(output,4);
244 //Write out symbol name vector.
245 for(unsigned i=0; i<names.size(); ++i)
246 ArchiveFile << names[i];
251 // AddMemberToArchive - Writes member file to archive. Returns false on errors.
253 // Overview of method:
254 // 1) Open file, and stat it.
255 // 2) Fill out header using stat information. If name is longer then 15
256 // characters, use "dummy" name.
257 // 3) Write header and file contents to disk.
258 // 4) Keep track of total offset into file, and insert a newline if it is odd.
260 bool AddMemberToArchive(string Member, std::ofstream &ArchiveFile) {
262 cout << "Member File Start: " << ArchiveFile.tellp() << "\n";
264 ar_hdr Hdr; //Header for archive member file.
266 //stat the file to get info
268 if (stat(Member.c_str(), &StatBuf) == -1 || StatBuf.st_size == 0)
273 //set name to white spaces
274 memset(Hdr.name,' ', sizeof(Hdr.name));
276 //check the size of the name, if less than 15, we can copy it directly
277 //otherwise we give it a dummy name for now
278 if(Member.length() < 16)
279 memcpy(Hdr.name,Member.c_str(),Member.length());
281 memcpy(Hdr.name, "Dummy", 5);
283 //terminate name with forward slash
286 //file member size in decimal
287 unsigned Length = StatBuf.st_size;
288 sprintf(Hdr.size,"%d", Length);
289 cout << "Size: " << Length << "\n";
291 //file member user id in decimal
292 sprintf(Hdr.uid, "%d", StatBuf.st_uid);
294 //file member group id in decimal
295 sprintf(Hdr.gid, "%d", StatBuf.st_gid);
297 //file member date in decimal
298 sprintf(Hdr.date,"%d", (int)StatBuf.st_mtime);
300 //file member mode in OCTAL
301 sprintf(Hdr.mode,"%d", StatBuf.st_mode);
303 //add our header trailer
304 memcpy(Hdr.fmag,ARFMAG,sizeof(ARFMAG));
306 //write header to archive file
307 ArchiveFile.write((char*)&Hdr, sizeof(Hdr));
309 //open Member file for reading and copy to buffer
310 int FD = open(Member.c_str(),O_RDONLY);
312 std::cerr << "Error opening file!\n";
316 unsigned char *buf = (unsigned char*)mmap(0, Length,PROT_READ,
319 //check if mmap failed
320 if (buf == (unsigned char*)MAP_FAILED) {
321 std::cerr << "Error mmapping file!\n";
325 //write to archive file
326 ArchiveFile.write((char*)buf,Length);
328 // Unmmap the memberfile
329 munmap((char*)buf, Length);
331 cout << "Member File End: " << ArchiveFile.tellp() << "\n";
337 // CreateArchive - Generates archive with or without symbol table.
339 void CreateArchive() {
341 std::cerr << "Archive File: " << Archive << "\n";
343 //Create archive file for output.
344 std::ofstream ArchiveFile(Archive.c_str());
346 //Check for errors opening or creating archive file.
347 if(!ArchiveFile.is_open() || ArchiveFile.bad() ) {
348 std::cerr << "Error opening Archive File\n";
352 //Write magic string to archive.
353 ArchiveFile << ARMAG;
355 //If the '-s' option was specified, generate symbol table.
357 cout << "Symbol Table Start: " << ArchiveFile.tellp() << "\n";
358 if(!WriteSymbolTable(ArchiveFile)) {
359 std::cerr << "Error creating symbol table. Exiting program.";
362 cout << "Symbol Table End: " << ArchiveFile.tellp() << "\n";
364 //Loop over all member files, and add to the archive.
365 for(unsigned i=0; i < Members.size(); ++i) {
366 if(ArchiveFile.tellp() % 2 != 0)
367 ArchiveFile << ARFMAG;
368 if(AddMemberToArchive(Members[i],ArchiveFile) != true) {
369 std::cerr << "Error adding " << Members[i] << "to archive. Exiting program.\n";
374 //Close archive file.
378 //Print out usage for errors in command line
380 std::cout << "USAGE: ar [-X32_64] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] [count] archive-file [files..]\n\n";
382 std::cout << "commands:\n" <<
383 "d - delete file(s) from the archive\n"
384 << "m[ab] - move file(s) in the archive\n"
385 << "p - print file(s) found in the archive\n"
386 << "q[f] - quick append file(s) to the archive\n"
387 << "r[ab][f][u] - replace existing or insert new file(s) into the archive\n"
388 << "t - display contents of archive\n"
389 << "x[o] - extract file(s) from the archive\n";
391 std::cout << "\ncommand specific modifiers:\n"
392 << "[a] - put file(s) after [member-name]\n"
393 << "[b] - put file(s) before [member-name] (same as [i])\n"
394 << "[N] - use instance [count] of name\n"
395 << "[f] - truncate inserted file names\n"
396 << "[P] - use full path names when matching\n"
397 << "[o] - preserve original dates\n"
398 << "[u] - only replace files that are newer than current archive contents\n";
400 std::cout << "generic modifiers:\n"
401 << "[c] - do not warn if the library had to be created\n"
402 << "[s] - create an archive index (cf. ranlib)\n"
403 << "[S] - do not build a symbol table\n"
404 << "[v] - be verbose\n"
405 << "[V] - display the version number\n";
411 void printVersion() {
416 //Extract the memberfile name from the command line
418 if(RestofArgs.size() > 0) {
419 RelPos = RestofArgs[0];
420 RestofArgs.erase(RestofArgs.begin());
422 //Throw error if needed and not present
427 //Extract count from the command line
429 if(RestofArgs.size() > 0) {
430 Count = atoi(RestofArgs[0].c_str());
431 RestofArgs.erase(RestofArgs.begin());
433 //Throw error if needed and not present
438 //Get the Archive File Name from the command line
440 std::cerr << RestofArgs.size() << "\n";
441 if(RestofArgs.size() > 0) {
442 Archive = RestofArgs[0];
443 RestofArgs.erase(RestofArgs.begin());
445 //Throw error if needed and not present
451 //Copy over remaining items in RestofArgs to our Member File vector.
452 //This is just for clarity.
454 std::cerr << RestofArgs.size() << "\n";
455 if(RestofArgs.size() > 0)
456 Members = vector<string>(RestofArgs);
459 // Parse the operations and operation modifiers
460 // FIXME: Not all of these options has been implemented, but we still
461 // do all the command line parsing for them.
464 //Keep track of number of operations. We can only specify one
466 unsigned NumOperations = 0;
468 for(unsigned i=0; i<Options.size(); ++i) {
484 InsertWithReplacement = true;
506 TruncateNames = true;
519 OriginalDates = true;
544 //Check that only one operation has been specified
545 if(NumOperations > 1)
553 int main(int argc, char **argv) {
555 //Parse Command line options
556 cl::ParseCommandLineOptions(argc, argv);