blob: 2ec431727a6bf29d821a952d4a49a3408aaf94cd [file] [log] [blame]
Chris Lattner97f752f2003-12-30 07:45:46 +00001//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Tanya Lattnerd6074912004-11-15 19:21:49 +00005// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Tanya Lattner14baebf2003-08-28 15:22:38 +00009//
Misha Brukman3da94ae2005-04-22 00:00:37 +000010// Builds up (relatively) standard unix archive files (.a) containing LLVM
Reid Spencer3a1582b2004-11-14 22:20:07 +000011// bytecode or other files.
Tanya Lattner14baebf2003-08-28 15:22:38 +000012//
13//===----------------------------------------------------------------------===//
Brian Gaeke4fa9fd32003-10-10 18:47:08 +000014
Tanya Lattner14baebf2003-08-28 15:22:38 +000015#include "llvm/Module.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000016#include "llvm/Bytecode/Archive.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000017#include "llvm/Support/CommandLine.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000018#include "llvm/Support/Compressor.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000019#include "llvm/System/Signals.h"
Reid Spencer86f42bd2004-07-04 12:20:55 +000020#include <iostream>
Reid Spencer3a1582b2004-11-14 22:20:07 +000021#include <algorithm>
22#include <iomanip>
Duraid Madina6927b062005-12-28 06:56:09 +000023#include <memory>
Reid Spencer3a1582b2004-11-14 22:20:07 +000024
Brian Gaeked0fde302003-11-11 22:41:34 +000025using namespace llvm;
26
Reid Spencer3a1582b2004-11-14 22:20:07 +000027// Option for compatibility with ASIX, not used but must allow it to be present.
Misha Brukman3da94ae2005-04-22 00:00:37 +000028static cl::opt<bool>
29X32Option ("X32_64", cl::Hidden,
Reid Spencerbede5832004-11-16 06:41:09 +000030 cl::desc("Ignored option for compatibility with AIX"));
Tanya Lattner14baebf2003-08-28 15:22:38 +000031
Reid Spencerbede5832004-11-16 06:41:09 +000032// llvm-ar operation code and modifier flags. This must come first.
Misha Brukman3da94ae2005-04-22 00:00:37 +000033static cl::opt<std::string>
Reid Spencer3a1582b2004-11-14 22:20:07 +000034Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000035
Reid Spencerbede5832004-11-16 06:41:09 +000036// llvm-ar remaining positional arguments.
Misha Brukman3da94ae2005-04-22 00:00:37 +000037static cl::list<std::string>
38RestOfArgs(cl::Positional, cl::OneOrMore,
Reid Spencer3a1582b2004-11-14 22:20:07 +000039 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000040
Reid Spencerbede5832004-11-16 06:41:09 +000041// MoreHelp - Provide additional help output explaining the operations and
42// modifiers of llvm-ar. This object instructs the CommandLine library
43// to print the text of the constructor when the --help option is given.
44static cl::extrahelp MoreHelp(
Misha Brukman3da94ae2005-04-22 00:00:37 +000045 "\nOPERATIONS:\n"
Reid Spencerbede5832004-11-16 06:41:09 +000046 " d[NsS] - delete file(s) from the archive\n"
47 " m[abiSs] - move file(s) in the archive\n"
48 " p[kN] - print file(s) found in the archive\n"
49 " q[ufsS] - quick append file(s) to the archive\n"
50 " r[abfiuzRsS] - replace or insert file(s) into the archive\n"
51 " t - display contents of archive\n"
52 " x[No] - extract file(s) from the archive\n"
53 "\nMODIFIERS (operation specific):\n"
54 " [a] - put file(s) after [relpos]\n"
55 " [b] - put file(s) before [relpos] (same as [i])\n"
56 " [f] - truncate inserted file names\n"
57 " [i] - put file(s) before [relpos] (same as [b])\n"
58 " [k] - always print bytecode files (default is to skip them)\n"
59 " [N] - use instance [count] of name\n"
60 " [o] - preserve original dates\n"
61 " [P] - use full path names when matching\n"
62 " [R] - recurse through directories when inserting\n"
63 " [s] - create an archive index (cf. ranlib)\n"
64 " [S] - do not build a symbol table\n"
65 " [u] - update only files newer than archive contents\n"
66 " [z] - compress files before inserting/extracting\n"
67 "\nMODIFIERS (generic):\n"
68 " [c] - do not warn if the library had to be created\n"
69 " [v] - be verbose about actions taken\n"
70 " [V] - be *really* verbose about actions taken\n"
71);
72
Reid Spencer3a1582b2004-11-14 22:20:07 +000073// This enumeration delineates the kinds of operations on an archive
74// that are permitted.
75enum ArchiveOperation {
76 NoOperation, ///< An operation hasn't been specified
77 Print, ///< Print the contents of the archive
78 Delete, ///< Delete the specified members
79 Move, ///< Move members to end or as given by {a,b,i} modifiers
80 QuickAppend, ///< Quickly append to end of archive
81 ReplaceOrInsert, ///< Replace or Insert members
82 DisplayTable, ///< Display the table of contents
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000083 Extract ///< Extract files back to file system
Tanya Lattner57bd7962003-12-06 23:01:25 +000084};
Tanya Lattner14baebf2003-08-28 15:22:38 +000085
Reid Spencer3a1582b2004-11-14 22:20:07 +000086// Modifiers to follow operation to vary behavior
87bool AddAfter = false; ///< 'a' modifier
88bool AddBefore = false; ///< 'b' modifier
Misha Brukman3da94ae2005-04-22 00:00:37 +000089bool Create = false; ///< 'c' modifier
Reid Spencer3a1582b2004-11-14 22:20:07 +000090bool TruncateNames = false; ///< 'f' modifier
91bool InsertBefore = false; ///< 'i' modifier
92bool DontSkipBytecode = false; ///< 'k' modifier
93bool UseCount = false; ///< 'N' modifier
94bool OriginalDates = false; ///< 'o' modifier
95bool FullPath = false; ///< 'P' modifier
96bool RecurseDirectories = false; ///< 'R' modifier
97bool SymTable = true; ///< 's' & 'S' modifiers
98bool OnlyUpdate = false; ///< 'u' modifier
99bool Verbose = false; ///< 'v' modifier
100bool ReallyVerbose = false; ///< 'V' modifier
101bool Compression = false; ///< 'z' modifier
Tanya Lattner14baebf2003-08-28 15:22:38 +0000102
Reid Spencer3a1582b2004-11-14 22:20:07 +0000103// Relative Positional Argument (for insert/move). This variable holds
104// the name of the archive member to which the 'a', 'b' or 'i' modifier
105// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
106// one variable.
107std::string RelPos;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000108
Reid Spencer3a1582b2004-11-14 22:20:07 +0000109// Select which of multiple entries in the archive with the same name should be
110// used (specified with -N) for the delete and extract operations.
111int Count = 1;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000112
Reid Spencer3a1582b2004-11-14 22:20:07 +0000113// This variable holds the name of the archive file as given on the
114// command line.
115std::string ArchiveName;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000116
Reid Spencer3a1582b2004-11-14 22:20:07 +0000117// This variable holds the list of member files to proecess, as given
118// on the command line.
119std::vector<std::string> Members;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000120
Reid Spencer3a1582b2004-11-14 22:20:07 +0000121// This variable holds the (possibly expanded) list of path objects that
122// correspond to files we will
Reid Spencerbede5832004-11-16 06:41:09 +0000123std::set<sys::Path> Paths;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000124
Reid Spencer3a1582b2004-11-14 22:20:07 +0000125// The Archive object to which all the editing operations will be sent.
126Archive* TheArchive = 0;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000127
Reid Spencer3a1582b2004-11-14 22:20:07 +0000128// getRelPos - Extract the member filename from the command line for
129// the [relpos] argument associated with a, b, and i modifiers
Tanya Lattner57bd7962003-12-06 23:01:25 +0000130void getRelPos() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000131 if(RestOfArgs.size() > 0) {
132 RelPos = RestOfArgs[0];
133 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000134 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000135 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000136 throw "Expected [relpos] for a, b, or i modifier";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000137}
138
Misha Brukman3da94ae2005-04-22 00:00:37 +0000139// getCount - Extract the [count] argument associated with the N modifier
Reid Spencer3a1582b2004-11-14 22:20:07 +0000140// from the command line and check its value.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000141void getCount() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000142 if(RestOfArgs.size() > 0) {
143 Count = atoi(RestOfArgs[0].c_str());
144 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000145 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000146 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000147 throw "Expected [count] value with N modifier";
148
149 // Non-positive counts are not allowed
150 if (Count < 1)
151 throw "Invalid [count] value (not a positive integer)";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000152}
153
Reid Spencer3a1582b2004-11-14 22:20:07 +0000154// getArchive - Get the archive file name from the command line
Tanya Lattner57bd7962003-12-06 23:01:25 +0000155void getArchive() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000156 if(RestOfArgs.size() > 0) {
157 ArchiveName = RestOfArgs[0];
158 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000159 }
Tanya Lattner57bd7962003-12-06 23:01:25 +0000160 else
Reid Spencer3a1582b2004-11-14 22:20:07 +0000161 throw "An archive name must be specified.";
Tanya Lattner57bd7962003-12-06 23:01:25 +0000162}
163
Reid Spencer3a1582b2004-11-14 22:20:07 +0000164// getMembers - Copy over remaining items in RestOfArgs to our Members vector
165// This is just for clarity.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000166void getMembers() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000167 if(RestOfArgs.size() > 0)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000168 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattner57bd7962003-12-06 23:01:25 +0000169}
170
Reid Spencer3a1582b2004-11-14 22:20:07 +0000171// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman3da94ae2005-04-22 00:00:37 +0000172// operation specified. Process all modifiers and check to make sure that
Reid Spencer3a1582b2004-11-14 22:20:07 +0000173// constraints on modifier/operation pairs have not been violated.
174ArchiveOperation parseCommandLine() {
Tanya Lattner57bd7962003-12-06 23:01:25 +0000175
Reid Spencer3a1582b2004-11-14 22:20:07 +0000176 // Keep track of number of operations. We can only specify one
177 // per execution.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000178 unsigned NumOperations = 0;
179
Reid Spencer3a1582b2004-11-14 22:20:07 +0000180 // Keep track of the number of positional modifiers (a,b,i). Only
181 // one can be specified.
182 unsigned NumPositional = 0;
183
184 // Keep track of which operation was requested
185 ArchiveOperation Operation = NoOperation;
186
Tanya Lattner57bd7962003-12-06 23:01:25 +0000187 for(unsigned i=0; i<Options.size(); ++i) {
188 switch(Options[i]) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000189 case 'd': ++NumOperations; Operation = Delete; break;
190 case 'm': ++NumOperations; Operation = Move ; break;
191 case 'p': ++NumOperations; Operation = Print; break;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000192 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000193 case 't': ++NumOperations; Operation = DisplayTable; break;
194 case 'x': ++NumOperations; Operation = Extract; break;
195 case 'c': Create = true; break;
196 case 'f': TruncateNames = true; break;
197 case 'k': DontSkipBytecode = true; break;
198 case 'l': /* accepted but unused */ break;
199 case 'o': OriginalDates = true; break;
200 case 'P': FullPath = true; break;
201 case 'R': RecurseDirectories = true; break;
202 case 's': SymTable = true; break;
203 case 'S': SymTable = false; break;
204 case 'u': OnlyUpdate = true; break;
205 case 'v': Verbose = true; break;
206 case 'V': Verbose = ReallyVerbose = true; break;
207 case 'z': Compression = true; break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000208 case 'a':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000209 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000210 AddAfter = true;
211 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000212 break;
213 case 'b':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000214 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000215 AddBefore = true;
216 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000217 break;
218 case 'i':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000219 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000220 InsertBefore = true;
221 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000222 break;
223 case 'N':
Misha Brukman3da94ae2005-04-22 00:00:37 +0000224 getCount();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000225 UseCount = true;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000226 break;
227 default:
Reid Spencerbede5832004-11-16 06:41:09 +0000228 cl::PrintHelpMessage();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000229 }
230 }
231
Misha Brukman3da94ae2005-04-22 00:00:37 +0000232 // At this point, the next thing on the command line must be
Reid Spencer3a1582b2004-11-14 22:20:07 +0000233 // the archive name.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000234 getArchive();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000235
236 // Everything on the command line at this point is a member.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000237 getMembers();
238
Reid Spencer3a1582b2004-11-14 22:20:07 +0000239 // Perform various checks on the operation/modifier specification
240 // to make sure we are dealing with a legal request.
241 if (NumOperations == 0)
242 throw "You must specify at least one of the operations";
243 if (NumOperations > 1)
244 throw "Only one operation may be specified";
245 if (NumPositional > 1)
246 throw "You may only specify one of a, b, and i modifiers";
247 if (AddAfter || AddBefore || InsertBefore)
248 if (Operation != Move && Operation != ReplaceOrInsert)
249 throw "The 'a', 'b' and 'i' modifiers can only be specified with "
250 "the 'm' or 'r' operations";
251 if (RecurseDirectories && Operation != ReplaceOrInsert)
252 throw "The 'R' modifiers is only applicabe to the 'r' operation";
253 if (OriginalDates && Operation != Extract)
254 throw "The 'o' modifier is only applicable to the 'x' operation";
255 if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
256 throw "The 'f' modifier is only applicable to the 'q' and 'r' operations";
257 if (OnlyUpdate && Operation != ReplaceOrInsert)
258 throw "The 'u' modifier is only applicable to the 'r' operation";
259 if (Compression && Operation!=ReplaceOrInsert && Operation!=Extract)
260 throw "The 'z' modifier is only applicable to the 'r' and 'x' operations";
261 if (Count > 1 && Members.size() > 1)
262 throw "Only one member name may be specified with the 'N' modifier";
263
264 // Return the parsed operation to the caller
265 return Operation;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000266}
Tanya Lattner14baebf2003-08-28 15:22:38 +0000267
Reid Spencer3a1582b2004-11-14 22:20:07 +0000268// recurseDirectories - Implements the "R" modifier. This function scans through
269// the Paths vector (built by buildPaths, below) and replaces any directories it
270// finds with all the files in that directory (recursively). It uses the
271// sys::Path::getDirectoryContent method to perform the actual directory scans.
Reid Spencerbede5832004-11-16 06:41:09 +0000272std::set<sys::Path> recurseDirectories(const sys::Path& path) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000273 assert(path.isDirectory() && "Oops, can't recurse a file");
Reid Spencerbede5832004-11-16 06:41:09 +0000274 std::set<sys::Path> result;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000275 if (RecurseDirectories) {
Reid Spencerbede5832004-11-16 06:41:09 +0000276 std::set<sys::Path> content;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000277 path.getDirectoryContents(content);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000278 for (std::set<sys::Path>::iterator I = content.begin(), E = content.end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000279 I != E; ++I) {
280 if (I->isDirectory()) {
Reid Spencerbede5832004-11-16 06:41:09 +0000281 std::set<sys::Path> moreResults = recurseDirectories(*I);
282 result.insert(moreResults.begin(), moreResults.end());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000283 } else {
Reid Spencerbede5832004-11-16 06:41:09 +0000284 result.insert(*I);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000285 }
286 }
287 }
288 return result;
289}
290
291// buildPaths - Convert the strings in the Members vector to sys::Path objects
Misha Brukman3da94ae2005-04-22 00:00:37 +0000292// and make sure they are valid and exist exist. This check is only needed for
Reid Spencer3a1582b2004-11-14 22:20:07 +0000293// the operations that add/replace files to the archive ('q' and 'r')
294void buildPaths(bool checkExistence = true) {
295 for (unsigned i = 0; i < Members.size(); i++) {
296 sys::Path aPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000297 if (!aPath.set(Members[i]))
Reid Spencer3a1582b2004-11-14 22:20:07 +0000298 throw std::string("File member name invalid: ") + Members[i];
299 if (checkExistence) {
300 if (!aPath.exists())
301 throw std::string("File does not exist: ") + Members[i];
Chris Lattner252ad032006-07-28 22:03:44 +0000302 sys::FileStatus si;
303 std::string Err;
304 if (aPath.getFileStatus(si, &Err))
305 throw Err;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000306 if (si.isDir) {
Reid Spencerbede5832004-11-16 06:41:09 +0000307 std::set<sys::Path> dirpaths = recurseDirectories(aPath);
308 Paths.insert(dirpaths.begin(),dirpaths.end());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000309 } else {
Reid Spencerbede5832004-11-16 06:41:09 +0000310 Paths.insert(aPath);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000311 }
312 } else {
Reid Spencerbede5832004-11-16 06:41:09 +0000313 Paths.insert(aPath);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000314 }
315 }
316}
317
Reid Spencerbede5832004-11-16 06:41:09 +0000318// printSymbolTable - print out the archive's symbol table.
319void printSymbolTable() {
320 std::cout << "\nArchive Symbol Table:\n";
321 const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000322 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
Reid Spencerbede5832004-11-16 06:41:09 +0000323 I != E; ++I ) {
324 unsigned offset = TheArchive->getFirstFileOffset() + I->second;
325 std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
326 }
327}
328
Reid Spencer3a1582b2004-11-14 22:20:07 +0000329// doPrint - Implements the 'p' operation. This function traverses the archive
330// looking for members that match the path list. It is careful to uncompress
331// things that should be and to skip bytecode files unless the 'k' modifier was
332// given.
333void doPrint() {
334 buildPaths(false);
335 unsigned countDown = Count;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000336 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000337 I != E; ++I ) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000338 if (Paths.empty() ||
Reid Spencer3a1582b2004-11-14 22:20:07 +0000339 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
340 if (countDown == 1) {
341 const char* data = reinterpret_cast<const char*>(I->getData());
342
343 // Skip things that don't make sense to print
Misha Brukman3da94ae2005-04-22 00:00:37 +0000344 if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
345 I->isBSD4SymbolTable() || (!DontSkipBytecode &&
Reid Spencer3a1582b2004-11-14 22:20:07 +0000346 (I->isBytecode() || I->isCompressedBytecode())))
347 continue;
348
349 if (Verbose)
Reid Spencer1fce0912004-12-11 00:14:15 +0000350 std::cout << "Printing " << I->getPath().toString() << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000351
352 if (I->isCompressedBytecode())
Reid Spencerb55bc062004-11-14 23:17:41 +0000353 Compressor::decompressToStream(data+4,I->getSize()-4,std::cout);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000354 else if (I->isCompressed()) {
Reid Spencerb55bc062004-11-14 23:17:41 +0000355 Compressor::decompressToStream(data,I->getSize(),std::cout);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000356 } else {
357 unsigned len = I->getSize();
358 std::cout.write(data, len);
359 }
360 } else {
361 countDown--;
362 }
363 }
364 }
365}
366
367// putMode - utility function for printing out the file mode when the 't'
368// operation is in verbose mode.
Reid Spencerbede5832004-11-16 06:41:09 +0000369void printMode(unsigned mode) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000370 if (mode & 004)
Reid Spencer3a1582b2004-11-14 22:20:07 +0000371 std::cout << "r";
372 else
373 std::cout << "-";
374 if (mode & 002)
375 std::cout << "w";
376 else
377 std::cout << "-";
378 if (mode & 001)
379 std::cout << "x";
380 else
381 std::cout << "-";
382}
383
384// doDisplayTable - Implement the 't' operation. This function prints out just
385// the file names of each of the members. However, if verbose mode is requested
386// ('v' modifier) then the file type, permission mode, user, group, size, and
387// modification time are also printed.
388void doDisplayTable() {
389 buildPaths(false);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000390 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000391 I != E; ++I ) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000392 if (Paths.empty() ||
Reid Spencer3a1582b2004-11-14 22:20:07 +0000393 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
394 if (Verbose) {
395 // FIXME: Output should be this format:
396 // Zrw-r--r-- 500/ 500 525 Nov 8 17:42 2004 Makefile
397 if (I->isBytecode())
398 std::cout << "b";
399 else if (I->isCompressedBytecode())
400 std::cout << "B";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000401 else if (I->isCompressed())
402 std::cout << "Z";
403 else
404 std::cout << " ";
405 unsigned mode = I->getMode();
Reid Spencerbede5832004-11-16 06:41:09 +0000406 printMode((mode >> 6) & 007);
407 printMode((mode >> 3) & 007);
408 printMode(mode & 007);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000409 std::cout << " " << std::setw(4) << I->getUser();
410 std::cout << "/" << std::setw(4) << I->getGroup();
411 std::cout << " " << std::setw(8) << I->getSize();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000412 std::cout << " " << std::setw(20) <<
Reid Spencerb55bc062004-11-14 23:17:41 +0000413 I->getModTime().toString().substr(4);
Reid Spencer1fce0912004-12-11 00:14:15 +0000414 std::cout << " " << I->getPath().toString() << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000415 } else {
Reid Spencer1fce0912004-12-11 00:14:15 +0000416 std::cout << I->getPath().toString() << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000417 }
418 }
419 }
Reid Spencerbede5832004-11-16 06:41:09 +0000420 if (ReallyVerbose)
421 printSymbolTable();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000422}
423
424// doExtract - Implement the 'x' operation. This function extracts files back to
425// the file system, making sure to uncompress any that were compressed.
426void doExtract() {
427 buildPaths(false);
428 unsigned countDown = Count;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000429 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000430 I != E; ++I ) {
431 if (Paths.empty() ||
432 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
433
434 // Make sure the intervening directories are created
435 if (I->hasPath()) {
436 sys::Path dirs(I->getPath());
Reid Spencerdd04df02005-07-07 23:21:43 +0000437 dirs.eraseComponent();
Reid Spencera229c5c2005-07-08 03:08:58 +0000438 dirs.createDirectoryOnDisk(/*create_parents=*/true);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000439 }
440
441 // Open up a file stream for writing
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000442 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
443 std::ios::binary;
444 std::ofstream file(I->getPath().c_str(), io_mode);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000445
446 // Get the data and its length
447 const char* data = reinterpret_cast<const char*>(I->getData());
448 unsigned len = I->getSize();
449
450 // Write the data, making sure to uncompress things first
451 if (I->isCompressed()) {
Reid Spencerb55bc062004-11-14 23:17:41 +0000452 Compressor::decompressToStream(data,len,file);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000453 } else {
454 file.write(data,len);
455 }
456 file.close();
457
458 // If we're supposed to retain the original modification times, etc. do so
459 // now.
460 if (OriginalDates)
Chris Lattner252ad032006-07-28 22:03:44 +0000461 I->getPath().setStatusInfoOnDisk(I->getFileStatus());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000462 }
463 }
464}
465
466// doDelete - Implement the delete operation. This function deletes zero or more
467// members from the archive. Note that if the count is specified, there should
468// be no more than one path in the Paths list or else this algorithm breaks.
469// That check is enforced in parseCommandLine (above).
470void doDelete() {
471 buildPaths(false);
472 if (Paths.empty()) return;
473 unsigned countDown = Count;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000474 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000475 I != E; ) {
476 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
477 if (countDown == 1) {
478 Archive::iterator J = I;
479 ++I;
Reid Spencerbede5832004-11-16 06:41:09 +0000480 TheArchive->erase(J);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000481 } else
482 countDown--;
483 } else {
484 ++I;
485 }
486 }
487
488 // We're done editting, reconstruct the archive.
Reid Spencer3039b992006-07-07 19:09:14 +0000489 std::string errmsg;
490 if (!TheArchive->writeToDisk(SymTable,TruncateNames,Compression,&errmsg))
491 throw errmsg;
Reid Spencerbede5832004-11-16 06:41:09 +0000492 if (ReallyVerbose)
493 printSymbolTable();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000494}
495
496// doMore - Implement the move operation. This function re-arranges just the
497// order of the archive members so that when the archive is written the move
498// of the members is accomplished. Note the use of the RelPos variable to
499// determine where the items should be moved to.
500void doMove() {
501
502 buildPaths(false);
503
504 // By default and convention the place to move members to is the end of the
505 // archive.
506 Archive::iterator moveto_spot = TheArchive->end();
507
508 // However, if the relative positioning modifiers were used, we need to scan
509 // the archive to find the member in question. If we don't find it, its no
510 // crime, we just move to the end.
511 if (AddBefore || InsertBefore || AddAfter) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000512 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000513 I != E; ++I ) {
Reid Spencer1fce0912004-12-11 00:14:15 +0000514 if (RelPos == I->getPath().toString()) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000515 if (AddAfter) {
516 moveto_spot = I;
517 moveto_spot++;
518 } else {
519 moveto_spot = I;
520 }
521 break;
522 }
523 }
524 }
525
526 // Keep a list of the paths remaining to be moved
Reid Spencerbede5832004-11-16 06:41:09 +0000527 std::set<sys::Path> remaining(Paths);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000528
529 // Scan the archive again, this time looking for the members to move to the
530 // moveto_spot.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000531 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000532 I != E && !remaining.empty(); ++I ) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000533 std::set<sys::Path>::iterator found =
Reid Spencer3a1582b2004-11-14 22:20:07 +0000534 std::find(remaining.begin(),remaining.end(),I->getPath());
535 if (found != remaining.end()) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000536 if (I != moveto_spot)
Reid Spencerbede5832004-11-16 06:41:09 +0000537 TheArchive->splice(moveto_spot,*TheArchive,I);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000538 remaining.erase(found);
539 }
540 }
541
542 // We're done editting, reconstruct the archive.
Reid Spencer3039b992006-07-07 19:09:14 +0000543 std::string errmsg;
544 if (!TheArchive->writeToDisk(SymTable,TruncateNames,Compression,&errmsg))
545 throw errmsg;
Reid Spencerbede5832004-11-16 06:41:09 +0000546 if (ReallyVerbose)
547 printSymbolTable();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000548}
549
550// doQuickAppend - Implements the 'q' operation. This function just
551// indiscriminantly adds the members to the archive and rebuilds it.
552void doQuickAppend() {
553 // Get the list of paths to append.
554 buildPaths(true);
555 if (Paths.empty()) return;
556
557 // Append them quickly.
Reid Spencerbede5832004-11-16 06:41:09 +0000558 for (std::set<sys::Path>::iterator PI = Paths.begin(), PE = Paths.end();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000559 PI != PE; ++PI) {
560 TheArchive->addFileBefore(*PI,TheArchive->end());
561 }
562
563 // We're done editting, reconstruct the archive.
Reid Spencer3039b992006-07-07 19:09:14 +0000564 std::string errmsg;
565 if (!TheArchive->writeToDisk(SymTable,TruncateNames,Compression,&errmsg))
566 throw errmsg;
Reid Spencerbede5832004-11-16 06:41:09 +0000567 if (ReallyVerbose)
568 printSymbolTable();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000569}
570
571// doReplaceOrInsert - Implements the 'r' operation. This function will replace
Misha Brukman3da94ae2005-04-22 00:00:37 +0000572// any existing files or insert new ones into the archive.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000573void doReplaceOrInsert() {
574
575 // Build the list of files to be added/replaced.
576 buildPaths(true);
577 if (Paths.empty()) return;
578
579 // Keep track of the paths that remain to be inserted.
Reid Spencerbede5832004-11-16 06:41:09 +0000580 std::set<sys::Path> remaining(Paths);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000581
582 // Default the insertion spot to the end of the archive
583 Archive::iterator insert_spot = TheArchive->end();
584
585 // Iterate over the archive contents
586 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
587 I != E && !remaining.empty(); ++I ) {
588
589 // Determine if this archive member matches one of the paths we're trying
590 // to replace.
Reid Spencer0de66b52004-12-02 09:21:55 +0000591
592 std::set<sys::Path>::iterator found = remaining.end();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000593 for (std::set<sys::Path>::iterator RI = remaining.begin(),
Reid Spencer0de66b52004-12-02 09:21:55 +0000594 RE = remaining.end(); RI != RE; ++RI ) {
Reid Spencer1fce0912004-12-11 00:14:15 +0000595 std::string compare(RI->toString());
Reid Spencer0de66b52004-12-02 09:21:55 +0000596 if (TruncateNames && compare.length() > 15) {
597 const char* nm = compare.c_str();
598 unsigned len = compare.length();
599 size_t slashpos = compare.rfind('/');
600 if (slashpos != std::string::npos) {
601 nm += slashpos + 1;
602 len -= slashpos +1;
603 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000604 if (len > 15)
Reid Spencer0de66b52004-12-02 09:21:55 +0000605 len = 15;
606 compare.assign(nm,len);
607 }
Reid Spencer1fce0912004-12-11 00:14:15 +0000608 if (compare == I->getPath().toString()) {
Reid Spencer0de66b52004-12-02 09:21:55 +0000609 found = RI;
610 break;
611 }
612 }
613
Reid Spencer3a1582b2004-11-14 22:20:07 +0000614 if (found != remaining.end()) {
Chris Lattner252ad032006-07-28 22:03:44 +0000615 sys::FileStatus si;
616 std::string Err;
617 if (found->getFileStatus(si, &Err))
618 throw Err;
Reid Spencerbede5832004-11-16 06:41:09 +0000619 if (si.isDir) {
620 if (OnlyUpdate) {
621 // Replace the item only if it is newer.
622 if (si.modTime > I->getModTime())
623 I->replaceWith(*found);
624 } else {
625 // Replace the item regardless of time stamp
Reid Spencer3a1582b2004-11-14 22:20:07 +0000626 I->replaceWith(*found);
Reid Spencerbede5832004-11-16 06:41:09 +0000627 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000628 } else {
Reid Spencerbede5832004-11-16 06:41:09 +0000629 // We purposefully ignore directories.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000630 }
631
632 // Remove it from our "to do" list
633 remaining.erase(found);
634 }
635
636 // Determine if this is the place where we should insert
Reid Spencer1fce0912004-12-11 00:14:15 +0000637 if ((AddBefore || InsertBefore) && (RelPos == I->getPath().toString()))
Reid Spencer3a1582b2004-11-14 22:20:07 +0000638 insert_spot = I;
Reid Spencer1fce0912004-12-11 00:14:15 +0000639 else if (AddAfter && (RelPos == I->getPath().toString())) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000640 insert_spot = I;
641 insert_spot++;
642 }
643 }
644
645 // If we didn't replace all the members, some will remain and need to be
646 // inserted at the previously computed insert-spot.
647 if (!remaining.empty()) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000648 for (std::set<sys::Path>::iterator PI = remaining.begin(),
Reid Spencer3a1582b2004-11-14 22:20:07 +0000649 PE = remaining.end(); PI != PE; ++PI) {
650 TheArchive->addFileBefore(*PI,insert_spot);
651 }
652 }
653
654 // We're done editting, reconstruct the archive.
Reid Spencer3039b992006-07-07 19:09:14 +0000655 std::string errmsg;
656 if (!TheArchive->writeToDisk(SymTable,TruncateNames,Compression,&errmsg))
657 throw errmsg;
Reid Spencerbede5832004-11-16 06:41:09 +0000658 if (ReallyVerbose)
659 printSymbolTable();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000660}
661
662// main - main program for llvm-ar .. see comments in the code
Tanya Lattner14baebf2003-08-28 15:22:38 +0000663int main(int argc, char **argv) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000664
Reid Spencer3a1582b2004-11-14 22:20:07 +0000665 // Have the command line options parsed and handle things
666 // like --help and --version.
667 cl::ParseCommandLineOptions(argc, argv,
668 " LLVM Archiver (llvm-ar)\n\n"
669 " This program archives bytecode files into single libraries\n"
670 );
671
672 // Print a stack trace if we signal out.
Reid Spencer9de7b332004-08-29 19:28:55 +0000673 sys::PrintStackTraceOnErrorSignal();
Chris Lattnerf73b4ca2004-02-19 20:32:12 +0000674
Reid Spencer3a1582b2004-11-14 22:20:07 +0000675 int exitCode = 0;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000676
Reid Spencer3a1582b2004-11-14 22:20:07 +0000677 // Make sure we don't exit with "unhandled exception".
678 try {
679 // Do our own parsing of the command line because the CommandLine utility
680 // can't handle the grouped positional parameters without a dash.
681 ArchiveOperation Operation = parseCommandLine();
Tanya Lattner14baebf2003-08-28 15:22:38 +0000682
Reid Spencer3a1582b2004-11-14 22:20:07 +0000683 // Check the path name of the archive
684 sys::Path ArchivePath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000685 if (!ArchivePath.set(ArchiveName))
Reid Spencer3a1582b2004-11-14 22:20:07 +0000686 throw std::string("Archive name invalid: ") + ArchiveName;
687
688 // Create or open the archive object.
689 if (!ArchivePath.exists()) {
690 // Produce a warning if we should and we're creating the archive
691 if (!Create)
Reid Spencer1fce0912004-12-11 00:14:15 +0000692 std::cerr << argv[0] << ": creating " << ArchivePath.toString() << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000693 TheArchive = Archive::CreateEmpty(ArchivePath);
694 } else {
Chris Lattner67c38212004-12-15 07:44:15 +0000695 std::string Error;
696 TheArchive = Archive::OpenAndLoad(ArchivePath, &Error);
Reid Spencerb4ed7b02004-12-15 21:58:03 +0000697 if (TheArchive == 0) {
Chris Lattner67c38212004-12-15 07:44:15 +0000698 std::cerr << argv[0] << ": error loading '" << ArchivePath << "': "
699 << Error << "!\n";
Reid Spencerb4ed7b02004-12-15 21:58:03 +0000700 return 1;
701 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000702 }
703
704 // Make sure we're not fooling ourselves.
705 assert(TheArchive && "Unable to instantiate the archive");
706
Reid Spencerbede5832004-11-16 06:41:09 +0000707 // Make sure we clean up the archive even on failure.
708 std::auto_ptr<Archive> AutoArchive(TheArchive);
709
Reid Spencer3a1582b2004-11-14 22:20:07 +0000710 // Perform the operation
711 switch (Operation) {
712 case Print: doPrint(); break;
713 case Delete: doDelete(); break;
714 case Move: doMove(); break;
715 case QuickAppend: /* FALL THROUGH */
716 case ReplaceOrInsert: doReplaceOrInsert(); break;
717 case DisplayTable: doDisplayTable(); break;
718 case Extract: doExtract(); break;
719 case NoOperation:
720 std::cerr << argv[0] << ": No operation was selected.\n";
721 break;
722 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000723 } catch (const char*msg) {
724 // These errors are usage errors, thrown only by the various checks in the
725 // code above.
726 std::cerr << argv[0] << ": " << msg << "\n\n";
Reid Spencerbede5832004-11-16 06:41:09 +0000727 cl::PrintHelpMessage();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000728 exitCode = 1;
729 } catch (const std::string& msg) {
730 // These errors are thrown by LLVM libraries (e.g. lib System) and represent
731 // a more serious error so we bump the exitCode and don't print the usage.
732 std::cerr << argv[0] << ": " << msg << "\n";
733 exitCode = 2;
734 } catch (...) {
735 // This really shouldn't happen, but just in case ....
Reid Spencerbede5832004-11-16 06:41:09 +0000736 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000737 exitCode = 3;
738 }
739
740 // Return result code back to operating system.
741 return exitCode;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000742}