blob: 26f8d5be0a2b7c0d1ef64471db86299da623d27e [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"
Pavel Labath757ca882016-10-24 10:59:17 +000024#include "llvm/Support/Chrono.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000025#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000026#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000027#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000028#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000029#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000030#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000031#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000032#include "llvm/Support/Path.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000033#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000034#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000035#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000036#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000038#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000039#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000041
42#if !defined(_MSC_VER) && !defined(__MINGW32__)
43#include <unistd.h>
44#else
45#include <io.h>
46#endif
47
Brian Gaeke960707c2003-11-11 22:41:34 +000048using namespace llvm;
49
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000050// The name this program was invoked as.
51static StringRef ToolName;
52
Rafael Espindola90b85702014-10-21 15:49:46 +000053// Show the error message and exit.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000054LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
55 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000056 exit(1);
57}
58
Rafael Espindola4453e42942014-06-13 03:07:50 +000059static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000060 if (!EC)
61 return;
62
63 std::string ContextStr = Context.str();
64 if (ContextStr == "")
65 fail(EC.message());
66 fail(Context + ": " + EC.message());
67}
68
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000069static void failIfError(Error E, Twine Context = "") {
70 if (!E)
71 return;
72
73 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
74 std::string ContextStr = Context.str();
75 if (ContextStr == "")
76 fail(EIB.message());
77 fail(Context + ": " + EIB.message());
78 });
79}
80
Rafael Espindola0c8a3522013-08-28 16:22:16 +000081// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000082static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000083 RestOfArgs(cl::Positional, cl::ZeroOrMore,
84 cl::desc("[relpos] [count] <archive-file> [members]..."));
85
86static cl::opt<bool> MRI("M", cl::desc(""));
Davide Italiano9ffb5542016-06-27 20:38:39 +000087static cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
Tanya Lattner57c70a62003-08-28 15:22:38 +000088
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000089namespace {
90enum Format { Default, GNU, BSD };
91}
92
93static cl::opt<Format>
94 FormatOpt("format", cl::desc("Archive format to create"),
Saleem Abdulrasool983e6f92016-06-21 17:19:28 +000095 cl::values(clEnumValN(Default, "default", "default"),
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000096 clEnumValN(GNU, "gnu", "gnu"),
Mehdi Amini732afdd2016-10-08 19:41:06 +000097 clEnumValN(BSD, "bsd", "bsd")));
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000098
Rafael Espindola2f5e8872015-11-01 00:14:59 +000099static std::string Options;
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000100
Rafael Espindola90b85702014-10-21 15:49:46 +0000101// Provide additional help output explaining the operations and modifiers of
102// llvm-ar. This object instructs the CommandLine library to print the text of
103// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +0000104static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +0000105 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000106 " d[NsS] - delete file(s) from the archive\n"
107 " m[abiSs] - move file(s) in the archive\n"
108 " p[kN] - print file(s) found in the archive\n"
109 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +0000110 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000111 " t - display contents of archive\n"
112 " x[No] - extract file(s) from the archive\n"
113 "\nMODIFIERS (operation specific):\n"
114 " [a] - put file(s) after [relpos]\n"
115 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000116 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000117 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000118 " [s] - create an archive index (cf. ranlib)\n"
119 " [S] - do not build a symbol table\n"
Teresa Johnsonb8f95b52016-07-22 19:41:00 +0000120 " [T] - create a thin archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000121 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000122 "\nMODIFIERS (generic):\n"
123 " [c] - do not warn if the library had to be created\n"
124 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000125);
126
Reid Spencer84a12bf2004-11-14 22:20:07 +0000127// This enumeration delineates the kinds of operations on an archive
128// that are permitted.
129enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000130 Print, ///< Print the contents of the archive
131 Delete, ///< Delete the specified members
132 Move, ///< Move members to end or as given by {a,b,i} modifiers
133 QuickAppend, ///< Quickly append to end of archive
134 ReplaceOrInsert, ///< Replace or Insert members
135 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000136 Extract, ///< Extract files back to file system
137 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000138};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000139
Reid Spencer84a12bf2004-11-14 22:20:07 +0000140// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000141static bool AddAfter = false; ///< 'a' modifier
142static bool AddBefore = false; ///< 'b' modifier
143static bool Create = false; ///< 'c' modifier
144static bool OriginalDates = false; ///< 'o' modifier
145static bool OnlyUpdate = false; ///< 'u' modifier
146static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000147static bool Symtab = true; ///< 's' modifier
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000148static bool Deterministic = true; ///< 'D' and 'U' modifiers
Rafael Espindolae6492582015-07-15 05:47:46 +0000149static bool Thin = false; ///< 'T' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000150
Reid Spencer84a12bf2004-11-14 22:20:07 +0000151// Relative Positional Argument (for insert/move). This variable holds
152// the name of the archive member to which the 'a', 'b' or 'i' modifier
153// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
154// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000155static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000156
Reid Spencer84a12bf2004-11-14 22:20:07 +0000157// This variable holds the name of the archive file as given on the
158// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000159static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000160
Reid Spencer84a12bf2004-11-14 22:20:07 +0000161// This variable holds the list of member files to proecess, as given
162// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000163static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000164
Rafael Espindola90b85702014-10-21 15:49:46 +0000165// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000166LLVM_ATTRIBUTE_NORETURN static void
167show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000168 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000169 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000170 std::exit(1);
171}
172
Rafael Espindola90b85702014-10-21 15:49:46 +0000173// Extract the member filename from the command line for the [relpos] argument
174// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000175static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000176 if(RestOfArgs.size() == 0)
177 show_help("Expected [relpos] for a, b, or i modifier");
178 RelPos = RestOfArgs[0];
179 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000180}
181
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000182static void getOptions() {
183 if(RestOfArgs.size() == 0)
184 show_help("Expected options");
185 Options = RestOfArgs[0];
186 RestOfArgs.erase(RestOfArgs.begin());
187}
188
Rafael Espindola90b85702014-10-21 15:49:46 +0000189// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000190static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000191 if(RestOfArgs.size() == 0)
192 show_help("An archive name must be specified");
193 ArchiveName = RestOfArgs[0];
194 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000195}
196
Rafael Espindola90b85702014-10-21 15:49:46 +0000197// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000198static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000199 for (auto &Arg : RestOfArgs)
200 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000201}
202
Rafael Espindola8a463522014-10-21 21:56:47 +0000203static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000204
Rafael Espindola90b85702014-10-21 15:49:46 +0000205// Parse the command line options as presented and return the operation
206// specified. Process all modifiers and check to make sure that constraints on
207// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000208static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000209 if (MRI) {
210 if (!RestOfArgs.empty())
211 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000212 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000213 }
214
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000215 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000216
Reid Spencer84a12bf2004-11-14 22:20:07 +0000217 // Keep track of number of operations. We can only specify one
218 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000219 unsigned NumOperations = 0;
220
Reid Spencer84a12bf2004-11-14 22:20:07 +0000221 // Keep track of the number of positional modifiers (a,b,i). Only
222 // one can be specified.
223 unsigned NumPositional = 0;
224
225 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000226 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000227
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000228 bool MaybeJustCreateSymTab = false;
229
Tanya Lattnerc970a382003-12-06 23:01:25 +0000230 for(unsigned i=0; i<Options.size(); ++i) {
231 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000232 case 'd': ++NumOperations; Operation = Delete; break;
233 case 'm': ++NumOperations; Operation = Move ; break;
234 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000235 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000236 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000237 case 't': ++NumOperations; Operation = DisplayTable; break;
238 case 'x': ++NumOperations; Operation = Extract; break;
239 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000240 case 'l': /* accepted but unused */ break;
241 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000242 case 's':
243 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000244 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000245 break;
246 case 'S':
247 Symtab = false;
248 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000249 case 'u': OnlyUpdate = true; break;
250 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000251 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000252 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000253 AddAfter = true;
254 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000255 break;
256 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000257 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000258 AddBefore = true;
259 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000260 break;
261 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000262 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000263 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000264 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000265 break;
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000266 case 'D':
267 Deterministic = true;
268 break;
269 case 'U':
270 Deterministic = false;
271 break;
Rafael Espindolae6492582015-07-15 05:47:46 +0000272 case 'T':
273 Thin = true;
274 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000275 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000276 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000277 }
278 }
279
Misha Brukman650ba8e2005-04-22 00:00:37 +0000280 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000281 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000282 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000283
284 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000285 getMembers();
286
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000287 if (NumOperations == 0 && MaybeJustCreateSymTab) {
288 NumOperations = 1;
289 Operation = CreateSymTab;
290 if (!Members.empty())
291 show_help("The s operation takes only an archive as argument");
292 }
293
Reid Spencer84a12bf2004-11-14 22:20:07 +0000294 // Perform various checks on the operation/modifier specification
295 // to make sure we are dealing with a legal request.
296 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000297 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000298 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000299 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000300 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000301 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000302 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000303 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000304 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
305 "the 'm' or 'r' operations");
306 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000307 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000308 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000309 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000310 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000311
312 // Return the parsed operation to the caller
313 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000314}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000315
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000316// Implements the 'p' operation. This function traverses the archive
317// looking for members that match the path list.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000318static void doPrint(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000319 if (Verbose)
320 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000321
Kevin Enderby27e85bd2016-08-03 21:57:47 +0000322 Expected<StringRef> DataOrErr = C.getBuffer();
323 failIfError(DataOrErr.takeError());
Rafael Espindola4b83cb52015-07-14 22:18:43 +0000324 StringRef Data = *DataOrErr;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000325 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000326}
327
Rafael Espindola90b85702014-10-21 15:49:46 +0000328// Utility function for printing out the file mode when the 't' operation is in
329// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000330static void printMode(unsigned mode) {
Davide Italianoc529c7f2015-11-14 18:25:18 +0000331 outs() << ((mode & 004) ? "r" : "-");
332 outs() << ((mode & 002) ? "w" : "-");
333 outs() << ((mode & 001) ? "x" : "-");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000334}
335
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000336// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000337// the file names of each of the members. However, if verbose mode is requested
338// ('v' modifier) then the file type, permission mode, user, group, size, and
339// modification time are also printed.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000340static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000341 if (Verbose) {
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000342 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
343 failIfError(ModeOrErr.takeError());
344 sys::fs::perms Mode = ModeOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000345 printMode((Mode >> 6) & 007);
346 printMode((Mode >> 3) & 007);
347 printMode(Mode & 007);
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000348 Expected<unsigned> UIDOrErr = C.getUID();
349 failIfError(UIDOrErr.takeError());
350 outs() << ' ' << UIDOrErr.get();
351 Expected<unsigned> GIDOrErr = C.getGID();
352 failIfError(GIDOrErr.takeError());
353 outs() << '/' << GIDOrErr.get();
Kevin Enderby6524bd82016-07-19 20:47:07 +0000354 Expected<uint64_t> Size = C.getSize();
355 failIfError(Size.takeError());
Kevin Enderby7a969422015-11-05 19:24:56 +0000356 outs() << ' ' << format("%6llu", Size.get());
Pavel Labath757ca882016-10-24 10:59:17 +0000357 auto ModTimeOrErr = C.getLastModified();
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000358 failIfError(ModTimeOrErr.takeError());
Pavel Labath757ca882016-10-24 10:59:17 +0000359 outs() << ' ' << ModTimeOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000360 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000361 }
Rafael Espindola7e00c8c2016-12-04 06:52:30 +0000362
363 if (C.getParent()->isThin()) {
364 outs() << sys::path::parent_path(ArchiveName);
365 outs() << sys::path::get_separator();
366 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000367 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000368}
369
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000370// Implement the 'x' operation. This function extracts files back to the file
371// system.
Rafael Espindolae098bd62015-07-14 15:22:42 +0000372static void doExtract(StringRef Name, const object::Archive::Child &C) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000373 // Retain the original mode.
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000374 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
375 failIfError(ModeOrErr.takeError());
376 sys::fs::perms Mode = ModeOrErr.get();
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000377
Rafael Espindola6d354812013-07-16 19:44:17 +0000378 int FD;
Rafael Espindola9268a5d2016-05-02 22:53:32 +0000379 failIfError(sys::fs::openFileForWrite(Name, FD, sys::fs::F_None, Mode), Name);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000380
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000381 {
382 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000383
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000384 // Get the data and its length
Kevin Enderby27e85bd2016-08-03 21:57:47 +0000385 Expected<StringRef> BufOrErr = C.getBuffer();
386 failIfError(BufOrErr.takeError());
387 StringRef Data = BufOrErr.get();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000388
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000389 // Write the data.
390 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000391 }
392
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000393 // If we're supposed to retain the original modification times, etc. do so
394 // now.
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000395 if (OriginalDates) {
Pavel Labath757ca882016-10-24 10:59:17 +0000396 auto ModTimeOrErr = C.getLastModified();
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000397 failIfError(ModTimeOrErr.takeError());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000398 failIfError(
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000399 sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
400 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000401
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000402 if (close(FD))
403 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000404}
405
Rafael Espindola05571532013-07-12 16:29:27 +0000406static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000407 switch (Op) {
408 case Print:
409 case Delete:
410 case Move:
411 case DisplayTable:
412 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000413 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000414 return false;
415
416 case QuickAppend:
417 case ReplaceOrInsert:
418 return true;
419 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000420
421 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000422}
423
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000424static void performReadOperation(ArchiveOperation Operation,
425 object::Archive *OldArchive) {
Davide Italiano7bfbb592015-11-14 18:33:47 +0000426 if (Operation == Extract && OldArchive->isThin())
427 fail("extracting from a thin archive is not supported");
Rafael Espindolae549b8c2015-07-14 16:55:13 +0000428
Rafael Espindolac3eec452015-07-14 16:02:40 +0000429 bool Filter = !Members.empty();
Lang Hamesfc209622016-07-14 02:24:01 +0000430 {
Mehdi Amini41af4302016-11-11 04:28:40 +0000431 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000432 for (auto &C : OldArchive->children(Err)) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000433 Expected<StringRef> NameOrErr = C.getName();
434 failIfError(NameOrErr.takeError());
Lang Hamesfc209622016-07-14 02:24:01 +0000435 StringRef Name = NameOrErr.get();
Kevin Enderby7a969422015-11-05 19:24:56 +0000436
Lang Hamesfc209622016-07-14 02:24:01 +0000437 if (Filter) {
David Majnemer0d955d02016-08-11 22:21:41 +0000438 auto I = find(Members, Name);
Lang Hamesfc209622016-07-14 02:24:01 +0000439 if (I == Members.end())
440 continue;
441 Members.erase(I);
442 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000443
Lang Hamesfc209622016-07-14 02:24:01 +0000444 switch (Operation) {
445 default:
446 llvm_unreachable("Not a read operation");
447 case Print:
448 doPrint(Name, C);
449 break;
450 case DisplayTable:
451 doDisplayTable(Name, C);
452 break;
453 case Extract:
454 doExtract(Name, C);
455 break;
456 }
Rafael Espindolac3eec452015-07-14 16:02:40 +0000457 }
Lang Hamesfc209622016-07-14 02:24:01 +0000458 failIfError(std::move(Err));
Lang Hamesae610ab2016-07-14 00:37:04 +0000459 }
Lang Hamesfc209622016-07-14 02:24:01 +0000460
Rafael Espindolac3eec452015-07-14 16:02:40 +0000461 if (Members.empty())
462 return;
463 for (StringRef Name : Members)
464 errs() << Name << " was not found\n";
465 std::exit(1);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000466}
467
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000468static void addMember(std::vector<NewArchiveMember> &Members,
Rafael Espindola2f5e8872015-11-01 00:14:59 +0000469 StringRef FileName, int Pos = -1) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000470 Expected<NewArchiveMember> NMOrErr =
471 NewArchiveMember::getFile(FileName, Deterministic);
472 failIfError(NMOrErr.takeError(), FileName);
Rafael Espindola449208d2015-07-15 20:45:56 +0000473 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000474 Members.push_back(std::move(*NMOrErr));
Rafael Espindola449208d2015-07-15 20:45:56 +0000475 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000476 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola449208d2015-07-15 20:45:56 +0000477}
478
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000479static void addMember(std::vector<NewArchiveMember> &Members,
480 const object::Archive::Child &M, int Pos = -1) {
Rafael Espindolae0d30802015-11-01 00:10:37 +0000481 if (Thin && !M.getParent()->isThin())
Rafael Espindola449208d2015-07-15 20:45:56 +0000482 fail("Cannot convert a regular archive to a thin one");
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000483 Expected<NewArchiveMember> NMOrErr =
484 NewArchiveMember::getOldMember(M, Deterministic);
485 failIfError(NMOrErr.takeError());
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000486 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000487 Members.push_back(std::move(*NMOrErr));
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000488 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000489 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000490}
491
Rafael Espindola623c3d82013-07-22 15:11:51 +0000492enum InsertAction {
493 IA_AddOldMember,
494 IA_AddNewMeber,
495 IA_Delete,
496 IA_MoveOldMember,
497 IA_MoveNewMember
498};
499
Rafael Espindola76619702014-10-21 21:47:27 +0000500static InsertAction computeInsertAction(ArchiveOperation Operation,
Rafael Espindola54d263c2015-11-02 13:30:46 +0000501 const object::Archive::Child &Member,
Rafael Espindola76619702014-10-21 21:47:27 +0000502 StringRef Name,
503 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000504 if (Operation == QuickAppend || Members.empty())
505 return IA_AddOldMember;
506
David Majnemer562e8292016-08-12 00:18:03 +0000507 auto MI = find_if(Members, [Name](StringRef Path) {
508 return Name == sys::path::filename(Path);
509 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000510
511 if (MI == Members.end())
512 return IA_AddOldMember;
513
514 Pos = MI;
515
516 if (Operation == Delete)
517 return IA_Delete;
518
519 if (Operation == Move)
520 return IA_MoveOldMember;
521
522 if (Operation == ReplaceOrInsert) {
523 StringRef PosName = sys::path::filename(RelPos);
524 if (!OnlyUpdate) {
525 if (PosName.empty())
526 return IA_AddNewMeber;
527 return IA_MoveNewMember;
528 }
529
530 // We could try to optimize this to a fstat, but it is not a common
531 // operation.
532 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000533 failIfError(sys::fs::status(*MI, Status), *MI);
Pavel Labath757ca882016-10-24 10:59:17 +0000534 auto ModTimeOrErr = Member.getLastModified();
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000535 failIfError(ModTimeOrErr.takeError());
Pavel Labathbff47b52016-10-24 13:38:27 +0000536 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000537 if (PosName.empty())
538 return IA_AddOldMember;
539 return IA_MoveOldMember;
540 }
541
542 if (PosName.empty())
543 return IA_AddNewMeber;
544 return IA_MoveNewMember;
545 }
546 llvm_unreachable("No such operation");
547}
548
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000549// We have to walk this twice and computing it is not trivial, so creating an
550// explicit std::vector is actually fairly efficient.
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000551static std::vector<NewArchiveMember>
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000552computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000553 object::Archive *OldArchive) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000554 std::vector<NewArchiveMember> Ret;
555 std::vector<NewArchiveMember> Moved;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000556 int InsertPos = -1;
557 StringRef PosName = sys::path::filename(RelPos);
558 if (OldArchive) {
Mehdi Amini41af4302016-11-11 04:28:40 +0000559 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000560 for (auto &Child : OldArchive->children(Err)) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000561 int Pos = Ret.size();
Kevin Enderbyf4586032016-07-29 17:44:13 +0000562 Expected<StringRef> NameOrErr = Child.getName();
563 failIfError(NameOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000564 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000565 if (Name == PosName) {
566 assert(AddAfter || AddBefore);
567 if (AddBefore)
568 InsertPos = Pos;
569 else
570 InsertPos = Pos + 1;
571 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000572
Rafael Espindola76619702014-10-21 21:47:27 +0000573 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000574 InsertAction Action =
575 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000576 switch (Action) {
577 case IA_AddOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000578 addMember(Ret, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000579 break;
580 case IA_AddNewMeber:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000581 addMember(Ret, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000582 break;
583 case IA_Delete:
584 break;
585 case IA_MoveOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000586 addMember(Moved, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000587 break;
588 case IA_MoveNewMember:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000589 addMember(Moved, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000590 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000591 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000592 if (MemberI != Members.end())
593 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000594 }
Lang Hamesfc209622016-07-14 02:24:01 +0000595 failIfError(std::move(Err));
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000596 }
597
598 if (Operation == Delete)
599 return Ret;
600
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000601 if (!RelPos.empty() && InsertPos == -1)
602 fail("Insertion point not found");
603
Rafael Espindola623c3d82013-07-22 15:11:51 +0000604 if (RelPos.empty())
605 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000606
Rafael Espindola623c3d82013-07-22 15:11:51 +0000607 assert(unsigned(InsertPos) <= Ret.size());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000608 int Pos = InsertPos;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000609 for (auto &M : Moved) {
610 Ret.insert(Ret.begin() + Pos, std::move(M));
611 ++Pos;
612 }
613
614 for (unsigned I = 0; I != Members.size(); ++I)
615 Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
616 Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000617 for (auto &Member : Members) {
Rafael Espindola0a74a602015-07-15 22:46:53 +0000618 addMember(Ret, Member, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000619 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000620 }
621
622 return Ret;
623}
624
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000625static object::Archive::Kind getDefaultForHost() {
626 return Triple(sys::getProcessTriple()).isOSDarwin() ? object::Archive::K_BSD
627 : object::Archive::K_GNU;
628}
629
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000630static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
631 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
632 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000633
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000634 if (OptionalObject)
635 return isa<object::MachOObjectFile>(**OptionalObject)
636 ? object::Archive::K_BSD
637 : object::Archive::K_GNU;
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000638
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000639 // squelch the error in case we had a non-object file
640 consumeError(OptionalObject.takeError());
641 return getDefaultForHost();
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000642}
643
Rafael Espindola8a463522014-10-21 21:56:47 +0000644static void
Rafael Espindola484983f2016-05-09 13:31:11 +0000645performWriteOperation(ArchiveOperation Operation,
646 object::Archive *OldArchive,
647 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000648 std::vector<NewArchiveMember> *NewMembersP) {
649 std::vector<NewArchiveMember> NewMembers;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000650 if (!NewMembersP)
651 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
652
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000653 object::Archive::Kind Kind;
654 switch (FormatOpt) {
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000655 case Default:
656 if (Thin)
Rafael Espindola2535ea02015-07-09 20:12:50 +0000657 Kind = object::Archive::K_GNU;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000658 else if (OldArchive)
659 Kind = OldArchive->kind();
660 else if (NewMembersP)
661 Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
662 : getDefaultForHost();
663 else
664 Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
665 : getDefaultForHost();
Rafael Espindola2535ea02015-07-09 20:12:50 +0000666 break;
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000667 case GNU:
668 Kind = object::Archive::K_GNU;
669 break;
670 case BSD:
Rafael Espindola21507a42016-05-02 21:06:57 +0000671 if (Thin)
672 fail("Only the gnu format has a thin mode");
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000673 Kind = object::Archive::K_BSD;
674 break;
675 }
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000676
677 std::pair<StringRef, std::error_code> Result =
678 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
679 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
Peter Collingbournefd66a482015-06-08 02:32:01 +0000680 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000681}
682
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000683static void createSymbolTable(object::Archive *OldArchive) {
684 // When an archive is created or modified, if the s option is given, the
685 // resulting archive will have a current symbol table. If the S option
686 // is given, it will have no symbol table.
687 // In summary, we only need to update the symbol table if we have none.
688 // This is actually very common because of broken build systems that think
689 // they have to run ranlib.
690 if (OldArchive->hasSymbolTable())
691 return;
692
Rafael Espindola484983f2016-05-09 13:31:11 +0000693 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000694}
695
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000696static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000697 object::Archive *OldArchive,
Rafael Espindola484983f2016-05-09 13:31:11 +0000698 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000699 std::vector<NewArchiveMember> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000700 switch (Operation) {
701 case Print:
702 case DisplayTable:
703 case Extract:
704 performReadOperation(Operation, OldArchive);
705 return;
706
707 case Delete:
708 case Move:
709 case QuickAppend:
710 case ReplaceOrInsert:
Rafael Espindola484983f2016-05-09 13:31:11 +0000711 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
712 NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000713 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000714 case CreateSymTab:
715 createSymbolTable(OldArchive);
716 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000717 }
718 llvm_unreachable("Unknown operation.");
719}
720
Rafael Espindola8a463522014-10-21 21:56:47 +0000721static int performOperation(ArchiveOperation Operation,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000722 std::vector<NewArchiveMember> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000723 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000724 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
725 MemoryBuffer::getFile(ArchiveName, -1, false);
726 std::error_code EC = Buf.getError();
Davide Italiano43c35622015-11-14 19:00:33 +0000727 if (EC && EC != errc::no_such_file_or_directory)
728 fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000729
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000730 if (!EC) {
Mehdi Amini41af4302016-11-11 04:28:40 +0000731 Error Err = Error::success();
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000732 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
733 EC = errorToErrorCode(std::move(Err));
Davide Italiano43c35622015-11-14 19:00:33 +0000734 failIfError(EC,
735 "error loading '" + ArchiveName + "': " + EC.message() + "!");
Rafael Espindola484983f2016-05-09 13:31:11 +0000736 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000737 return 0;
738 }
739
Rafael Espindola2a826e42014-06-13 17:20:48 +0000740 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000741
742 if (!shouldCreateArchive(Operation)) {
743 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
744 } else {
745 if (!Create) {
746 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000747 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000748 }
749 }
750
Rafael Espindola484983f2016-05-09 13:31:11 +0000751 performOperation(Operation, nullptr, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000752 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000753}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000754
Rafael Espindola8a463522014-10-21 21:56:47 +0000755static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000756 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000757
758 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
759 failIfError(Buf.getError());
760 const MemoryBuffer &Ref = *Buf.get();
761 bool Saved = false;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000762 std::vector<NewArchiveMember> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000763 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
764 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000765
766 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
767 StringRef Line = *I;
768 StringRef CommandStr, Rest;
769 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000770 Rest = Rest.trim();
771 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
772 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000773 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000774 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000775 .Case("addmod", MRICommand::AddMod)
776 .Case("create", MRICommand::Create)
777 .Case("save", MRICommand::Save)
778 .Case("end", MRICommand::End)
779 .Default(MRICommand::Invalid);
780
781 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000782 case MRICommand::AddLib: {
783 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
784 failIfError(BufOrErr.getError(), "Could not open library");
785 ArchiveBuffers.push_back(std::move(*BufOrErr));
786 auto LibOrErr =
787 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000788 failIfError(errorToErrorCode(LibOrErr.takeError()),
789 "Could not parse library");
Rafael Espindola915fbb32014-10-21 23:18:51 +0000790 Archives.push_back(std::move(*LibOrErr));
791 object::Archive &Lib = *Archives.back();
Lang Hamesfc209622016-07-14 02:24:01 +0000792 {
Mehdi Amini41af4302016-11-11 04:28:40 +0000793 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +0000794 for (auto &Member : Lib.children(Err))
795 addMember(NewMembers, Member);
796 failIfError(std::move(Err));
Rafael Espindola915fbb32014-10-21 23:18:51 +0000797 }
798 break;
799 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000800 case MRICommand::AddMod:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000801 addMember(NewMembers, Rest);
Rafael Espindola8a463522014-10-21 21:56:47 +0000802 break;
803 case MRICommand::Create:
804 Create = true;
805 if (!ArchiveName.empty())
806 fail("Editing multiple archives not supported");
807 if (Saved)
808 fail("File already saved");
809 ArchiveName = Rest;
810 break;
811 case MRICommand::Save:
812 Saved = true;
813 break;
814 case MRICommand::End:
815 break;
816 case MRICommand::Invalid:
817 fail("Unknown command: " + CommandStr);
818 }
819 }
820
821 // Nothing to do if not saved.
822 if (Saved)
823 performOperation(ReplaceOrInsert, &NewMembers);
824 exit(0);
825}
826
Rafael Espindola47ee3392014-11-07 21:33:09 +0000827static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000828 // Do our own parsing of the command line because the CommandLine utility
829 // can't handle the grouped positional parameters without a dash.
830 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000831 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000832}
833
Rafael Espindoladbc04162014-10-22 15:05:51 +0000834static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000835 if (RestOfArgs.size() != 1)
Sunil Srivastava3780b682016-04-08 00:02:14 +0000836 fail(ToolName + " takes just one archive as an argument");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000837 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000838 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000839}
840
841int main(int argc, char **argv) {
842 ToolName = argv[0];
843 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000844 sys::PrintStackTraceOnErrorSignal(argv[0]);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000845 PrettyStackTraceProgram X(argc, argv);
846 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
847
Peter Collingbournebc051632015-06-09 21:50:22 +0000848 llvm::InitializeAllTargetInfos();
849 llvm::InitializeAllTargetMCs();
850 llvm::InitializeAllAsmParsers();
851
852 StringRef Stem = sys::path::stem(ToolName);
853 if (Stem.find("ranlib") == StringRef::npos &&
854 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000855 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000856
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000857 // Have the command line options parsed and handle things
858 // like --help and --version.
859 cl::ParseCommandLineOptions(argc, argv,
860 "LLVM Archiver (llvm-ar)\n\n"
861 " This program archives bitcode files into single libraries\n"
862 );
863
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000864 if (Stem.find("ranlib") != StringRef::npos)
865 return ranlib_main();
Ed Schoutenbaff6b42015-10-27 16:37:49 +0000866 if (Stem.find("ar") != StringRef::npos)
867 return ar_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000868 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000869}