blob: 1f55e8a4968b9010353db745404714254b17c717 [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"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000018#include "llvm/Object/Archive.h"
Peter Collingbournefd66a482015-06-08 02:32:01 +000019#include "llvm/Object/ArchiveWriter.h"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000020#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000021#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000022#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000023#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000024#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000025#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000026#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000027#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000028#include "llvm/Support/Path.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000029#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000030#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000031#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000032#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000033#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000034#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000035#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000037
38#if !defined(_MSC_VER) && !defined(__MINGW32__)
39#include <unistd.h>
40#else
41#include <io.h>
42#endif
43
Brian Gaeke960707c2003-11-11 22:41:34 +000044using namespace llvm;
45
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000046// The name this program was invoked as.
47static StringRef ToolName;
48
Rafael Espindola90b85702014-10-21 15:49:46 +000049// Show the error message and exit.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000050LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
51 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000052 exit(1);
53}
54
Rafael Espindola4453e42942014-06-13 03:07:50 +000055static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000056 if (!EC)
57 return;
58
59 std::string ContextStr = Context.str();
60 if (ContextStr == "")
61 fail(EC.message());
62 fail(Context + ": " + EC.message());
63}
64
Rafael Espindola0c8a3522013-08-28 16:22:16 +000065// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000066static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000067 RestOfArgs(cl::Positional, cl::ZeroOrMore,
68 cl::desc("[relpos] [count] <archive-file> [members]..."));
69
70static cl::opt<bool> MRI("M", cl::desc(""));
Tanya Lattner57c70a62003-08-28 15:22:38 +000071
Rafael Espindola0c8a3522013-08-28 16:22:16 +000072std::string Options;
73
Rafael Espindola90b85702014-10-21 15:49:46 +000074// Provide additional help output explaining the operations and modifiers of
75// llvm-ar. This object instructs the CommandLine library to print the text of
76// the constructor when the --help option is given.
Reid Spencer9fc38b12004-11-16 06:41:09 +000077static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000078 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000079 " d[NsS] - delete file(s) from the archive\n"
80 " m[abiSs] - move file(s) in the archive\n"
81 " p[kN] - print file(s) found in the archive\n"
82 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000083 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000084 " t - display contents of archive\n"
85 " x[No] - extract file(s) from the archive\n"
86 "\nMODIFIERS (operation specific):\n"
87 " [a] - put file(s) after [relpos]\n"
88 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000089 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000090 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000091 " [s] - create an archive index (cf. ranlib)\n"
92 " [S] - do not build a symbol table\n"
93 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000094 "\nMODIFIERS (generic):\n"
95 " [c] - do not warn if the library had to be created\n"
96 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000097);
98
Reid Spencer84a12bf2004-11-14 22:20:07 +000099// This enumeration delineates the kinds of operations on an archive
100// that are permitted.
101enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000102 Print, ///< Print the contents of the archive
103 Delete, ///< Delete the specified members
104 Move, ///< Move members to end or as given by {a,b,i} modifiers
105 QuickAppend, ///< Quickly append to end of archive
106 ReplaceOrInsert, ///< Replace or Insert members
107 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000108 Extract, ///< Extract files back to file system
109 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000110};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000111
Reid Spencer84a12bf2004-11-14 22:20:07 +0000112// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000113static bool AddAfter = false; ///< 'a' modifier
114static bool AddBefore = false; ///< 'b' modifier
115static bool Create = false; ///< 'c' modifier
116static bool OriginalDates = false; ///< 'o' modifier
117static bool OnlyUpdate = false; ///< 'u' modifier
118static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000119static bool Symtab = true; ///< 's' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000120
Reid Spencer84a12bf2004-11-14 22:20:07 +0000121// Relative Positional Argument (for insert/move). This variable holds
122// the name of the archive member to which the 'a', 'b' or 'i' modifier
123// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
124// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000125static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000126
Reid Spencer84a12bf2004-11-14 22:20:07 +0000127// This variable holds the name of the archive file as given on the
128// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000129static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000130
Reid Spencer84a12bf2004-11-14 22:20:07 +0000131// This variable holds the list of member files to proecess, as given
132// on the command line.
Rafael Espindola76619702014-10-21 21:47:27 +0000133static std::vector<StringRef> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000134
Rafael Espindola90b85702014-10-21 15:49:46 +0000135// Show the error message, the help message and exit.
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000136LLVM_ATTRIBUTE_NORETURN static void
137show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000138 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000139 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000140 std::exit(1);
141}
142
Rafael Espindola90b85702014-10-21 15:49:46 +0000143// Extract the member filename from the command line for the [relpos] argument
144// associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000145static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000146 if(RestOfArgs.size() == 0)
147 show_help("Expected [relpos] for a, b, or i modifier");
148 RelPos = RestOfArgs[0];
149 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000150}
151
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000152static void getOptions() {
153 if(RestOfArgs.size() == 0)
154 show_help("Expected options");
155 Options = RestOfArgs[0];
156 RestOfArgs.erase(RestOfArgs.begin());
157}
158
Rafael Espindola90b85702014-10-21 15:49:46 +0000159// Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000160static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000161 if(RestOfArgs.size() == 0)
162 show_help("An archive name must be specified");
163 ArchiveName = RestOfArgs[0];
164 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000165}
166
Rafael Espindola90b85702014-10-21 15:49:46 +0000167// Copy over remaining items in RestOfArgs to our Members vector
Rafael Espindola05571532013-07-12 16:29:27 +0000168static void getMembers() {
Rafael Espindola76619702014-10-21 21:47:27 +0000169 for (auto &Arg : RestOfArgs)
170 Members.push_back(Arg);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000171}
172
Rafael Espindola8a463522014-10-21 21:56:47 +0000173static void runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000174
Rafael Espindola90b85702014-10-21 15:49:46 +0000175// Parse the command line options as presented and return the operation
176// specified. Process all modifiers and check to make sure that constraints on
177// modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000178static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000179 if (MRI) {
180 if (!RestOfArgs.empty())
181 fail("Cannot mix -M and other options");
Rafael Espindola8a463522014-10-21 21:56:47 +0000182 runMRIScript();
Rafael Espindolab2757972014-10-10 18:33:51 +0000183 }
184
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000185 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000186
Reid Spencer84a12bf2004-11-14 22:20:07 +0000187 // Keep track of number of operations. We can only specify one
188 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000189 unsigned NumOperations = 0;
190
Reid Spencer84a12bf2004-11-14 22:20:07 +0000191 // Keep track of the number of positional modifiers (a,b,i). Only
192 // one can be specified.
193 unsigned NumPositional = 0;
194
195 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000196 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000197
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000198 bool MaybeJustCreateSymTab = false;
199
Tanya Lattnerc970a382003-12-06 23:01:25 +0000200 for(unsigned i=0; i<Options.size(); ++i) {
201 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000202 case 'd': ++NumOperations; Operation = Delete; break;
203 case 'm': ++NumOperations; Operation = Move ; break;
204 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000205 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000206 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000207 case 't': ++NumOperations; Operation = DisplayTable; break;
208 case 'x': ++NumOperations; Operation = Extract; break;
209 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000210 case 'l': /* accepted but unused */ break;
211 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000212 case 's':
213 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000214 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000215 break;
216 case 'S':
217 Symtab = false;
218 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000219 case 'u': OnlyUpdate = true; break;
220 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000221 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000222 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000223 AddAfter = true;
224 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000225 break;
226 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000227 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000228 AddBefore = true;
229 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000230 break;
231 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000232 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000233 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000234 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000235 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000236 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000237 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000238 }
239 }
240
Misha Brukman650ba8e2005-04-22 00:00:37 +0000241 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000242 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000243 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000244
245 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000246 getMembers();
247
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000248 if (NumOperations == 0 && MaybeJustCreateSymTab) {
249 NumOperations = 1;
250 Operation = CreateSymTab;
251 if (!Members.empty())
252 show_help("The s operation takes only an archive as argument");
253 }
254
Reid Spencer84a12bf2004-11-14 22:20:07 +0000255 // Perform various checks on the operation/modifier specification
256 // to make sure we are dealing with a legal request.
257 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000258 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000259 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000260 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000261 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000262 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000263 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000264 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000265 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
266 "the 'm' or 'r' operations");
267 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000268 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000269 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000270 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000271 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000272
273 // Return the parsed operation to the caller
274 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000275}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000276
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000277// Implements the 'p' operation. This function traverses the archive
278// looking for members that match the path list.
279static void doPrint(StringRef Name, object::Archive::child_iterator I) {
280 if (Verbose)
281 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000282
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000283 StringRef Data = I->getBuffer();
284 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000285}
286
Rafael Espindola90b85702014-10-21 15:49:46 +0000287// Utility function for printing out the file mode when the 't' operation is in
288// verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000289static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000290 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000291 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000292 else
Chris Lattner2907f442010-11-29 23:02:20 +0000293 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000294 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000295 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000296 else
Chris Lattner2907f442010-11-29 23:02:20 +0000297 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000298 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000299 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000300 else
Chris Lattner2907f442010-11-29 23:02:20 +0000301 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000302}
303
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000304// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000305// the file names of each of the members. However, if verbose mode is requested
306// ('v' modifier) then the file type, permission mode, user, group, size, and
307// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000308static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
309 if (Verbose) {
310 sys::fs::perms Mode = I->getAccessMode();
311 printMode((Mode >> 6) & 007);
312 printMode((Mode >> 3) & 007);
313 printMode(Mode & 007);
314 outs() << ' ' << I->getUID();
315 outs() << '/' << I->getGID();
316 outs() << ' ' << format("%6llu", I->getSize());
317 outs() << ' ' << I->getLastModified().str();
318 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000319 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000320 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000321}
322
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000323// Implement the 'x' operation. This function extracts files back to the file
324// system.
325static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000326 // Retain the original mode.
327 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000328 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000329
Rafael Espindola6d354812013-07-16 19:44:17 +0000330 int FD;
331 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000332 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000333 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000334
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000335 {
336 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000337
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000338 // Get the data and its length
339 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000340
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000341 // Write the data.
342 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000343 }
344
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000345 // If we're supposed to retain the original modification times, etc. do so
346 // now.
347 if (OriginalDates)
348 failIfError(
349 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000350
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000351 if (close(FD))
352 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000353}
354
Rafael Espindola05571532013-07-12 16:29:27 +0000355static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000356 switch (Op) {
357 case Print:
358 case Delete:
359 case Move:
360 case DisplayTable:
361 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000362 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000363 return false;
364
365 case QuickAppend:
366 case ReplaceOrInsert:
367 return true;
368 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000369
370 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000371}
372
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000373static void performReadOperation(ArchiveOperation Operation,
374 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000375 for (object::Archive::child_iterator I = OldArchive->child_begin(),
376 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000377 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000378 ErrorOr<StringRef> NameOrErr = I->getName();
379 failIfError(NameOrErr.getError());
380 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000381
382 if (!Members.empty() &&
383 std::find(Members.begin(), Members.end(), Name) == Members.end())
384 continue;
385
386 switch (Operation) {
387 default:
388 llvm_unreachable("Not a read operation");
389 case Print:
390 doPrint(Name, I);
391 break;
392 case DisplayTable:
393 doDisplayTable(Name, I);
394 break;
395 case Extract:
396 doExtract(Name, I);
397 break;
398 }
399 }
400}
401
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000402template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000403void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
404 int Pos = -1) {
405 NewArchiveIterator NI(I, Name);
406 if (Pos == -1)
407 Members.push_back(NI);
408 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000409 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000410}
411
Rafael Espindola623c3d82013-07-22 15:11:51 +0000412enum InsertAction {
413 IA_AddOldMember,
414 IA_AddNewMeber,
415 IA_Delete,
416 IA_MoveOldMember,
417 IA_MoveNewMember
418};
419
Rafael Espindola76619702014-10-21 21:47:27 +0000420static InsertAction computeInsertAction(ArchiveOperation Operation,
421 object::Archive::child_iterator I,
422 StringRef Name,
423 std::vector<StringRef>::iterator &Pos) {
Rafael Espindola623c3d82013-07-22 15:11:51 +0000424 if (Operation == QuickAppend || Members.empty())
425 return IA_AddOldMember;
426
Rafael Espindola76619702014-10-21 21:47:27 +0000427 auto MI =
428 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
429 return Name == sys::path::filename(Path);
430 });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000431
432 if (MI == Members.end())
433 return IA_AddOldMember;
434
435 Pos = MI;
436
437 if (Operation == Delete)
438 return IA_Delete;
439
440 if (Operation == Move)
441 return IA_MoveOldMember;
442
443 if (Operation == ReplaceOrInsert) {
444 StringRef PosName = sys::path::filename(RelPos);
445 if (!OnlyUpdate) {
446 if (PosName.empty())
447 return IA_AddNewMeber;
448 return IA_MoveNewMember;
449 }
450
451 // We could try to optimize this to a fstat, but it is not a common
452 // operation.
453 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000454 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000455 if (Status.getLastModificationTime() < I->getLastModified()) {
456 if (PosName.empty())
457 return IA_AddOldMember;
458 return IA_MoveOldMember;
459 }
460
461 if (PosName.empty())
462 return IA_AddNewMeber;
463 return IA_MoveNewMember;
464 }
465 llvm_unreachable("No such operation");
466}
467
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000468// We have to walk this twice and computing it is not trivial, so creating an
469// explicit std::vector is actually fairly efficient.
470static std::vector<NewArchiveIterator>
471computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000472 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000473 std::vector<NewArchiveIterator> Ret;
474 std::vector<NewArchiveIterator> Moved;
475 int InsertPos = -1;
476 StringRef PosName = sys::path::filename(RelPos);
477 if (OldArchive) {
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000478 for (auto &Child : OldArchive->children()) {
Rafael Espindola9cd24352013-07-21 12:58:07 +0000479 int Pos = Ret.size();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000480 ErrorOr<StringRef> NameOrErr = Child.getName();
Rafael Espindolaae460022014-06-16 16:08:36 +0000481 failIfError(NameOrErr.getError());
482 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000483 if (Name == PosName) {
484 assert(AddAfter || AddBefore);
485 if (AddBefore)
486 InsertPos = Pos;
487 else
488 InsertPos = Pos + 1;
489 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000490
Rafael Espindola76619702014-10-21 21:47:27 +0000491 std::vector<StringRef>::iterator MemberI = Members.end();
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000492 InsertAction Action =
493 computeInsertAction(Operation, Child, Name, MemberI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000494 switch (Action) {
495 case IA_AddOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000496 addMember(Ret, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000497 break;
498 case IA_AddNewMeber:
Rafael Espindola76619702014-10-21 21:47:27 +0000499 addMember(Ret, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000500 break;
501 case IA_Delete:
502 break;
503 case IA_MoveOldMember:
Rafael Espindolaef1c9ad2014-10-21 23:04:55 +0000504 addMember(Moved, Child, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000505 break;
506 case IA_MoveNewMember:
Rafael Espindola76619702014-10-21 21:47:27 +0000507 addMember(Moved, *MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000508 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000509 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000510 if (MemberI != Members.end())
511 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000512 }
513 }
514
515 if (Operation == Delete)
516 return Ret;
517
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000518 if (!RelPos.empty() && InsertPos == -1)
519 fail("Insertion point not found");
520
Rafael Espindola623c3d82013-07-22 15:11:51 +0000521 if (RelPos.empty())
522 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000523
Rafael Espindola623c3d82013-07-22 15:11:51 +0000524 assert(unsigned(InsertPos) <= Ret.size());
525 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000526
Rafael Espindola623c3d82013-07-22 15:11:51 +0000527 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000528 int Pos = InsertPos;
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000529 for (auto &Member : Members) {
530 StringRef Name = sys::path::filename(Member);
Rafael Espindola76619702014-10-21 21:47:27 +0000531 addMember(Ret, Member, Name, Pos);
Rafael Espindola4c1f8012014-10-21 21:07:49 +0000532 ++Pos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000533 }
534
535 return Ret;
536}
537
Rafael Espindola8a463522014-10-21 21:56:47 +0000538static void
539performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
540 std::vector<NewArchiveIterator> *NewMembersP) {
541 if (NewMembersP) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000542 std::pair<StringRef, std::error_code> Result =
543 writeArchive(ArchiveName, *NewMembersP, Symtab);
544 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000545 return;
546 }
547 std::vector<NewArchiveIterator> NewMembers =
548 computeNewArchiveMembers(Operation, OldArchive);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000549 auto Result = writeArchive(ArchiveName, NewMembers, Symtab);
550 failIfError(Result.second, Result.first);
Rafael Espindola8a463522014-10-21 21:56:47 +0000551}
552
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000553static void createSymbolTable(object::Archive *OldArchive) {
554 // When an archive is created or modified, if the s option is given, the
555 // resulting archive will have a current symbol table. If the S option
556 // is given, it will have no symbol table.
557 // In summary, we only need to update the symbol table if we have none.
558 // This is actually very common because of broken build systems that think
559 // they have to run ranlib.
560 if (OldArchive->hasSymbolTable())
561 return;
562
Rafael Espindola8a463522014-10-21 21:56:47 +0000563 performWriteOperation(CreateSymTab, OldArchive, nullptr);
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000564}
565
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000566static void performOperation(ArchiveOperation Operation,
Rafael Espindola8a463522014-10-21 21:56:47 +0000567 object::Archive *OldArchive,
568 std::vector<NewArchiveIterator> *NewMembers) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000569 switch (Operation) {
570 case Print:
571 case DisplayTable:
572 case Extract:
573 performReadOperation(Operation, OldArchive);
574 return;
575
576 case Delete:
577 case Move:
578 case QuickAppend:
579 case ReplaceOrInsert:
Rafael Espindola8a463522014-10-21 21:56:47 +0000580 performWriteOperation(Operation, OldArchive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000581 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000582 case CreateSymTab:
583 createSymbolTable(OldArchive);
584 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000585 }
586 llvm_unreachable("Unknown operation.");
587}
588
Rafael Espindola8a463522014-10-21 21:56:47 +0000589static int performOperation(ArchiveOperation Operation,
590 std::vector<NewArchiveIterator> *NewMembers) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000591 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000592 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
593 MemoryBuffer::getFile(ArchiveName, -1, false);
594 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000595 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000596 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000597 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000598 return 1;
599 }
600
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000601 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000602 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000603
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000604 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000605 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000606 << "': " << EC.message() << "!\n";
607 return 1;
608 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000609 performOperation(Operation, &Archive, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000610 return 0;
611 }
612
Rafael Espindola2a826e42014-06-13 17:20:48 +0000613 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000614
615 if (!shouldCreateArchive(Operation)) {
616 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
617 } else {
618 if (!Create) {
619 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000620 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000621 }
622 }
623
Rafael Espindola8a463522014-10-21 21:56:47 +0000624 performOperation(Operation, nullptr, NewMembers);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000625 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000626}
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000627
Rafael Espindola8a463522014-10-21 21:56:47 +0000628static void runMRIScript() {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000629 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
Rafael Espindola8a463522014-10-21 21:56:47 +0000630
631 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
632 failIfError(Buf.getError());
633 const MemoryBuffer &Ref = *Buf.get();
634 bool Saved = false;
635 std::vector<NewArchiveIterator> NewMembers;
Rafael Espindola915fbb32014-10-21 23:18:51 +0000636 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
637 std::vector<std::unique_ptr<object::Archive>> Archives;
Rafael Espindola8a463522014-10-21 21:56:47 +0000638
639 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
640 StringRef Line = *I;
641 StringRef CommandStr, Rest;
642 std::tie(CommandStr, Rest) = Line.split(' ');
Rafael Espindola68bae2c2014-10-22 03:10:56 +0000643 Rest = Rest.trim();
644 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
645 Rest = Rest.drop_front().drop_back();
Rafael Espindola8a463522014-10-21 21:56:47 +0000646 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
Rafael Espindola915fbb32014-10-21 23:18:51 +0000647 .Case("addlib", MRICommand::AddLib)
Rafael Espindola8a463522014-10-21 21:56:47 +0000648 .Case("addmod", MRICommand::AddMod)
649 .Case("create", MRICommand::Create)
650 .Case("save", MRICommand::Save)
651 .Case("end", MRICommand::End)
652 .Default(MRICommand::Invalid);
653
654 switch (Command) {
Rafael Espindola915fbb32014-10-21 23:18:51 +0000655 case MRICommand::AddLib: {
656 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
657 failIfError(BufOrErr.getError(), "Could not open library");
658 ArchiveBuffers.push_back(std::move(*BufOrErr));
659 auto LibOrErr =
660 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
661 failIfError(LibOrErr.getError(), "Could not parse library");
662 Archives.push_back(std::move(*LibOrErr));
663 object::Archive &Lib = *Archives.back();
664 for (auto &Member : Lib.children()) {
665 ErrorOr<StringRef> NameOrErr = Member.getName();
666 failIfError(NameOrErr.getError());
667 addMember(NewMembers, Member, *NameOrErr);
668 }
669 break;
670 }
Rafael Espindola8a463522014-10-21 21:56:47 +0000671 case MRICommand::AddMod:
672 addMember(NewMembers, Rest, sys::path::filename(Rest));
673 break;
674 case MRICommand::Create:
675 Create = true;
676 if (!ArchiveName.empty())
677 fail("Editing multiple archives not supported");
678 if (Saved)
679 fail("File already saved");
680 ArchiveName = Rest;
681 break;
682 case MRICommand::Save:
683 Saved = true;
684 break;
685 case MRICommand::End:
686 break;
687 case MRICommand::Invalid:
688 fail("Unknown command: " + CommandStr);
689 }
690 }
691
692 // Nothing to do if not saved.
693 if (Saved)
694 performOperation(ReplaceOrInsert, &NewMembers);
695 exit(0);
696}
697
Rafael Espindola47ee3392014-11-07 21:33:09 +0000698static int ar_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000699 // Do our own parsing of the command line because the CommandLine utility
700 // can't handle the grouped positional parameters without a dash.
701 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola8a463522014-10-21 21:56:47 +0000702 return performOperation(Operation, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000703}
704
Rafael Espindoladbc04162014-10-22 15:05:51 +0000705static int ranlib_main() {
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000706 if (RestOfArgs.size() != 1)
707 fail(ToolName + "takes just one archive as argument");
708 ArchiveName = RestOfArgs[0];
Rafael Espindola8a463522014-10-21 21:56:47 +0000709 return performOperation(CreateSymTab, nullptr);
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000710}
711
712int main(int argc, char **argv) {
713 ToolName = argv[0];
714 // Print a stack trace if we signal out.
715 sys::PrintStackTraceOnErrorSignal();
716 PrettyStackTraceProgram X(argc, argv);
717 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
718
719 // Have the command line options parsed and handle things
720 // like --help and --version.
721 cl::ParseCommandLineOptions(argc, argv,
722 "LLVM Archiver (llvm-ar)\n\n"
723 " This program archives bitcode files into single libraries\n"
724 );
725
726 llvm::InitializeAllTargetInfos();
727 llvm::InitializeAllTargetMCs();
728 llvm::InitializeAllAsmParsers();
729
730 StringRef Stem = sys::path::stem(ToolName);
731 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola47ee3392014-11-07 21:33:09 +0000732 return ar_main();
Rafael Espindolaea16d6e2014-10-21 20:34:57 +0000733 if (Stem.find("ranlib") != StringRef::npos)
734 return ranlib_main();
735 fail("Not ranlib or ar!");
736}