blob: 32bcb49a1db9a64c86ba939817035e0f847fad1b [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;
44
45// fail - Show the error message and exit.
46LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
47 outs() << ToolName << ": " << Error << ".\n";
48 if (TemporaryOutput)
49 sys::fs::remove(TemporaryOutput);
50 exit(1);
51}
52
53static void failIfError(error_code EC, Twine Context = "") {
54 if (!EC)
55 return;
56
57 std::string ContextStr = Context.str();
58 if (ContextStr == "")
59 fail(EC.message());
60 fail(Context + ": " + EC.message());
61}
62
Dan Gohman82f209e2007-10-15 21:10:03 +000063// Option for compatibility with AIX, not used but must allow it to be present.
Misha Brukman3da94ae2005-04-22 00:00:37 +000064static cl::opt<bool>
65X32Option ("X32_64", cl::Hidden,
Reid Spencerbede5832004-11-16 06:41:09 +000066 cl::desc("Ignored option for compatibility with AIX"));
Tanya Lattner14baebf2003-08-28 15:22:38 +000067
Reid Spencerbede5832004-11-16 06:41:09 +000068// llvm-ar operation code and modifier flags. This must come first.
Misha Brukman3da94ae2005-04-22 00:00:37 +000069static cl::opt<std::string>
Reid Spencer3a1582b2004-11-14 22:20:07 +000070Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000071
Reid Spencerbede5832004-11-16 06:41:09 +000072// llvm-ar remaining positional arguments.
Misha Brukman3da94ae2005-04-22 00:00:37 +000073static cl::list<std::string>
74RestOfArgs(cl::Positional, cl::OneOrMore,
Reid Spencer3a1582b2004-11-14 22:20:07 +000075 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000076
Reid Spencerbede5832004-11-16 06:41:09 +000077// MoreHelp - Provide additional help output explaining the operations and
78// modifiers of llvm-ar. This object instructs the CommandLine library
79// to print the text of the constructor when the --help option is given.
80static cl::extrahelp MoreHelp(
Misha Brukman3da94ae2005-04-22 00:00:37 +000081 "\nOPERATIONS:\n"
Reid Spencerbede5832004-11-16 06:41:09 +000082 " d[NsS] - delete file(s) from the archive\n"
83 " m[abiSs] - move file(s) in the archive\n"
84 " p[kN] - print file(s) found in the archive\n"
85 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola94bc2462012-08-10 01:57:52 +000086 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencerbede5832004-11-16 06:41:09 +000087 " t - display contents of archive\n"
88 " x[No] - extract file(s) from the archive\n"
89 "\nMODIFIERS (operation specific):\n"
90 " [a] - put file(s) after [relpos]\n"
91 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencerbede5832004-11-16 06:41:09 +000092 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencerbede5832004-11-16 06:41:09 +000093 " [N] - use instance [count] of name\n"
94 " [o] - preserve original dates\n"
Reid Spencerbede5832004-11-16 06:41:09 +000095 " [s] - create an archive index (cf. ranlib)\n"
96 " [S] - do not build a symbol table\n"
97 " [u] - update only files newer than archive contents\n"
Reid Spencerbede5832004-11-16 06:41:09 +000098 "\nMODIFIERS (generic):\n"
99 " [c] - do not warn if the library had to be created\n"
100 " [v] - be verbose about actions taken\n"
Reid Spencerbede5832004-11-16 06:41:09 +0000101);
102
Reid Spencer3a1582b2004-11-14 22:20:07 +0000103// This enumeration delineates the kinds of operations on an archive
104// that are permitted.
105enum ArchiveOperation {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000106 Print, ///< Print the contents of the archive
107 Delete, ///< Delete the specified members
108 Move, ///< Move members to end or as given by {a,b,i} modifiers
109 QuickAppend, ///< Quickly append to end of archive
110 ReplaceOrInsert, ///< Replace or Insert members
111 DisplayTable, ///< Display the table of contents
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000112 Extract ///< Extract files back to file system
Tanya Lattner57bd7962003-12-06 23:01:25 +0000113};
Tanya Lattner14baebf2003-08-28 15:22:38 +0000114
Reid Spencer3a1582b2004-11-14 22:20:07 +0000115// Modifiers to follow operation to vary behavior
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000116static bool AddAfter = false; ///< 'a' modifier
117static bool AddBefore = false; ///< 'b' modifier
118static bool Create = false; ///< 'c' modifier
119static bool OriginalDates = false; ///< 'o' modifier
120static bool OnlyUpdate = false; ///< 'u' modifier
121static bool Verbose = false; ///< 'v' modifier
Tanya Lattner14baebf2003-08-28 15:22:38 +0000122
Reid Spencer3a1582b2004-11-14 22:20:07 +0000123// Relative Positional Argument (for insert/move). This variable holds
124// the name of the archive member to which the 'a', 'b' or 'i' modifier
125// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
126// one variable.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000127static std::string RelPos;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000128
Reid Spencer3a1582b2004-11-14 22:20:07 +0000129// This variable holds the name of the archive file as given on the
130// command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000131static std::string ArchiveName;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000132
Reid Spencer3a1582b2004-11-14 22:20:07 +0000133// This variable holds the list of member files to proecess, as given
134// on the command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000135static std::vector<std::string> Members;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000136
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000137// show_help - Show the error message, the help message and exit.
138LLVM_ATTRIBUTE_NORETURN static void
139show_help(const std::string &msg) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000140 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000141 cl::PrintHelpMessage();
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000142 std::exit(1);
143}
144
Reid Spencer3a1582b2004-11-14 22:20:07 +0000145// getRelPos - Extract the member filename from the command line for
146// the [relpos] argument associated with a, b, and i modifiers
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000147static void getRelPos() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000148 if(RestOfArgs.size() == 0)
149 show_help("Expected [relpos] for a, b, or i modifier");
150 RelPos = RestOfArgs[0];
151 RestOfArgs.erase(RestOfArgs.begin());
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
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000155static void getArchive() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000156 if(RestOfArgs.size() == 0)
157 show_help("An archive name must be specified");
158 ArchiveName = RestOfArgs[0];
159 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000160}
161
Reid Spencer3a1582b2004-11-14 22:20:07 +0000162// getMembers - Copy over remaining items in RestOfArgs to our Members vector
163// This is just for clarity.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000164static void getMembers() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000165 if(RestOfArgs.size() > 0)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000166 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattner57bd7962003-12-06 23:01:25 +0000167}
168
Reid Spencer3a1582b2004-11-14 22:20:07 +0000169// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman3da94ae2005-04-22 00:00:37 +0000170// operation specified. Process all modifiers and check to make sure that
Reid Spencer3a1582b2004-11-14 22:20:07 +0000171// constraints on modifier/operation pairs have not been violated.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000172static ArchiveOperation parseCommandLine() {
Tanya Lattner57bd7962003-12-06 23:01:25 +0000173
Reid Spencer3a1582b2004-11-14 22:20:07 +0000174 // Keep track of number of operations. We can only specify one
175 // per execution.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000176 unsigned NumOperations = 0;
177
Reid Spencer3a1582b2004-11-14 22:20:07 +0000178 // Keep track of the number of positional modifiers (a,b,i). Only
179 // one can be specified.
180 unsigned NumPositional = 0;
181
182 // Keep track of which operation was requested
Rafael Espindola87b8a7f92013-07-05 12:12:43 +0000183 ArchiveOperation Operation;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000184
Tanya Lattner57bd7962003-12-06 23:01:25 +0000185 for(unsigned i=0; i<Options.size(); ++i) {
186 switch(Options[i]) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000187 case 'd': ++NumOperations; Operation = Delete; break;
188 case 'm': ++NumOperations; Operation = Move ; break;
189 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeondc32d192007-12-25 13:53:47 +0000190 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000191 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000192 case 't': ++NumOperations; Operation = DisplayTable; break;
193 case 'x': ++NumOperations; Operation = Extract; break;
194 case 'c': Create = true; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000195 case 'l': /* accepted but unused */ break;
196 case 'o': OriginalDates = true; break;
Rafael Espindola6f2c88a2013-06-20 13:00:30 +0000197 case 's': break; // Ignore for now.
198 case 'S': break; // Ignore for now.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000199 case 'u': OnlyUpdate = true; break;
200 case 'v': Verbose = true; break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000201 case 'a':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000202 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000203 AddAfter = true;
204 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000205 break;
206 case 'b':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000207 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000208 AddBefore = true;
209 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000210 break;
211 case 'i':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000212 getRelPos();
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000213 AddBefore = true;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000214 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000215 break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000216 default:
Reid Spencerbede5832004-11-16 06:41:09 +0000217 cl::PrintHelpMessage();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000218 }
219 }
220
Misha Brukman3da94ae2005-04-22 00:00:37 +0000221 // At this point, the next thing on the command line must be
Reid Spencer3a1582b2004-11-14 22:20:07 +0000222 // the archive name.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000223 getArchive();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000224
225 // Everything on the command line at this point is a member.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000226 getMembers();
227
Reid Spencer3a1582b2004-11-14 22:20:07 +0000228 // Perform various checks on the operation/modifier specification
229 // to make sure we are dealing with a legal request.
230 if (NumOperations == 0)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000231 show_help("You must specify at least one of the operations");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000232 if (NumOperations > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000233 show_help("Only one operation may be specified");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000234 if (NumPositional > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000235 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000236 if (AddAfter || AddBefore) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000237 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000238 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
239 "the 'm' or 'r' operations");
240 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000241 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000242 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000243 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000244 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000245
246 // Return the parsed operation to the caller
247 return Operation;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000248}
Tanya Lattner14baebf2003-08-28 15:22:38 +0000249
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000250// Implements the 'p' operation. This function traverses the archive
251// looking for members that match the path list.
252static void doPrint(StringRef Name, object::Archive::child_iterator I) {
253 if (Verbose)
254 outs() << "Printing " << Name << "\n";
Rafael Espindola8fe960e2013-06-19 14:58:16 +0000255
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000256 StringRef Data = I->getBuffer();
257 outs().write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000258}
259
260// putMode - utility function for printing out the file mode when the 't'
261// operation is in verbose mode.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000262static void printMode(unsigned mode) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000263 if (mode & 004)
Chris Lattner424a04e2010-11-29 23:02:20 +0000264 outs() << "r";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000265 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000266 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000267 if (mode & 002)
Chris Lattner424a04e2010-11-29 23:02:20 +0000268 outs() << "w";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000269 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000270 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000271 if (mode & 001)
Chris Lattner424a04e2010-11-29 23:02:20 +0000272 outs() << "x";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000273 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000274 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000275}
276
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000277// Implement the 't' operation. This function prints out just
Reid Spencer3a1582b2004-11-14 22:20:07 +0000278// the file names of each of the members. However, if verbose mode is requested
279// ('v' modifier) then the file type, permission mode, user, group, size, and
280// modification time are also printed.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000281static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
282 if (Verbose) {
283 sys::fs::perms Mode = I->getAccessMode();
284 printMode((Mode >> 6) & 007);
285 printMode((Mode >> 3) & 007);
286 printMode(Mode & 007);
287 outs() << ' ' << I->getUID();
288 outs() << '/' << I->getGID();
289 outs() << ' ' << format("%6llu", I->getSize());
290 outs() << ' ' << I->getLastModified().str();
291 outs() << ' ';
Reid Spencer3a1582b2004-11-14 22:20:07 +0000292 }
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000293 outs() << Name << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000294}
295
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000296// Implement the 'x' operation. This function extracts files back to the file
297// system.
298static void doExtract(StringRef Name, object::Archive::child_iterator I) {
299 // Open up a file stream for writing
300 // FIXME: we should abstract this, O_BINARY in particular.
301 int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000302#ifdef O_BINARY
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000303 OpenFlags |= O_BINARY;
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000304#endif
Reid Spencer3a1582b2004-11-14 22:20:07 +0000305
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000306 // Retain the original mode.
307 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola35637fc2013-07-08 16:16:51 +0000308
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000309 int FD = open(Name.str().c_str(), OpenFlags, Mode);
310 if (FD < 0)
311 fail("Could not open output file");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000312
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000313 {
314 raw_fd_ostream file(FD, false);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000315
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000316 // Get the data and its length
317 StringRef Data = I->getBuffer();
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000318
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000319 // Write the data.
320 file.write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000321 }
322
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000323 // If we're supposed to retain the original modification times, etc. do so
324 // now.
325 if (OriginalDates)
326 failIfError(
327 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer3a1582b2004-11-14 22:20:07 +0000328
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000329 if (close(FD))
330 fail("Could not close the file");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000331}
332
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000333static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola61de1422013-07-05 13:03:07 +0000334 switch (Op) {
335 case Print:
336 case Delete:
337 case Move:
338 case DisplayTable:
339 case Extract:
340 return false;
341
342 case QuickAppend:
343 case ReplaceOrInsert:
344 return true;
345 }
Michael Gottesman2be430d2013-07-06 02:39:51 +0000346
347 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola61de1422013-07-05 13:03:07 +0000348}
349
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000350static void performReadOperation(ArchiveOperation Operation,
351 object::Archive *OldArchive) {
352 for (object::Archive::child_iterator I = OldArchive->begin_children(),
353 E = OldArchive->end_children();
354 I != E; ++I) {
355 StringRef Name;
356 failIfError(I->getName(Name));
357
358 if (!Members.empty() &&
359 std::find(Members.begin(), Members.end(), Name) == Members.end())
360 continue;
361
362 switch (Operation) {
363 default:
364 llvm_unreachable("Not a read operation");
365 case Print:
366 doPrint(Name, I);
367 break;
368 case DisplayTable:
369 doDisplayTable(Name, I);
370 break;
371 case Extract:
372 doExtract(Name, I);
373 break;
374 }
375 }
376}
377
378namespace {
379class NewArchiveIterator {
380 bool IsNewMember;
381 SmallString<16> MemberName;
Rafael Espindola33ccfb22013-07-12 20:28:02 +0000382 object::Archive::child_iterator OldI;
383 std::vector<std::string>::const_iterator NewI;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000384
385public:
386 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
387 NewArchiveIterator(std::vector<std::string>::const_iterator I, Twine Name);
388 bool isNewMember() const;
389 object::Archive::child_iterator getOld() const;
Rafael Espindola289e2412013-07-16 03:30:10 +0000390 const char *getNew() const;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000391 StringRef getMemberName() const { return MemberName; }
392};
393}
394
395NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
396 Twine Name)
397 : IsNewMember(false), OldI(I) {
398 Name.toVector(MemberName);
399}
400
401NewArchiveIterator::NewArchiveIterator(
402 std::vector<std::string>::const_iterator I, Twine Name)
403 : IsNewMember(true), NewI(I) {
404 Name.toVector(MemberName);
405}
406
407bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
408
409object::Archive::child_iterator NewArchiveIterator::getOld() const {
410 assert(!IsNewMember);
411 return OldI;
412}
413
Rafael Espindola289e2412013-07-16 03:30:10 +0000414const char *NewArchiveIterator::getNew() const {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000415 assert(IsNewMember);
Rafael Espindola289e2412013-07-16 03:30:10 +0000416 return NewI->c_str();
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000417}
418
419template <typename T>
420void addMember(std::vector<NewArchiveIterator> &Members,
421 std::string &StringTable, T I, StringRef Name) {
Rafael Espindolac9516512013-07-13 04:14:13 +0000422 if (Name.size() < 16) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000423 NewArchiveIterator NI(I, Twine(Name) + "/");
424 Members.push_back(NI);
425 } else {
426 int MapIndex = StringTable.size();
427 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
428 Members.push_back(NI);
429 StringTable += Name;
430 StringTable += "/\n";
431 }
432}
433
434namespace {
435class HasName {
436 StringRef Name;
437
438public:
439 HasName(StringRef Name) : Name(Name) {}
440 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
441};
442}
443
444// We have to walk this twice and computing it is not trivial, so creating an
445// explicit std::vector is actually fairly efficient.
446static std::vector<NewArchiveIterator>
447computeNewArchiveMembers(ArchiveOperation Operation,
448 object::Archive *OldArchive,
449 std::string &StringTable) {
450 std::vector<NewArchiveIterator> Ret;
451 std::vector<NewArchiveIterator> Moved;
452 int InsertPos = -1;
453 StringRef PosName = sys::path::filename(RelPos);
454 if (OldArchive) {
455 int Pos = 0;
456 for (object::Archive::child_iterator I = OldArchive->begin_children(),
457 E = OldArchive->end_children();
458 I != E; ++I, ++Pos) {
459 StringRef Name;
460 failIfError(I->getName(Name));
461 if (Name == PosName) {
462 assert(AddAfter || AddBefore);
463 if (AddBefore)
464 InsertPos = Pos;
465 else
466 InsertPos = Pos + 1;
467 }
468 if (Operation != QuickAppend && !Members.empty()) {
469 std::vector<std::string>::iterator MI =
470 std::find_if(Members.begin(), Members.end(), HasName(Name));
471 if (MI != Members.end()) {
472 if (Operation == Move) {
473 addMember(Moved, StringTable, I, Name);
474 continue;
475 }
476 if (Operation != ReplaceOrInsert || !OnlyUpdate)
477 continue;
478 // Ignore if the file if it is older than the member.
479 sys::fs::file_status Status;
480 failIfError(sys::fs::status(*MI, Status));
481 if (Status.getLastModificationTime() < I->getLastModified())
482 Members.erase(MI);
483 else
484 continue;
485 }
486 }
487 addMember(Ret, StringTable, I, Name);
488 }
489 }
490
491 if (Operation == Delete)
492 return Ret;
493
494 if (Operation == Move) {
495 if (RelPos.empty()) {
496 Ret.insert(Ret.end(), Moved.begin(), Moved.end());
497 return Ret;
498 }
499 if (InsertPos == -1)
500 fail("Insertion point not found");
501 assert(unsigned(InsertPos) <= Ret.size());
502 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
503 return Ret;
504 }
505
506 for (std::vector<std::string>::iterator I = Members.begin(),
507 E = Members.end();
508 I != E; ++I) {
509 StringRef Name = sys::path::filename(*I);
510 addMember(Ret, StringTable, I, Name);
511 }
512
513 return Ret;
514}
515
516template <typename T>
517static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
518 uint64_t OldPos = OS.tell();
519 OS << Data;
520 unsigned SizeSoFar = OS.tell() - OldPos;
521 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
522 unsigned Remaining = Size - SizeSoFar;
523 for (unsigned I = 0; I < Remaining; ++I)
524 OS << ' ';
525}
526
527static void performWriteOperation(ArchiveOperation Operation,
528 object::Archive *OldArchive) {
529 int TmpArchiveFD;
530 SmallString<128> TmpArchive;
531 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
532 TmpArchiveFD, TmpArchive));
533
534 TemporaryOutput = TmpArchive.c_str();
535 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
536 raw_fd_ostream &Out = Output.os();
537 Out << "!<arch>\n";
538
539 std::string StringTable;
540 std::vector<NewArchiveIterator> NewMembers =
541 computeNewArchiveMembers(Operation, OldArchive, StringTable);
542 if (!StringTable.empty()) {
543 if (StringTable.size() % 2)
544 StringTable += '\n';
545 printWithSpacePadding(Out, "//", 48);
546 printWithSpacePadding(Out, StringTable.size(), 10);
547 Out << "`\n";
548 Out << StringTable;
549 }
550
551 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
552 E = NewMembers.end();
553 I != E; ++I) {
554 StringRef Name = I->getMemberName();
555 printWithSpacePadding(Out, Name, 16);
556
557 if (I->isNewMember()) {
Rafael Espindola289e2412013-07-16 03:30:10 +0000558 const char *FileName = I->getNew();
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000559
560 int OpenFlags = O_RDONLY;
561#ifdef O_BINARY
562 OpenFlags |= O_BINARY;
563#endif
564 int FD = ::open(FileName, OpenFlags);
565 if (FD == -1)
566 return failIfError(error_code(errno, posix_category()), FileName);
567
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000568 sys::fs::file_status Status;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000569 failIfError(sys::fs::status(FD, Status), FileName);
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000570
Rafael Espindola718af782013-07-13 05:07:22 +0000571 OwningPtr<MemoryBuffer> File;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000572 failIfError(
573 MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
574 FileName);
Rafael Espindola718af782013-07-13 05:07:22 +0000575
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000576 uint64_t secondsSinceEpoch =
577 Status.getLastModificationTime().toEpochTime();
578 printWithSpacePadding(Out, secondsSinceEpoch, 12);
579
580 printWithSpacePadding(Out, Status.getUser(), 6);
581 printWithSpacePadding(Out, Status.getGroup(), 6);
582 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
583 printWithSpacePadding(Out, Status.getSize(), 10);
584 Out << "`\n";
585
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000586 Out << File->getBuffer();
587 } else {
588 object::Archive::child_iterator OldMember = I->getOld();
589
590 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
591 printWithSpacePadding(Out, secondsSinceEpoch, 12);
592
593 printWithSpacePadding(Out, OldMember->getUID(), 6);
594 printWithSpacePadding(Out, OldMember->getGID(), 6);
595 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
596 printWithSpacePadding(Out, OldMember->getSize(), 10);
597 Out << "`\n";
598
599 Out << OldMember->getBuffer();
600 }
601
602 if (Out.tell() % 2)
603 Out << '\n';
604 }
605 Output.keep();
606 Out.close();
607 sys::fs::rename(TemporaryOutput, ArchiveName);
608 TemporaryOutput = NULL;
609}
610
611static void performOperation(ArchiveOperation Operation,
612 object::Archive *OldArchive) {
613 switch (Operation) {
614 case Print:
615 case DisplayTable:
616 case Extract:
617 performReadOperation(Operation, OldArchive);
618 return;
619
620 case Delete:
621 case Move:
622 case QuickAppend:
623 case ReplaceOrInsert:
624 performWriteOperation(Operation, OldArchive);
625 return;
626 }
627 llvm_unreachable("Unknown operation.");
628}
629
Reid Spencer3a1582b2004-11-14 22:20:07 +0000630// main - main program for llvm-ar .. see comments in the code
Tanya Lattner14baebf2003-08-28 15:22:38 +0000631int main(int argc, char **argv) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000632 ToolName = argv[0];
Chris Lattnercc14d252009-03-06 05:34:10 +0000633 // Print a stack trace if we signal out.
634 sys::PrintStackTraceOnErrorSignal();
635 PrettyStackTraceProgram X(argc, argv);
636 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000637
Reid Spencer3a1582b2004-11-14 22:20:07 +0000638 // Have the command line options parsed and handle things
639 // like --help and --version.
640 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000641 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greifa99be512007-07-05 17:07:56 +0000642 " This program archives bitcode files into single libraries\n"
Reid Spencer3a1582b2004-11-14 22:20:07 +0000643 );
644
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000645 // Do our own parsing of the command line because the CommandLine utility
646 // can't handle the grouped positional parameters without a dash.
647 ArchiveOperation Operation = parseCommandLine();
Tanya Lattner14baebf2003-08-28 15:22:38 +0000648
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000649 // Create or open the archive object.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000650 OwningPtr<MemoryBuffer> Buf;
651 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
652 if (EC && EC != llvm::errc::no_such_file_or_directory) {
653 errs() << argv[0] << ": error opening '" << ArchiveName
654 << "': " << EC.message() << "!\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000655 return 1;
656 }
657
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000658 if (!EC) {
659 object::Archive Archive(Buf.take(), EC);
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000660
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000661 if (EC) {
662 errs() << argv[0] << ": error loading '" << ArchiveName
663 << "': " << EC.message() << "!\n";
664 return 1;
665 }
666 performOperation(Operation, &Archive);
667 return 0;
668 }
669
670 assert(EC == llvm::errc::no_such_file_or_directory);
671
672 if (!shouldCreateArchive(Operation)) {
673 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
674 } else {
675 if (!Create) {
676 // Produce a warning if we should and we're creating the archive
677 errs() << argv[0] << ": creating " << ArchiveName << "\n";
678 }
679 }
680
681 performOperation(Operation, NULL);
682 return 0;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000683}