blob: fa0842992ec506a0bb8d1cc97df2d00147fb5dec [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"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000019#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/Support/CommandLine.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000021#include "llvm/Support/Errc.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000022#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000023#include "llvm/Support/Format.h"
Rafael Espindolab2757972014-10-10 18:33:51 +000024#include "llvm/Support/LineIterator.h"
Chris Lattner76d46322006-12-06 01:18:01 +000025#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000026#include "llvm/Support/MemoryBuffer.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000027#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000028#include "llvm/Support/Signals.h"
Rafael Espindola8e8debc2014-07-03 19:40:08 +000029#include "llvm/Support/TargetSelect.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000030#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000031#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000032#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000033#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000035
36#if !defined(_MSC_VER) && !defined(__MINGW32__)
37#include <unistd.h>
38#else
39#include <io.h>
40#endif
41
Brian Gaeke960707c2003-11-11 22:41:34 +000042using namespace llvm;
43
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000044// The name this program was invoked as.
45static StringRef ToolName;
46
47static const char *TemporaryOutput;
Rafael Espindola7303af32013-07-16 16:00:32 +000048static int TmpArchiveFD = -1;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000049
50// fail - Show the error message and exit.
51LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
52 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola7303af32013-07-16 16:00:32 +000053 if (TmpArchiveFD != -1)
54 close(TmpArchiveFD);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000055 if (TemporaryOutput)
56 sys::fs::remove(TemporaryOutput);
57 exit(1);
58}
59
Rafael Espindola4453e42942014-06-13 03:07:50 +000060static void failIfError(std::error_code EC, Twine Context = "") {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000061 if (!EC)
62 return;
63
64 std::string ContextStr = Context.str();
65 if (ContextStr == "")
66 fail(EC.message());
67 fail(Context + ": " + EC.message());
68}
69
Rafael Espindola0c8a3522013-08-28 16:22:16 +000070// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000071static cl::list<std::string>
Rafael Espindolab2757972014-10-10 18:33:51 +000072 RestOfArgs(cl::Positional, cl::ZeroOrMore,
73 cl::desc("[relpos] [count] <archive-file> [members]..."));
74
75static cl::opt<bool> MRI("M", cl::desc(""));
Tanya Lattner57c70a62003-08-28 15:22:38 +000076
Rafael Espindola0c8a3522013-08-28 16:22:16 +000077std::string Options;
78
Reid Spencer9fc38b12004-11-16 06:41:09 +000079// MoreHelp - Provide additional help output explaining the operations and
80// modifiers of llvm-ar. This object instructs the CommandLine library
81// to print the text of the constructor when the --help option is given.
82static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000083 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000084 " d[NsS] - delete file(s) from the archive\n"
85 " m[abiSs] - move file(s) in the archive\n"
86 " p[kN] - print file(s) found in the archive\n"
87 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000088 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000089 " t - display contents of archive\n"
90 " x[No] - extract file(s) from the archive\n"
91 "\nMODIFIERS (operation specific):\n"
92 " [a] - put file(s) after [relpos]\n"
93 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000094 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000095 " [N] - use instance [count] of name\n"
96 " [o] - preserve original dates\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000097 " [s] - create an archive index (cf. ranlib)\n"
98 " [S] - do not build a symbol table\n"
99 " [u] - update only files newer than archive contents\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000100 "\nMODIFIERS (generic):\n"
101 " [c] - do not warn if the library had to be created\n"
102 " [v] - be verbose about actions taken\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +0000103);
104
Reid Spencer84a12bf2004-11-14 22:20:07 +0000105// This enumeration delineates the kinds of operations on an archive
106// that are permitted.
107enum ArchiveOperation {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000108 Print, ///< Print the contents of the archive
109 Delete, ///< Delete the specified members
110 Move, ///< Move members to end or as given by {a,b,i} modifiers
111 QuickAppend, ///< Quickly append to end of archive
112 ReplaceOrInsert, ///< Replace or Insert members
113 DisplayTable, ///< Display the table of contents
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000114 Extract, ///< Extract files back to file system
115 CreateSymTab ///< Create a symbol table in an existing archive
Tanya Lattnerc970a382003-12-06 23:01:25 +0000116};
Tanya Lattner57c70a62003-08-28 15:22:38 +0000117
Reid Spencer84a12bf2004-11-14 22:20:07 +0000118// Modifiers to follow operation to vary behavior
Rafael Espindola05571532013-07-12 16:29:27 +0000119static bool AddAfter = false; ///< 'a' modifier
120static bool AddBefore = false; ///< 'b' modifier
121static bool Create = false; ///< 'c' modifier
122static bool OriginalDates = false; ///< 'o' modifier
123static bool OnlyUpdate = false; ///< 'u' modifier
124static bool Verbose = false; ///< 'v' modifier
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000125static bool Symtab = true; ///< 's' modifier
Tanya Lattner57c70a62003-08-28 15:22:38 +0000126
Reid Spencer84a12bf2004-11-14 22:20:07 +0000127// Relative Positional Argument (for insert/move). This variable holds
128// the name of the archive member to which the 'a', 'b' or 'i' modifier
129// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
130// one variable.
Rafael Espindola05571532013-07-12 16:29:27 +0000131static std::string RelPos;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000132
Reid Spencer84a12bf2004-11-14 22:20:07 +0000133// This variable holds the name of the archive file as given on the
134// command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000135static std::string ArchiveName;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000136
Reid Spencer84a12bf2004-11-14 22:20:07 +0000137// This variable holds the list of member files to proecess, as given
138// on the command line.
Rafael Espindola05571532013-07-12 16:29:27 +0000139static std::vector<std::string> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000140
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000141// show_help - Show the error message, the help message and exit.
142LLVM_ATTRIBUTE_NORETURN static void
143show_help(const std::string &msg) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000144 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000145 cl::PrintHelpMessage();
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000146 std::exit(1);
147}
148
Reid Spencer84a12bf2004-11-14 22:20:07 +0000149// getRelPos - Extract the member filename from the command line for
150// the [relpos] argument associated with a, b, and i modifiers
Rafael Espindola05571532013-07-12 16:29:27 +0000151static void getRelPos() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000152 if(RestOfArgs.size() == 0)
153 show_help("Expected [relpos] for a, b, or i modifier");
154 RelPos = RestOfArgs[0];
155 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000156}
157
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000158static void getOptions() {
159 if(RestOfArgs.size() == 0)
160 show_help("Expected options");
161 Options = RestOfArgs[0];
162 RestOfArgs.erase(RestOfArgs.begin());
163}
164
Reid Spencer84a12bf2004-11-14 22:20:07 +0000165// getArchive - Get the archive file name from the command line
Rafael Espindola05571532013-07-12 16:29:27 +0000166static void getArchive() {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000167 if(RestOfArgs.size() == 0)
168 show_help("An archive name must be specified");
169 ArchiveName = RestOfArgs[0];
170 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattnerc970a382003-12-06 23:01:25 +0000171}
172
Reid Spencer84a12bf2004-11-14 22:20:07 +0000173// getMembers - Copy over remaining items in RestOfArgs to our Members vector
174// This is just for clarity.
Rafael Espindola05571532013-07-12 16:29:27 +0000175static void getMembers() {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000176 if(RestOfArgs.size() > 0)
Misha Brukman650ba8e2005-04-22 00:00:37 +0000177 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000178}
179
Rafael Espindolab2757972014-10-10 18:33:51 +0000180namespace {
181enum class MRICommand { Create, Save, End, Invalid };
182}
183
184static ArchiveOperation parseMRIScript() {
185 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
186 failIfError(Buf.getError());
187 const MemoryBuffer &Ref = *Buf.get();
188 bool Saved = false;
189
190 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
191 StringRef Line = *I;
192 StringRef CommandStr, Rest;
193 std::tie(CommandStr, Rest) = Line.split(' ');
194 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
195 .Case("create", MRICommand::Create)
196 .Case("save", MRICommand::Save)
197 .Case("end", MRICommand::End)
198 .Default(MRICommand::Invalid);
199
200 switch (Command) {
201 case MRICommand::Create:
202 Create = true;
203 if (!ArchiveName.empty())
204 fail("Editing multiple archives not supported");
205 if (Saved)
206 fail("File already saved");
207 ArchiveName = Rest;
208 break;
209 case MRICommand::Save:
210 Saved = true;
211 break;
212 case MRICommand::End:
213 break;
214 case MRICommand::Invalid:
215 fail("Unknown command: " + CommandStr);
216 }
217 }
218
219 // Nothing to do if not saved.
220 if (!Saved)
221 exit(0);
222 return ReplaceOrInsert;
223}
224
Reid Spencer84a12bf2004-11-14 22:20:07 +0000225// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman650ba8e2005-04-22 00:00:37 +0000226// operation specified. Process all modifiers and check to make sure that
Reid Spencer84a12bf2004-11-14 22:20:07 +0000227// constraints on modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000228static ArchiveOperation parseCommandLine() {
Rafael Espindolab2757972014-10-10 18:33:51 +0000229 if (MRI) {
230 if (!RestOfArgs.empty())
231 fail("Cannot mix -M and other options");
232 return parseMRIScript();
233 }
234
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000235 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000236
Reid Spencer84a12bf2004-11-14 22:20:07 +0000237 // Keep track of number of operations. We can only specify one
238 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000239 unsigned NumOperations = 0;
240
Reid Spencer84a12bf2004-11-14 22:20:07 +0000241 // Keep track of the number of positional modifiers (a,b,i). Only
242 // one can be specified.
243 unsigned NumPositional = 0;
244
245 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000246 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000247
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000248 bool MaybeJustCreateSymTab = false;
249
Tanya Lattnerc970a382003-12-06 23:01:25 +0000250 for(unsigned i=0; i<Options.size(); ++i) {
251 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000252 case 'd': ++NumOperations; Operation = Delete; break;
253 case 'm': ++NumOperations; Operation = Move ; break;
254 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000255 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000256 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000257 case 't': ++NumOperations; Operation = DisplayTable; break;
258 case 'x': ++NumOperations; Operation = Extract; break;
259 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000260 case 'l': /* accepted but unused */ break;
261 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000262 case 's':
263 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000264 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000265 break;
266 case 'S':
267 Symtab = false;
268 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000269 case 'u': OnlyUpdate = true; break;
270 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000271 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000272 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000273 AddAfter = true;
274 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000275 break;
276 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000277 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000278 AddBefore = true;
279 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000280 break;
281 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000282 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000283 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000284 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000285 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000286 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000287 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000288 }
289 }
290
Misha Brukman650ba8e2005-04-22 00:00:37 +0000291 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000292 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000293 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000294
295 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000296 getMembers();
297
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000298 if (NumOperations == 0 && MaybeJustCreateSymTab) {
299 NumOperations = 1;
300 Operation = CreateSymTab;
301 if (!Members.empty())
302 show_help("The s operation takes only an archive as argument");
303 }
304
Reid Spencer84a12bf2004-11-14 22:20:07 +0000305 // Perform various checks on the operation/modifier specification
306 // to make sure we are dealing with a legal request.
307 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000308 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000309 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000310 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000311 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000312 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000313 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000314 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000315 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
316 "the 'm' or 'r' operations");
317 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000318 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000319 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000320 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000321 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000322
323 // Return the parsed operation to the caller
324 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000325}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000326
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000327// Implements the 'p' operation. This function traverses the archive
328// looking for members that match the path list.
329static void doPrint(StringRef Name, object::Archive::child_iterator I) {
330 if (Verbose)
331 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000332
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000333 StringRef Data = I->getBuffer();
334 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000335}
336
337// putMode - utility function for printing out the file mode when the 't'
338// operation is in verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000339static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000340 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000341 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000342 else
Chris Lattner2907f442010-11-29 23:02:20 +0000343 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000344 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000345 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000346 else
Chris Lattner2907f442010-11-29 23:02:20 +0000347 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000348 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000349 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000350 else
Chris Lattner2907f442010-11-29 23:02:20 +0000351 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000352}
353
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000354// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000355// the file names of each of the members. However, if verbose mode is requested
356// ('v' modifier) then the file type, permission mode, user, group, size, and
357// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000358static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
359 if (Verbose) {
360 sys::fs::perms Mode = I->getAccessMode();
361 printMode((Mode >> 6) & 007);
362 printMode((Mode >> 3) & 007);
363 printMode(Mode & 007);
364 outs() << ' ' << I->getUID();
365 outs() << '/' << I->getGID();
366 outs() << ' ' << format("%6llu", I->getSize());
367 outs() << ' ' << I->getLastModified().str();
368 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000369 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000370 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000371}
372
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000373// Implement the 'x' operation. This function extracts files back to the file
374// system.
375static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000376 // Retain the original mode.
377 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000378 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000379
Rafael Espindola6d354812013-07-16 19:44:17 +0000380 int FD;
381 failIfError(
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000382 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000383 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000384
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000385 {
386 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000387
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000388 // Get the data and its length
389 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000390
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000391 // Write the data.
392 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000393 }
394
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000395 // If we're supposed to retain the original modification times, etc. do so
396 // now.
397 if (OriginalDates)
398 failIfError(
399 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000400
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000401 if (close(FD))
402 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000403}
404
Rafael Espindola05571532013-07-12 16:29:27 +0000405static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000406 switch (Op) {
407 case Print:
408 case Delete:
409 case Move:
410 case DisplayTable:
411 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000412 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000413 return false;
414
415 case QuickAppend:
416 case ReplaceOrInsert:
417 return true;
418 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000419
420 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000421}
422
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000423static void performReadOperation(ArchiveOperation Operation,
424 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000425 for (object::Archive::child_iterator I = OldArchive->child_begin(),
426 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000427 I != E; ++I) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000428 ErrorOr<StringRef> NameOrErr = I->getName();
429 failIfError(NameOrErr.getError());
430 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000431
432 if (!Members.empty() &&
433 std::find(Members.begin(), Members.end(), Name) == Members.end())
434 continue;
435
436 switch (Operation) {
437 default:
438 llvm_unreachable("Not a read operation");
439 case Print:
440 doPrint(Name, I);
441 break;
442 case DisplayTable:
443 doDisplayTable(Name, I);
444 break;
445 case Extract:
446 doExtract(Name, I);
447 break;
448 }
449 }
450}
451
452namespace {
453class NewArchiveIterator {
454 bool IsNewMember;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000455 StringRef Name;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000456
Rafael Espindola023e6562013-07-12 20:28:02 +0000457 object::Archive::child_iterator OldI;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000458
Rafael Espindola623c3d82013-07-22 15:11:51 +0000459 std::string NewFilename;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000460 mutable int NewFD;
461 mutable sys::fs::file_status NewStatus;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000462
463public:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000464 NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
465 NewArchiveIterator(std::string *I, StringRef Name);
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000466 NewArchiveIterator();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000467 bool isNewMember() const;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000468 StringRef getName() const;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000469
470 object::Archive::child_iterator getOld() const;
471
472 const char *getNew() const;
473 int getFD() const;
474 const sys::fs::file_status &getStatus() const;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000475};
476}
477
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000478NewArchiveIterator::NewArchiveIterator() {}
479
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000480NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000481 StringRef Name)
482 : IsNewMember(false), Name(Name), OldI(I) {}
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000483
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000484NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
Rafael Espindolab6082a32014-01-22 16:43:45 +0000485 : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000486
487StringRef NewArchiveIterator::getName() const { return Name; }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000488
489bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
490
491object::Archive::child_iterator NewArchiveIterator::getOld() const {
492 assert(!IsNewMember);
493 return OldI;
494}
495
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000496const char *NewArchiveIterator::getNew() const {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000497 assert(IsNewMember);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000498 return NewFilename.c_str();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000499}
500
Rafael Espindolab6082a32014-01-22 16:43:45 +0000501int NewArchiveIterator::getFD() const {
502 assert(IsNewMember);
503 if (NewFD != -1)
504 return NewFD;
505 failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
506 assert(NewFD != -1);
507
508 failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
509
510 // Opening a directory doesn't make sense. Let it fail.
511 // Linux cannot open directories with open(2), although
512 // cygwin and *bsd can.
513 if (NewStatus.type() == sys::fs::file_type::directory_file)
Rafael Espindola2a826e42014-06-13 17:20:48 +0000514 failIfError(make_error_code(errc::is_a_directory), NewFilename);
Rafael Espindolab6082a32014-01-22 16:43:45 +0000515
516 return NewFD;
517}
518
519const sys::fs::file_status &NewArchiveIterator::getStatus() const {
520 assert(IsNewMember);
521 assert(NewFD != -1 && "Must call getFD first");
522 return NewStatus;
523}
524
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000525template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000526void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
527 int Pos = -1) {
528 NewArchiveIterator NI(I, Name);
529 if (Pos == -1)
530 Members.push_back(NI);
531 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000532 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000533}
534
Rafael Espindola623c3d82013-07-22 15:11:51 +0000535enum InsertAction {
536 IA_AddOldMember,
537 IA_AddNewMeber,
538 IA_Delete,
539 IA_MoveOldMember,
540 IA_MoveNewMember
541};
542
543static InsertAction
544computeInsertAction(ArchiveOperation Operation,
545 object::Archive::child_iterator I, StringRef Name,
546 std::vector<std::string>::iterator &Pos) {
547 if (Operation == QuickAppend || Members.empty())
548 return IA_AddOldMember;
549
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000550 std::vector<std::string>::iterator MI = std::find_if(
551 Members.begin(), Members.end(),
552 [Name](StringRef Path) { return Name == sys::path::filename(Path); });
Rafael Espindola623c3d82013-07-22 15:11:51 +0000553
554 if (MI == Members.end())
555 return IA_AddOldMember;
556
557 Pos = MI;
558
559 if (Operation == Delete)
560 return IA_Delete;
561
562 if (Operation == Move)
563 return IA_MoveOldMember;
564
565 if (Operation == ReplaceOrInsert) {
566 StringRef PosName = sys::path::filename(RelPos);
567 if (!OnlyUpdate) {
568 if (PosName.empty())
569 return IA_AddNewMeber;
570 return IA_MoveNewMember;
571 }
572
573 // We could try to optimize this to a fstat, but it is not a common
574 // operation.
575 sys::fs::file_status Status;
Filipe Cabecinhasb4988592014-05-23 05:52:12 +0000576 failIfError(sys::fs::status(*MI, Status), *MI);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000577 if (Status.getLastModificationTime() < I->getLastModified()) {
578 if (PosName.empty())
579 return IA_AddOldMember;
580 return IA_MoveOldMember;
581 }
582
583 if (PosName.empty())
584 return IA_AddNewMeber;
585 return IA_MoveNewMember;
586 }
587 llvm_unreachable("No such operation");
588}
589
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000590// We have to walk this twice and computing it is not trivial, so creating an
591// explicit std::vector is actually fairly efficient.
592static std::vector<NewArchiveIterator>
593computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000594 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000595 std::vector<NewArchiveIterator> Ret;
596 std::vector<NewArchiveIterator> Moved;
597 int InsertPos = -1;
598 StringRef PosName = sys::path::filename(RelPos);
599 if (OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000600 for (object::Archive::child_iterator I = OldArchive->child_begin(),
601 E = OldArchive->child_end();
Rafael Espindola9cd24352013-07-21 12:58:07 +0000602 I != E; ++I) {
603 int Pos = Ret.size();
Rafael Espindolaae460022014-06-16 16:08:36 +0000604 ErrorOr<StringRef> NameOrErr = I->getName();
605 failIfError(NameOrErr.getError());
606 StringRef Name = NameOrErr.get();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000607 if (Name == PosName) {
608 assert(AddAfter || AddBefore);
609 if (AddBefore)
610 InsertPos = Pos;
611 else
612 InsertPos = Pos + 1;
613 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000614
615 std::vector<std::string>::iterator MemberI = Members.end();
616 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
617 switch (Action) {
618 case IA_AddOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000619 addMember(Ret, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000620 break;
621 case IA_AddNewMeber:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000622 addMember(Ret, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000623 break;
624 case IA_Delete:
625 break;
626 case IA_MoveOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000627 addMember(Moved, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000628 break;
629 case IA_MoveNewMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000630 addMember(Moved, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000631 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000632 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000633 if (MemberI != Members.end())
634 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000635 }
636 }
637
638 if (Operation == Delete)
639 return Ret;
640
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000641 if (!RelPos.empty() && InsertPos == -1)
642 fail("Insertion point not found");
643
Rafael Espindola623c3d82013-07-22 15:11:51 +0000644 if (RelPos.empty())
645 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000646
Rafael Espindola623c3d82013-07-22 15:11:51 +0000647 assert(unsigned(InsertPos) <= Ret.size());
648 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000649
Rafael Espindola623c3d82013-07-22 15:11:51 +0000650 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000651 int Pos = InsertPos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000652 for (std::vector<std::string>::iterator I = Members.begin(),
Rafael Espindola623c3d82013-07-22 15:11:51 +0000653 E = Members.end();
654 I != E; ++I, ++Pos) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000655 StringRef Name = sys::path::filename(*I);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000656 addMember(Ret, &*I, Name, Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000657 }
658
659 return Ret;
660}
661
662template <typename T>
Rafael Espindolaed900302014-01-14 17:02:09 +0000663static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
664 bool MayTruncate = false) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000665 uint64_t OldPos = OS.tell();
666 OS << Data;
667 unsigned SizeSoFar = OS.tell() - OldPos;
Rafael Espindolaed900302014-01-14 17:02:09 +0000668 if (Size > SizeSoFar) {
669 unsigned Remaining = Size - SizeSoFar;
670 for (unsigned I = 0; I < Remaining; ++I)
671 OS << ' ';
672 } else if (Size < SizeSoFar) {
673 assert(MayTruncate && "Data doesn't fit in Size");
674 // Some of the data this is used for (like UID) can be larger than the
675 // space available in the archive format. Truncate in that case.
676 OS.seek(OldPos + Size);
677 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000678}
679
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000680static void print32BE(raw_fd_ostream &Out, unsigned Val) {
681 for (int I = 3; I >= 0; --I) {
682 char V = (Val >> (8 * I)) & 0xff;
683 Out << V;
684 }
685}
686
687static void printRestOfMemberHeader(raw_fd_ostream &Out,
688 const sys::TimeValue &ModTime, unsigned UID,
689 unsigned GID, unsigned Perms,
690 unsigned Size) {
691 printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
Rafael Espindolaed900302014-01-14 17:02:09 +0000692 printWithSpacePadding(Out, UID, 6, true);
693 printWithSpacePadding(Out, GID, 6, true);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000694 printWithSpacePadding(Out, format("%o", Perms), 8);
695 printWithSpacePadding(Out, Size, 10);
696 Out << "`\n";
697}
698
699static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
700 const sys::TimeValue &ModTime, unsigned UID,
701 unsigned GID, unsigned Perms, unsigned Size) {
702 printWithSpacePadding(Out, Twine(Name) + "/", 16);
703 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
704}
705
706static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
707 const sys::TimeValue &ModTime, unsigned UID,
708 unsigned GID, unsigned Perms, unsigned Size) {
709 Out << '/';
710 printWithSpacePadding(Out, NameOffset, 15);
711 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
712}
713
714static void writeStringTable(raw_fd_ostream &Out,
715 ArrayRef<NewArchiveIterator> Members,
716 std::vector<unsigned> &StringMapIndexes) {
717 unsigned StartOffset = 0;
718 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
719 E = Members.end();
720 I != E; ++I) {
721 StringRef Name = I->getName();
722 if (Name.size() < 16)
723 continue;
724 if (StartOffset == 0) {
725 printWithSpacePadding(Out, "//", 58);
726 Out << "`\n";
727 StartOffset = Out.tell();
728 }
729 StringMapIndexes.push_back(Out.tell() - StartOffset);
730 Out << Name << "/\n";
731 }
732 if (StartOffset == 0)
733 return;
734 if (Out.tell() % 2)
735 Out << '\n';
736 int Pos = Out.tell();
737 Out.seek(StartOffset - 12);
738 printWithSpacePadding(Out, Pos - StartOffset, 10);
739 Out.seek(Pos);
740}
741
Rafael Espindola62b13442014-06-23 21:15:27 +0000742static void
743writeSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
Rafael Espindola48af1c22014-08-19 18:44:46 +0000744 ArrayRef<MemoryBufferRef> Buffers,
Rafael Espindola62b13442014-06-23 21:15:27 +0000745 std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000746 unsigned StartOffset = 0;
747 unsigned MemberNum = 0;
Alp Tokere69170a2014-06-26 22:52:05 +0000748 std::string NameBuf;
749 raw_string_ostream NameOS(NameBuf);
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000750 unsigned NumSyms = 0;
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000751 LLVMContext &Context = getGlobalContext();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000752 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
753 E = Members.end();
754 I != E; ++I, ++MemberNum) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000755 MemoryBufferRef MemberBuffer = Buffers[MemberNum];
Rafael Espindola437b0d52014-07-31 03:12:45 +0000756 ErrorOr<std::unique_ptr<object::SymbolicFile>> ObjOrErr =
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000757 object::SymbolicFile::createSymbolicFile(
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +0000758 MemberBuffer, sys::fs::file_magic::unknown, &Context);
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000759 if (!ObjOrErr)
760 continue; // FIXME: check only for "not an object file" errors.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000761 object::SymbolicFile &Obj = *ObjOrErr.get();
Rafael Espindolab6082a32014-01-22 16:43:45 +0000762
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000763 if (!StartOffset) {
764 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
765 StartOffset = Out.tell();
766 print32BE(Out, 0);
767 }
768
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000769 for (const object::BasicSymbolRef &S : Obj.symbols()) {
Rafael Espindola1fe2c5a2014-06-18 21:14:57 +0000770 uint32_t Symflags = S.getFlags();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000771 if (Symflags & object::SymbolRef::SF_FormatSpecific)
772 continue;
773 if (!(Symflags & object::SymbolRef::SF_Global))
774 continue;
775 if (Symflags & object::SymbolRef::SF_Undefined)
776 continue;
Rafael Espindola1fe2c5a2014-06-18 21:14:57 +0000777 failIfError(S.printName(NameOS));
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000778 NameOS << '\0';
779 ++NumSyms;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000780 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
781 print32BE(Out, 0);
782 }
783 }
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000784 Out << NameOS.str();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000785
786 if (StartOffset == 0)
787 return;
788
789 if (Out.tell() % 2)
790 Out << '\0';
791
792 unsigned Pos = Out.tell();
793 Out.seek(StartOffset - 12);
794 printWithSpacePadding(Out, Pos - StartOffset, 10);
795 Out.seek(StartOffset);
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000796 print32BE(Out, NumSyms);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000797 Out.seek(Pos);
798}
799
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000800static void performWriteOperation(ArchiveOperation Operation,
801 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000802 SmallString<128> TmpArchive;
803 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
804 TmpArchiveFD, TmpArchive));
805
806 TemporaryOutput = TmpArchive.c_str();
807 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
808 raw_fd_ostream &Out = Output.os();
809 Out << "!<arch>\n";
810
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000811 std::vector<NewArchiveIterator> NewMembers =
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000812 computeNewArchiveMembers(Operation, OldArchive);
813
814 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
815
Rafael Espindola48af1c22014-08-19 18:44:46 +0000816 std::vector<std::unique_ptr<MemoryBuffer>> Buffers;
817 std::vector<MemoryBufferRef> Members;
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000818
819 for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000820 NewArchiveIterator &Member = NewMembers[I];
Rafael Espindola48af1c22014-08-19 18:44:46 +0000821 MemoryBufferRef MemberRef;
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000822
823 if (Member.isNewMember()) {
824 const char *Filename = Member.getNew();
825 int FD = Member.getFD();
826 const sys::fs::file_status &Status = Member.getStatus();
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000827 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
828 MemoryBuffer::getOpenFile(FD, Filename, Status.getSize(), false);
829 failIfError(MemberBufferOrErr.getError(), Filename);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000830 Buffers.push_back(std::move(MemberBufferOrErr.get()));
831 MemberRef = Buffers.back()->getMemBufferRef();
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000832 } else {
833 object::Archive::child_iterator OldMember = Member.getOld();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000834 ErrorOr<MemoryBufferRef> MemberBufferOrErr =
835 OldMember->getMemoryBufferRef();
Rafael Espindolaae460022014-06-16 16:08:36 +0000836 failIfError(MemberBufferOrErr.getError());
Rafael Espindola48af1c22014-08-19 18:44:46 +0000837 MemberRef = MemberBufferOrErr.get();
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000838 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000839 Members.push_back(MemberRef);
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000840 }
841
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000842 if (Symtab) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000843 writeSymbolTable(Out, NewMembers, Members, MemberOffsetRefs);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000844 }
845
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000846 std::vector<unsigned> StringMapIndexes;
847 writeStringTable(Out, NewMembers, StringMapIndexes);
848
849 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
850 MemberOffsetRefs.begin();
851
852 unsigned MemberNum = 0;
853 unsigned LongNameMemberNum = 0;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000854 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
855 E = NewMembers.end();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000856 I != E; ++I, ++MemberNum) {
857
858 unsigned Pos = Out.tell();
859 while (MemberRefsI != MemberOffsetRefs.end() &&
860 MemberRefsI->second == MemberNum) {
861 Out.seek(MemberRefsI->first);
862 print32BE(Out, Pos);
863 ++MemberRefsI;
864 }
865 Out.seek(Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000866
Rafael Espindola48af1c22014-08-19 18:44:46 +0000867 MemoryBufferRef File = Members[MemberNum];
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000868 if (I->isNewMember()) {
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000869 const char *FileName = I->getNew();
Rafael Espindolab6082a32014-01-22 16:43:45 +0000870 const sys::fs::file_status &Status = I->getStatus();
NAKAMURA Takumi0d82bac2013-11-08 12:35:56 +0000871
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000872 StringRef Name = sys::path::filename(FileName);
873 if (Name.size() < 16)
874 printMemberHeader(Out, Name, Status.getLastModificationTime(),
875 Status.getUser(), Status.getGroup(),
876 Status.permissions(), Status.getSize());
877 else
878 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
879 Status.getLastModificationTime(), Status.getUser(),
880 Status.getGroup(), Status.permissions(),
881 Status.getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000882 } else {
883 object::Archive::child_iterator OldMember = I->getOld();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000884 StringRef Name = I->getName();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000885
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000886 if (Name.size() < 16)
887 printMemberHeader(Out, Name, OldMember->getLastModified(),
888 OldMember->getUID(), OldMember->getGID(),
889 OldMember->getAccessMode(), OldMember->getSize());
890 else
891 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
892 OldMember->getLastModified(), OldMember->getUID(),
893 OldMember->getGID(), OldMember->getAccessMode(),
894 OldMember->getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000895 }
896
Rafael Espindola48af1c22014-08-19 18:44:46 +0000897 Out << File.getBuffer();
Rafael Espindolaafcc3df2014-01-24 21:32:21 +0000898
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000899 if (Out.tell() % 2)
900 Out << '\n';
901 }
Rafael Espindola09419ad2014-01-24 21:52:44 +0000902
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000903 Output.keep();
904 Out.close();
905 sys::fs::rename(TemporaryOutput, ArchiveName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000906 TemporaryOutput = nullptr;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000907}
908
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000909static void createSymbolTable(object::Archive *OldArchive) {
910 // When an archive is created or modified, if the s option is given, the
911 // resulting archive will have a current symbol table. If the S option
912 // is given, it will have no symbol table.
913 // In summary, we only need to update the symbol table if we have none.
914 // This is actually very common because of broken build systems that think
915 // they have to run ranlib.
916 if (OldArchive->hasSymbolTable())
917 return;
918
919 performWriteOperation(CreateSymTab, OldArchive);
920}
921
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000922static void performOperation(ArchiveOperation Operation,
923 object::Archive *OldArchive) {
924 switch (Operation) {
925 case Print:
926 case DisplayTable:
927 case Extract:
928 performReadOperation(Operation, OldArchive);
929 return;
930
931 case Delete:
932 case Move:
933 case QuickAppend:
934 case ReplaceOrInsert:
935 performWriteOperation(Operation, OldArchive);
936 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000937 case CreateSymTab:
938 createSymbolTable(OldArchive);
939 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000940 }
941 llvm_unreachable("Unknown operation.");
942}
943
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000944static int ar_main(char **argv);
945static int ranlib_main();
946
Reid Spencer84a12bf2004-11-14 22:20:07 +0000947// main - main program for llvm-ar .. see comments in the code
Tanya Lattner57c70a62003-08-28 15:22:38 +0000948int main(int argc, char **argv) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000949 ToolName = argv[0];
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000950 // Print a stack trace if we signal out.
951 sys::PrintStackTraceOnErrorSignal();
952 PrettyStackTraceProgram X(argc, argv);
953 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer84a12bf2004-11-14 22:20:07 +0000954
Reid Spencer84a12bf2004-11-14 22:20:07 +0000955 // Have the command line options parsed and handle things
956 // like --help and --version.
957 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000958 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greife16561c2007-07-05 17:07:56 +0000959 " This program archives bitcode files into single libraries\n"
Reid Spencer84a12bf2004-11-14 22:20:07 +0000960 );
961
Rafael Espindola8e8debc2014-07-03 19:40:08 +0000962 llvm::InitializeAllTargetInfos();
963 llvm::InitializeAllTargetMCs();
964 llvm::InitializeAllAsmParsers();
965
Rafael Espindola0642df32013-08-28 21:00:03 +0000966 StringRef Stem = sys::path::stem(ToolName);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000967 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000968 return ar_main(argv);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000969 if (Stem.find("ranlib") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000970 return ranlib_main();
971 fail("Not ranlib or ar!");
972}
973
974static int performOperation(ArchiveOperation Operation);
975
976int ranlib_main() {
977 if (RestOfArgs.size() != 1)
978 fail(ToolName + "takes just one archive as argument");
979 ArchiveName = RestOfArgs[0];
980 return performOperation(CreateSymTab);
981}
982
983int ar_main(char **argv) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000984 // Do our own parsing of the command line because the CommandLine utility
985 // can't handle the grouped positional parameters without a dash.
986 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000987 return performOperation(Operation);
988}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000989
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000990static int performOperation(ArchiveOperation Operation) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000991 // Create or open the archive object.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000992 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
993 MemoryBuffer::getFile(ArchiveName, -1, false);
994 std::error_code EC = Buf.getError();
Rafael Espindola2a826e42014-06-13 17:20:48 +0000995 if (EC && EC != errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000996 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000997 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000998 return 1;
999 }
1000
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001001 if (!EC) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00001002 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +00001003
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001004 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +00001005 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001006 << "': " << EC.message() << "!\n";
1007 return 1;
1008 }
1009 performOperation(Operation, &Archive);
1010 return 0;
1011 }
1012
Rafael Espindola2a826e42014-06-13 17:20:48 +00001013 assert(EC == errc::no_such_file_or_directory);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001014
1015 if (!shouldCreateArchive(Operation)) {
1016 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
1017 } else {
1018 if (!Create) {
1019 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +00001020 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001021 }
1022 }
1023
Craig Toppere6cb63e2014-04-25 04:24:47 +00001024 performOperation(Operation, nullptr);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +00001025 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +00001026}