blob: 2d1d6219acb6a016caee87f44375c7c812d8f3b9 [file] [log] [blame]
Chris Lattner97f752f2003-12-30 07:45:46 +00001//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer3a1582b2004-11-14 22:20:07 +00005// This file was developed by the Reid Spencer based on the original design by
6// Tanya Lattner and is distributed by the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
John Criswell7c0e0222003-10-20 17:47:21 +00008//
9//===----------------------------------------------------------------------===//
Tanya Lattner14baebf2003-08-28 15:22:38 +000010//
Reid Spencer3a1582b2004-11-14 22:20:07 +000011// Builds up (relatively) standard unix archive files (.a) containing LLVM
12// bytecode or other files.
Tanya Lattner14baebf2003-08-28 15:22:38 +000013//
14//===----------------------------------------------------------------------===//
Brian Gaeke4fa9fd32003-10-10 18:47:08 +000015
Tanya Lattner14baebf2003-08-28 15:22:38 +000016#include "llvm/Module.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000017#include "llvm/Bytecode/Archive.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000018#include "llvm/Support/CommandLine.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000019#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/Support/FileUtilities.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000021#include "llvm/System/Signals.h"
Reid Spencer86f42bd2004-07-04 12:20:55 +000022#include <iostream>
Reid Spencer3a1582b2004-11-14 22:20:07 +000023#include <algorithm>
24#include <iomanip>
25
Brian Gaeked0fde302003-11-11 22:41:34 +000026using namespace llvm;
27
Reid Spencer3a1582b2004-11-14 22:20:07 +000028// Option for compatibility with ASIX, not used but must allow it to be present.
29cl::opt<bool>
30X32Option ("X32_64", cl::desc("Ignored option for compatibility with AIX"));
Tanya Lattner14baebf2003-08-28 15:22:38 +000031
Reid Spencer3a1582b2004-11-14 22:20:07 +000032// llvm-ar operation code and modifier flags. This must come first
33cl::opt<std::string>
34Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000035
Reid Spencer3a1582b2004-11-14 22:20:07 +000036// llvm-ar remaining positional arguments
37cl::list<std::string>
38RestOfArgs(cl::Positional, cl::OneOrMore,
39 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000040
Reid Spencer3a1582b2004-11-14 22:20:07 +000041// This enumeration delineates the kinds of operations on an archive
42// that are permitted.
43enum ArchiveOperation {
44 NoOperation, ///< An operation hasn't been specified
45 Print, ///< Print the contents of the archive
46 Delete, ///< Delete the specified members
47 Move, ///< Move members to end or as given by {a,b,i} modifiers
48 QuickAppend, ///< Quickly append to end of archive
49 ReplaceOrInsert, ///< Replace or Insert members
50 DisplayTable, ///< Display the table of contents
51 Extract, ///< Extract files back to file system
Tanya Lattner57bd7962003-12-06 23:01:25 +000052};
Tanya Lattner14baebf2003-08-28 15:22:38 +000053
Reid Spencer3a1582b2004-11-14 22:20:07 +000054// Modifiers to follow operation to vary behavior
55bool AddAfter = false; ///< 'a' modifier
56bool AddBefore = false; ///< 'b' modifier
57bool Create = false; ///< 'c' modifier
58bool TruncateNames = false; ///< 'f' modifier
59bool InsertBefore = false; ///< 'i' modifier
60bool DontSkipBytecode = false; ///< 'k' modifier
61bool UseCount = false; ///< 'N' modifier
62bool OriginalDates = false; ///< 'o' modifier
63bool FullPath = false; ///< 'P' modifier
64bool RecurseDirectories = false; ///< 'R' modifier
65bool SymTable = true; ///< 's' & 'S' modifiers
66bool OnlyUpdate = false; ///< 'u' modifier
67bool Verbose = false; ///< 'v' modifier
68bool ReallyVerbose = false; ///< 'V' modifier
69bool Compression = false; ///< 'z' modifier
Tanya Lattner14baebf2003-08-28 15:22:38 +000070
Reid Spencer3a1582b2004-11-14 22:20:07 +000071// Relative Positional Argument (for insert/move). This variable holds
72// the name of the archive member to which the 'a', 'b' or 'i' modifier
73// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
74// one variable.
75std::string RelPos;
Tanya Lattner57bd7962003-12-06 23:01:25 +000076
Reid Spencer3a1582b2004-11-14 22:20:07 +000077// Select which of multiple entries in the archive with the same name should be
78// used (specified with -N) for the delete and extract operations.
79int Count = 1;
Tanya Lattner57bd7962003-12-06 23:01:25 +000080
Reid Spencer3a1582b2004-11-14 22:20:07 +000081// This variable holds the name of the archive file as given on the
82// command line.
83std::string ArchiveName;
Tanya Lattner57bd7962003-12-06 23:01:25 +000084
Reid Spencer3a1582b2004-11-14 22:20:07 +000085// This variable holds the list of member files to proecess, as given
86// on the command line.
87std::vector<std::string> Members;
Tanya Lattner57bd7962003-12-06 23:01:25 +000088
Reid Spencer3a1582b2004-11-14 22:20:07 +000089// This variable holds the (possibly expanded) list of path objects that
90// correspond to files we will
91sys::Path::Vector Paths;
Tanya Lattner57bd7962003-12-06 23:01:25 +000092
Reid Spencer3a1582b2004-11-14 22:20:07 +000093// The Archive object to which all the editing operations will be sent.
94Archive* TheArchive = 0;
Tanya Lattner57bd7962003-12-06 23:01:25 +000095
Reid Spencer3a1582b2004-11-14 22:20:07 +000096// printMoreHelp - Provide additional help output explaining the operations and
97// modifiers of llvm-ar. This function is called by the CommandLine library
98// when the --help option is given because we set the global cl::MoreHelp
99// variable to the address of this function.
100void printMoreHelp() {
101 std::cout
102 << "\nOPERATIONS:\n"
103 << " d[NsS] - delete file(s) from the archive\n"
104 << " m[abiSs] - move file(s) in the archive\n"
105 << " p[kN] - print file(s) found in the archive\n"
106 << " q[ufsS] - quick append file(s) to the archive\n"
107 << " r[abfiuzRsS] - replace or insert file(s) into the archive\n"
108 << " t - display contents of archive\n"
109 << " x[No] - extract file(s) from the archive\n";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000110
Reid Spencer3a1582b2004-11-14 22:20:07 +0000111 std::cout
112 << "\nMODIFIERS (operation specific):\n"
113 << " [a] - put file(s) after [relpos]\n"
114 << " [b] - put file(s) before [relpos] (same as [i])\n"
115 << " [f] - truncate inserted file names\n"
116 << " [i] - put file(s) before [relpos] (same as [b])\n"
117 << " [k] - always print bytecode files (default is to skip them)\n"
118 << " [N] - use instance [count] of name\n"
119 << " [o] - preserve original dates\n"
120 << " [P] - use full path names when matching\n"
121 << " [R] - recurse through directories when inserting\n"
122 << " [s] - create an archive index (cf. ranlib)\n"
123 << " [S] - do not build a symbol table\n"
124 << " [u] - update only files newer than archive contents\n"
125 << " [z] - compress files before inserting/extracting\n";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000126
Reid Spencer3a1582b2004-11-14 22:20:07 +0000127 std::cout
128 << "\nMODIFIERS (generic):\n"
129 << " [c] - do not warn if the library had to be created\n"
130 << " [v] - be verbose about actions taken\n"
131 << " [V] - be *really* verbose about actions taken\n";
Tanya Lattner14baebf2003-08-28 15:22:38 +0000132}
133
Reid Spencer3a1582b2004-11-14 22:20:07 +0000134// printUse - Print out our usage information. This is used in cases where the
135// user has made a mistake on the command line syntax.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000136void printUse() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000137 std::cout
138 << "OVERVIEW: LLVM Archiver (llvm-ar)\n\n"
139 << " This program archives bytecode files into single libraries\n\n"
140 << "USAGE: llvm-ar [-X32_64] [-]{operation}[modifiers]... "
141 << "[relpos] [count] archive-file [files..]\n";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000142
Reid Spencer3a1582b2004-11-14 22:20:07 +0000143 printMoreHelp();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000144 exit(1);
145}
146
Reid Spencer3a1582b2004-11-14 22:20:07 +0000147// getRelPos - Extract the member filename from the command line for
148// the [relpos] argument associated with a, b, and i modifiers
Tanya Lattner57bd7962003-12-06 23:01:25 +0000149void getRelPos() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000150 if(RestOfArgs.size() > 0) {
151 RelPos = RestOfArgs[0];
152 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000153 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000154 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000155 throw "Expected [relpos] for a, b, or i modifier";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000156}
157
Reid Spencer3a1582b2004-11-14 22:20:07 +0000158// getCount - Extract the [count] argument associated with the N modifier
159// from the command line and check its value.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000160void getCount() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000161 if(RestOfArgs.size() > 0) {
162 Count = atoi(RestOfArgs[0].c_str());
163 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000164 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000165 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000166 throw "Expected [count] value with N modifier";
167
168 // Non-positive counts are not allowed
169 if (Count < 1)
170 throw "Invalid [count] value (not a positive integer)";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000171}
172
Reid Spencer3a1582b2004-11-14 22:20:07 +0000173// getArchive - Get the archive file name from the command line
Tanya Lattner57bd7962003-12-06 23:01:25 +0000174void getArchive() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000175 if(RestOfArgs.size() > 0) {
176 ArchiveName = RestOfArgs[0];
177 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000178 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000179 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000180 throw "An archive name must be specified.";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000181}
182
Reid Spencer3a1582b2004-11-14 22:20:07 +0000183// getMembers - Copy over remaining items in RestOfArgs to our Members vector
184// This is just for clarity.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000185void getMembers() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000186 if(RestOfArgs.size() > 0)
187 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattner57bd7962003-12-06 23:01:25 +0000188}
189
Reid Spencer3a1582b2004-11-14 22:20:07 +0000190// parseCommandLine - Parse the command line options as presented and return the
191// operation specified. Process all modifiers and check to make sure that
192// constraints on modifier/operation pairs have not been violated.
193ArchiveOperation parseCommandLine() {
Tanya Lattner57bd7962003-12-06 23:01:25 +0000194
Reid Spencer3a1582b2004-11-14 22:20:07 +0000195 // Keep track of number of operations. We can only specify one
196 // per execution.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000197 unsigned NumOperations = 0;
198
Reid Spencer3a1582b2004-11-14 22:20:07 +0000199 // Keep track of the number of positional modifiers (a,b,i). Only
200 // one can be specified.
201 unsigned NumPositional = 0;
202
203 // Keep track of which operation was requested
204 ArchiveOperation Operation = NoOperation;
205
Tanya Lattner57bd7962003-12-06 23:01:25 +0000206 for(unsigned i=0; i<Options.size(); ++i) {
207 switch(Options[i]) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000208 case 'd': ++NumOperations; Operation = Delete; break;
209 case 'm': ++NumOperations; Operation = Move ; break;
210 case 'p': ++NumOperations; Operation = Print; break;
211 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
212 case 't': ++NumOperations; Operation = DisplayTable; break;
213 case 'x': ++NumOperations; Operation = Extract; break;
214 case 'c': Create = true; break;
215 case 'f': TruncateNames = true; break;
216 case 'k': DontSkipBytecode = true; break;
217 case 'l': /* accepted but unused */ break;
218 case 'o': OriginalDates = true; break;
219 case 'P': FullPath = true; break;
220 case 'R': RecurseDirectories = true; break;
221 case 's': SymTable = true; break;
222 case 'S': SymTable = false; break;
223 case 'u': OnlyUpdate = true; break;
224 case 'v': Verbose = true; break;
225 case 'V': Verbose = ReallyVerbose = true; break;
226 case 'z': Compression = true; break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000227 case 'a':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000228 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000229 AddAfter = true;
230 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000231 break;
232 case 'b':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000233 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000234 AddBefore = true;
235 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000236 break;
237 case 'i':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000238 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000239 InsertBefore = true;
240 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000241 break;
242 case 'N':
Reid Spencer3a1582b2004-11-14 22:20:07 +0000243 getCount();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000244 UseCount = true;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000245 break;
246 default:
247 printUse();
248 }
249 }
250
Reid Spencer3a1582b2004-11-14 22:20:07 +0000251 // At this point, the next thing on the command line must be
252 // the archive name.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000253 getArchive();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000254
255 // Everything on the command line at this point is a member.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000256 getMembers();
257
Reid Spencer3a1582b2004-11-14 22:20:07 +0000258 // Perform various checks on the operation/modifier specification
259 // to make sure we are dealing with a legal request.
260 if (NumOperations == 0)
261 throw "You must specify at least one of the operations";
262 if (NumOperations > 1)
263 throw "Only one operation may be specified";
264 if (NumPositional > 1)
265 throw "You may only specify one of a, b, and i modifiers";
266 if (AddAfter || AddBefore || InsertBefore)
267 if (Operation != Move && Operation != ReplaceOrInsert)
268 throw "The 'a', 'b' and 'i' modifiers can only be specified with "
269 "the 'm' or 'r' operations";
270 if (RecurseDirectories && Operation != ReplaceOrInsert)
271 throw "The 'R' modifiers is only applicabe to the 'r' operation";
272 if (OriginalDates && Operation != Extract)
273 throw "The 'o' modifier is only applicable to the 'x' operation";
274 if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
275 throw "The 'f' modifier is only applicable to the 'q' and 'r' operations";
276 if (OnlyUpdate && Operation != ReplaceOrInsert)
277 throw "The 'u' modifier is only applicable to the 'r' operation";
278 if (Compression && Operation!=ReplaceOrInsert && Operation!=Extract)
279 throw "The 'z' modifier is only applicable to the 'r' and 'x' operations";
280 if (Count > 1 && Members.size() > 1)
281 throw "Only one member name may be specified with the 'N' modifier";
282
283 // Return the parsed operation to the caller
284 return Operation;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000285}
Tanya Lattner14baebf2003-08-28 15:22:38 +0000286
Reid Spencer3a1582b2004-11-14 22:20:07 +0000287// recurseDirectories - Implements the "R" modifier. This function scans through
288// the Paths vector (built by buildPaths, below) and replaces any directories it
289// finds with all the files in that directory (recursively). It uses the
290// sys::Path::getDirectoryContent method to perform the actual directory scans.
291sys::Path::Vector recurseDirectories(const sys::Path& path) {
292 assert(path.isDirectory() && "Oops, can't recurse a file");
293 sys::Path::Vector result;
294 if (RecurseDirectories) {
295 sys::Path::Vector content;
296 path.getDirectoryContents(content);
297 for (sys::Path::Vector::iterator I = content.begin(), E = content.end();
298 I != E; ++I) {
299 if (I->isDirectory()) {
300 sys::Path::Vector moreResults = recurseDirectories(*I);
301 result.insert(result.begin(), moreResults.begin(), moreResults.end());
302 } else {
303 result.push_back(*I);
304 }
305 }
306 }
307 return result;
308}
309
310// buildPaths - Convert the strings in the Members vector to sys::Path objects
311// and make sure they are valid and exist exist. This check is only needed for
312// the operations that add/replace files to the archive ('q' and 'r')
313void buildPaths(bool checkExistence = true) {
314 for (unsigned i = 0; i < Members.size(); i++) {
315 sys::Path aPath;
316 if (!aPath.setFile(Members[i]))
317 throw std::string("File member name invalid: ") + Members[i];
318 if (checkExistence) {
319 if (!aPath.exists())
320 throw std::string("File does not exist: ") + Members[i];
321 sys::Path::StatusInfo si;
322 aPath.getStatusInfo(si);
323 if (si.isDir) {
324 sys::Path::Vector dirpaths = recurseDirectories(aPath);
325 Paths.insert(Paths.end(),dirpaths.begin(),dirpaths.end());
326 } else {
327 Paths.push_back(aPath);
328 }
329 } else {
330 Paths.push_back(aPath);
331 }
332 }
333}
334
335// doPrint - Implements the 'p' operation. This function traverses the archive
336// looking for members that match the path list. It is careful to uncompress
337// things that should be and to skip bytecode files unless the 'k' modifier was
338// given.
339void doPrint() {
340 buildPaths(false);
341 unsigned countDown = Count;
342 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
343 I != E; ++I ) {
344 if (Paths.empty() ||
345 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
346 if (countDown == 1) {
347 const char* data = reinterpret_cast<const char*>(I->getData());
348
349 // Skip things that don't make sense to print
350 if (I->isLLVMSymbolTable() || I->isForeignSymbolTable() ||
351 (!DontSkipBytecode &&
352 (I->isBytecode() || I->isCompressedBytecode())))
353 continue;
354
355 if (Verbose)
356 std::cout << "Printing " << I->getPath().get() << "\n";
357
358 if (I->isCompressedBytecode())
359 Compressor::decompressToFile(data+4,I->getSize()-4,std::cout);
360 else if (I->isCompressed()) {
361 Compressor::decompressToFile(data,I->getSize(),std::cout);
362 } else {
363 unsigned len = I->getSize();
364 std::cout.write(data, len);
365 }
366 } else {
367 countDown--;
368 }
369 }
370 }
371}
372
373// putMode - utility function for printing out the file mode when the 't'
374// operation is in verbose mode.
375void putMode(unsigned mode) {
376 if (mode & 004)
377 std::cout << "r";
378 else
379 std::cout << "-";
380 if (mode & 002)
381 std::cout << "w";
382 else
383 std::cout << "-";
384 if (mode & 001)
385 std::cout << "x";
386 else
387 std::cout << "-";
388}
389
390// doDisplayTable - Implement the 't' operation. This function prints out just
391// the file names of each of the members. However, if verbose mode is requested
392// ('v' modifier) then the file type, permission mode, user, group, size, and
393// modification time are also printed.
394void doDisplayTable() {
395 buildPaths(false);
396 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
397 I != E; ++I ) {
398 if (Paths.empty() ||
399 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
400 if (Verbose) {
401 // FIXME: Output should be this format:
402 // Zrw-r--r-- 500/ 500 525 Nov 8 17:42 2004 Makefile
403 if (I->isBytecode())
404 std::cout << "b";
405 else if (I->isCompressedBytecode())
406 std::cout << "B";
407 else if (I->isForeignSymbolTable())
408 std::cout << "s";
409 else if (I->isLLVMSymbolTable())
410 std::cout << "S";
411 else if (I->isCompressed())
412 std::cout << "Z";
413 else
414 std::cout << " ";
415 unsigned mode = I->getMode();
416 putMode((mode >> 6) & 007);
417 putMode((mode >> 3) & 007);
418 putMode(mode & 007);
419 std::cout << " " << std::setw(4) << I->getUser();
420 std::cout << "/" << std::setw(4) << I->getGroup();
421 std::cout << " " << std::setw(8) << I->getSize();
422 std::cout << " " << std::setw(20) <<
423 I->getModTime().ToString().substr(4);
424 std::cout << " " << I->getPath().get() << "\n";
425 } else {
426 std::cout << I->getPath().get() << "\n";
427 }
428 }
429 }
430 if (ReallyVerbose) {
431 std::cout << "\nArchive Symbol Table:\n";
432 const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
433 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
434 I != E; ++I ) {
435 unsigned offset = TheArchive->getFirstFileOffset() + I->second;
436 std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
437 }
438 }
439}
440
441// doExtract - Implement the 'x' operation. This function extracts files back to
442// the file system, making sure to uncompress any that were compressed.
443void doExtract() {
444 buildPaths(false);
445 unsigned countDown = Count;
446 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
447 I != E; ++I ) {
448 if (Paths.empty() ||
449 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
450
451 // Make sure the intervening directories are created
452 if (I->hasPath()) {
453 sys::Path dirs(I->getPath());
454 dirs.elideFile();
455 dirs.createDirectory(/*create_parents=*/true);
456 }
457
458 // Open up a file stream for writing
459 std::ofstream file(I->getPath().c_str());
460
461 // Get the data and its length
462 const char* data = reinterpret_cast<const char*>(I->getData());
463 unsigned len = I->getSize();
464
465 // Write the data, making sure to uncompress things first
466 if (I->isCompressed()) {
467 Compressor::decompressToFile(data,len,file);
468 } else {
469 file.write(data,len);
470 }
471 file.close();
472
473 // If we're supposed to retain the original modification times, etc. do so
474 // now.
475 if (OriginalDates)
476 I->getPath().setStatusInfo(I->getStatusInfo());
477 }
478 }
479}
480
481// doDelete - Implement the delete operation. This function deletes zero or more
482// members from the archive. Note that if the count is specified, there should
483// be no more than one path in the Paths list or else this algorithm breaks.
484// That check is enforced in parseCommandLine (above).
485void doDelete() {
486 buildPaths(false);
487 if (Paths.empty()) return;
488 unsigned countDown = Count;
489 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
490 I != E; ) {
491 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
492 if (countDown == 1) {
493 Archive::iterator J = I;
494 ++I;
495 TheArchive->remove(J);
496 } else
497 countDown--;
498 } else {
499 ++I;
500 }
501 }
502
503 // We're done editting, reconstruct the archive.
504 TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
505}
506
507// doMore - Implement the move operation. This function re-arranges just the
508// order of the archive members so that when the archive is written the move
509// of the members is accomplished. Note the use of the RelPos variable to
510// determine where the items should be moved to.
511void doMove() {
512
513 buildPaths(false);
514
515 // By default and convention the place to move members to is the end of the
516 // archive.
517 Archive::iterator moveto_spot = TheArchive->end();
518
519 // However, if the relative positioning modifiers were used, we need to scan
520 // the archive to find the member in question. If we don't find it, its no
521 // crime, we just move to the end.
522 if (AddBefore || InsertBefore || AddAfter) {
523 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
524 I != E; ++I ) {
525 if (RelPos == I->getPath().get()) {
526 if (AddAfter) {
527 moveto_spot = I;
528 moveto_spot++;
529 } else {
530 moveto_spot = I;
531 }
532 break;
533 }
534 }
535 }
536
537 // Keep a list of the paths remaining to be moved
538 sys::Path::Vector remaining(Paths);
539
540 // Scan the archive again, this time looking for the members to move to the
541 // moveto_spot.
542 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
543 I != E && !remaining.empty(); ++I ) {
544 sys::Path::Vector::iterator found =
545 std::find(remaining.begin(),remaining.end(),I->getPath());
546 if (found != remaining.end()) {
547 if (I != moveto_spot)
548 TheArchive->moveMemberBefore(I,moveto_spot);
549 remaining.erase(found);
550 }
551 }
552
553 // We're done editting, reconstruct the archive.
554 TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
555}
556
557// doQuickAppend - Implements the 'q' operation. This function just
558// indiscriminantly adds the members to the archive and rebuilds it.
559void doQuickAppend() {
560 // Get the list of paths to append.
561 buildPaths(true);
562 if (Paths.empty()) return;
563
564 // Append them quickly.
565 for (sys::Path::Vector::iterator PI = Paths.begin(), PE = Paths.end();
566 PI != PE; ++PI) {
567 TheArchive->addFileBefore(*PI,TheArchive->end());
568 }
569
570 // We're done editting, reconstruct the archive.
571 TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
572}
573
574// doReplaceOrInsert - Implements the 'r' operation. This function will replace
575// any existing files or insert new ones into the archive.
576void doReplaceOrInsert() {
577
578 // Build the list of files to be added/replaced.
579 buildPaths(true);
580 if (Paths.empty()) return;
581
582 // Keep track of the paths that remain to be inserted.
583 sys::Path::Vector remaining(Paths);
584
585 // Default the insertion spot to the end of the archive
586 Archive::iterator insert_spot = TheArchive->end();
587
588 // Iterate over the archive contents
589 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
590 I != E && !remaining.empty(); ++I ) {
591
592 // Determine if this archive member matches one of the paths we're trying
593 // to replace.
594 sys::Path::Vector::iterator found =
595 std::find(remaining.begin(),remaining.end(), I->getPath());
596 if (found != remaining.end()) {
597 if (OnlyUpdate) {
598 // Replace the item only if it is newer.
599 sys::Path::StatusInfo si;
600 found->getStatusInfo(si);
601 if (si.modTime > I->getModTime())
602 I->replaceWith(*found);
603 } else {
604 // Replace the item regardless of time stamp
605 I->replaceWith(*found);
606 }
607
608 // Remove it from our "to do" list
609 remaining.erase(found);
610 }
611
612 // Determine if this is the place where we should insert
613 if ((AddBefore || InsertBefore) && (RelPos == I->getPath().get()))
614 insert_spot = I;
615 else if (AddAfter && (RelPos == I->getPath().get())) {
616 insert_spot = I;
617 insert_spot++;
618 }
619 }
620
621 // If we didn't replace all the members, some will remain and need to be
622 // inserted at the previously computed insert-spot.
623 if (!remaining.empty()) {
624 for (sys::Path::Vector::iterator PI = remaining.begin(),
625 PE = remaining.end(); PI != PE; ++PI) {
626 TheArchive->addFileBefore(*PI,insert_spot);
627 }
628 }
629
630 // We're done editting, reconstruct the archive.
631 TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
632}
633
634// main - main program for llvm-ar .. see comments in the code
Tanya Lattner14baebf2003-08-28 15:22:38 +0000635int main(int argc, char **argv) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000636
637 // Ensure we initialize the global MoreHelp to tell the command line utility
638 // that we have a MoreHelp function. This function is called to print more
639 // help if the --help option is given on the command line
640 cl::MoreHelp = printMoreHelp;
641
642 // Have the command line options parsed and handle things
643 // like --help and --version.
644 cl::ParseCommandLineOptions(argc, argv,
645 " LLVM Archiver (llvm-ar)\n\n"
646 " This program archives bytecode files into single libraries\n"
647 );
648
649 // Print a stack trace if we signal out.
Reid Spencer9de7b332004-08-29 19:28:55 +0000650 sys::PrintStackTraceOnErrorSignal();
Chris Lattnerf73b4ca2004-02-19 20:32:12 +0000651
Reid Spencer3a1582b2004-11-14 22:20:07 +0000652 int exitCode = 0;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000653
Reid Spencer3a1582b2004-11-14 22:20:07 +0000654 // Make sure we don't exit with "unhandled exception".
655 try {
656 // Do our own parsing of the command line because the CommandLine utility
657 // can't handle the grouped positional parameters without a dash.
658 ArchiveOperation Operation = parseCommandLine();
Tanya Lattner14baebf2003-08-28 15:22:38 +0000659
Reid Spencer3a1582b2004-11-14 22:20:07 +0000660 // Check the path name of the archive
661 sys::Path ArchivePath;
662 if (!ArchivePath.setFile(ArchiveName))
663 throw std::string("Archive name invalid: ") + ArchiveName;
664
665 // Create or open the archive object.
666 if (!ArchivePath.exists()) {
667 // Produce a warning if we should and we're creating the archive
668 if (!Create)
669 std::cerr << argv[0] << ": creating " << ArchivePath.get() << "\n";
670 TheArchive = Archive::CreateEmpty(ArchivePath);
671 } else {
672 TheArchive = Archive::OpenAndLoad(ArchivePath);
673 }
674
675 // Make sure we're not fooling ourselves.
676 assert(TheArchive && "Unable to instantiate the archive");
677
678 // Perform the operation
679 switch (Operation) {
680 case Print: doPrint(); break;
681 case Delete: doDelete(); break;
682 case Move: doMove(); break;
683 case QuickAppend: /* FALL THROUGH */
684 case ReplaceOrInsert: doReplaceOrInsert(); break;
685 case DisplayTable: doDisplayTable(); break;
686 case Extract: doExtract(); break;
687 case NoOperation:
688 std::cerr << argv[0] << ": No operation was selected.\n";
689 break;
690 }
691
692 // Close up shop
693 delete TheArchive;
694
695 } catch (const char*msg) {
696 // These errors are usage errors, thrown only by the various checks in the
697 // code above.
698 std::cerr << argv[0] << ": " << msg << "\n\n";
699 printUse();
700 exitCode = 1;
701 } catch (const std::string& msg) {
702 // These errors are thrown by LLVM libraries (e.g. lib System) and represent
703 // a more serious error so we bump the exitCode and don't print the usage.
704 std::cerr << argv[0] << ": " << msg << "\n";
705 exitCode = 2;
706 } catch (...) {
707 // This really shouldn't happen, but just in case ....
708 std::cerr << argv[0] << ": An nexpected unknown exception occurred.\n";
709 exitCode = 3;
710 }
711
712 // Return result code back to operating system.
713 return exitCode;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000714}