blob: 40e4a3a493c44b5794813fe62d4fc787cf26c3ea [file] [log] [blame]
Chris Lattnerce8781c2003-12-30 07:45:46 +00001//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Tanya Lattner57c70a62003-08-28 15:22:38 +00009//
Misha Brukman650ba8e2005-04-22 00:00:37 +000010// Builds up (relatively) standard unix archive files (.a) containing LLVM
Gabor Greife16561c2007-07-05 17:07:56 +000011// bitcode or other files.
Tanya Lattner57c70a62003-08-28 15:22:38 +000012//
13//===----------------------------------------------------------------------===//
Brian Gaeke81d153e2003-10-10 18:47:08 +000014
Rafael Espindolab2757972014-10-10 18:33:51 +000015#include "llvm/ADT/StringSwitch.h"
Rafael Espindola2535ea02015-07-09 20:12:50 +000016#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Module.h"
Peter Collingbournebc051632015-06-09 21:50:22 +000019#include "llvm/LibDriver/LibDriver.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000020#include "llvm/Object/Archive.h"
Peter Collingbournefd66a482015-06-08 02:32:01 +000021#include "llvm/Object/ArchiveWriter.h"
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +000022#include "llvm/Object/MachO.h"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000023#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000024#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000025#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000026#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000027#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000028#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000029#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000030#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000031#include "llvm/Support/Path.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000032#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000033#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000034#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000035#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000037#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000038#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000040
41#if !defined(_MSC_VER) && !defined(__MINGW32__)
42#include <unistd.h>
43#else
44#include <io.h>
45#endif
46
Brian Gaeke960707c2003-11-11 22:41:34 +000047using namespace llvm;
48
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000049// The name this program was invoked as.
50static StringRef ToolName;
51
Rafael Espindola90b85702014-10-21 15:49:46 +000052// Show the error message and exit.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000053LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
54 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000055 exit(1);
56}
57
Rafael Espindola4453e42942014-06-13 03:07:50 +000058static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000059 if (!EC)
60 return;
61
62 std::string ContextStr = Context.str();
63 if (ContextStr == "")
64 fail(EC.message());
65 fail(Context + ": " + EC.message());
66}
67
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000068static void failIfError(Error E, Twine Context = "") {
69 if (!E)
70 return;
71
72 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
73 std::string ContextStr = Context.str();
74 if (ContextStr == "")
75 fail(EIB.message());
76 fail(Context + ": " + EIB.message());
77 });
78}
79
Rafael Espindola0c8a3522013-08-28 16:22:16 +000080// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000081static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000082 RestOfArgs(cl::Positional, cl::ZeroOrMore,
83 cl::desc("[relpos] [count] <archive-file> [members]..."));
84
85static cl::opt<bool> MRI("M", cl::desc(""));
Davide Italiano9ffb5542016-06-27 20:38:39 +000086static cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
Tanya Lattner57c70a62003-08-28 15:22:38 +000087
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000088namespace {
89enum Format { Default, GNU, BSD };
90}
91
92static cl::opt<Format>
93 FormatOpt("format", cl::desc("Archive format to create"),
Saleem Abdulrasool983e6f92016-06-21 17:19:28 +000094 cl::values(clEnumValN(Default, "default", "default"),
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000095 clEnumValN(GNU, "gnu", "gnu"),
96 clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
97
Rafael Espindola2f5e8872015-11-01 00:14:59 +000098static std::string Options;
Rafael Espindola0c8a3522013-08-28 16:22:16 +000099
Rafael Espindola90b85702014-10-21 15:49:46 +0000100// Provide additional help output explaining the operations and modifiers of
101// llvm-ar. This object instructs the CommandLine library to print the text of
102// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +0000103static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +0000104 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000105 " d[NsS] - delete file(s) from the archive\n"
106 " m[abiSs] - move file(s) in the archive\n"
107 " p[kN] - print file(s) found in the archive\n"
108 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +0000109 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000110 " t - display contents of archive\n"
111 " x[No] - extract file(s) from the archive\n"
112 "\nMODIFIERS (operation specific):\n"
113 " [a] - put file(s) after [relpos]\n"
114 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000115 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000116 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000117 " [s] - create an archive index (cf. ranlib)\n"
118 " [S] - do not build a symbol table\n"
Teresa Johnsonb8f95b52016-07-22 19:41:00 +0000119 " [T] - create a thin archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000120 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000121 "\nMODIFIERS (generic):\n"
122 " [c] - do not warn if the library had to be created\n"
123 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000124);
125
Reid Spencer84a12bf2004-11-14 22:20:07 +0000126// This enumeration delineates the kinds of operations on an archive
127// that are permitted.
128enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000129 Print, ///< Print the contents of the archive
130 Delete, ///< Delete the specified members
131 Move, ///< Move members to end or as given by {a,b,i} modifiers
132 QuickAppend, ///< Quickly append to end of archive
133 ReplaceOrInsert, ///< Replace or Insert members
134 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000135 Extract, ///< Extract files back to file system
136 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000137};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000138
Reid Spencer84a12bf2004-11-14 22:20:07 +0000139// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000140static bool AddAfter = false; ///< 'a' modifier
141static bool AddBefore = false; ///< 'b' modifier
142static bool Create = false; ///< 'c' modifier
143static bool OriginalDates = false; ///< 'o' modifier
144static bool OnlyUpdate = false; ///< 'u' modifier
145static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000146static bool Symtab = true; ///< 's' modifier
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000147static bool Deterministic = true; ///< 'D' and 'U' modifiers
Rafael Espindolae6492582015-07-15 05:47:46 +0000148static bool Thin = false; ///< 'T' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000149
Reid Spencer84a12bf2004-11-14 22:20:07 +0000150// Relative Positional Argument (for insert/move). This variable holds
151// the name of the archive member to which the 'a', 'b' or 'i' modifier
152// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
153// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000154static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000155
Reid Spencer84a12bf2004-11-14 22:20:07 +0000156// This variable holds the name of the archive file as given on the
157// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000158static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000159
Reid Spencer84a12bf2004-11-14 22:20:07 +0000160// This variable holds the list of member files to proecess, as given
161// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000162static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000163
Rafael Espindola90b85702014-10-21 15:49:46 +0000164// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000165LLVM_ATTRIBUTE_NORETURN static void
166show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000167 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000168 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000169 std::exit(1);
170}
171
Rafael Espindola90b85702014-10-21 15:49:46 +0000172// Extract the member filename from the command line for the [relpos] argument
173// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000174static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000175 if(RestOfArgs.size() == 0)
176 show_help("Expected [relpos] for a, b, or i modifier");
177 RelPos = RestOfArgs[0];
178 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000179}
180
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000181static void getOptions() {
182 if(RestOfArgs.size() == 0)
183 show_help("Expected options");
184 Options = RestOfArgs[0];
185 RestOfArgs.erase(RestOfArgs.begin());
186}
187
Rafael Espindola90b85702014-10-21 15:49:46 +0000188// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000189static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000190 if(RestOfArgs.size() == 0)
191 show_help("An archive name must be specified");
192 ArchiveName = RestOfArgs[0];
193 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000194}
195
Rafael Espindola90b85702014-10-21 15:49:46 +0000196// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000197static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000198 for (auto &Arg : RestOfArgs)
199 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000200}
201
Rafael Espindola8a463522014-10-21 21:56:47 +0000202static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000203
Rafael Espindola90b85702014-10-21 15:49:46 +0000204// Parse the command line options as presented and return the operation
205// specified. Process all modifiers and check to make sure that constraints on
206// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000207static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000208 if (MRI) {
209 if (!RestOfArgs.empty())
210 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000211 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000212 }
213
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000214 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000215
Reid Spencer84a12bf2004-11-14 22:20:07 +0000216 // Keep track of number of operations. We can only specify one
217 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000218 unsigned NumOperations = 0;
219
Reid Spencer84a12bf2004-11-14 22:20:07 +0000220 // Keep track of the number of positional modifiers (a,b,i). Only
221 // one can be specified.
222 unsigned NumPositional = 0;
223
224 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000225 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000226
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000227 bool MaybeJustCreateSymTab = false;
228
Tanya Lattnerc970a382003-12-06 23:01:25 +0000229 for(unsigned i=0; i<Options.size(); ++i) {
230 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000231 case 'd': ++NumOperations; Operation = Delete; break;
232 case 'm': ++NumOperations; Operation = Move ; break;
233 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000234 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000235 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000236 case 't': ++NumOperations; Operation = DisplayTable; break;
237 case 'x': ++NumOperations; Operation = Extract; break;
238 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000239 case 'l': /* accepted but unused */ break;
240 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000241 case 's':
242 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000243 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000244 break;
245 case 'S':
246 Symtab = false;
247 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000248 case 'u': OnlyUpdate = true; break;
249 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000250 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000251 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000252 AddAfter = true;
253 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000254 break;
255 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000256 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000257 AddBefore = true;
258 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000259 break;
260 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000261 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000262 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000263 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000264 break;
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000265 case 'D':
266 Deterministic = true;
267 break;
268 case 'U':
269 Deterministic = false;
270 break;
Rafael Espindolae6492582015-07-15 05:47:46 +0000271 case 'T':
272 Thin = true;
273 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000274 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000275 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000276 }
277 }
278
Misha Brukman650ba8e2005-04-22 00:00:37 +0000279 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000280 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000281 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000282
283 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000284 getMembers();
285
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000286 if (NumOperations == 0 && MaybeJustCreateSymTab) {
287 NumOperations = 1;
288 Operation = CreateSymTab;
289 if (!Members.empty())
290 show_help("The s operation takes only an archive as argument");
291 }
292
Reid Spencer84a12bf2004-11-14 22:20:07 +0000293 // Perform various checks on the operation/modifier specification
294 // to make sure we are dealing with a legal request.
295 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000296 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000297 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000298 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000299 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000300 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000301 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000302 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000303 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
304 "the 'm' or 'r' operations");
305 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000306 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000307 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000308 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000309 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000310
311 // Return the parsed operation to the caller
312 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000313}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000314
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000315// Implements the 'p' operation. This function traverses the archive
316// looking for members that match the path list.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000317static void doPrint(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000318 if (Verbose)
319 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000320
Kevin Enderby27e85bd2016-08-03 21:57:47 +0000321 Expected<StringRef> DataOrErr = C.getBuffer();
322 failIfError(DataOrErr.takeError());
Rafael Espindola4b83cb52015-07-14 22:18:43 +0000323 StringRef Data = *DataOrErr;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000324 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000325}
326
Rafael Espindola90b85702014-10-21 15:49:46 +0000327// Utility function for printing out the file mode when the 't' operation is in
328// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000329static void printMode(unsigned mode) {
Davide Italianoc529c7f2015-11-14 18:25:18 +0000330 outs() << ((mode & 004) ? "r" : "-");
331 outs() << ((mode & 002) ? "w" : "-");
332 outs() << ((mode & 001) ? "x" : "-");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000333}
334
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000335// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000336// the file names of each of the members. However, if verbose mode is requested
337// ('v' modifier) then the file type, permission mode, user, group, size, and
338// modification time are also printed.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000339static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000340 if (Verbose) {
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000341 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
342 failIfError(ModeOrErr.takeError());
343 sys::fs::perms Mode = ModeOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000344 printMode((Mode >> 6) & 007);
345 printMode((Mode >> 3) & 007);
346 printMode(Mode & 007);
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000347 Expected<unsigned> UIDOrErr = C.getUID();
348 failIfError(UIDOrErr.takeError());
349 outs() << ' ' << UIDOrErr.get();
350 Expected<unsigned> GIDOrErr = C.getGID();
351 failIfError(GIDOrErr.takeError());
352 outs() << '/' << GIDOrErr.get();
Kevin Enderby6524bd82016-07-19 20:47:07 +0000353 Expected<uint64_t> Size = C.getSize();
354 failIfError(Size.takeError());
Kevin Enderby7a969422015-11-05 19:24:56 +0000355 outs() << ' ' << format("%6llu", Size.get());
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000356 Expected<sys::TimeValue> ModTimeOrErr = C.getLastModified();
357 failIfError(ModTimeOrErr.takeError());
358 outs() << ' ' << ModTimeOrErr.get().str();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000359 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000360 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000361 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000362}
363
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000364// Implement the 'x' operation. This function extracts files back to the file
365// system.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000366static void doExtract(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000367 // Retain the original mode.
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000368 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
369 failIfError(ModeOrErr.takeError());
370 sys::fs::perms Mode = ModeOrErr.get();
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000371
Rafael Espindola6d354812013-07-16 19:44:17 +0000372 int FD;
Rafael Espindola9268a5d2016-05-02 22:53:32 +0000373 failIfError(sys::fs::openFileForWrite(Name, FD, sys::fs::F_None, Mode), Name);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000374
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000375 {
376 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000377
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000378 // Get the data and its length
Kevin Enderby27e85bd2016-08-03 21:57:47 +0000379 Expected<StringRef> BufOrErr = C.getBuffer();
380 failIfError(BufOrErr.takeError());
381 StringRef Data = BufOrErr.get();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000382
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000383 // Write the data.
384 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000385 }
386
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000387 // If we're supposed to retain the original modification times, etc. do so
388 // now.
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000389 if (OriginalDates) {
390 Expected<sys::TimeValue> ModTimeOrErr = C.getLastModified();
391 failIfError(ModTimeOrErr.takeError());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000392 failIfError(
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000393 sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
394 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000395
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000396 if (close(FD))
397 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000398}
399
Rafael Espindola05571532013-07-12 16:29:27 +0000400static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000401 switch (Op) {
402 case Print:
403 case Delete:
404 case Move:
405 case DisplayTable:
406 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000407 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000408 return false;
409
410 case QuickAppend:
411 case ReplaceOrInsert:
412 return true;
413 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000414
415 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000416}
417
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000418static void performReadOperation(ArchiveOperation Operation,
419 object::Archive *OldArchive) {
Davide Italiano7bfbb592015-11-14 18:33:47 +0000420 if (Operation == Extract && OldArchive->isThin())
421 fail("extracting from a thin archive is not supported");
Rafael Espindolae549b8c2015-07-14 16:55:13 +0000422
Rafael Espindolac3eec452015-07-14 16:02:40 +0000423 bool Filter = !Members.empty();
Lang Hamesfc209622016-07-14 02:24:01 +0000424 {
425 Error Err;
426 for (auto &C : OldArchive->children(Err)) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000427 Expected<StringRef> NameOrErr = C.getName();
428 failIfError(NameOrErr.takeError());
Lang Hamesfc209622016-07-14 02:24:01 +0000429 StringRef Name = NameOrErr.get();
Kevin Enderby7a969422015-11-05 19:24:56 +0000430
Lang Hamesfc209622016-07-14 02:24:01 +0000431 if (Filter) {
David Majnemer0d955d02016-08-11 22:21:41 +0000432 auto I = find(Members, Name);
Lang Hamesfc209622016-07-14 02:24:01 +0000433 if (I == Members.end())
434 continue;
435 Members.erase(I);
436 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000437
Lang Hamesfc209622016-07-14 02:24:01 +0000438 switch (Operation) {
439 default:
440 llvm_unreachable("Not a read operation");
441 case Print:
442 doPrint(Name, C);
443 break;
444 case DisplayTable:
445 doDisplayTable(Name, C);
446 break;
447 case Extract:
448 doExtract(Name, C);
449 break;
450 }
Rafael Espindolac3eec452015-07-14 16:02:40 +0000451 }
Lang Hamesfc209622016-07-14 02:24:01 +0000452 failIfError(std::move(Err));
Lang Hamesae610ab2016-07-14 00:37:04 +0000453 }
Lang Hamesfc209622016-07-14 02:24:01 +0000454
Rafael Espindolac3eec452015-07-14 16:02:40 +0000455 if (Members.empty())
456 return;
457 for (StringRef Name : Members)
458 errs() << Name << " was not found\n";
459 std::exit(1);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000460}
461
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000462static void addMember(std::vector<NewArchiveMember> &Members,
Rafael Espindola2f5e8872015-11-01 00:14:59 +0000463 StringRef FileName, int Pos = -1) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000464 Expected<NewArchiveMember> NMOrErr =
465 NewArchiveMember::getFile(FileName, Deterministic);
466 failIfError(NMOrErr.takeError(), FileName);
Rafael Espindola449208d2015-07-15 20:45:56 +0000467 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000468 Members.push_back(std::move(*NMOrErr));
Rafael Espindola449208d2015-07-15 20:45:56 +0000469 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000470 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola449208d2015-07-15 20:45:56 +0000471}
472
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000473static void addMember(std::vector<NewArchiveMember> &Members,
474 const object::Archive::Child &M, int Pos = -1) {
Rafael Espindolae0d30802015-11-01 00:10:37 +0000475 if (Thin && !M.getParent()->isThin())
Rafael Espindola449208d2015-07-15 20:45:56 +0000476 fail("Cannot convert a regular archive to a thin one");
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000477 Expected<NewArchiveMember> NMOrErr =
478 NewArchiveMember::getOldMember(M, Deterministic);
479 failIfError(NMOrErr.takeError());
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000480 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000481 Members.push_back(std::move(*NMOrErr));
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000482 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000483 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000484}
485
Rafael Espindola623c3d82013-07-22 15:11:51 +0000486enum InsertAction {
487 IA_AddOldMember,
488 IA_AddNewMeber,
489 IA_Delete,
490 IA_MoveOldMember,
491 IA_MoveNewMember
492};
493
Rafael Espindola76619702014-10-21 21:47:27 +0000494static InsertAction computeInsertAction(ArchiveOperation Operation,
Rafael Espindola54d263c2015-11-02 13:30:46 +0000495 const object::Archive::Child &Member,
Rafael Espindola76619702014-10-21 21:47:27 +0000496 StringRef Name,
497 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000498 if (Operation == QuickAppend || Members.empty())
499 return IA_AddOldMember;
500
David Majnemer562e8292016-08-12 00:18:03 +0000501 auto MI = find_if(Members, [Name](StringRef Path) {
502 return Name == sys::path::filename(Path);
503 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000504
505 if (MI == Members.end())
506 return IA_AddOldMember;
507
508 Pos = MI;
509
510 if (Operation == Delete)
511 return IA_Delete;
512
513 if (Operation == Move)
514 return IA_MoveOldMember;
515
516 if (Operation == ReplaceOrInsert) {
517 StringRef PosName = sys::path::filename(RelPos);
518 if (!OnlyUpdate) {
519 if (PosName.empty())
520 return IA_AddNewMeber;
521 return IA_MoveNewMember;
522 }
523
524 // We could try to optimize this to a fstat, but it is not a common
525 // operation.
526 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000527 failIfError(sys::fs::status(*MI, Status), *MI);
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000528 Expected<sys::TimeValue> ModTimeOrErr = Member.getLastModified();
529 failIfError(ModTimeOrErr.takeError());
530 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000531 if (PosName.empty())
532 return IA_AddOldMember;
533 return IA_MoveOldMember;
534 }
535
536 if (PosName.empty())
537 return IA_AddNewMeber;
538 return IA_MoveNewMember;
539 }
540 llvm_unreachable("No such operation");
541}
542
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000543// We have to walk this twice and computing it is not trivial, so creating an
544// explicit std::vector is actually fairly efficient.
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000545static std::vector<NewArchiveMember>
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000546computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000547 object::Archive *OldArchive) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000548 std::vector<NewArchiveMember> Ret;
549 std::vector<NewArchiveMember> Moved;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000550 int InsertPos = -1;
551 StringRef PosName = sys::path::filename(RelPos);
552 if (OldArchive) {
Lang Hamesfc209622016-07-14 02:24:01 +0000553 Error Err;
554 for (auto &Child : OldArchive->children(Err)) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000555 int Pos = Ret.size();
Kevin Enderbyf4586032016-07-29 17:44:13 +0000556 Expected<StringRef> NameOrErr = Child.getName();
557 failIfError(NameOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000558 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000559 if (Name == PosName) {
560 assert(AddAfter || AddBefore);
561 if (AddBefore)
562 InsertPos = Pos;
563 else
564 InsertPos = Pos + 1;
565 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000566
Rafael Espindola76619702014-10-21 21:47:27 +0000567 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000568 InsertAction Action =
569 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000570 switch (Action) {
571 case IA_AddOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000572 addMember(Ret, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000573 break;
574 case IA_AddNewMeber:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000575 addMember(Ret, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000576 break;
577 case IA_Delete:
578 break;
579 case IA_MoveOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000580 addMember(Moved, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000581 break;
582 case IA_MoveNewMember:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000583 addMember(Moved, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000584 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000585 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000586 if (MemberI != Members.end())
587 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000588 }
Lang Hamesfc209622016-07-14 02:24:01 +0000589 failIfError(std::move(Err));
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000590 }
591
592 if (Operation == Delete)
593 return Ret;
594
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000595 if (!RelPos.empty() && InsertPos == -1)
596 fail("Insertion point not found");
597
Rafael Espindola623c3d82013-07-22 15:11:51 +0000598 if (RelPos.empty())
599 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000600
Rafael Espindola623c3d82013-07-22 15:11:51 +0000601 assert(unsigned(InsertPos) <= Ret.size());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000602 int Pos = InsertPos;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000603 for (auto &M : Moved) {
604 Ret.insert(Ret.begin() + Pos, std::move(M));
605 ++Pos;
606 }
607
608 for (unsigned I = 0; I != Members.size(); ++I)
609 Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
610 Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000611 for (auto &Member : Members) {
Rafael Espindola0a74a602015-07-15 22:46:53 +0000612 addMember(Ret, Member, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000613 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000614 }
615
616 return Ret;
617}
618
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000619static object::Archive::Kind getDefaultForHost() {
620 return Triple(sys::getProcessTriple()).isOSDarwin() ? object::Archive::K_BSD
621 : object::Archive::K_GNU;
622}
623
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000624static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
625 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
626 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000627
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000628 if (OptionalObject)
629 return isa<object::MachOObjectFile>(**OptionalObject)
630 ? object::Archive::K_BSD
631 : object::Archive::K_GNU;
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000632
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000633 // squelch the error in case we had a non-object file
634 consumeError(OptionalObject.takeError());
635 return getDefaultForHost();
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000636}
637
Rafael Espindola8a463522014-10-21 21:56:47 +0000638static void
Rafael Espindola484983f2016-05-09 13:31:11 +0000639performWriteOperation(ArchiveOperation Operation,
640 object::Archive *OldArchive,
641 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000642 std::vector<NewArchiveMember> *NewMembersP) {
643 std::vector<NewArchiveMember> NewMembers;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000644 if (!NewMembersP)
645 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
646
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000647 object::Archive::Kind Kind;
648 switch (FormatOpt) {
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000649 case Default:
650 if (Thin)
Rafael Espindola2535ea02015-07-09 20:12:50 +0000651 Kind = object::Archive::K_GNU;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000652 else if (OldArchive)
653 Kind = OldArchive->kind();
654 else if (NewMembersP)
655 Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
656 : getDefaultForHost();
657 else
658 Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
659 : getDefaultForHost();
Rafael Espindola2535ea02015-07-09 20:12:50 +0000660 break;
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000661 case GNU:
662 Kind = object::Archive::K_GNU;
663 break;
664 case BSD:
Rafael Espindola21507a42016-05-02 21:06:57 +0000665 if (Thin)
666 fail("Only the gnu format has a thin mode");
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000667 Kind = object::Archive::K_BSD;
668 break;
669 }
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000670
671 std::pair<StringRef, std::error_code> Result =
672 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
673 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
Peter Collingbournefd66a482015-06-08 02:32:01 +0000674 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000675}
676
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000677static void createSymbolTable(object::Archive *OldArchive) {
678 // When an archive is created or modified, if the s option is given, the
679 // resulting archive will have a current symbol table. If the S option
680 // is given, it will have no symbol table.
681 // In summary, we only need to update the symbol table if we have none.
682 // This is actually very common because of broken build systems that think
683 // they have to run ranlib.
684 if (OldArchive->hasSymbolTable())
685 return;
686
Rafael Espindola484983f2016-05-09 13:31:11 +0000687 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000688}
689
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000690static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000691 object::Archive *OldArchive,
Rafael Espindola484983f2016-05-09 13:31:11 +0000692 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000693 std::vector<NewArchiveMember> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000694 switch (Operation) {
695 case Print:
696 case DisplayTable:
697 case Extract:
698 performReadOperation(Operation, OldArchive);
699 return;
700
701 case Delete:
702 case Move:
703 case QuickAppend:
704 case ReplaceOrInsert:
Rafael Espindola484983f2016-05-09 13:31:11 +0000705 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
706 NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000707 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000708 case CreateSymTab:
709 createSymbolTable(OldArchive);
710 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000711 }
712 llvm_unreachable("Unknown operation.");
713}
714
Rafael Espindola8a463522014-10-21 21:56:47 +0000715static int performOperation(ArchiveOperation Operation,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000716 std::vector<NewArchiveMember> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000717 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000718 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
719 MemoryBuffer::getFile(ArchiveName, -1, false);
720 std::error_code EC = Buf.getError();
Davide Italiano43c35622015-11-14 19:00:33 +0000721 if (EC && EC != errc::no_such_file_or_directory)
722 fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000723
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000724 if (!EC) {
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000725 Error Err;
726 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
727 EC = errorToErrorCode(std::move(Err));
Davide Italiano43c35622015-11-14 19:00:33 +0000728 failIfError(EC,
729 "error loading '" + ArchiveName + "': " + EC.message() + "!");
Rafael Espindola484983f2016-05-09 13:31:11 +0000730 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000731 return 0;
732 }
733
Rafael Espindola2a826e42014-06-13 17:20:48 +0000734 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000735
736 if (!shouldCreateArchive(Operation)) {
737 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
738 } else {
739 if (!Create) {
740 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000741 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000742 }
743 }
744
Rafael Espindola484983f2016-05-09 13:31:11 +0000745 performOperation(Operation, nullptr, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000746 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000747}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000748
Rafael Espindola8a463522014-10-21 21:56:47 +0000749static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000750 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000751
752 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
753 failIfError(Buf.getError());
754 const MemoryBuffer &Ref = *Buf.get();
755 bool Saved = false;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000756 std::vector<NewArchiveMember> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000757 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
758 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000759
760 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
761 StringRef Line = *I;
762 StringRef CommandStr, Rest;
763 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000764 Rest = Rest.trim();
765 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
766 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000767 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000768 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000769 .Case("addmod", MRICommand::AddMod)
770 .Case("create", MRICommand::Create)
771 .Case("save", MRICommand::Save)
772 .Case("end", MRICommand::End)
773 .Default(MRICommand::Invalid);
774
775 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000776 case MRICommand::AddLib: {
777 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
778 failIfError(BufOrErr.getError(), "Could not open library");
779 ArchiveBuffers.push_back(std::move(*BufOrErr));
780 auto LibOrErr =
781 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000782 failIfError(errorToErrorCode(LibOrErr.takeError()),
783 "Could not parse library");
Rafael Espindola915fbb32014-10-21 23:18:51 +0000784 Archives.push_back(std::move(*LibOrErr));
785 object::Archive &Lib = *Archives.back();
Lang Hamesfc209622016-07-14 02:24:01 +0000786 {
787 Error Err;
788 for (auto &Member : Lib.children(Err))
789 addMember(NewMembers, Member);
790 failIfError(std::move(Err));
Rafael Espindola915fbb32014-10-21 23:18:51 +0000791 }
792 break;
793 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000794 case MRICommand::AddMod:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000795 addMember(NewMembers, Rest);
Rafael Espindola8a463522014-10-21 21:56:47 +0000796 break;
797 case MRICommand::Create:
798 Create = true;
799 if (!ArchiveName.empty())
800 fail("Editing multiple archives not supported");
801 if (Saved)
802 fail("File already saved");
803 ArchiveName = Rest;
804 break;
805 case MRICommand::Save:
806 Saved = true;
807 break;
808 case MRICommand::End:
809 break;
810 case MRICommand::Invalid:
811 fail("Unknown command: " + CommandStr);
812 }
813 }
814
815 // Nothing to do if not saved.
816 if (Saved)
817 performOperation(ReplaceOrInsert, &NewMembers);
818 exit(0);
819}
820
Rafael Espindola47ee3392014-11-07 21:33:09 +0000821static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000822 // Do our own parsing of the command line because the CommandLine utility
823 // can't handle the grouped positional parameters without a dash.
824 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000825 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000826}
827
Rafael Espindoladbc04162014-10-22 15:05:51 +0000828static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000829 if (RestOfArgs.size() != 1)
Sunil Srivastava3780b682016-04-08 00:02:14 +0000830 fail(ToolName + " takes just one archive as an argument");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000831 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000832 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000833}
834
835int main(int argc, char **argv) {
836 ToolName = argv[0];
837 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000838 sys::PrintStackTraceOnErrorSignal(argv[0]);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000839 PrettyStackTraceProgram X(argc, argv);
840 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
841
Peter Collingbournebc051632015-06-09 21:50:22 +0000842 llvm::InitializeAllTargetInfos();
843 llvm::InitializeAllTargetMCs();
844 llvm::InitializeAllAsmParsers();
845
846 StringRef Stem = sys::path::stem(ToolName);
847 if (Stem.find("ranlib") == StringRef::npos &&
848 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000849 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000850
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000851 // Have the command line options parsed and handle things
852 // like --help and --version.
853 cl::ParseCommandLineOptions(argc, argv,
854 "LLVM Archiver (llvm-ar)\n\n"
855 " This program archives bitcode files into single libraries\n"
856 );
857
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000858 if (Stem.find("ranlib") != StringRef::npos)
859 return ranlib_main();
Ed Schoutenbaff6b42015-10-27 16:37:49 +0000860 if (Stem.find("ar") != StringRef::npos)
861 return ar_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000862 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000863}