blob: cf2f98f83e1be5b95ae9e9ab45bf0fedb31e98e0 [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
Rafael Espindola4b83cb52015-07-14 22:18:43 +0000321 ErrorOr<StringRef> DataOrErr = C.getBuffer();
322 failIfError(DataOrErr.getError());
323 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
Rafael Espindola4b83cb52015-07-14 22:18:43 +0000379 StringRef Data = *C.getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000380
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000381 // Write the data.
382 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000383 }
384
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000385 // If we're supposed to retain the original modification times, etc. do so
386 // now.
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000387 if (OriginalDates) {
388 Expected<sys::TimeValue> ModTimeOrErr = C.getLastModified();
389 failIfError(ModTimeOrErr.takeError());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000390 failIfError(
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000391 sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
392 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000393
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000394 if (close(FD))
395 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000396}
397
Rafael Espindola05571532013-07-12 16:29:27 +0000398static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000399 switch (Op) {
400 case Print:
401 case Delete:
402 case Move:
403 case DisplayTable:
404 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000405 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000406 return false;
407
408 case QuickAppend:
409 case ReplaceOrInsert:
410 return true;
411 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000412
413 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000414}
415
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000416static void performReadOperation(ArchiveOperation Operation,
417 object::Archive *OldArchive) {
Davide Italiano7bfbb592015-11-14 18:33:47 +0000418 if (Operation == Extract && OldArchive->isThin())
419 fail("extracting from a thin archive is not supported");
Rafael Espindolae549b8c2015-07-14 16:55:13 +0000420
Rafael Espindolac3eec452015-07-14 16:02:40 +0000421 bool Filter = !Members.empty();
Lang Hamesfc209622016-07-14 02:24:01 +0000422 {
423 Error Err;
424 for (auto &C : OldArchive->children(Err)) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000425 Expected<StringRef> NameOrErr = C.getName();
426 failIfError(NameOrErr.takeError());
Lang Hamesfc209622016-07-14 02:24:01 +0000427 StringRef Name = NameOrErr.get();
Kevin Enderby7a969422015-11-05 19:24:56 +0000428
Lang Hamesfc209622016-07-14 02:24:01 +0000429 if (Filter) {
430 auto I = std::find(Members.begin(), Members.end(), Name);
431 if (I == Members.end())
432 continue;
433 Members.erase(I);
434 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000435
Lang Hamesfc209622016-07-14 02:24:01 +0000436 switch (Operation) {
437 default:
438 llvm_unreachable("Not a read operation");
439 case Print:
440 doPrint(Name, C);
441 break;
442 case DisplayTable:
443 doDisplayTable(Name, C);
444 break;
445 case Extract:
446 doExtract(Name, C);
447 break;
448 }
Rafael Espindolac3eec452015-07-14 16:02:40 +0000449 }
Lang Hamesfc209622016-07-14 02:24:01 +0000450 failIfError(std::move(Err));
Lang Hamesae610ab2016-07-14 00:37:04 +0000451 }
Lang Hamesfc209622016-07-14 02:24:01 +0000452
Rafael Espindolac3eec452015-07-14 16:02:40 +0000453 if (Members.empty())
454 return;
455 for (StringRef Name : Members)
456 errs() << Name << " was not found\n";
457 std::exit(1);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000458}
459
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000460static void addMember(std::vector<NewArchiveMember> &Members,
Rafael Espindola2f5e8872015-11-01 00:14:59 +0000461 StringRef FileName, int Pos = -1) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000462 Expected<NewArchiveMember> NMOrErr =
463 NewArchiveMember::getFile(FileName, Deterministic);
464 failIfError(NMOrErr.takeError(), FileName);
Rafael Espindola449208d2015-07-15 20:45:56 +0000465 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000466 Members.push_back(std::move(*NMOrErr));
Rafael Espindola449208d2015-07-15 20:45:56 +0000467 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000468 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola449208d2015-07-15 20:45:56 +0000469}
470
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000471static void addMember(std::vector<NewArchiveMember> &Members,
472 const object::Archive::Child &M, int Pos = -1) {
Rafael Espindolae0d30802015-11-01 00:10:37 +0000473 if (Thin && !M.getParent()->isThin())
Rafael Espindola449208d2015-07-15 20:45:56 +0000474 fail("Cannot convert a regular archive to a thin one");
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000475 Expected<NewArchiveMember> NMOrErr =
476 NewArchiveMember::getOldMember(M, Deterministic);
477 failIfError(NMOrErr.takeError());
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000478 if (Pos == -1)
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000479 Members.push_back(std::move(*NMOrErr));
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000480 else
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000481 Members[Pos] = std::move(*NMOrErr);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000482}
483
Rafael Espindola623c3d82013-07-22 15:11:51 +0000484enum InsertAction {
485 IA_AddOldMember,
486 IA_AddNewMeber,
487 IA_Delete,
488 IA_MoveOldMember,
489 IA_MoveNewMember
490};
491
Rafael Espindola76619702014-10-21 21:47:27 +0000492static InsertAction computeInsertAction(ArchiveOperation Operation,
Rafael Espindola54d263c2015-11-02 13:30:46 +0000493 const object::Archive::Child &Member,
Rafael Espindola76619702014-10-21 21:47:27 +0000494 StringRef Name,
495 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000496 if (Operation == QuickAppend || Members.empty())
497 return IA_AddOldMember;
498
Rafael Espindola76619702014-10-21 21:47:27 +0000499 auto MI =
500 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
501 return Name == sys::path::filename(Path);
502 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000503
504 if (MI == Members.end())
505 return IA_AddOldMember;
506
507 Pos = MI;
508
509 if (Operation == Delete)
510 return IA_Delete;
511
512 if (Operation == Move)
513 return IA_MoveOldMember;
514
515 if (Operation == ReplaceOrInsert) {
516 StringRef PosName = sys::path::filename(RelPos);
517 if (!OnlyUpdate) {
518 if (PosName.empty())
519 return IA_AddNewMeber;
520 return IA_MoveNewMember;
521 }
522
523 // We could try to optimize this to a fstat, but it is not a common
524 // operation.
525 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000526 failIfError(sys::fs::status(*MI, Status), *MI);
Vedant Kumar4031d9f2016-08-03 19:02:50 +0000527 Expected<sys::TimeValue> ModTimeOrErr = Member.getLastModified();
528 failIfError(ModTimeOrErr.takeError());
529 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000530 if (PosName.empty())
531 return IA_AddOldMember;
532 return IA_MoveOldMember;
533 }
534
535 if (PosName.empty())
536 return IA_AddNewMeber;
537 return IA_MoveNewMember;
538 }
539 llvm_unreachable("No such operation");
540}
541
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000542// We have to walk this twice and computing it is not trivial, so creating an
543// explicit std::vector is actually fairly efficient.
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000544static std::vector<NewArchiveMember>
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000545computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000546 object::Archive *OldArchive) {
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000547 std::vector<NewArchiveMember> Ret;
548 std::vector<NewArchiveMember> Moved;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000549 int InsertPos = -1;
550 StringRef PosName = sys::path::filename(RelPos);
551 if (OldArchive) {
Lang Hamesfc209622016-07-14 02:24:01 +0000552 Error Err;
553 for (auto &Child : OldArchive->children(Err)) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000554 int Pos = Ret.size();
Kevin Enderbyf4586032016-07-29 17:44:13 +0000555 Expected<StringRef> NameOrErr = Child.getName();
556 failIfError(NameOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000557 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000558 if (Name == PosName) {
559 assert(AddAfter || AddBefore);
560 if (AddBefore)
561 InsertPos = Pos;
562 else
563 InsertPos = Pos + 1;
564 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000565
Rafael Espindola76619702014-10-21 21:47:27 +0000566 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000567 InsertAction Action =
568 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000569 switch (Action) {
570 case IA_AddOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000571 addMember(Ret, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000572 break;
573 case IA_AddNewMeber:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000574 addMember(Ret, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000575 break;
576 case IA_Delete:
577 break;
578 case IA_MoveOldMember:
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000579 addMember(Moved, Child);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000580 break;
581 case IA_MoveNewMember:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000582 addMember(Moved, *MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000583 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000584 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000585 if (MemberI != Members.end())
586 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000587 }
Lang Hamesfc209622016-07-14 02:24:01 +0000588 failIfError(std::move(Err));
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000589 }
590
591 if (Operation == Delete)
592 return Ret;
593
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000594 if (!RelPos.empty() && InsertPos == -1)
595 fail("Insertion point not found");
596
Rafael Espindola623c3d82013-07-22 15:11:51 +0000597 if (RelPos.empty())
598 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000599
Rafael Espindola623c3d82013-07-22 15:11:51 +0000600 assert(unsigned(InsertPos) <= Ret.size());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000601 int Pos = InsertPos;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000602 for (auto &M : Moved) {
603 Ret.insert(Ret.begin() + Pos, std::move(M));
604 ++Pos;
605 }
606
607 for (unsigned I = 0; I != Members.size(); ++I)
608 Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
609 Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000610 for (auto &Member : Members) {
Rafael Espindola0a74a602015-07-15 22:46:53 +0000611 addMember(Ret, Member, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000612 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000613 }
614
615 return Ret;
616}
617
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000618static object::Archive::Kind getDefaultForHost() {
619 return Triple(sys::getProcessTriple()).isOSDarwin() ? object::Archive::K_BSD
620 : object::Archive::K_GNU;
621}
622
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000623static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
624 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
625 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000626
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000627 if (OptionalObject)
628 return isa<object::MachOObjectFile>(**OptionalObject)
629 ? object::Archive::K_BSD
630 : object::Archive::K_GNU;
Saleem Abdulrasool1a7a6952016-06-22 15:44:25 +0000631
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000632 // squelch the error in case we had a non-object file
633 consumeError(OptionalObject.takeError());
634 return getDefaultForHost();
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000635}
636
Rafael Espindola8a463522014-10-21 21:56:47 +0000637static void
Rafael Espindola484983f2016-05-09 13:31:11 +0000638performWriteOperation(ArchiveOperation Operation,
639 object::Archive *OldArchive,
640 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000641 std::vector<NewArchiveMember> *NewMembersP) {
642 std::vector<NewArchiveMember> NewMembers;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000643 if (!NewMembersP)
644 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
645
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000646 object::Archive::Kind Kind;
647 switch (FormatOpt) {
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000648 case Default:
649 if (Thin)
Rafael Espindola2535ea02015-07-09 20:12:50 +0000650 Kind = object::Archive::K_GNU;
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000651 else if (OldArchive)
652 Kind = OldArchive->kind();
653 else if (NewMembersP)
654 Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
655 : getDefaultForHost();
656 else
657 Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
658 : getDefaultForHost();
Rafael Espindola2535ea02015-07-09 20:12:50 +0000659 break;
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000660 case GNU:
661 Kind = object::Archive::K_GNU;
662 break;
663 case BSD:
Rafael Espindola21507a42016-05-02 21:06:57 +0000664 if (Thin)
665 fail("Only the gnu format has a thin mode");
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000666 Kind = object::Archive::K_BSD;
667 break;
668 }
Saleem Abdulrasoola0d42c82016-06-22 04:03:28 +0000669
670 std::pair<StringRef, std::error_code> Result =
671 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
672 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
Peter Collingbournefd66a482015-06-08 02:32:01 +0000673 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000674}
675
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000676static void createSymbolTable(object::Archive *OldArchive) {
677 // When an archive is created or modified, if the s option is given, the
678 // resulting archive will have a current symbol table. If the S option
679 // is given, it will have no symbol table.
680 // In summary, we only need to update the symbol table if we have none.
681 // This is actually very common because of broken build systems that think
682 // they have to run ranlib.
683 if (OldArchive->hasSymbolTable())
684 return;
685
Rafael Espindola484983f2016-05-09 13:31:11 +0000686 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000687}
688
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000689static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000690 object::Archive *OldArchive,
Rafael Espindola484983f2016-05-09 13:31:11 +0000691 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000692 std::vector<NewArchiveMember> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000693 switch (Operation) {
694 case Print:
695 case DisplayTable:
696 case Extract:
697 performReadOperation(Operation, OldArchive);
698 return;
699
700 case Delete:
701 case Move:
702 case QuickAppend:
703 case ReplaceOrInsert:
Rafael Espindola484983f2016-05-09 13:31:11 +0000704 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
705 NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000706 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000707 case CreateSymTab:
708 createSymbolTable(OldArchive);
709 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000710 }
711 llvm_unreachable("Unknown operation.");
712}
713
Rafael Espindola8a463522014-10-21 21:56:47 +0000714static int performOperation(ArchiveOperation Operation,
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000715 std::vector<NewArchiveMember> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000716 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000717 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
718 MemoryBuffer::getFile(ArchiveName, -1, false);
719 std::error_code EC = Buf.getError();
Davide Italiano43c35622015-11-14 19:00:33 +0000720 if (EC && EC != errc::no_such_file_or_directory)
721 fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000722
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000723 if (!EC) {
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000724 Error Err;
725 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
726 EC = errorToErrorCode(std::move(Err));
Davide Italiano43c35622015-11-14 19:00:33 +0000727 failIfError(EC,
728 "error loading '" + ArchiveName + "': " + EC.message() + "!");
Rafael Espindola484983f2016-05-09 13:31:11 +0000729 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000730 return 0;
731 }
732
Rafael Espindola2a826e42014-06-13 17:20:48 +0000733 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000734
735 if (!shouldCreateArchive(Operation)) {
736 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
737 } else {
738 if (!Create) {
739 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000740 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000741 }
742 }
743
Rafael Espindola484983f2016-05-09 13:31:11 +0000744 performOperation(Operation, nullptr, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000745 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000746}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000747
Rafael Espindola8a463522014-10-21 21:56:47 +0000748static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000749 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000750
751 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
752 failIfError(Buf.getError());
753 const MemoryBuffer &Ref = *Buf.get();
754 bool Saved = false;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000755 std::vector<NewArchiveMember> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000756 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
757 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000758
759 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
760 StringRef Line = *I;
761 StringRef CommandStr, Rest;
762 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000763 Rest = Rest.trim();
764 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
765 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000766 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000767 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000768 .Case("addmod", MRICommand::AddMod)
769 .Case("create", MRICommand::Create)
770 .Case("save", MRICommand::Save)
771 .Case("end", MRICommand::End)
772 .Default(MRICommand::Invalid);
773
774 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000775 case MRICommand::AddLib: {
776 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
777 failIfError(BufOrErr.getError(), "Could not open library");
778 ArchiveBuffers.push_back(std::move(*BufOrErr));
779 auto LibOrErr =
780 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000781 failIfError(errorToErrorCode(LibOrErr.takeError()),
782 "Could not parse library");
Rafael Espindola915fbb32014-10-21 23:18:51 +0000783 Archives.push_back(std::move(*LibOrErr));
784 object::Archive &Lib = *Archives.back();
Lang Hamesfc209622016-07-14 02:24:01 +0000785 {
786 Error Err;
787 for (auto &Member : Lib.children(Err))
788 addMember(NewMembers, Member);
789 failIfError(std::move(Err));
Rafael Espindola915fbb32014-10-21 23:18:51 +0000790 }
791 break;
792 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000793 case MRICommand::AddMod:
Rafael Espindola0a74a602015-07-15 22:46:53 +0000794 addMember(NewMembers, Rest);
Rafael Espindola8a463522014-10-21 21:56:47 +0000795 break;
796 case MRICommand::Create:
797 Create = true;
798 if (!ArchiveName.empty())
799 fail("Editing multiple archives not supported");
800 if (Saved)
801 fail("File already saved");
802 ArchiveName = Rest;
803 break;
804 case MRICommand::Save:
805 Saved = true;
806 break;
807 case MRICommand::End:
808 break;
809 case MRICommand::Invalid:
810 fail("Unknown command: " + CommandStr);
811 }
812 }
813
814 // Nothing to do if not saved.
815 if (Saved)
816 performOperation(ReplaceOrInsert, &NewMembers);
817 exit(0);
818}
819
Rafael Espindola47ee3392014-11-07 21:33:09 +0000820static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000821 // Do our own parsing of the command line because the CommandLine utility
822 // can't handle the grouped positional parameters without a dash.
823 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000824 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000825}
826
Rafael Espindoladbc04162014-10-22 15:05:51 +0000827static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000828 if (RestOfArgs.size() != 1)
Sunil Srivastava3780b682016-04-08 00:02:14 +0000829 fail(ToolName + " takes just one archive as an argument");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000830 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000831 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000832}
833
834int main(int argc, char **argv) {
835 ToolName = argv[0];
836 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000837 sys::PrintStackTraceOnErrorSignal(argv[0]);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000838 PrettyStackTraceProgram X(argc, argv);
839 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
840
Peter Collingbournebc051632015-06-09 21:50:22 +0000841 llvm::InitializeAllTargetInfos();
842 llvm::InitializeAllTargetMCs();
843 llvm::InitializeAllAsmParsers();
844
845 StringRef Stem = sys::path::stem(ToolName);
846 if (Stem.find("ranlib") == StringRef::npos &&
847 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000848 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000849
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000850 // Have the command line options parsed and handle things
851 // like --help and --version.
852 cl::ParseCommandLineOptions(argc, argv,
853 "LLVM Archiver (llvm-ar)\n\n"
854 " This program archives bitcode files into single libraries\n"
855 );
856
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000857 if (Stem.find("ranlib") != StringRef::npos)
858 return ranlib_main();
Ed Schoutenbaff6b42015-10-27 16:37:49 +0000859 if (Stem.find("ar") != StringRef::npos)
860 return ar_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000861 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000862}