blob: 66daba30a4acdf28194dc0730281a3c679a366df [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
Tanya Lattner57c70a62003-08-28 15:22:38 +0000132
Reid Spencer84a12bf2004-11-14 22:20:07 +0000133// Relative Positional Argument (for insert/move). This variable holds
134// the name of the archive member to which the 'a', 'b' or 'i' modifier
135// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
136// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000137static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000138
Reid Spencer84a12bf2004-11-14 22:20:07 +0000139// This variable holds the name of the archive file as given on the
140// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000141static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000142
Reid Spencer84a12bf2004-11-14 22:20:07 +0000143// This variable holds the list of member files to proecess, as given
144// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000145static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000146
Rafael Espindola90b85702014-10-21 15:49:46 +0000147// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000148LLVM_ATTRIBUTE_NORETURN static void
149show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000150 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000151 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000152 std::exit(1);
153}
154
Rafael Espindola90b85702014-10-21 15:49:46 +0000155// Extract the member filename from the command line for the [relpos] argument
156// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000157static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000158 if(RestOfArgs.size() == 0)
159 show_help("Expected [relpos] for a, b, or i modifier");
160 RelPos = RestOfArgs[0];
161 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000162}
163
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000164static void getOptions() {
165 if(RestOfArgs.size() == 0)
166 show_help("Expected options");
167 Options = RestOfArgs[0];
168 RestOfArgs.erase(RestOfArgs.begin());
169}
170
Rafael Espindola90b85702014-10-21 15:49:46 +0000171// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000172static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000173 if(RestOfArgs.size() == 0)
174 show_help("An archive name must be specified");
175 ArchiveName = RestOfArgs[0];
176 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000177}
178
Rafael Espindola90b85702014-10-21 15:49:46 +0000179// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000180static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000181 for (auto &Arg : RestOfArgs)
182 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000183}
184
Rafael Espindola8a463522014-10-21 21:56:47 +0000185static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000186
Rafael Espindola90b85702014-10-21 15:49:46 +0000187// Parse the command line options as presented and return the operation
188// specified. Process all modifiers and check to make sure that constraints on
189// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000190static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000191 if (MRI) {
192 if (!RestOfArgs.empty())
193 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000194 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000195 }
196
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000197 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000198
Reid Spencer84a12bf2004-11-14 22:20:07 +0000199 // Keep track of number of operations. We can only specify one
200 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000201 unsigned NumOperations = 0;
202
Reid Spencer84a12bf2004-11-14 22:20:07 +0000203 // Keep track of the number of positional modifiers (a,b,i). Only
204 // one can be specified.
205 unsigned NumPositional = 0;
206
207 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000208 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000209
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000210 bool MaybeJustCreateSymTab = false;
211
Tanya Lattnerc970a382003-12-06 23:01:25 +0000212 for(unsigned i=0; i<Options.size(); ++i) {
213 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000214 case 'd': ++NumOperations; Operation = Delete; break;
215 case 'm': ++NumOperations; Operation = Move ; break;
216 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000217 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000218 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000219 case 't': ++NumOperations; Operation = DisplayTable; break;
220 case 'x': ++NumOperations; Operation = Extract; break;
221 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000222 case 'l': /* accepted but unused */ break;
223 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000224 case 's':
225 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000226 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000227 break;
228 case 'S':
229 Symtab = false;
230 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000231 case 'u': OnlyUpdate = true; break;
232 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000233 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000234 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000235 AddAfter = true;
236 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000237 break;
238 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000239 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000240 AddBefore = true;
241 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000242 break;
243 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000244 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000245 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000246 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000247 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000248 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000249 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000250 }
251 }
252
Misha Brukman650ba8e2005-04-22 00:00:37 +0000253 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000254 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000255 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000256
257 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000258 getMembers();
259
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000260 if (NumOperations == 0 && MaybeJustCreateSymTab) {
261 NumOperations = 1;
262 Operation = CreateSymTab;
263 if (!Members.empty())
264 show_help("The s operation takes only an archive as argument");
265 }
266
Reid Spencer84a12bf2004-11-14 22:20:07 +0000267 // Perform various checks on the operation/modifier specification
268 // to make sure we are dealing with a legal request.
269 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000270 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000271 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000272 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000273 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000274 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000275 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000276 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000277 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
278 "the 'm' or 'r' operations");
279 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000280 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000281 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000282 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000283 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000284
285 // Return the parsed operation to the caller
286 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000287}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000288
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000289// Implements the 'p' operation. This function traverses the archive
290// looking for members that match the path list.
291static void doPrint(StringRef Name, object::Archive::child_iterator I) {
292 if (Verbose)
293 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000294
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000295 StringRef Data = I->getBuffer();
296 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000297}
298
Rafael Espindola90b85702014-10-21 15:49:46 +0000299// Utility function for printing out the file mode when the 't' operation is in
300// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000301static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000302 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000303 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000304 else
Chris Lattner2907f442010-11-29 23:02:20 +0000305 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000306 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000307 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000308 else
Chris Lattner2907f442010-11-29 23:02:20 +0000309 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000310 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000311 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000312 else
Chris Lattner2907f442010-11-29 23:02:20 +0000313 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000314}
315
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000316// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000317// the file names of each of the members. However, if verbose mode is requested
318// ('v' modifier) then the file type, permission mode, user, group, size, and
319// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000320static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
321 if (Verbose) {
322 sys::fs::perms Mode = I->getAccessMode();
323 printMode((Mode >> 6) & 007);
324 printMode((Mode >> 3) & 007);
325 printMode(Mode & 007);
326 outs() << ' ' << I->getUID();
327 outs() << '/' << I->getGID();
328 outs() << ' ' << format("%6llu", I->getSize());
329 outs() << ' ' << I->getLastModified().str();
330 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000331 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000332 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000333}
334
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000335// Implement the 'x' operation. This function extracts files back to the file
336// system.
337static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000338 // Retain the original mode.
339 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000340 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000341
Rafael Espindola6d354812013-07-16 19:44:17 +0000342 int FD;
343 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000344 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000345 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000346
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000347 {
348 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000349
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000350 // Get the data and its length
351 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000352
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000353 // Write the data.
354 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000355 }
356
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000357 // If we're supposed to retain the original modification times, etc. do so
358 // now.
359 if (OriginalDates)
360 failIfError(
361 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000362
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000363 if (close(FD))
364 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000365}
366
Rafael Espindola05571532013-07-12 16:29:27 +0000367static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000368 switch (Op) {
369 case Print:
370 case Delete:
371 case Move:
372 case DisplayTable:
373 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000374 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000375 return false;
376
377 case QuickAppend:
378 case ReplaceOrInsert:
379 return true;
380 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000381
382 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000383}
384
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000385static void performReadOperation(ArchiveOperation Operation,
386 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000387 for (object::Archive::child_iterator I = OldArchive->child_begin(),
388 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000389 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000390 ErrorOr<StringRef> NameOrErr = I->getName();
391 failIfError(NameOrErr.getError());
392 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000393
394 if (!Members.empty() &&
395 std::find(Members.begin(), Members.end(), Name) == Members.end())
396 continue;
397
398 switch (Operation) {
399 default:
400 llvm_unreachable("Not a read operation");
401 case Print:
402 doPrint(Name, I);
403 break;
404 case DisplayTable:
405 doDisplayTable(Name, I);
406 break;
407 case Extract:
408 doExtract(Name, I);
409 break;
410 }
411 }
412}
413
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000414template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000415void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
416 int Pos = -1) {
417 NewArchiveIterator NI(I, Name);
418 if (Pos == -1)
419 Members.push_back(NI);
420 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000421 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000422}
423
Rafael Espindola623c3d82013-07-22 15:11:51 +0000424enum InsertAction {
425 IA_AddOldMember,
426 IA_AddNewMeber,
427 IA_Delete,
428 IA_MoveOldMember,
429 IA_MoveNewMember
430};
431
Rafael Espindola76619702014-10-21 21:47:27 +0000432static InsertAction computeInsertAction(ArchiveOperation Operation,
433 object::Archive::child_iterator I,
434 StringRef Name,
435 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000436 if (Operation == QuickAppend || Members.empty())
437 return IA_AddOldMember;
438
Rafael Espindola76619702014-10-21 21:47:27 +0000439 auto MI =
440 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
441 return Name == sys::path::filename(Path);
442 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000443
444 if (MI == Members.end())
445 return IA_AddOldMember;
446
447 Pos = MI;
448
449 if (Operation == Delete)
450 return IA_Delete;
451
452 if (Operation == Move)
453 return IA_MoveOldMember;
454
455 if (Operation == ReplaceOrInsert) {
456 StringRef PosName = sys::path::filename(RelPos);
457 if (!OnlyUpdate) {
458 if (PosName.empty())
459 return IA_AddNewMeber;
460 return IA_MoveNewMember;
461 }
462
463 // We could try to optimize this to a fstat, but it is not a common
464 // operation.
465 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000466 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000467 if (Status.getLastModificationTime() < I->getLastModified()) {
468 if (PosName.empty())
469 return IA_AddOldMember;
470 return IA_MoveOldMember;
471 }
472
473 if (PosName.empty())
474 return IA_AddNewMeber;
475 return IA_MoveNewMember;
476 }
477 llvm_unreachable("No such operation");
478}
479
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000480// We have to walk this twice and computing it is not trivial, so creating an
481// explicit std::vector is actually fairly efficient.
482static std::vector<NewArchiveIterator>
483computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000484 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000485 std::vector<NewArchiveIterator> Ret;
486 std::vector<NewArchiveIterator> Moved;
487 int InsertPos = -1;
488 StringRef PosName = sys::path::filename(RelPos);
489 if (OldArchive) {
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000490 for (auto &Child : OldArchive->children()) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000491 int Pos = Ret.size();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000492 ErrorOr<StringRef> NameOrErr = Child.getName();
Rafael Espindolaae460022014-06-16 16:08:36 +0000493 failIfError(NameOrErr.getError());
494 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000495 if (Name == PosName) {
496 assert(AddAfter || AddBefore);
497 if (AddBefore)
498 InsertPos = Pos;
499 else
500 InsertPos = Pos + 1;
501 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000502
Rafael Espindola76619702014-10-21 21:47:27 +0000503 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000504 InsertAction Action =
505 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000506 switch (Action) {
507 case IA_AddOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000508 addMember(Ret, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000509 break;
510 case IA_AddNewMeber:
Rafael Espindola76619702014-10-21 21:47:27 +0000511 addMember(Ret, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000512 break;
513 case IA_Delete:
514 break;
515 case IA_MoveOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000516 addMember(Moved, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000517 break;
518 case IA_MoveNewMember:
Rafael Espindola76619702014-10-21 21:47:27 +0000519 addMember(Moved, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000520 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000521 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000522 if (MemberI != Members.end())
523 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000524 }
525 }
526
527 if (Operation == Delete)
528 return Ret;
529
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000530 if (!RelPos.empty() && InsertPos == -1)
531 fail("Insertion point not found");
532
Rafael Espindola623c3d82013-07-22 15:11:51 +0000533 if (RelPos.empty())
534 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000535
Rafael Espindola623c3d82013-07-22 15:11:51 +0000536 assert(unsigned(InsertPos) <= Ret.size());
537 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000538
Rafael Espindolac91177e2015-07-08 22:15:07 +0000539 Ret.insert(Ret.begin() + InsertPos, Members.size(),
540 NewArchiveIterator("", ""));
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000541 int Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000542 for (auto &Member : Members) {
543 StringRef Name = sys::path::filename(Member);
Rafael Espindola76619702014-10-21 21:47:27 +0000544 addMember(Ret, Member, Name, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000545 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000546 }
547
548 return Ret;
549}
550
Rafael Espindola8a463522014-10-21 21:56:47 +0000551static void
552performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
553 std::vector<NewArchiveIterator> *NewMembersP) {
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000554 object::Archive::Kind Kind;
555 switch (FormatOpt) {
Rafael Espindola2535ea02015-07-09 20:12:50 +0000556 case Default: {
557 Triple T(sys::getProcessTriple());
558 if (T.isOSDarwin())
559 Kind = object::Archive::K_BSD;
560 else
561 Kind = object::Archive::K_GNU;
562 break;
563 }
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000564 case GNU:
565 Kind = object::Archive::K_GNU;
566 break;
567 case BSD:
568 Kind = object::Archive::K_BSD;
569 break;
570 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000571 if (NewMembersP) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000572 std::pair<StringRef, std::error_code> Result =
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000573 writeArchive(ArchiveName, *NewMembersP, Symtab, Kind);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000574 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000575 return;
576 }
577 std::vector<NewArchiveIterator> NewMembers =
578 computeNewArchiveMembers(Operation, OldArchive);
Rafael Espindolaa2ed0b02015-07-08 20:47:32 +0000579 auto Result = writeArchive(ArchiveName, NewMembers, Symtab, Kind);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000580 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000581}
582
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000583static void createSymbolTable(object::Archive *OldArchive) {
584 // When an archive is created or modified, if the s option is given, the
585 // resulting archive will have a current symbol table. If the S option
586 // is given, it will have no symbol table.
587 // In summary, we only need to update the symbol table if we have none.
588 // This is actually very common because of broken build systems that think
589 // they have to run ranlib.
590 if (OldArchive->hasSymbolTable())
591 return;
592
Rafael Espindola8a463522014-10-21 21:56:47 +0000593 performWriteOperation(CreateSymTab, OldArchive, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000594}
595
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000596static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000597 object::Archive *OldArchive,
598 std::vector<NewArchiveIterator> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000599 switch (Operation) {
600 case Print:
601 case DisplayTable:
602 case Extract:
603 performReadOperation(Operation, OldArchive);
604 return;
605
606 case Delete:
607 case Move:
608 case QuickAppend:
609 case ReplaceOrInsert:
Rafael Espindola8a463522014-10-21 21:56:47 +0000610 performWriteOperation(Operation, OldArchive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000611 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000612 case CreateSymTab:
613 createSymbolTable(OldArchive);
614 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000615 }
616 llvm_unreachable("Unknown operation.");
617}
618
Rafael Espindola8a463522014-10-21 21:56:47 +0000619static int performOperation(ArchiveOperation Operation,
620 std::vector<NewArchiveIterator> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000621 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000622 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
623 MemoryBuffer::getFile(ArchiveName, -1, false);
624 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000625 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000626 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000627 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000628 return 1;
629 }
630
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000631 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000632 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000633
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000634 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000635 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000636 << "': " << EC.message() << "!\n";
637 return 1;
638 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000639 performOperation(Operation, &Archive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000640 return 0;
641 }
642
Rafael Espindola2a826e42014-06-13 17:20:48 +0000643 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000644
645 if (!shouldCreateArchive(Operation)) {
646 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
647 } else {
648 if (!Create) {
649 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000650 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000651 }
652 }
653
Rafael Espindola8a463522014-10-21 21:56:47 +0000654 performOperation(Operation, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000655 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000656}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000657
Rafael Espindola8a463522014-10-21 21:56:47 +0000658static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000659 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000660
661 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
662 failIfError(Buf.getError());
663 const MemoryBuffer &Ref = *Buf.get();
664 bool Saved = false;
665 std::vector<NewArchiveIterator> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000666 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
667 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000668
669 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
670 StringRef Line = *I;
671 StringRef CommandStr, Rest;
672 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000673 Rest = Rest.trim();
674 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
675 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000676 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000677 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000678 .Case("addmod", MRICommand::AddMod)
679 .Case("create", MRICommand::Create)
680 .Case("save", MRICommand::Save)
681 .Case("end", MRICommand::End)
682 .Default(MRICommand::Invalid);
683
684 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000685 case MRICommand::AddLib: {
686 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
687 failIfError(BufOrErr.getError(), "Could not open library");
688 ArchiveBuffers.push_back(std::move(*BufOrErr));
689 auto LibOrErr =
690 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
691 failIfError(LibOrErr.getError(), "Could not parse library");
692 Archives.push_back(std::move(*LibOrErr));
693 object::Archive &Lib = *Archives.back();
694 for (auto &Member : Lib.children()) {
695 ErrorOr<StringRef> NameOrErr = Member.getName();
696 failIfError(NameOrErr.getError());
697 addMember(NewMembers, Member, *NameOrErr);
698 }
699 break;
700 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000701 case MRICommand::AddMod:
702 addMember(NewMembers, Rest, sys::path::filename(Rest));
703 break;
704 case MRICommand::Create:
705 Create = true;
706 if (!ArchiveName.empty())
707 fail("Editing multiple archives not supported");
708 if (Saved)
709 fail("File already saved");
710 ArchiveName = Rest;
711 break;
712 case MRICommand::Save:
713 Saved = true;
714 break;
715 case MRICommand::End:
716 break;
717 case MRICommand::Invalid:
718 fail("Unknown command: " + CommandStr);
719 }
720 }
721
722 // Nothing to do if not saved.
723 if (Saved)
724 performOperation(ReplaceOrInsert, &NewMembers);
725 exit(0);
726}
727
Rafael Espindola47ee3392014-11-07 21:33:09 +0000728static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000729 // Do our own parsing of the command line because the CommandLine utility
730 // can't handle the grouped positional parameters without a dash.
731 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000732 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000733}
734
Rafael Espindoladbc04162014-10-22 15:05:51 +0000735static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000736 if (RestOfArgs.size() != 1)
737 fail(ToolName + "takes just one archive as argument");
738 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000739 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000740}
741
742int main(int argc, char **argv) {
743 ToolName = argv[0];
744 // Print a stack trace if we signal out.
745 sys::PrintStackTraceOnErrorSignal();
746 PrettyStackTraceProgram X(argc, argv);
747 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
748
Peter Collingbournebc051632015-06-09 21:50:22 +0000749 llvm::InitializeAllTargetInfos();
750 llvm::InitializeAllTargetMCs();
751 llvm::InitializeAllAsmParsers();
752
753 StringRef Stem = sys::path::stem(ToolName);
754 if (Stem.find("ranlib") == StringRef::npos &&
755 Stem.find("lib") != StringRef::npos)
David Blaikie8b31d412015-06-21 06:31:56 +0000756 return libDriverMain(makeArrayRef(argv, argc));
Peter Collingbournebc051632015-06-09 21:50:22 +0000757
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000758 // Have the command line options parsed and handle things
759 // like --help and --version.
760 cl::ParseCommandLineOptions(argc, argv,
761 "LLVM Archiver (llvm-ar)\n\n"
762 " This program archives bitcode files into single libraries\n"
763 );
764
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000765 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola47ee3392014-11-07 21:33:09 +0000766 return ar_main();
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000767 if (Stem.find("ranlib") != StringRef::npos)
768 return ranlib_main();
Peter Collingbournebc051632015-06-09 21:50:22 +0000769 fail("Not ranlib, ar or lib!");
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000770}