blob: 6782b9c126abc0ae248102333c8e84d91e9b3fa9 [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 Espindola0c8a3522013-08-28 16:22:16 +000073std::string Options;
74
Rafael Espindola90b85702014-10-21 15:49:46 +000075// Provide additional help output explaining the operations and modifiers of
76// llvm-ar. This object instructs the CommandLine library to print the text of
77// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +000078static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000079 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000080 " d[NsS] - delete file(s) from the archive\n"
81 " m[abiSs] - move file(s) in the archive\n"
82 " p[kN] - print file(s) found in the archive\n"
83 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000084 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000085 " t - display contents of archive\n"
86 " x[No] - extract file(s) from the archive\n"
87 "\nMODIFIERS (operation specific):\n"
88 " [a] - put file(s) after [relpos]\n"
89 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000090 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000091 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000092 " [s] - create an archive index (cf. ranlib)\n"
93 " [S] - do not build a symbol table\n"
94 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000095 "\nMODIFIERS (generic):\n"
96 " [c] - do not warn if the library had to be created\n"
97 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000098);
99
Reid Spencer84a12bf2004-11-14 22:20:07 +0000100// This enumeration delineates the kinds of operations on an archive
101// that are permitted.
102enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000103 Print, ///< Print the contents of the archive
104 Delete, ///< Delete the specified members
105 Move, ///< Move members to end or as given by {a,b,i} modifiers
106 QuickAppend, ///< Quickly append to end of archive
107 ReplaceOrInsert, ///< Replace or Insert members
108 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000109 Extract, ///< Extract files back to file system
110 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000111};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000112
Reid Spencer84a12bf2004-11-14 22:20:07 +0000113// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000114static bool AddAfter = false; ///< 'a' modifier
115static bool AddBefore = false; ///< 'b' modifier
116static bool Create = false; ///< 'c' modifier
117static bool OriginalDates = false; ///< 'o' modifier
118static bool OnlyUpdate = false; ///< 'u' modifier
119static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000120static bool Symtab = true; ///< 's' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000121
Reid Spencer84a12bf2004-11-14 22:20:07 +0000122// Relative Positional Argument (for insert/move). This variable holds
123// the name of the archive member to which the 'a', 'b' or 'i' modifier
124// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
125// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000126static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000127
Reid Spencer84a12bf2004-11-14 22:20:07 +0000128// This variable holds the name of the archive file as given on the
129// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000130static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000131
Reid Spencer84a12bf2004-11-14 22:20:07 +0000132// This variable holds the list of member files to proecess, as given
133// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000134static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000135
Rafael Espindola90b85702014-10-21 15:49:46 +0000136// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000137LLVM_ATTRIBUTE_NORETURN static void
138show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000139 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000140 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000141 std::exit(1);
142}
143
Rafael Espindola90b85702014-10-21 15:49:46 +0000144// Extract the member filename from the command line for the [relpos] argument
145// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000146static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000147 if(RestOfArgs.size() == 0)
148 show_help("Expected [relpos] for a, b, or i modifier");
149 RelPos = RestOfArgs[0];
150 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000151}
152
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000153static void getOptions() {
154 if(RestOfArgs.size() == 0)
155 show_help("Expected options");
156 Options = RestOfArgs[0];
157 RestOfArgs.erase(RestOfArgs.begin());
158}
159
Rafael Espindola90b85702014-10-21 15:49:46 +0000160// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000161static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000162 if(RestOfArgs.size() == 0)
163 show_help("An archive name must be specified");
164 ArchiveName = RestOfArgs[0];
165 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000166}
167
Rafael Espindola90b85702014-10-21 15:49:46 +0000168// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000169static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000170 for (auto &Arg : RestOfArgs)
171 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000172}
173
Rafael Espindola8a463522014-10-21 21:56:47 +0000174static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000175
Rafael Espindola90b85702014-10-21 15:49:46 +0000176// Parse the command line options as presented and return the operation
177// specified. Process all modifiers and check to make sure that constraints on
178// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000179static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000180 if (MRI) {
181 if (!RestOfArgs.empty())
182 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000183 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000184 }
185
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000186 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000187
Reid Spencer84a12bf2004-11-14 22:20:07 +0000188 // Keep track of number of operations. We can only specify one
189 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000190 unsigned NumOperations = 0;
191
Reid Spencer84a12bf2004-11-14 22:20:07 +0000192 // Keep track of the number of positional modifiers (a,b,i). Only
193 // one can be specified.
194 unsigned NumPositional = 0;
195
196 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000197 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000198
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000199 bool MaybeJustCreateSymTab = false;
200
Tanya Lattnerc970a382003-12-06 23:01:25 +0000201 for(unsigned i=0; i<Options.size(); ++i) {
202 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000203 case 'd': ++NumOperations; Operation = Delete; break;
204 case 'm': ++NumOperations; Operation = Move ; break;
205 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000206 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000207 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000208 case 't': ++NumOperations; Operation = DisplayTable; break;
209 case 'x': ++NumOperations; Operation = Extract; break;
210 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000211 case 'l': /* accepted but unused */ break;
212 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000213 case 's':
214 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000215 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000216 break;
217 case 'S':
218 Symtab = false;
219 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000220 case 'u': OnlyUpdate = true; break;
221 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000222 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000223 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000224 AddAfter = true;
225 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000226 break;
227 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000228 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000229 AddBefore = true;
230 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000231 break;
232 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000233 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000234 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000235 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000236 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000237 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000238 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000239 }
240 }
241
Misha Brukman650ba8e2005-04-22 00:00:37 +0000242 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000243 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000244 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000245
246 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000247 getMembers();
248
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000249 if (NumOperations == 0 && MaybeJustCreateSymTab) {
250 NumOperations = 1;
251 Operation = CreateSymTab;
252 if (!Members.empty())
253 show_help("The s operation takes only an archive as argument");
254 }
255
Reid Spencer84a12bf2004-11-14 22:20:07 +0000256 // Perform various checks on the operation/modifier specification
257 // to make sure we are dealing with a legal request.
258 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000259 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000260 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000261 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000262 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000263 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000264 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000265 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000266 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
267 "the 'm' or 'r' operations");
268 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000269 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000270 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000271 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000272 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000273
274 // Return the parsed operation to the caller
275 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000276}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000277
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000278// Implements the 'p' operation. This function traverses the archive
279// looking for members that match the path list.
280static void doPrint(StringRef Name, object::Archive::child_iterator I) {
281 if (Verbose)
282 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000283
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000284 StringRef Data = I->getBuffer();
285 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000286}
287
Rafael Espindola90b85702014-10-21 15:49:46 +0000288// Utility function for printing out the file mode when the 't' operation is in
289// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000290static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000291 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000292 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000293 else
Chris Lattner2907f442010-11-29 23:02:20 +0000294 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000295 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000296 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000297 else
Chris Lattner2907f442010-11-29 23:02:20 +0000298 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000299 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000300 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000301 else
Chris Lattner2907f442010-11-29 23:02:20 +0000302 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000303}
304
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000305// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000306// the file names of each of the members. However, if verbose mode is requested
307// ('v' modifier) then the file type, permission mode, user, group, size, and
308// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000309static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
310 if (Verbose) {
311 sys::fs::perms Mode = I->getAccessMode();
312 printMode((Mode >> 6) & 007);
313 printMode((Mode >> 3) & 007);
314 printMode(Mode & 007);
315 outs() << ' ' << I->getUID();
316 outs() << '/' << I->getGID();
317 outs() << ' ' << format("%6llu", I->getSize());
318 outs() << ' ' << I->getLastModified().str();
319 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000320 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000321 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000322}
323
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000324// Implement the 'x' operation. This function extracts files back to the file
325// system.
326static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000327 // Retain the original mode.
328 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000329 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000330
Rafael Espindola6d354812013-07-16 19:44:17 +0000331 int FD;
332 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000333 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000334 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000335
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000336 {
337 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000338
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000339 // Get the data and its length
340 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000341
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000342 // Write the data.
343 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000344 }
345
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000346 // If we're supposed to retain the original modification times, etc. do so
347 // now.
348 if (OriginalDates)
349 failIfError(
350 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000351
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000352 if (close(FD))
353 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000354}
355
Rafael Espindola05571532013-07-12 16:29:27 +0000356static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000357 switch (Op) {
358 case Print:
359 case Delete:
360 case Move:
361 case DisplayTable:
362 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000363 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000364 return false;
365
366 case QuickAppend:
367 case ReplaceOrInsert:
368 return true;
369 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000370
371 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000372}
373
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000374static void performReadOperation(ArchiveOperation Operation,
375 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000376 for (object::Archive::child_iterator I = OldArchive->child_begin(),
377 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000378 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000379 ErrorOr<StringRef> NameOrErr = I->getName();
380 failIfError(NameOrErr.getError());
381 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000382
383 if (!Members.empty() &&
384 std::find(Members.begin(), Members.end(), Name) == Members.end())
385 continue;
386
387 switch (Operation) {
388 default:
389 llvm_unreachable("Not a read operation");
390 case Print:
391 doPrint(Name, I);
392 break;
393 case DisplayTable:
394 doDisplayTable(Name, I);
395 break;
396 case Extract:
397 doExtract(Name, I);
398 break;
399 }
400 }
401}
402
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000403template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000404void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
405 int Pos = -1) {
406 NewArchiveIterator NI(I, Name);
407 if (Pos == -1)
408 Members.push_back(NI);
409 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000410 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000411}
412
Rafael Espindola623c3d82013-07-22 15:11:51 +0000413enum InsertAction {
414 IA_AddOldMember,
415 IA_AddNewMeber,
416 IA_Delete,
417 IA_MoveOldMember,
418 IA_MoveNewMember
419};
420
Rafael Espindola76619702014-10-21 21:47:27 +0000421static InsertAction computeInsertAction(ArchiveOperation Operation,
422 object::Archive::child_iterator I,
423 StringRef Name,
424 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000425 if (Operation == QuickAppend || Members.empty())
426 return IA_AddOldMember;
427
Rafael Espindola76619702014-10-21 21:47:27 +0000428 auto MI =
429 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
430 return Name == sys::path::filename(Path);
431 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000432
433 if (MI == Members.end())
434 return IA_AddOldMember;
435
436 Pos = MI;
437
438 if (Operation == Delete)
439 return IA_Delete;
440
441 if (Operation == Move)
442 return IA_MoveOldMember;
443
444 if (Operation == ReplaceOrInsert) {
445 StringRef PosName = sys::path::filename(RelPos);
446 if (!OnlyUpdate) {
447 if (PosName.empty())
448 return IA_AddNewMeber;
449 return IA_MoveNewMember;
450 }
451
452 // We could try to optimize this to a fstat, but it is not a common
453 // operation.
454 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000455 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000456 if (Status.getLastModificationTime() < I->getLastModified()) {
457 if (PosName.empty())
458 return IA_AddOldMember;
459 return IA_MoveOldMember;
460 }
461
462 if (PosName.empty())
463 return IA_AddNewMeber;
464 return IA_MoveNewMember;
465 }
466 llvm_unreachable("No such operation");
467}
468
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000469// We have to walk this twice and computing it is not trivial, so creating an
470// explicit std::vector is actually fairly efficient.
471static std::vector<NewArchiveIterator>
472computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000473 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000474 std::vector<NewArchiveIterator> Ret;
475 std::vector<NewArchiveIterator> Moved;
476 int InsertPos = -1;
477 StringRef PosName = sys::path::filename(RelPos);
478 if (OldArchive) {
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000479 for (auto &Child : OldArchive->children()) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000480 int Pos = Ret.size();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000481 ErrorOr<StringRef> NameOrErr = Child.getName();
Rafael Espindolaae460022014-06-16 16:08:36 +0000482 failIfError(NameOrErr.getError());
483 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000484 if (Name == PosName) {
485 assert(AddAfter || AddBefore);
486 if (AddBefore)
487 InsertPos = Pos;
488 else
489 InsertPos = Pos + 1;
490 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000491
Rafael Espindola76619702014-10-21 21:47:27 +0000492 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000493 InsertAction Action =
494 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000495 switch (Action) {
496 case IA_AddOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000497 addMember(Ret, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000498 break;
499 case IA_AddNewMeber:
Rafael Espindola76619702014-10-21 21:47:27 +0000500 addMember(Ret, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000501 break;
502 case IA_Delete:
503 break;
504 case IA_MoveOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000505 addMember(Moved, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000506 break;
507 case IA_MoveNewMember:
Rafael Espindola76619702014-10-21 21:47:27 +0000508 addMember(Moved, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000509 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000510 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000511 if (MemberI != Members.end())
512 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000513 }
514 }
515
516 if (Operation == Delete)
517 return Ret;
518
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000519 if (!RelPos.empty() && InsertPos == -1)
520 fail("Insertion point not found");
521
Rafael Espindola623c3d82013-07-22 15:11:51 +0000522 if (RelPos.empty())
523 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000524
Rafael Espindola623c3d82013-07-22 15:11:51 +0000525 assert(unsigned(InsertPos) <= Ret.size());
526 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000527
Rafael Espindola623c3d82013-07-22 15:11:51 +0000528 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000529 int Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000530 for (auto &Member : Members) {
531 StringRef Name = sys::path::filename(Member);
Rafael Espindola76619702014-10-21 21:47:27 +0000532 addMember(Ret, Member, Name, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000533 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000534 }
535
536 return Ret;
537}
538
Rafael Espindola8a463522014-10-21 21:56:47 +0000539static void
540performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
541 std::vector<NewArchiveIterator> *NewMembersP) {
542 if (NewMembersP) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000543 std::pair<StringRef, std::error_code> Result =
544 writeArchive(ArchiveName, *NewMembersP, Symtab);
545 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000546 return;
547 }
548 std::vector<NewArchiveIterator> NewMembers =
549 computeNewArchiveMembers(Operation, OldArchive);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000550 auto Result = writeArchive(ArchiveName, NewMembers, Symtab);
551 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000552}
553
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000554static void createSymbolTable(object::Archive *OldArchive) {
555 // When an archive is created or modified, if the s option is given, the
556 // resulting archive will have a current symbol table. If the S option
557 // is given, it will have no symbol table.
558 // In summary, we only need to update the symbol table if we have none.
559 // This is actually very common because of broken build systems that think
560 // they have to run ranlib.
561 if (OldArchive->hasSymbolTable())
562 return;
563
Rafael Espindola8a463522014-10-21 21:56:47 +0000564 performWriteOperation(CreateSymTab, OldArchive, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000565}
566
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000567static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000568 object::Archive *OldArchive,
569 std::vector<NewArchiveIterator> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000570 switch (Operation) {
571 case Print:
572 case DisplayTable:
573 case Extract:
574 performReadOperation(Operation, OldArchive);
575 return;
576
577 case Delete:
578 case Move:
579 case QuickAppend:
580 case ReplaceOrInsert:
Rafael Espindola8a463522014-10-21 21:56:47 +0000581 performWriteOperation(Operation, OldArchive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000582 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000583 case CreateSymTab:
584 createSymbolTable(OldArchive);
585 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000586 }
587 llvm_unreachable("Unknown operation.");
588}
589
Rafael Espindola8a463522014-10-21 21:56:47 +0000590static int performOperation(ArchiveOperation Operation,
591 std::vector<NewArchiveIterator> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000592 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000593 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
594 MemoryBuffer::getFile(ArchiveName, -1, false);
595 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000596 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000597 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000598 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000599 return 1;
600 }
601
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000602 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000603 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000604
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000605 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000606 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000607 << "': " << EC.message() << "!\n";
608 return 1;
609 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000610 performOperation(Operation, &Archive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000611 return 0;
612 }
613
Rafael Espindola2a826e42014-06-13 17:20:48 +0000614 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000615
616 if (!shouldCreateArchive(Operation)) {
617 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
618 } else {
619 if (!Create) {
620 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000621 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000622 }
623 }
624
Rafael Espindola8a463522014-10-21 21:56:47 +0000625 performOperation(Operation, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000626 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000627}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000628
Rafael Espindola8a463522014-10-21 21:56:47 +0000629static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000630 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000631
632 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
633 failIfError(Buf.getError());
634 const MemoryBuffer &Ref = *Buf.get();
635 bool Saved = false;
636 std::vector<NewArchiveIterator> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000637 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
638 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000639
640 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
641 StringRef Line = *I;
642 StringRef CommandStr, Rest;
643 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000644 Rest = Rest.trim();
645 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
646 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000647 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000648 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000649 .Case("addmod", MRICommand::AddMod)
650 .Case("create", MRICommand::Create)
651 .Case("save", MRICommand::Save)
652 .Case("end", MRICommand::End)
653 .Default(MRICommand::Invalid);
654
655 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000656 case MRICommand::AddLib: {
657 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
658 failIfError(BufOrErr.getError(), "Could not open library");
659 ArchiveBuffers.push_back(std::move(*BufOrErr));
660 auto LibOrErr =
661 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
662 failIfError(LibOrErr.getError(), "Could not parse library");
663 Archives.push_back(std::move(*LibOrErr));
664 object::Archive &Lib = *Archives.back();
665 for (auto &Member : Lib.children()) {
666 ErrorOr<StringRef> NameOrErr = Member.getName();
667 failIfError(NameOrErr.getError());
668 addMember(NewMembers, Member, *NameOrErr);
669 }
670 break;
671 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000672 case MRICommand::AddMod:
673 addMember(NewMembers, Rest, sys::path::filename(Rest));
674 break;
675 case MRICommand::Create:
676 Create = true;
677 if (!ArchiveName.empty())
678 fail("Editing multiple archives not supported");
679 if (Saved)
680 fail("File already saved");
681 ArchiveName = Rest;
682 break;
683 case MRICommand::Save:
684 Saved = true;
685 break;
686 case MRICommand::End:
687 break;
688 case MRICommand::Invalid:
689 fail("Unknown command: " + CommandStr);
690 }
691 }
692
693 // Nothing to do if not saved.
694 if (Saved)
695 performOperation(ReplaceOrInsert, &NewMembers);
696 exit(0);
697}
698
Rafael Espindola47ee3392014-11-07 21:33:09 +0000699static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000700 // Do our own parsing of the command line because the CommandLine utility
701 // can't handle the grouped positional parameters without a dash.
702 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000703 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000704}
705
Rafael Espindoladbc04162014-10-22 15:05:51 +0000706static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000707 if (RestOfArgs.size() != 1)
708 fail(ToolName + "takes just one archive as argument");
709 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000710 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000711}
712
713int main(int argc, char **argv) {
714 ToolName = argv[0];
715 // Print a stack trace if we signal out.
716 sys::PrintStackTraceOnErrorSignal();
717 PrettyStackTraceProgram X(argc, argv);
718 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
719
Peter Collingbournebc051632015-06-09 21:50:22 +0000720 llvm::InitializeAllTargetInfos();
721 llvm::InitializeAllTargetMCs();
722 llvm::InitializeAllAsmParsers();
723
724 StringRef Stem = sys::path::stem(ToolName);
725 if (Stem.find("ranlib") == StringRef::npos &&
726 Stem.find("lib") != StringRef::npos)
727 return libDriverMain(argc, const_cast<const char **>(argv));
728
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000729 // Have the command line options parsed and handle things
730 // like --help and --version.
731 cl::ParseCommandLineOptions(argc, argv,
732 "LLVM Archiver (llvm-ar)\n\n"
733 " This program archives bitcode files into single libraries\n"
734 );
735
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000736 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola47ee3392014-11-07 21:33:09 +0000737 return ar_main();
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000738 if (Stem.find("ranlib") != StringRef::npos)
739 return ranlib_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000740 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000741}