blob: 698c9bb38c9d1c1fa0e13d046d49174f93fbba39 [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"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000022#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000023#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000024#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000025#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000026#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000027#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000028#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000029#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000030#include "llvm/Support/Path.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000031#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000032#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000033#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000034#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000035#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000036#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000037#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000039
40#if !defined(_MSC_VER) && !defined(__MINGW32__)
41#include <unistd.h>
42#else
43#include <io.h>
44#endif
45
Brian Gaeke960707c2003-11-11 22:41:34 +000046using namespace llvm;
47
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000048// The name this program was invoked as.
49static StringRef ToolName;
50
Rafael Espindola90b85702014-10-21 15:49:46 +000051// Show the error message and exit.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000052LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
53 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000054 exit(1);
55}
56
Rafael Espindola4453e42942014-06-13 03:07:50 +000057static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000058 if (!EC)
59 return;
60
61 std::string ContextStr = Context.str();
62 if (ContextStr == "")
63 fail(EC.message());
64 fail(Context + ": " + EC.message());
65}
66
Rafael Espindola0c8a3522013-08-28 16:22:16 +000067// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000068static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000069 RestOfArgs(cl::Positional, cl::ZeroOrMore,
70 cl::desc("[relpos] [count] <archive-file> [members]..."));
71
72static cl::opt<bool> MRI("M", cl::desc(""));
Tanya Lattner57c70a62003-08-28 15:22:38 +000073
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000074namespace {
75enum Format { Default, GNU, BSD };
76}
77
78static cl::opt<Format>
79 FormatOpt("format", cl::desc("Archive format to create"),
80 cl::values(clEnumValN(Default, "defalut", "default"),
81 clEnumValN(GNU, "gnu", "gnu"),
82 clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
83
Rafael Espindola0c8a3522013-08-28 16:22:16 +000084std::string Options;
85
Rafael Espindola90b85702014-10-21 15:49:46 +000086// Provide additional help output explaining the operations and modifiers of
87// llvm-ar. This object instructs the CommandLine library to print the text of
88// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +000089static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000090 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000091 " d[NsS] - delete file(s) from the archive\n"
92 " m[abiSs] - move file(s) in the archive\n"
93 " p[kN] - print file(s) found in the archive\n"
94 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000095 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000096 " t - display contents of archive\n"
97 " x[No] - extract file(s) from the archive\n"
98 "\nMODIFIERS (operation specific):\n"
99 " [a] - put file(s) after [relpos]\n"
100 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000101 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000102 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000103 " [s] - create an archive index (cf. ranlib)\n"
104 " [S] - do not build a symbol table\n"
105 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000106 "\nMODIFIERS (generic):\n"
107 " [c] - do not warn if the library had to be created\n"
108 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000109);
110
Reid Spencer84a12bf2004-11-14 22:20:07 +0000111// This enumeration delineates the kinds of operations on an archive
112// that are permitted.
113enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000114 Print, ///< Print the contents of the archive
115 Delete, ///< Delete the specified members
116 Move, ///< Move members to end or as given by {a,b,i} modifiers
117 QuickAppend, ///< Quickly append to end of archive
118 ReplaceOrInsert, ///< Replace or Insert members
119 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000120 Extract, ///< Extract files back to file system
121 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000122};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000123
Reid Spencer84a12bf2004-11-14 22:20:07 +0000124// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000125static bool AddAfter = false; ///< 'a' modifier
126static bool AddBefore = false; ///< 'b' modifier
127static bool Create = false; ///< 'c' modifier
128static bool OriginalDates = false; ///< 'o' modifier
129static bool OnlyUpdate = false; ///< 'u' modifier
130static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000131static bool Symtab = true; ///< 's' modifier
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000132static bool Deterministic = true; ///< 'D' and 'U' modifiers
Tanya Lattner57c70a62003-08-28 15:22:38 +0000133
Reid Spencer84a12bf2004-11-14 22:20:07 +0000134// Relative Positional Argument (for insert/move). This variable holds
135// the name of the archive member to which the 'a', 'b' or 'i' modifier
136// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
137// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000138static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000139
Reid Spencer84a12bf2004-11-14 22:20:07 +0000140// This variable holds the name of the archive file as given on the
141// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000142static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000143
Reid Spencer84a12bf2004-11-14 22:20:07 +0000144// This variable holds the list of member files to proecess, as given
145// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000146static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000147
Rafael Espindola90b85702014-10-21 15:49:46 +0000148// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000149LLVM_ATTRIBUTE_NORETURN static void
150show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000151 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000152 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000153 std::exit(1);
154}
155
Rafael Espindola90b85702014-10-21 15:49:46 +0000156// Extract the member filename from the command line for the [relpos] argument
157// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000158static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000159 if(RestOfArgs.size() == 0)
160 show_help("Expected [relpos] for a, b, or i modifier");
161 RelPos = RestOfArgs[0];
162 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000163}
164
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000165static void getOptions() {
166 if(RestOfArgs.size() == 0)
167 show_help("Expected options");
168 Options = RestOfArgs[0];
169 RestOfArgs.erase(RestOfArgs.begin());
170}
171
Rafael Espindola90b85702014-10-21 15:49:46 +0000172// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000173static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000174 if(RestOfArgs.size() == 0)
175 show_help("An archive name must be specified");
176 ArchiveName = RestOfArgs[0];
177 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000178}
179
Rafael Espindola90b85702014-10-21 15:49:46 +0000180// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000181static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000182 for (auto &Arg : RestOfArgs)
183 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000184}
185
Rafael Espindola8a463522014-10-21 21:56:47 +0000186static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000187
Rafael Espindola90b85702014-10-21 15:49:46 +0000188// Parse the command line options as presented and return the operation
189// specified. Process all modifiers and check to make sure that constraints on
190// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000191static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000192 if (MRI) {
193 if (!RestOfArgs.empty())
194 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000195 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000196 }
197
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000198 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000199
Reid Spencer84a12bf2004-11-14 22:20:07 +0000200 // Keep track of number of operations. We can only specify one
201 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000202 unsigned NumOperations = 0;
203
Reid Spencer84a12bf2004-11-14 22:20:07 +0000204 // Keep track of the number of positional modifiers (a,b,i). Only
205 // one can be specified.
206 unsigned NumPositional = 0;
207
208 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000209 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000210
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000211 bool MaybeJustCreateSymTab = false;
212
Tanya Lattnerc970a382003-12-06 23:01:25 +0000213 for(unsigned i=0; i<Options.size(); ++i) {
214 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000215 case 'd': ++NumOperations; Operation = Delete; break;
216 case 'm': ++NumOperations; Operation = Move ; break;
217 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000218 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000219 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000220 case 't': ++NumOperations; Operation = DisplayTable; break;
221 case 'x': ++NumOperations; Operation = Extract; break;
222 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000223 case 'l': /* accepted but unused */ break;
224 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000225 case 's':
226 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000227 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000228 break;
229 case 'S':
230 Symtab = false;
231 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000232 case 'u': OnlyUpdate = true; break;
233 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000234 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000235 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000236 AddAfter = true;
237 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000238 break;
239 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000240 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000241 AddBefore = true;
242 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000243 break;
244 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000245 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000246 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000247 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000248 break;
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000249 case 'D':
250 Deterministic = true;
251 break;
252 case 'U':
253 Deterministic = false;
254 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000255 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000256 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000257 }
258 }
259
Misha Brukman650ba8e2005-04-22 00:00:37 +0000260 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000261 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000262 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000263
264 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000265 getMembers();
266
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000267 if (NumOperations == 0 && MaybeJustCreateSymTab) {
268 NumOperations = 1;
269 Operation = CreateSymTab;
270 if (!Members.empty())
271 show_help("The s operation takes only an archive as argument");
272 }
273
Reid Spencer84a12bf2004-11-14 22:20:07 +0000274 // Perform various checks on the operation/modifier specification
275 // to make sure we are dealing with a legal request.
276 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000277 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000278 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000279 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000280 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000281 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000282 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000283 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000284 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
285 "the 'm' or 'r' operations");
286 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000287 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000288 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000289 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000290 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000291
292 // Return the parsed operation to the caller
293 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000294}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000295
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000296// Implements the 'p' operation. This function traverses the archive
297// looking for members that match the path list.
298static void doPrint(StringRef Name, object::Archive::child_iterator I) {
299 if (Verbose)
300 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000301
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000302 StringRef Data = I->getBuffer();
303 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000304}
305
Rafael Espindola90b85702014-10-21 15:49:46 +0000306// Utility function for printing out the file mode when the 't' operation is in
307// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000308static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000309 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000310 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000311 else
Chris Lattner2907f442010-11-29 23:02:20 +0000312 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000313 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000314 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000315 else
Chris Lattner2907f442010-11-29 23:02:20 +0000316 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000317 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000318 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000319 else
Chris Lattner2907f442010-11-29 23:02:20 +0000320 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000321}
322
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000323// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000324// the file names of each of the members. However, if verbose mode is requested
325// ('v' modifier) then the file type, permission mode, user, group, size, and
326// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000327static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
328 if (Verbose) {
329 sys::fs::perms Mode = I->getAccessMode();
330 printMode((Mode >> 6) & 007);
331 printMode((Mode >> 3) & 007);
332 printMode(Mode & 007);
333 outs() << ' ' << I->getUID();
334 outs() << '/' << I->getGID();
335 outs() << ' ' << format("%6llu", I->getSize());
336 outs() << ' ' << I->getLastModified().str();
337 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000338 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000339 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000340}
341
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000342// Implement the 'x' operation. This function extracts files back to the file
343// system.
344static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000345 // Retain the original mode.
346 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000347 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000348
Rafael Espindola6d354812013-07-16 19:44:17 +0000349 int FD;
350 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000351 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000352 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000353
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000354 {
355 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000356
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000357 // Get the data and its length
358 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000359
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000360 // Write the data.
361 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000362 }
363
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000364 // If we're supposed to retain the original modification times, etc. do so
365 // now.
366 if (OriginalDates)
367 failIfError(
368 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000369
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000370 if (close(FD))
371 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000372}
373
Rafael Espindola05571532013-07-12 16:29:27 +0000374static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000375 switch (Op) {
376 case Print:
377 case Delete:
378 case Move:
379 case DisplayTable:
380 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000381 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000382 return false;
383
384 case QuickAppend:
385 case ReplaceOrInsert:
386 return true;
387 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000388
389 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000390}
391
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000392static void performReadOperation(ArchiveOperation Operation,
393 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000394 for (object::Archive::child_iterator I = OldArchive->child_begin(),
395 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000396 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000397 ErrorOr<StringRef> NameOrErr = I->getName();
398 failIfError(NameOrErr.getError());
399 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000400
401 if (!Members.empty() &&
402 std::find(Members.begin(), Members.end(), Name) == Members.end())
403 continue;
404
405 switch (Operation) {
406 default:
407 llvm_unreachable("Not a read operation");
408 case Print:
409 doPrint(Name, I);
410 break;
411 case DisplayTable:
412 doDisplayTable(Name, I);
413 break;
414 case Extract:
415 doExtract(Name, I);
416 break;
417 }
418 }
419}
420
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000421template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000422void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
423 int Pos = -1) {
424 NewArchiveIterator NI(I, Name);
425 if (Pos == -1)
426 Members.push_back(NI);
427 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000428 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000429}
430
Rafael Espindola623c3d82013-07-22 15:11:51 +0000431enum InsertAction {
432 IA_AddOldMember,
433 IA_AddNewMeber,
434 IA_Delete,
435 IA_MoveOldMember,
436 IA_MoveNewMember
437};
438
Rafael Espindola76619702014-10-21 21:47:27 +0000439static InsertAction computeInsertAction(ArchiveOperation Operation,
440 object::Archive::child_iterator I,
441 StringRef Name,
442 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000443 if (Operation == QuickAppend || Members.empty())
444 return IA_AddOldMember;
445
Rafael Espindola76619702014-10-21 21:47:27 +0000446 auto MI =
447 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
448 return Name == sys::path::filename(Path);
449 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000450
451 if (MI == Members.end())
452 return IA_AddOldMember;
453
454 Pos = MI;
455
456 if (Operation == Delete)
457 return IA_Delete;
458
459 if (Operation == Move)
460 return IA_MoveOldMember;
461
462 if (Operation == ReplaceOrInsert) {
463 StringRef PosName = sys::path::filename(RelPos);
464 if (!OnlyUpdate) {
465 if (PosName.empty())
466 return IA_AddNewMeber;
467 return IA_MoveNewMember;
468 }
469
470 // We could try to optimize this to a fstat, but it is not a common
471 // operation.
472 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000473 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000474 if (Status.getLastModificationTime() < I->getLastModified()) {
475 if (PosName.empty())
476 return IA_AddOldMember;
477 return IA_MoveOldMember;
478 }
479
480 if (PosName.empty())
481 return IA_AddNewMeber;
482 return IA_MoveNewMember;
483 }
484 llvm_unreachable("No such operation");
485}
486
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000487// We have to walk this twice and computing it is not trivial, so creating an
488// explicit std::vector is actually fairly efficient.
489static std::vector<NewArchiveIterator>
490computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000491 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000492 std::vector<NewArchiveIterator> Ret;
493 std::vector<NewArchiveIterator> Moved;
494 int InsertPos = -1;
495 StringRef PosName = sys::path::filename(RelPos);
496 if (OldArchive) {
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000497 for (auto &Child : OldArchive->children()) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000498 int Pos = Ret.size();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000499 ErrorOr<StringRef> NameOrErr = Child.getName();
Rafael Espindolaae460022014-06-16 16:08:36 +0000500 failIfError(NameOrErr.getError());
501 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000502 if (Name == PosName) {
503 assert(AddAfter || AddBefore);
504 if (AddBefore)
505 InsertPos = Pos;
506 else
507 InsertPos = Pos + 1;
508 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000509
Rafael Espindola76619702014-10-21 21:47:27 +0000510 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000511 InsertAction Action =
512 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000513 switch (Action) {
514 case IA_AddOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000515 addMember(Ret, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000516 break;
517 case IA_AddNewMeber:
Rafael Espindola76619702014-10-21 21:47:27 +0000518 addMember(Ret, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000519 break;
520 case IA_Delete:
521 break;
522 case IA_MoveOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000523 addMember(Moved, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000524 break;
525 case IA_MoveNewMember:
Rafael Espindola76619702014-10-21 21:47:27 +0000526 addMember(Moved, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000527 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000528 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000529 if (MemberI != Members.end())
530 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000531 }
532 }
533
534 if (Operation == Delete)
535 return Ret;
536
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000537 if (!RelPos.empty() && InsertPos == -1)
538 fail("Insertion point not found");
539
Rafael Espindola623c3d82013-07-22 15:11:51 +0000540 if (RelPos.empty())
541 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000542
Rafael Espindola623c3d82013-07-22 15:11:51 +0000543 assert(unsigned(InsertPos) <= Ret.size());
544 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000545
Rafael Espindolac91177e2015-07-08 22:15:07 +0000546 Ret.insert(Ret.begin() + InsertPos, Members.size(),
547 NewArchiveIterator("", ""));
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000548 int Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000549 for (auto &Member : Members) {
550 StringRef Name = sys::path::filename(Member);
Rafael Espindola76619702014-10-21 21:47:27 +0000551 addMember(Ret, Member, Name, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000552 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000553 }
554
555 return Ret;
556}
557
Rafael Espindola8a463522014-10-21 21:56:47 +0000558static void
559performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
560 std::vector<NewArchiveIterator> *NewMembersP) {
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000561 object::Archive::Kind Kind;
562 switch (FormatOpt) {
Rafael Espindola2535ea02015-07-09 20:12:50 +0000563 case Default: {
564 Triple T(sys::getProcessTriple());
565 if (T.isOSDarwin())
566 Kind = object::Archive::K_BSD;
567 else
568 Kind = object::Archive::K_GNU;
569 break;
570 }
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000571 case GNU:
572 Kind = object::Archive::K_GNU;
573 break;
574 case BSD:
575 Kind = object::Archive::K_BSD;
576 break;
577 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000578 if (NewMembersP) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000579 std::pair<StringRef, std::error_code> Result =
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000580 writeArchive(ArchiveName, *NewMembersP, Symtab, Kind, Deterministic);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000581 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000582 return;
583 }
584 std::vector<NewArchiveIterator> NewMembers =
585 computeNewArchiveMembers(Operation, OldArchive);
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000586 auto Result =
587 writeArchive(ArchiveName, NewMembers, Symtab, Kind, Deterministic);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000588 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000589}
590
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000591static void createSymbolTable(object::Archive *OldArchive) {
592 // When an archive is created or modified, if the s option is given, the
593 // resulting archive will have a current symbol table. If the S option
594 // is given, it will have no symbol table.
595 // In summary, we only need to update the symbol table if we have none.
596 // This is actually very common because of broken build systems that think
597 // they have to run ranlib.
598 if (OldArchive->hasSymbolTable())
599 return;
600
Rafael Espindola8a463522014-10-21 21:56:47 +0000601 performWriteOperation(CreateSymTab, OldArchive, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000602}
603
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000604static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000605 object::Archive *OldArchive,
606 std::vector<NewArchiveIterator> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000607 switch (Operation) {
608 case Print:
609 case DisplayTable:
610 case Extract:
611 performReadOperation(Operation, OldArchive);
612 return;
613
614 case Delete:
615 case Move:
616 case QuickAppend:
617 case ReplaceOrInsert:
Rafael Espindola8a463522014-10-21 21:56:47 +0000618 performWriteOperation(Operation, OldArchive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000619 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000620 case CreateSymTab:
621 createSymbolTable(OldArchive);
622 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000623 }
624 llvm_unreachable("Unknown operation.");
625}
626
Rafael Espindola8a463522014-10-21 21:56:47 +0000627static int performOperation(ArchiveOperation Operation,
628 std::vector<NewArchiveIterator> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000629 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000630 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
631 MemoryBuffer::getFile(ArchiveName, -1, false);
632 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000633 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000634 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000635 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000636 return 1;
637 }
638
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000639 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000640 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000641
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000642 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000643 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000644 << "': " << EC.message() << "!\n";
645 return 1;
646 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000647 performOperation(Operation, &Archive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000648 return 0;
649 }
650
Rafael Espindola2a826e42014-06-13 17:20:48 +0000651 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000652
653 if (!shouldCreateArchive(Operation)) {
654 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
655 } else {
656 if (!Create) {
657 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000658 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000659 }
660 }
661
Rafael Espindola8a463522014-10-21 21:56:47 +0000662 performOperation(Operation, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000663 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000664}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000665
Rafael Espindola8a463522014-10-21 21:56:47 +0000666static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000667 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000668
669 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
670 failIfError(Buf.getError());
671 const MemoryBuffer &Ref = *Buf.get();
672 bool Saved = false;
673 std::vector<NewArchiveIterator> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000674 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
675 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000676
677 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
678 StringRef Line = *I;
679 StringRef CommandStr, Rest;
680 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000681 Rest = Rest.trim();
682 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
683 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000684 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000685 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000686 .Case("addmod", MRICommand::AddMod)
687 .Case("create", MRICommand::Create)
688 .Case("save", MRICommand::Save)
689 .Case("end", MRICommand::End)
690 .Default(MRICommand::Invalid);
691
692 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000693 case MRICommand::AddLib: {
694 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
695 failIfError(BufOrErr.getError(), "Could not open library");
696 ArchiveBuffers.push_back(std::move(*BufOrErr));
697 auto LibOrErr =
698 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
699 failIfError(LibOrErr.getError(), "Could not parse library");
700 Archives.push_back(std::move(*LibOrErr));
701 object::Archive &Lib = *Archives.back();
702 for (auto &Member : Lib.children()) {
703 ErrorOr<StringRef> NameOrErr = Member.getName();
704 failIfError(NameOrErr.getError());
705 addMember(NewMembers, Member, *NameOrErr);
706 }
707 break;
708 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000709 case MRICommand::AddMod:
710 addMember(NewMembers, Rest, sys::path::filename(Rest));
711 break;
712 case MRICommand::Create:
713 Create = true;
714 if (!ArchiveName.empty())
715 fail("Editing multiple archives not supported");
716 if (Saved)
717 fail("File already saved");
718 ArchiveName = Rest;
719 break;
720 case MRICommand::Save:
721 Saved = true;
722 break;
723 case MRICommand::End:
724 break;
725 case MRICommand::Invalid:
726 fail("Unknown command: " + CommandStr);
727 }
728 }
729
730 // Nothing to do if not saved.
731 if (Saved)
732 performOperation(ReplaceOrInsert, &NewMembers);
733 exit(0);
734}
735
Rafael Espindola47ee3392014-11-07 21:33:09 +0000736static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000737 // Do our own parsing of the command line because the CommandLine utility
738 // can't handle the grouped positional parameters without a dash.
739 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000740 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000741}
742
Rafael Espindoladbc04162014-10-22 15:05:51 +0000743static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000744 if (RestOfArgs.size() != 1)
745 fail(ToolName + "takes just one archive as argument");
746 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000747 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000748}
749
750int main(int argc, char **argv) {
751 ToolName = argv[0];
752 // Print a stack trace if we signal out.
753 sys::PrintStackTraceOnErrorSignal();
754 PrettyStackTraceProgram X(argc, argv);
755 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
756
Peter Collingbournebc051632015-06-09 21:50:22 +0000757 llvm::InitializeAllTargetInfos();
758 llvm::InitializeAllTargetMCs();
759 llvm::InitializeAllAsmParsers();
760
761 StringRef Stem = sys::path::stem(ToolName);
762 if (Stem.find("ranlib") == StringRef::npos &&
763 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000764 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000765
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000766 // Have the command line options parsed and handle things
767 // like --help and --version.
768 cl::ParseCommandLineOptions(argc, argv,
769 "LLVM Archiver (llvm-ar)\n\n"
770 " This program archives bitcode files into single libraries\n"
771 );
772
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000773 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola47ee3392014-11-07 21:33:09 +0000774 return ar_main();
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000775 if (Stem.find("ranlib") != StringRef::npos)
776 return ranlib_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000777 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000778}