blob: 6fbfc15380824507ccea0f4e72840374232bbb84 [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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Module.h"
Peter Collingbournebc051632015-06-09 21:50:22 +000018#include "llvm/LibDriver/LibDriver.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000019#include "llvm/Object/Archive.h"
Peter Collingbournefd66a482015-06-08 02:32:01 +000020#include "llvm/Object/ArchiveWriter.h"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000021#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000023#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000024#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000025#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000026#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000027#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000029#include "llvm/Support/Path.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000030#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000031#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000032#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000033#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000035#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000036#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000038
39#if !defined(_MSC_VER) && !defined(__MINGW32__)
40#include <unistd.h>
41#else
42#include <io.h>
43#endif
44
Brian Gaeke960707c2003-11-11 22:41:34 +000045using namespace llvm;
46
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000047// The name this program was invoked as.
48static StringRef ToolName;
49
Rafael Espindola90b85702014-10-21 15:49:46 +000050// Show the error message and exit.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000051LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
52 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000053 exit(1);
54}
55
Rafael Espindola4453e42942014-06-13 03:07:50 +000056static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000057 if (!EC)
58 return;
59
60 std::string ContextStr = Context.str();
61 if (ContextStr == "")
62 fail(EC.message());
63 fail(Context + ": " + EC.message());
64}
65
Rafael Espindola0c8a3522013-08-28 16:22:16 +000066// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000067static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000068 RestOfArgs(cl::Positional, cl::ZeroOrMore,
69 cl::desc("[relpos] [count] <archive-file> [members]..."));
70
71static cl::opt<bool> MRI("M", cl::desc(""));
Tanya Lattner57c70a62003-08-28 15:22:38 +000072
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +000073namespace {
74enum Format { Default, GNU, BSD };
75}
76
77static cl::opt<Format>
78 FormatOpt("format", cl::desc("Archive format to create"),
79 cl::values(clEnumValN(Default, "defalut", "default"),
80 clEnumValN(GNU, "gnu", "gnu"),
81 clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
82
Rafael Espindola0c8a3522013-08-28 16:22:16 +000083std::string Options;
84
Rafael Espindola90b85702014-10-21 15:49:46 +000085// Provide additional help output explaining the operations and modifiers of
86// llvm-ar. This object instructs the CommandLine library to print the text of
87// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +000088static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000089 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000090 " d[NsS] - delete file(s) from the archive\n"
91 " m[abiSs] - move file(s) in the archive\n"
92 " p[kN] - print file(s) found in the archive\n"
93 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000094 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000095 " t - display contents of archive\n"
96 " x[No] - extract file(s) from the archive\n"
97 "\nMODIFIERS (operation specific):\n"
98 " [a] - put file(s) after [relpos]\n"
99 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000100 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000101 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000102 " [s] - create an archive index (cf. ranlib)\n"
103 " [S] - do not build a symbol table\n"
104 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000105 "\nMODIFIERS (generic):\n"
106 " [c] - do not warn if the library had to be created\n"
107 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000108);
109
Reid Spencer84a12bf2004-11-14 22:20:07 +0000110// This enumeration delineates the kinds of operations on an archive
111// that are permitted.
112enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000113 Print, ///< Print the contents of the archive
114 Delete, ///< Delete the specified members
115 Move, ///< Move members to end or as given by {a,b,i} modifiers
116 QuickAppend, ///< Quickly append to end of archive
117 ReplaceOrInsert, ///< Replace or Insert members
118 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000119 Extract, ///< Extract files back to file system
120 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000121};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000122
Reid Spencer84a12bf2004-11-14 22:20:07 +0000123// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000124static bool AddAfter = false; ///< 'a' modifier
125static bool AddBefore = false; ///< 'b' modifier
126static bool Create = false; ///< 'c' modifier
127static bool OriginalDates = false; ///< 'o' modifier
128static bool OnlyUpdate = false; ///< 'u' modifier
129static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000130static bool Symtab = true; ///< 's' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000131
Reid Spencer84a12bf2004-11-14 22:20:07 +0000132// Relative Positional Argument (for insert/move). This variable holds
133// the name of the archive member to which the 'a', 'b' or 'i' modifier
134// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
135// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000136static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000137
Reid Spencer84a12bf2004-11-14 22:20:07 +0000138// This variable holds the name of the archive file as given on the
139// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000140static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000141
Reid Spencer84a12bf2004-11-14 22:20:07 +0000142// This variable holds the list of member files to proecess, as given
143// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000144static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000145
Rafael Espindola90b85702014-10-21 15:49:46 +0000146// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000147LLVM_ATTRIBUTE_NORETURN static void
148show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000149 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000150 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000151 std::exit(1);
152}
153
Rafael Espindola90b85702014-10-21 15:49:46 +0000154// Extract the member filename from the command line for the [relpos] argument
155// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000156static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000157 if(RestOfArgs.size() == 0)
158 show_help("Expected [relpos] for a, b, or i modifier");
159 RelPos = RestOfArgs[0];
160 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000161}
162
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000163static void getOptions() {
164 if(RestOfArgs.size() == 0)
165 show_help("Expected options");
166 Options = RestOfArgs[0];
167 RestOfArgs.erase(RestOfArgs.begin());
168}
169
Rafael Espindola90b85702014-10-21 15:49:46 +0000170// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000171static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000172 if(RestOfArgs.size() == 0)
173 show_help("An archive name must be specified");
174 ArchiveName = RestOfArgs[0];
175 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000176}
177
Rafael Espindola90b85702014-10-21 15:49:46 +0000178// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000179static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000180 for (auto &Arg : RestOfArgs)
181 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000182}
183
Rafael Espindola8a463522014-10-21 21:56:47 +0000184static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000185
Rafael Espindola90b85702014-10-21 15:49:46 +0000186// Parse the command line options as presented and return the operation
187// specified. Process all modifiers and check to make sure that constraints on
188// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000189static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000190 if (MRI) {
191 if (!RestOfArgs.empty())
192 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000193 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000194 }
195
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000196 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000197
Reid Spencer84a12bf2004-11-14 22:20:07 +0000198 // Keep track of number of operations. We can only specify one
199 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000200 unsigned NumOperations = 0;
201
Reid Spencer84a12bf2004-11-14 22:20:07 +0000202 // Keep track of the number of positional modifiers (a,b,i). Only
203 // one can be specified.
204 unsigned NumPositional = 0;
205
206 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000207 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000208
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000209 bool MaybeJustCreateSymTab = false;
210
Tanya Lattnerc970a382003-12-06 23:01:25 +0000211 for(unsigned i=0; i<Options.size(); ++i) {
212 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000213 case 'd': ++NumOperations; Operation = Delete; break;
214 case 'm': ++NumOperations; Operation = Move ; break;
215 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000216 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000217 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000218 case 't': ++NumOperations; Operation = DisplayTable; break;
219 case 'x': ++NumOperations; Operation = Extract; break;
220 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000221 case 'l': /* accepted but unused */ break;
222 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000223 case 's':
224 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000225 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000226 break;
227 case 'S':
228 Symtab = false;
229 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000230 case 'u': OnlyUpdate = true; break;
231 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000232 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000233 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000234 AddAfter = true;
235 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000236 break;
237 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000238 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000239 AddBefore = true;
240 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000241 break;
242 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000243 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000244 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000245 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000246 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000247 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000248 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000249 }
250 }
251
Misha Brukman650ba8e2005-04-22 00:00:37 +0000252 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000253 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000254 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000255
256 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000257 getMembers();
258
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000259 if (NumOperations == 0 && MaybeJustCreateSymTab) {
260 NumOperations = 1;
261 Operation = CreateSymTab;
262 if (!Members.empty())
263 show_help("The s operation takes only an archive as argument");
264 }
265
Reid Spencer84a12bf2004-11-14 22:20:07 +0000266 // Perform various checks on the operation/modifier specification
267 // to make sure we are dealing with a legal request.
268 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000269 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000270 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000271 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000272 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000273 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000274 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000275 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000276 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
277 "the 'm' or 'r' operations");
278 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000279 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000280 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000281 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000282 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000283
284 // Return the parsed operation to the caller
285 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000286}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000287
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000288// Implements the 'p' operation. This function traverses the archive
289// looking for members that match the path list.
290static void doPrint(StringRef Name, object::Archive::child_iterator I) {
291 if (Verbose)
292 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000293
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000294 StringRef Data = I->getBuffer();
295 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000296}
297
Rafael Espindola90b85702014-10-21 15:49:46 +0000298// Utility function for printing out the file mode when the 't' operation is in
299// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000300static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000301 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000302 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000303 else
Chris Lattner2907f442010-11-29 23:02:20 +0000304 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000305 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000306 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000307 else
Chris Lattner2907f442010-11-29 23:02:20 +0000308 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000309 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000310 outs() << "x";
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}
314
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000315// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000316// the file names of each of the members. However, if verbose mode is requested
317// ('v' modifier) then the file type, permission mode, user, group, size, and
318// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000319static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
320 if (Verbose) {
321 sys::fs::perms Mode = I->getAccessMode();
322 printMode((Mode >> 6) & 007);
323 printMode((Mode >> 3) & 007);
324 printMode(Mode & 007);
325 outs() << ' ' << I->getUID();
326 outs() << '/' << I->getGID();
327 outs() << ' ' << format("%6llu", I->getSize());
328 outs() << ' ' << I->getLastModified().str();
329 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000330 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000331 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000332}
333
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000334// Implement the 'x' operation. This function extracts files back to the file
335// system.
336static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000337 // Retain the original mode.
338 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000339 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000340
Rafael Espindola6d354812013-07-16 19:44:17 +0000341 int FD;
342 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000343 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000344 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000345
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000346 {
347 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000348
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000349 // Get the data and its length
350 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000351
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000352 // Write the data.
353 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000354 }
355
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000356 // If we're supposed to retain the original modification times, etc. do so
357 // now.
358 if (OriginalDates)
359 failIfError(
360 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000361
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000362 if (close(FD))
363 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000364}
365
Rafael Espindola05571532013-07-12 16:29:27 +0000366static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000367 switch (Op) {
368 case Print:
369 case Delete:
370 case Move:
371 case DisplayTable:
372 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000373 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000374 return false;
375
376 case QuickAppend:
377 case ReplaceOrInsert:
378 return true;
379 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000380
381 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000382}
383
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000384static void performReadOperation(ArchiveOperation Operation,
385 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000386 for (object::Archive::child_iterator I = OldArchive->child_begin(),
387 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000388 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000389 ErrorOr<StringRef> NameOrErr = I->getName();
390 failIfError(NameOrErr.getError());
391 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000392
393 if (!Members.empty() &&
394 std::find(Members.begin(), Members.end(), Name) == Members.end())
395 continue;
396
397 switch (Operation) {
398 default:
399 llvm_unreachable("Not a read operation");
400 case Print:
401 doPrint(Name, I);
402 break;
403 case DisplayTable:
404 doDisplayTable(Name, I);
405 break;
406 case Extract:
407 doExtract(Name, I);
408 break;
409 }
410 }
411}
412
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000413template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000414void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
415 int Pos = -1) {
416 NewArchiveIterator NI(I, Name);
417 if (Pos == -1)
418 Members.push_back(NI);
419 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000420 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000421}
422
Rafael Espindola623c3d82013-07-22 15:11:51 +0000423enum InsertAction {
424 IA_AddOldMember,
425 IA_AddNewMeber,
426 IA_Delete,
427 IA_MoveOldMember,
428 IA_MoveNewMember
429};
430
Rafael Espindola76619702014-10-21 21:47:27 +0000431static InsertAction computeInsertAction(ArchiveOperation Operation,
432 object::Archive::child_iterator I,
433 StringRef Name,
434 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000435 if (Operation == QuickAppend || Members.empty())
436 return IA_AddOldMember;
437
Rafael Espindola76619702014-10-21 21:47:27 +0000438 auto MI =
439 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
440 return Name == sys::path::filename(Path);
441 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000442
443 if (MI == Members.end())
444 return IA_AddOldMember;
445
446 Pos = MI;
447
448 if (Operation == Delete)
449 return IA_Delete;
450
451 if (Operation == Move)
452 return IA_MoveOldMember;
453
454 if (Operation == ReplaceOrInsert) {
455 StringRef PosName = sys::path::filename(RelPos);
456 if (!OnlyUpdate) {
457 if (PosName.empty())
458 return IA_AddNewMeber;
459 return IA_MoveNewMember;
460 }
461
462 // We could try to optimize this to a fstat, but it is not a common
463 // operation.
464 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000465 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000466 if (Status.getLastModificationTime() < I->getLastModified()) {
467 if (PosName.empty())
468 return IA_AddOldMember;
469 return IA_MoveOldMember;
470 }
471
472 if (PosName.empty())
473 return IA_AddNewMeber;
474 return IA_MoveNewMember;
475 }
476 llvm_unreachable("No such operation");
477}
478
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000479// We have to walk this twice and computing it is not trivial, so creating an
480// explicit std::vector is actually fairly efficient.
481static std::vector<NewArchiveIterator>
482computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000483 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000484 std::vector<NewArchiveIterator> Ret;
485 std::vector<NewArchiveIterator> Moved;
486 int InsertPos = -1;
487 StringRef PosName = sys::path::filename(RelPos);
488 if (OldArchive) {
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000489 for (auto &Child : OldArchive->children()) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000490 int Pos = Ret.size();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000491 ErrorOr<StringRef> NameOrErr = Child.getName();
Rafael Espindolaae460022014-06-16 16:08:36 +0000492 failIfError(NameOrErr.getError());
493 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000494 if (Name == PosName) {
495 assert(AddAfter || AddBefore);
496 if (AddBefore)
497 InsertPos = Pos;
498 else
499 InsertPos = Pos + 1;
500 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000501
Rafael Espindola76619702014-10-21 21:47:27 +0000502 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000503 InsertAction Action =
504 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000505 switch (Action) {
506 case IA_AddOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000507 addMember(Ret, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000508 break;
509 case IA_AddNewMeber:
Rafael Espindola76619702014-10-21 21:47:27 +0000510 addMember(Ret, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000511 break;
512 case IA_Delete:
513 break;
514 case IA_MoveOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000515 addMember(Moved, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000516 break;
517 case IA_MoveNewMember:
Rafael Espindola76619702014-10-21 21:47:27 +0000518 addMember(Moved, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000519 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000520 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000521 if (MemberI != Members.end())
522 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000523 }
524 }
525
526 if (Operation == Delete)
527 return Ret;
528
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000529 if (!RelPos.empty() && InsertPos == -1)
530 fail("Insertion point not found");
531
Rafael Espindola623c3d82013-07-22 15:11:51 +0000532 if (RelPos.empty())
533 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000534
Rafael Espindola623c3d82013-07-22 15:11:51 +0000535 assert(unsigned(InsertPos) <= Ret.size());
536 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000537
Rafael Espindolac91177e2015-07-08 22:15:07 +0000538 Ret.insert(Ret.begin() + InsertPos, Members.size(),
539 NewArchiveIterator("", ""));
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000540 int Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000541 for (auto &Member : Members) {
542 StringRef Name = sys::path::filename(Member);
Rafael Espindola76619702014-10-21 21:47:27 +0000543 addMember(Ret, Member, Name, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000544 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000545 }
546
547 return Ret;
548}
549
Rafael Espindola8a463522014-10-21 21:56:47 +0000550static void
551performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
552 std::vector<NewArchiveIterator> *NewMembersP) {
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000553 object::Archive::Kind Kind;
554 switch (FormatOpt) {
555 case Default:
556 // FIXME: change as the support for other formats improve.
557 Kind = object::Archive::K_GNU;
558 case GNU:
559 Kind = object::Archive::K_GNU;
560 break;
561 case BSD:
562 Kind = object::Archive::K_BSD;
563 break;
564 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000565 if (NewMembersP) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000566 std::pair<StringRef, std::error_code> Result =
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000567 writeArchive(ArchiveName, *NewMembersP, Symtab, Kind);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000568 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000569 return;
570 }
571 std::vector<NewArchiveIterator> NewMembers =
572 computeNewArchiveMembers(Operation, OldArchive);
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000573 auto Result = writeArchive(ArchiveName, NewMembers, Symtab, Kind);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000574 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000575}
576
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000577static void createSymbolTable(object::Archive *OldArchive) {
578 // When an archive is created or modified, if the s option is given, the
579 // resulting archive will have a current symbol table. If the S option
580 // is given, it will have no symbol table.
581 // In summary, we only need to update the symbol table if we have none.
582 // This is actually very common because of broken build systems that think
583 // they have to run ranlib.
584 if (OldArchive->hasSymbolTable())
585 return;
586
Rafael Espindola8a463522014-10-21 21:56:47 +0000587 performWriteOperation(CreateSymTab, OldArchive, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000588}
589
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000590static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000591 object::Archive *OldArchive,
592 std::vector<NewArchiveIterator> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000593 switch (Operation) {
594 case Print:
595 case DisplayTable:
596 case Extract:
597 performReadOperation(Operation, OldArchive);
598 return;
599
600 case Delete:
601 case Move:
602 case QuickAppend:
603 case ReplaceOrInsert:
Rafael Espindola8a463522014-10-21 21:56:47 +0000604 performWriteOperation(Operation, OldArchive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000605 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000606 case CreateSymTab:
607 createSymbolTable(OldArchive);
608 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000609 }
610 llvm_unreachable("Unknown operation.");
611}
612
Rafael Espindola8a463522014-10-21 21:56:47 +0000613static int performOperation(ArchiveOperation Operation,
614 std::vector<NewArchiveIterator> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000615 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000616 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
617 MemoryBuffer::getFile(ArchiveName, -1, false);
618 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000619 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000620 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000621 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000622 return 1;
623 }
624
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000625 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000626 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000627
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000628 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000629 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000630 << "': " << EC.message() << "!\n";
631 return 1;
632 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000633 performOperation(Operation, &Archive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000634 return 0;
635 }
636
Rafael Espindola2a826e42014-06-13 17:20:48 +0000637 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000638
639 if (!shouldCreateArchive(Operation)) {
640 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
641 } else {
642 if (!Create) {
643 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000644 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000645 }
646 }
647
Rafael Espindola8a463522014-10-21 21:56:47 +0000648 performOperation(Operation, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000649 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000650}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000651
Rafael Espindola8a463522014-10-21 21:56:47 +0000652static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000653 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000654
655 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
656 failIfError(Buf.getError());
657 const MemoryBuffer &Ref = *Buf.get();
658 bool Saved = false;
659 std::vector<NewArchiveIterator> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000660 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
661 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000662
663 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
664 StringRef Line = *I;
665 StringRef CommandStr, Rest;
666 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000667 Rest = Rest.trim();
668 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
669 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000670 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000671 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000672 .Case("addmod", MRICommand::AddMod)
673 .Case("create", MRICommand::Create)
674 .Case("save", MRICommand::Save)
675 .Case("end", MRICommand::End)
676 .Default(MRICommand::Invalid);
677
678 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000679 case MRICommand::AddLib: {
680 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
681 failIfError(BufOrErr.getError(), "Could not open library");
682 ArchiveBuffers.push_back(std::move(*BufOrErr));
683 auto LibOrErr =
684 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
685 failIfError(LibOrErr.getError(), "Could not parse library");
686 Archives.push_back(std::move(*LibOrErr));
687 object::Archive &Lib = *Archives.back();
688 for (auto &Member : Lib.children()) {
689 ErrorOr<StringRef> NameOrErr = Member.getName();
690 failIfError(NameOrErr.getError());
691 addMember(NewMembers, Member, *NameOrErr);
692 }
693 break;
694 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000695 case MRICommand::AddMod:
696 addMember(NewMembers, Rest, sys::path::filename(Rest));
697 break;
698 case MRICommand::Create:
699 Create = true;
700 if (!ArchiveName.empty())
701 fail("Editing multiple archives not supported");
702 if (Saved)
703 fail("File already saved");
704 ArchiveName = Rest;
705 break;
706 case MRICommand::Save:
707 Saved = true;
708 break;
709 case MRICommand::End:
710 break;
711 case MRICommand::Invalid:
712 fail("Unknown command: " + CommandStr);
713 }
714 }
715
716 // Nothing to do if not saved.
717 if (Saved)
718 performOperation(ReplaceOrInsert, &NewMembers);
719 exit(0);
720}
721
Rafael Espindola47ee3392014-11-07 21:33:09 +0000722static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000723 // Do our own parsing of the command line because the CommandLine utility
724 // can't handle the grouped positional parameters without a dash.
725 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000726 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000727}
728
Rafael Espindoladbc04162014-10-22 15:05:51 +0000729static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000730 if (RestOfArgs.size() != 1)
731 fail(ToolName + "takes just one archive as argument");
732 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000733 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000734}
735
736int main(int argc, char **argv) {
737 ToolName = argv[0];
738 // Print a stack trace if we signal out.
739 sys::PrintStackTraceOnErrorSignal();
740 PrettyStackTraceProgram X(argc, argv);
741 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
742
Peter Collingbournebc051632015-06-09 21:50:22 +0000743 llvm::InitializeAllTargetInfos();
744 llvm::InitializeAllTargetMCs();
745 llvm::InitializeAllAsmParsers();
746
747 StringRef Stem = sys::path::stem(ToolName);
748 if (Stem.find("ranlib") == StringRef::npos &&
749 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000750 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000751
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000752 // Have the command line options parsed and handle things
753 // like --help and --version.
754 cl::ParseCommandLineOptions(argc, argv,
755 "LLVM Archiver (llvm-ar)\n\n"
756 " This program archives bitcode files into single libraries\n"
757 );
758
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000759 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola47ee3392014-11-07 21:33:09 +0000760 return ar_main();
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000761 if (Stem.find("ranlib") != StringRef::npos)
762 return ranlib_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000763 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000764}