blob: d65f9ecc9fe51a8b784bf554f353f37ee433744d [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//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gabor Greifa99be512007-07-05 17:07:56 +000011// bitcode or other files.
Tanya Lattner14baebf2003-08-28 15:22:38 +000012//
13//===----------------------------------------------------------------------===//
Brian Gaeke4fa9fd32003-10-10 18:47:08 +000014
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/LLVMContext.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/Module.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000017#include "llvm/Object/Archive.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000018#include "llvm/Support/CommandLine.h"
Michael J. Spencer54453f22011-01-10 02:34:23 +000019#include "llvm/Support/FileSystem.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000020#include "llvm/Support/Format.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000021#include "llvm/Support/ManagedStatic.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000023#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000024#include "llvm/Support/Signals.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000025#include "llvm/Support/ToolOutputFile.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000026#include "llvm/Support/raw_ostream.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000027#include <algorithm>
Joerg Sonnenberger975bc072012-10-26 10:49:15 +000028#include <cstdlib>
Rafael Espindola11ca2e52013-06-20 20:56:14 +000029#include <fcntl.h>
Chandler Carruthf010c462012-12-04 10:44:52 +000030#include <memory>
Rafael Espindola11ca2e52013-06-20 20:56:14 +000031
32#if !defined(_MSC_VER) && !defined(__MINGW32__)
33#include <unistd.h>
34#else
35#include <io.h>
36#endif
37
Brian Gaeked0fde302003-11-11 22:41:34 +000038using namespace llvm;
39
Rafael Espindola34ac52d2013-07-12 20:21:39 +000040// The name this program was invoked as.
41static StringRef ToolName;
42
43static const char *TemporaryOutput;
Rafael Espindola95779b62013-07-16 16:00:32 +000044static int TmpArchiveFD = -1;
Rafael Espindola34ac52d2013-07-12 20:21:39 +000045
46// fail - Show the error message and exit.
47LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
48 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola95779b62013-07-16 16:00:32 +000049 if (TmpArchiveFD != -1)
50 close(TmpArchiveFD);
Rafael Espindola34ac52d2013-07-12 20:21:39 +000051 if (TemporaryOutput)
52 sys::fs::remove(TemporaryOutput);
53 exit(1);
54}
55
56static void failIfError(error_code EC, Twine Context = "") {
57 if (!EC)
58 return;
59
60 std::string ContextStr = Context.str();
61 if (ContextStr == "")
62 fail(EC.message());
63 fail(Context + ": " + EC.message());
64}
65
Dan Gohman82f209e2007-10-15 21:10:03 +000066// Option for compatibility with AIX, not used but must allow it to be present.
Misha Brukman3da94ae2005-04-22 00:00:37 +000067static cl::opt<bool>
68X32Option ("X32_64", cl::Hidden,
Reid Spencerbede5832004-11-16 06:41:09 +000069 cl::desc("Ignored option for compatibility with AIX"));
Tanya Lattner14baebf2003-08-28 15:22:38 +000070
Reid Spencerbede5832004-11-16 06:41:09 +000071// llvm-ar operation code and modifier flags. This must come first.
Misha Brukman3da94ae2005-04-22 00:00:37 +000072static cl::opt<std::string>
Reid Spencer3a1582b2004-11-14 22:20:07 +000073Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000074
Reid Spencerbede5832004-11-16 06:41:09 +000075// llvm-ar remaining positional arguments.
Misha Brukman3da94ae2005-04-22 00:00:37 +000076static cl::list<std::string>
77RestOfArgs(cl::Positional, cl::OneOrMore,
Reid Spencer3a1582b2004-11-14 22:20:07 +000078 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000079
Reid Spencerbede5832004-11-16 06:41:09 +000080// MoreHelp - Provide additional help output explaining the operations and
81// modifiers of llvm-ar. This object instructs the CommandLine library
82// to print the text of the constructor when the --help option is given.
83static cl::extrahelp MoreHelp(
Misha Brukman3da94ae2005-04-22 00:00:37 +000084 "\nOPERATIONS:\n"
Reid Spencerbede5832004-11-16 06:41:09 +000085 " d[NsS] - delete file(s) from the archive\n"
86 " m[abiSs] - move file(s) in the archive\n"
87 " p[kN] - print file(s) found in the archive\n"
88 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola94bc2462012-08-10 01:57:52 +000089 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencerbede5832004-11-16 06:41:09 +000090 " t - display contents of archive\n"
91 " x[No] - extract file(s) from the archive\n"
92 "\nMODIFIERS (operation specific):\n"
93 " [a] - put file(s) after [relpos]\n"
94 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencerbede5832004-11-16 06:41:09 +000095 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencerbede5832004-11-16 06:41:09 +000096 " [N] - use instance [count] of name\n"
97 " [o] - preserve original dates\n"
Reid Spencerbede5832004-11-16 06:41:09 +000098 " [s] - create an archive index (cf. ranlib)\n"
99 " [S] - do not build a symbol table\n"
100 " [u] - update only files newer than archive contents\n"
Reid Spencerbede5832004-11-16 06:41:09 +0000101 "\nMODIFIERS (generic):\n"
102 " [c] - do not warn if the library had to be created\n"
103 " [v] - be verbose about actions taken\n"
Reid Spencerbede5832004-11-16 06:41:09 +0000104);
105
Reid Spencer3a1582b2004-11-14 22:20:07 +0000106// This enumeration delineates the kinds of operations on an archive
107// that are permitted.
108enum ArchiveOperation {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000109 Print, ///< Print the contents of the archive
110 Delete, ///< Delete the specified members
111 Move, ///< Move members to end or as given by {a,b,i} modifiers
112 QuickAppend, ///< Quickly append to end of archive
113 ReplaceOrInsert, ///< Replace or Insert members
114 DisplayTable, ///< Display the table of contents
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000115 Extract ///< Extract files back to file system
Tanya Lattner57bd7962003-12-06 23:01:25 +0000116};
Tanya Lattner14baebf2003-08-28 15:22:38 +0000117
Reid Spencer3a1582b2004-11-14 22:20:07 +0000118// Modifiers to follow operation to vary behavior
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000119static bool AddAfter = false; ///< 'a' modifier
120static bool AddBefore = false; ///< 'b' modifier
121static bool Create = false; ///< 'c' modifier
122static bool OriginalDates = false; ///< 'o' modifier
123static bool OnlyUpdate = false; ///< 'u' modifier
124static bool Verbose = false; ///< 'v' modifier
Tanya Lattner14baebf2003-08-28 15:22:38 +0000125
Reid Spencer3a1582b2004-11-14 22:20:07 +0000126// Relative Positional Argument (for insert/move). This variable holds
127// the name of the archive member to which the 'a', 'b' or 'i' modifier
128// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
129// one variable.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000130static std::string RelPos;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000131
Reid Spencer3a1582b2004-11-14 22:20:07 +0000132// This variable holds the name of the archive file as given on the
133// command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000134static std::string ArchiveName;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000135
Reid Spencer3a1582b2004-11-14 22:20:07 +0000136// This variable holds the list of member files to proecess, as given
137// on the command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000138static std::vector<std::string> Members;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000139
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000140// show_help - Show the error message, the help message and exit.
141LLVM_ATTRIBUTE_NORETURN static void
142show_help(const std::string &msg) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000143 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000144 cl::PrintHelpMessage();
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000145 std::exit(1);
146}
147
Reid Spencer3a1582b2004-11-14 22:20:07 +0000148// getRelPos - Extract the member filename from the command line for
149// the [relpos] argument associated with a, b, and i modifiers
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000150static void getRelPos() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000151 if(RestOfArgs.size() == 0)
152 show_help("Expected [relpos] for a, b, or i modifier");
153 RelPos = RestOfArgs[0];
154 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000155}
156
Reid Spencer3a1582b2004-11-14 22:20:07 +0000157// getArchive - Get the archive file name from the command line
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000158static void getArchive() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000159 if(RestOfArgs.size() == 0)
160 show_help("An archive name must be specified");
161 ArchiveName = RestOfArgs[0];
162 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000163}
164
Reid Spencer3a1582b2004-11-14 22:20:07 +0000165// getMembers - Copy over remaining items in RestOfArgs to our Members vector
166// This is just for clarity.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000167static void getMembers() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000168 if(RestOfArgs.size() > 0)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000169 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattner57bd7962003-12-06 23:01:25 +0000170}
171
Reid Spencer3a1582b2004-11-14 22:20:07 +0000172// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman3da94ae2005-04-22 00:00:37 +0000173// operation specified. Process all modifiers and check to make sure that
Reid Spencer3a1582b2004-11-14 22:20:07 +0000174// constraints on modifier/operation pairs have not been violated.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000175static ArchiveOperation parseCommandLine() {
Tanya Lattner57bd7962003-12-06 23:01:25 +0000176
Reid Spencer3a1582b2004-11-14 22:20:07 +0000177 // Keep track of number of operations. We can only specify one
178 // per execution.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000179 unsigned NumOperations = 0;
180
Reid Spencer3a1582b2004-11-14 22:20:07 +0000181 // Keep track of the number of positional modifiers (a,b,i). Only
182 // one can be specified.
183 unsigned NumPositional = 0;
184
185 // Keep track of which operation was requested
Rafael Espindola87b8a7f92013-07-05 12:12:43 +0000186 ArchiveOperation Operation;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000187
Tanya Lattner57bd7962003-12-06 23:01:25 +0000188 for(unsigned i=0; i<Options.size(); ++i) {
189 switch(Options[i]) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000190 case 'd': ++NumOperations; Operation = Delete; break;
191 case 'm': ++NumOperations; Operation = Move ; break;
192 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeondc32d192007-12-25 13:53:47 +0000193 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000194 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000195 case 't': ++NumOperations; Operation = DisplayTable; break;
196 case 'x': ++NumOperations; Operation = Extract; break;
197 case 'c': Create = true; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000198 case 'l': /* accepted but unused */ break;
199 case 'o': OriginalDates = true; break;
Rafael Espindola6f2c88a2013-06-20 13:00:30 +0000200 case 's': break; // Ignore for now.
201 case 'S': break; // Ignore for now.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000202 case 'u': OnlyUpdate = true; break;
203 case 'v': Verbose = true; break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000204 case 'a':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000205 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000206 AddAfter = true;
207 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000208 break;
209 case 'b':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000210 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000211 AddBefore = true;
212 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000213 break;
214 case 'i':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000215 getRelPos();
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000216 AddBefore = true;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000217 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000218 break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000219 default:
Reid Spencerbede5832004-11-16 06:41:09 +0000220 cl::PrintHelpMessage();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000221 }
222 }
223
Misha Brukman3da94ae2005-04-22 00:00:37 +0000224 // At this point, the next thing on the command line must be
Reid Spencer3a1582b2004-11-14 22:20:07 +0000225 // the archive name.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000226 getArchive();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000227
228 // Everything on the command line at this point is a member.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000229 getMembers();
230
Reid Spencer3a1582b2004-11-14 22:20:07 +0000231 // Perform various checks on the operation/modifier specification
232 // to make sure we are dealing with a legal request.
233 if (NumOperations == 0)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000234 show_help("You must specify at least one of the operations");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000235 if (NumOperations > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000236 show_help("Only one operation may be specified");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000237 if (NumPositional > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000238 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000239 if (AddAfter || AddBefore) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000240 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000241 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
242 "the 'm' or 'r' operations");
243 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000244 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000245 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000246 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000247 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000248
249 // Return the parsed operation to the caller
250 return Operation;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000251}
Tanya Lattner14baebf2003-08-28 15:22:38 +0000252
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000253// Implements the 'p' operation. This function traverses the archive
254// looking for members that match the path list.
255static void doPrint(StringRef Name, object::Archive::child_iterator I) {
256 if (Verbose)
257 outs() << "Printing " << Name << "\n";
Rafael Espindola8fe960e2013-06-19 14:58:16 +0000258
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000259 StringRef Data = I->getBuffer();
260 outs().write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000261}
262
263// putMode - utility function for printing out the file mode when the 't'
264// operation is in verbose mode.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000265static void printMode(unsigned mode) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000266 if (mode & 004)
Chris Lattner424a04e2010-11-29 23:02:20 +0000267 outs() << "r";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000268 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000269 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000270 if (mode & 002)
Chris Lattner424a04e2010-11-29 23:02:20 +0000271 outs() << "w";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000272 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000273 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000274 if (mode & 001)
Chris Lattner424a04e2010-11-29 23:02:20 +0000275 outs() << "x";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000276 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000277 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000278}
279
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000280// Implement the 't' operation. This function prints out just
Reid Spencer3a1582b2004-11-14 22:20:07 +0000281// the file names of each of the members. However, if verbose mode is requested
282// ('v' modifier) then the file type, permission mode, user, group, size, and
283// modification time are also printed.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000284static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
285 if (Verbose) {
286 sys::fs::perms Mode = I->getAccessMode();
287 printMode((Mode >> 6) & 007);
288 printMode((Mode >> 3) & 007);
289 printMode(Mode & 007);
290 outs() << ' ' << I->getUID();
291 outs() << '/' << I->getGID();
292 outs() << ' ' << format("%6llu", I->getSize());
293 outs() << ' ' << I->getLastModified().str();
294 outs() << ' ';
Reid Spencer3a1582b2004-11-14 22:20:07 +0000295 }
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000296 outs() << Name << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000297}
298
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000299// Implement the 'x' operation. This function extracts files back to the file
300// system.
301static void doExtract(StringRef Name, object::Archive::child_iterator I) {
302 // Open up a file stream for writing
303 // FIXME: we should abstract this, O_BINARY in particular.
304 int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000305#ifdef O_BINARY
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000306 OpenFlags |= O_BINARY;
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000307#endif
Reid Spencer3a1582b2004-11-14 22:20:07 +0000308
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000309 // Retain the original mode.
310 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola35637fc2013-07-08 16:16:51 +0000311
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000312 int FD = open(Name.str().c_str(), OpenFlags, Mode);
313 if (FD < 0)
314 fail("Could not open output file");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000315
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000316 {
317 raw_fd_ostream file(FD, false);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000318
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000319 // Get the data and its length
320 StringRef Data = I->getBuffer();
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000321
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000322 // Write the data.
323 file.write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000324 }
325
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000326 // If we're supposed to retain the original modification times, etc. do so
327 // now.
328 if (OriginalDates)
329 failIfError(
330 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer3a1582b2004-11-14 22:20:07 +0000331
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000332 if (close(FD))
333 fail("Could not close the file");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000334}
335
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000336static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola61de1422013-07-05 13:03:07 +0000337 switch (Op) {
338 case Print:
339 case Delete:
340 case Move:
341 case DisplayTable:
342 case Extract:
343 return false;
344
345 case QuickAppend:
346 case ReplaceOrInsert:
347 return true;
348 }
Michael Gottesman2be430d2013-07-06 02:39:51 +0000349
350 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola61de1422013-07-05 13:03:07 +0000351}
352
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000353static void performReadOperation(ArchiveOperation Operation,
354 object::Archive *OldArchive) {
355 for (object::Archive::child_iterator I = OldArchive->begin_children(),
356 E = OldArchive->end_children();
357 I != E; ++I) {
358 StringRef Name;
359 failIfError(I->getName(Name));
360
361 if (!Members.empty() &&
362 std::find(Members.begin(), Members.end(), Name) == Members.end())
363 continue;
364
365 switch (Operation) {
366 default:
367 llvm_unreachable("Not a read operation");
368 case Print:
369 doPrint(Name, I);
370 break;
371 case DisplayTable:
372 doDisplayTable(Name, I);
373 break;
374 case Extract:
375 doExtract(Name, I);
376 break;
377 }
378 }
379}
380
381namespace {
382class NewArchiveIterator {
383 bool IsNewMember;
384 SmallString<16> MemberName;
Rafael Espindola33ccfb22013-07-12 20:28:02 +0000385 object::Archive::child_iterator OldI;
386 std::vector<std::string>::const_iterator NewI;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000387
388public:
389 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
390 NewArchiveIterator(std::vector<std::string>::const_iterator I, Twine Name);
391 bool isNewMember() const;
392 object::Archive::child_iterator getOld() const;
Rafael Espindola289e2412013-07-16 03:30:10 +0000393 const char *getNew() const;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000394 StringRef getMemberName() const { return MemberName; }
395};
396}
397
398NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
399 Twine Name)
400 : IsNewMember(false), OldI(I) {
401 Name.toVector(MemberName);
402}
403
404NewArchiveIterator::NewArchiveIterator(
405 std::vector<std::string>::const_iterator I, Twine Name)
406 : IsNewMember(true), NewI(I) {
407 Name.toVector(MemberName);
408}
409
410bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
411
412object::Archive::child_iterator NewArchiveIterator::getOld() const {
413 assert(!IsNewMember);
414 return OldI;
415}
416
Rafael Espindola289e2412013-07-16 03:30:10 +0000417const char *NewArchiveIterator::getNew() const {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000418 assert(IsNewMember);
Rafael Espindola289e2412013-07-16 03:30:10 +0000419 return NewI->c_str();
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000420}
421
422template <typename T>
423void addMember(std::vector<NewArchiveIterator> &Members,
424 std::string &StringTable, T I, StringRef Name) {
Rafael Espindolac9516512013-07-13 04:14:13 +0000425 if (Name.size() < 16) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000426 NewArchiveIterator NI(I, Twine(Name) + "/");
427 Members.push_back(NI);
428 } else {
429 int MapIndex = StringTable.size();
430 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
431 Members.push_back(NI);
432 StringTable += Name;
433 StringTable += "/\n";
434 }
435}
436
437namespace {
438class HasName {
439 StringRef Name;
440
441public:
442 HasName(StringRef Name) : Name(Name) {}
443 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
444};
445}
446
447// We have to walk this twice and computing it is not trivial, so creating an
448// explicit std::vector is actually fairly efficient.
449static std::vector<NewArchiveIterator>
450computeNewArchiveMembers(ArchiveOperation Operation,
451 object::Archive *OldArchive,
452 std::string &StringTable) {
453 std::vector<NewArchiveIterator> Ret;
454 std::vector<NewArchiveIterator> Moved;
455 int InsertPos = -1;
456 StringRef PosName = sys::path::filename(RelPos);
457 if (OldArchive) {
458 int Pos = 0;
459 for (object::Archive::child_iterator I = OldArchive->begin_children(),
460 E = OldArchive->end_children();
461 I != E; ++I, ++Pos) {
462 StringRef Name;
463 failIfError(I->getName(Name));
464 if (Name == PosName) {
465 assert(AddAfter || AddBefore);
466 if (AddBefore)
467 InsertPos = Pos;
468 else
469 InsertPos = Pos + 1;
470 }
471 if (Operation != QuickAppend && !Members.empty()) {
472 std::vector<std::string>::iterator MI =
473 std::find_if(Members.begin(), Members.end(), HasName(Name));
474 if (MI != Members.end()) {
475 if (Operation == Move) {
476 addMember(Moved, StringTable, I, Name);
477 continue;
478 }
479 if (Operation != ReplaceOrInsert || !OnlyUpdate)
480 continue;
481 // Ignore if the file if it is older than the member.
482 sys::fs::file_status Status;
483 failIfError(sys::fs::status(*MI, Status));
484 if (Status.getLastModificationTime() < I->getLastModified())
485 Members.erase(MI);
486 else
487 continue;
488 }
489 }
490 addMember(Ret, StringTable, I, Name);
491 }
492 }
493
494 if (Operation == Delete)
495 return Ret;
496
497 if (Operation == Move) {
498 if (RelPos.empty()) {
499 Ret.insert(Ret.end(), Moved.begin(), Moved.end());
500 return Ret;
501 }
502 if (InsertPos == -1)
503 fail("Insertion point not found");
504 assert(unsigned(InsertPos) <= Ret.size());
505 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
506 return Ret;
507 }
508
509 for (std::vector<std::string>::iterator I = Members.begin(),
510 E = Members.end();
511 I != E; ++I) {
512 StringRef Name = sys::path::filename(*I);
513 addMember(Ret, StringTable, I, Name);
514 }
515
516 return Ret;
517}
518
519template <typename T>
520static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
521 uint64_t OldPos = OS.tell();
522 OS << Data;
523 unsigned SizeSoFar = OS.tell() - OldPos;
524 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
525 unsigned Remaining = Size - SizeSoFar;
526 for (unsigned I = 0; I < Remaining; ++I)
527 OS << ' ';
528}
529
530static void performWriteOperation(ArchiveOperation Operation,
531 object::Archive *OldArchive) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000532 SmallString<128> TmpArchive;
533 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
534 TmpArchiveFD, TmpArchive));
535
536 TemporaryOutput = TmpArchive.c_str();
537 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
538 raw_fd_ostream &Out = Output.os();
539 Out << "!<arch>\n";
540
541 std::string StringTable;
542 std::vector<NewArchiveIterator> NewMembers =
543 computeNewArchiveMembers(Operation, OldArchive, StringTable);
544 if (!StringTable.empty()) {
545 if (StringTable.size() % 2)
546 StringTable += '\n';
547 printWithSpacePadding(Out, "//", 48);
548 printWithSpacePadding(Out, StringTable.size(), 10);
549 Out << "`\n";
550 Out << StringTable;
551 }
552
553 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
554 E = NewMembers.end();
555 I != E; ++I) {
556 StringRef Name = I->getMemberName();
557 printWithSpacePadding(Out, Name, 16);
558
559 if (I->isNewMember()) {
Rafael Espindola289e2412013-07-16 03:30:10 +0000560 const char *FileName = I->getNew();
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000561
562 int OpenFlags = O_RDONLY;
563#ifdef O_BINARY
564 OpenFlags |= O_BINARY;
565#endif
566 int FD = ::open(FileName, OpenFlags);
567 if (FD == -1)
568 return failIfError(error_code(errno, posix_category()), FileName);
569
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000570 sys::fs::file_status Status;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000571 failIfError(sys::fs::status(FD, Status), FileName);
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000572
Rafael Espindola718af782013-07-13 05:07:22 +0000573 OwningPtr<MemoryBuffer> File;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000574 failIfError(
575 MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
576 FileName);
Rafael Espindola718af782013-07-13 05:07:22 +0000577
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000578 uint64_t secondsSinceEpoch =
579 Status.getLastModificationTime().toEpochTime();
580 printWithSpacePadding(Out, secondsSinceEpoch, 12);
581
582 printWithSpacePadding(Out, Status.getUser(), 6);
583 printWithSpacePadding(Out, Status.getGroup(), 6);
584 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
585 printWithSpacePadding(Out, Status.getSize(), 10);
586 Out << "`\n";
587
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000588 Out << File->getBuffer();
589 } else {
590 object::Archive::child_iterator OldMember = I->getOld();
591
592 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
593 printWithSpacePadding(Out, secondsSinceEpoch, 12);
594
595 printWithSpacePadding(Out, OldMember->getUID(), 6);
596 printWithSpacePadding(Out, OldMember->getGID(), 6);
597 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
598 printWithSpacePadding(Out, OldMember->getSize(), 10);
599 Out << "`\n";
600
601 Out << OldMember->getBuffer();
602 }
603
604 if (Out.tell() % 2)
605 Out << '\n';
606 }
607 Output.keep();
608 Out.close();
609 sys::fs::rename(TemporaryOutput, ArchiveName);
610 TemporaryOutput = NULL;
611}
612
613static void performOperation(ArchiveOperation Operation,
614 object::Archive *OldArchive) {
615 switch (Operation) {
616 case Print:
617 case DisplayTable:
618 case Extract:
619 performReadOperation(Operation, OldArchive);
620 return;
621
622 case Delete:
623 case Move:
624 case QuickAppend:
625 case ReplaceOrInsert:
626 performWriteOperation(Operation, OldArchive);
627 return;
628 }
629 llvm_unreachable("Unknown operation.");
630}
631
Reid Spencer3a1582b2004-11-14 22:20:07 +0000632// main - main program for llvm-ar .. see comments in the code
Tanya Lattner14baebf2003-08-28 15:22:38 +0000633int main(int argc, char **argv) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000634 ToolName = argv[0];
Chris Lattnercc14d252009-03-06 05:34:10 +0000635 // Print a stack trace if we signal out.
636 sys::PrintStackTraceOnErrorSignal();
637 PrettyStackTraceProgram X(argc, argv);
638 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000639
Reid Spencer3a1582b2004-11-14 22:20:07 +0000640 // Have the command line options parsed and handle things
641 // like --help and --version.
642 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000643 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greifa99be512007-07-05 17:07:56 +0000644 " This program archives bitcode files into single libraries\n"
Reid Spencer3a1582b2004-11-14 22:20:07 +0000645 );
646
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000647 // Do our own parsing of the command line because the CommandLine utility
648 // can't handle the grouped positional parameters without a dash.
649 ArchiveOperation Operation = parseCommandLine();
Tanya Lattner14baebf2003-08-28 15:22:38 +0000650
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000651 // Create or open the archive object.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000652 OwningPtr<MemoryBuffer> Buf;
653 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
654 if (EC && EC != llvm::errc::no_such_file_or_directory) {
655 errs() << argv[0] << ": error opening '" << ArchiveName
656 << "': " << EC.message() << "!\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000657 return 1;
658 }
659
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000660 if (!EC) {
661 object::Archive Archive(Buf.take(), EC);
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000662
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000663 if (EC) {
664 errs() << argv[0] << ": error loading '" << ArchiveName
665 << "': " << EC.message() << "!\n";
666 return 1;
667 }
668 performOperation(Operation, &Archive);
669 return 0;
670 }
671
672 assert(EC == llvm::errc::no_such_file_or_directory);
673
674 if (!shouldCreateArchive(Operation)) {
675 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
676 } else {
677 if (!Create) {
678 // Produce a warning if we should and we're creating the archive
679 errs() << argv[0] << ": creating " << ArchiveName << "\n";
680 }
681 }
682
683 performOperation(Operation, NULL);
684 return 0;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000685}