blob: b2081e1a7b09f4938165c8536d929fb6ce7b82da [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
Chandler Carruth9fb823b2013-01-02 11:36:10 +000015#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Module.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000017#include "llvm/Object/Archive.h"
Rafael Espindolace7f52d2013-07-23 10:47:01 +000018#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Michael J. Spencer58df2e02011-01-10 02:34:23 +000020#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000022#include "llvm/Support/ManagedStatic.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000023#include "llvm/Support/MemoryBuffer.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000024#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000025#include "llvm/Support/Signals.h"
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000026#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000027#include "llvm/Support/raw_ostream.h"
Reid Spencer84a12bf2004-11-14 22:20:07 +000028#include <algorithm>
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +000029#include <cstdlib>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include <memory>
Rafael Espindola4a3365c2013-06-20 20:56:14 +000031
32#if !defined(_MSC_VER) && !defined(__MINGW32__)
33#include <unistd.h>
34#else
35#include <io.h>
36#endif
37
Brian Gaeke960707c2003-11-11 22:41:34 +000038using namespace llvm;
39
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000040// The name this program was invoked as.
41static StringRef ToolName;
42
43static const char *TemporaryOutput;
Rafael Espindola7303af32013-07-16 16:00:32 +000044static int TmpArchiveFD = -1;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000045
46// fail - Show the error message and exit.
47LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
48 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola7303af32013-07-16 16:00:32 +000049 if (TmpArchiveFD != -1)
50 close(TmpArchiveFD);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +000051 if (TemporaryOutput)
52 sys::fs::remove(TemporaryOutput);
53 exit(1);
54}
55
56static void failIfError(error_code EC, Twine Context = "") {
57 if (!EC)
58 return;
59
60 std::string ContextStr = Context.str();
61 if (ContextStr == "")
62 fail(EC.message());
63 fail(Context + ": " + EC.message());
64}
65
Rafael Espindola0c8a3522013-08-28 16:22:16 +000066// llvm-ar/llvm-ranlib remaining positional arguments.
Misha Brukman650ba8e2005-04-22 00:00:37 +000067static cl::list<std::string>
68RestOfArgs(cl::Positional, cl::OneOrMore,
Reid Spencer84a12bf2004-11-14 22:20:07 +000069 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner57c70a62003-08-28 15:22:38 +000070
Rafael Espindola0c8a3522013-08-28 16:22:16 +000071std::string Options;
72
Reid Spencer9fc38b12004-11-16 06:41:09 +000073// MoreHelp - Provide additional help output explaining the operations and
74// modifiers of llvm-ar. This object instructs the CommandLine library
75// to print the text of the constructor when the --help option is given.
76static cl::extrahelp MoreHelp(
Misha Brukman650ba8e2005-04-22 00:00:37 +000077 "\nOPERATIONS:\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000078 " d[NsS] - delete file(s) from the archive\n"
79 " m[abiSs] - move file(s) in the archive\n"
80 " p[kN] - print file(s) found in the archive\n"
81 " q[ufsS] - quick append file(s) to the archive\n"
Rafael Espindola740a6bc2012-08-10 01:57:52 +000082 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000083 " t - display contents of archive\n"
84 " x[No] - extract file(s) from the archive\n"
85 "\nMODIFIERS (operation specific):\n"
86 " [a] - put file(s) after [relpos]\n"
87 " [b] - put file(s) before [relpos] (same as [i])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000088 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencer9fc38b12004-11-16 06:41:09 +000089 " [N] - use instance [count] of name\n"
90 " [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 Espindola05571532013-07-12 16:29:27 +0000133static std::vector<std::string> Members;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000134
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000135// show_help - Show the error message, the help message and exit.
136LLVM_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
Reid Spencer84a12bf2004-11-14 22:20:07 +0000143// getRelPos - Extract the member filename from the command line for
144// the [relpos] argument 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
Reid Spencer84a12bf2004-11-14 22:20:07 +0000159// getArchive - 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
Reid Spencer84a12bf2004-11-14 22:20:07 +0000167// getMembers - Copy over remaining items in RestOfArgs to our Members vector
168// This is just for clarity.
Rafael Espindola05571532013-07-12 16:29:27 +0000169static void getMembers() {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000170 if(RestOfArgs.size() > 0)
Misha Brukman650ba8e2005-04-22 00:00:37 +0000171 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattnerc970a382003-12-06 23:01:25 +0000172}
173
Reid Spencer84a12bf2004-11-14 22:20:07 +0000174// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman650ba8e2005-04-22 00:00:37 +0000175// operation specified. Process all modifiers and check to make sure that
Reid Spencer84a12bf2004-11-14 22:20:07 +0000176// constraints on modifier/operation pairs have not been violated.
Rafael Espindola05571532013-07-12 16:29:27 +0000177static ArchiveOperation parseCommandLine() {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000178 getOptions();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000179
Reid Spencer84a12bf2004-11-14 22:20:07 +0000180 // Keep track of number of operations. We can only specify one
181 // per execution.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000182 unsigned NumOperations = 0;
183
Reid Spencer84a12bf2004-11-14 22:20:07 +0000184 // Keep track of the number of positional modifiers (a,b,i). Only
185 // one can be specified.
186 unsigned NumPositional = 0;
187
188 // Keep track of which operation was requested
Rafael Espindola544615f2013-07-05 12:12:43 +0000189 ArchiveOperation Operation;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000190
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000191 bool MaybeJustCreateSymTab = false;
192
Tanya Lattnerc970a382003-12-06 23:01:25 +0000193 for(unsigned i=0; i<Options.size(); ++i) {
194 switch(Options[i]) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000195 case 'd': ++NumOperations; Operation = Delete; break;
196 case 'm': ++NumOperations; Operation = Move ; break;
197 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeond42a60b2007-12-25 13:53:47 +0000198 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000199 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000200 case 't': ++NumOperations; Operation = DisplayTable; break;
201 case 'x': ++NumOperations; Operation = Extract; break;
202 case 'c': Create = true; break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000203 case 'l': /* accepted but unused */ break;
204 case 'o': OriginalDates = true; break;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000205 case 's':
206 Symtab = true;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000207 MaybeJustCreateSymTab = true;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000208 break;
209 case 'S':
210 Symtab = false;
211 break;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000212 case 'u': OnlyUpdate = true; break;
213 case 'v': Verbose = true; break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000214 case 'a':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000215 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000216 AddAfter = true;
217 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000218 break;
219 case 'b':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000220 getRelPos();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000221 AddBefore = true;
222 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000223 break;
224 case 'i':
Tanya Lattnerc970a382003-12-06 23:01:25 +0000225 getRelPos();
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000226 AddBefore = true;
Reid Spencer84a12bf2004-11-14 22:20:07 +0000227 NumPositional++;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000228 break;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000229 default:
Reid Spencer9fc38b12004-11-16 06:41:09 +0000230 cl::PrintHelpMessage();
Tanya Lattnerc970a382003-12-06 23:01:25 +0000231 }
232 }
233
Misha Brukman650ba8e2005-04-22 00:00:37 +0000234 // At this point, the next thing on the command line must be
Reid Spencer84a12bf2004-11-14 22:20:07 +0000235 // the archive name.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000236 getArchive();
Reid Spencer84a12bf2004-11-14 22:20:07 +0000237
238 // Everything on the command line at this point is a member.
Tanya Lattnerc970a382003-12-06 23:01:25 +0000239 getMembers();
240
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000241 if (NumOperations == 0 && MaybeJustCreateSymTab) {
242 NumOperations = 1;
243 Operation = CreateSymTab;
244 if (!Members.empty())
245 show_help("The s operation takes only an archive as argument");
246 }
247
Reid Spencer84a12bf2004-11-14 22:20:07 +0000248 // Perform various checks on the operation/modifier specification
249 // to make sure we are dealing with a legal request.
250 if (NumOperations == 0)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000251 show_help("You must specify at least one of the operations");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000252 if (NumOperations > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000253 show_help("Only one operation may be specified");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000254 if (NumPositional > 1)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000255 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindolace2c84e2013-07-11 15:54:53 +0000256 if (AddAfter || AddBefore) {
Reid Spencer84a12bf2004-11-14 22:20:07 +0000257 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000258 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
259 "the 'm' or 'r' operations");
260 }
Reid Spencer84a12bf2004-11-14 22:20:07 +0000261 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000262 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000263 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000264 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000265
266 // Return the parsed operation to the caller
267 return Operation;
Tanya Lattnerc970a382003-12-06 23:01:25 +0000268}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000269
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000270// Implements the 'p' operation. This function traverses the archive
271// looking for members that match the path list.
272static void doPrint(StringRef Name, object::Archive::child_iterator I) {
273 if (Verbose)
274 outs() << "Printing " << Name << "\n";
Rafael Espindola3703fd02013-06-19 14:58:16 +0000275
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000276 StringRef Data = I->getBuffer();
277 outs().write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000278}
279
280// putMode - utility function for printing out the file mode when the 't'
281// operation is in verbose mode.
Rafael Espindola05571532013-07-12 16:29:27 +0000282static void printMode(unsigned mode) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000283 if (mode & 004)
Chris Lattner2907f442010-11-29 23:02:20 +0000284 outs() << "r";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000285 else
Chris Lattner2907f442010-11-29 23:02:20 +0000286 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000287 if (mode & 002)
Chris Lattner2907f442010-11-29 23:02:20 +0000288 outs() << "w";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000289 else
Chris Lattner2907f442010-11-29 23:02:20 +0000290 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000291 if (mode & 001)
Chris Lattner2907f442010-11-29 23:02:20 +0000292 outs() << "x";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000293 else
Chris Lattner2907f442010-11-29 23:02:20 +0000294 outs() << "-";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000295}
296
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000297// Implement the 't' operation. This function prints out just
Reid Spencer84a12bf2004-11-14 22:20:07 +0000298// the file names of each of the members. However, if verbose mode is requested
299// ('v' modifier) then the file type, permission mode, user, group, size, and
300// modification time are also printed.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000301static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
302 if (Verbose) {
303 sys::fs::perms Mode = I->getAccessMode();
304 printMode((Mode >> 6) & 007);
305 printMode((Mode >> 3) & 007);
306 printMode(Mode & 007);
307 outs() << ' ' << I->getUID();
308 outs() << '/' << I->getGID();
309 outs() << ' ' << format("%6llu", I->getSize());
310 outs() << ' ' << I->getLastModified().str();
311 outs() << ' ';
Reid Spencer84a12bf2004-11-14 22:20:07 +0000312 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000313 outs() << Name << "\n";
Reid Spencer84a12bf2004-11-14 22:20:07 +0000314}
315
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000316// Implement the 'x' operation. This function extracts files back to the file
317// system.
318static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000319 // Retain the original mode.
320 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindola6d354812013-07-16 19:44:17 +0000321 SmallString<128> Storage = Name;
Rafael Espindolabb625bb2013-07-08 16:16:51 +0000322
Rafael Espindola6d354812013-07-16 19:44:17 +0000323 int FD;
324 failIfError(
NAKAMURA Takumie08f5692013-07-17 12:31:50 +0000325 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_Binary, Mode),
Rafael Espindola6d354812013-07-16 19:44:17 +0000326 Storage.c_str());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000327
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000328 {
329 raw_fd_ostream file(FD, false);
Reid Spencer84a12bf2004-11-14 22:20:07 +0000330
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000331 // Get the data and its length
332 StringRef Data = I->getBuffer();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000333
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000334 // Write the data.
335 file.write(Data.data(), Data.size());
Reid Spencer84a12bf2004-11-14 22:20:07 +0000336 }
337
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000338 // If we're supposed to retain the original modification times, etc. do so
339 // now.
340 if (OriginalDates)
341 failIfError(
342 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer84a12bf2004-11-14 22:20:07 +0000343
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000344 if (close(FD))
345 fail("Could not close the file");
Reid Spencer84a12bf2004-11-14 22:20:07 +0000346}
347
Rafael Espindola05571532013-07-12 16:29:27 +0000348static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000349 switch (Op) {
350 case Print:
351 case Delete:
352 case Move:
353 case DisplayTable:
354 case Extract:
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000355 case CreateSymTab:
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000356 return false;
357
358 case QuickAppend:
359 case ReplaceOrInsert:
360 return true;
361 }
Michael Gottesman11dd1d02013-07-06 02:39:51 +0000362
363 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola8ef843f2013-07-05 13:03:07 +0000364}
365
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000366static void performReadOperation(ArchiveOperation Operation,
367 object::Archive *OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000368 for (object::Archive::child_iterator I = OldArchive->child_begin(),
369 E = OldArchive->child_end();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000370 I != E; ++I) {
371 StringRef Name;
372 failIfError(I->getName(Name));
373
374 if (!Members.empty() &&
375 std::find(Members.begin(), Members.end(), Name) == Members.end())
376 continue;
377
378 switch (Operation) {
379 default:
380 llvm_unreachable("Not a read operation");
381 case Print:
382 doPrint(Name, I);
383 break;
384 case DisplayTable:
385 doDisplayTable(Name, I);
386 break;
387 case Extract:
388 doExtract(Name, I);
389 break;
390 }
391 }
392}
393
394namespace {
395class NewArchiveIterator {
396 bool IsNewMember;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000397 StringRef Name;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000398
Rafael Espindola023e6562013-07-12 20:28:02 +0000399 object::Archive::child_iterator OldI;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000400
Rafael Espindola623c3d82013-07-22 15:11:51 +0000401 std::string NewFilename;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000402 mutable int NewFD;
403 mutable sys::fs::file_status NewStatus;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000404
405public:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000406 NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
407 NewArchiveIterator(std::string *I, StringRef Name);
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000408 NewArchiveIterator();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000409 bool isNewMember() const;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000410 StringRef getName() const;
Rafael Espindolab6082a32014-01-22 16:43:45 +0000411
412 object::Archive::child_iterator getOld() const;
413
414 const char *getNew() const;
415 int getFD() const;
416 const sys::fs::file_status &getStatus() const;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000417};
418}
419
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000420NewArchiveIterator::NewArchiveIterator() {}
421
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000422NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000423 StringRef Name)
424 : IsNewMember(false), Name(Name), OldI(I) {}
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000425
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000426NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
Rafael Espindolab6082a32014-01-22 16:43:45 +0000427 : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000428
429StringRef NewArchiveIterator::getName() const { return Name; }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000430
431bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
432
433object::Archive::child_iterator NewArchiveIterator::getOld() const {
434 assert(!IsNewMember);
435 return OldI;
436}
437
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000438const char *NewArchiveIterator::getNew() const {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000439 assert(IsNewMember);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000440 return NewFilename.c_str();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000441}
442
Rafael Espindolab6082a32014-01-22 16:43:45 +0000443int NewArchiveIterator::getFD() const {
444 assert(IsNewMember);
445 if (NewFD != -1)
446 return NewFD;
447 failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
448 assert(NewFD != -1);
449
450 failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
451
452 // Opening a directory doesn't make sense. Let it fail.
453 // Linux cannot open directories with open(2), although
454 // cygwin and *bsd can.
455 if (NewStatus.type() == sys::fs::file_type::directory_file)
456 failIfError(error_code(errc::is_a_directory, posix_category()),
457 NewFilename);
458
459 return NewFD;
460}
461
462const sys::fs::file_status &NewArchiveIterator::getStatus() const {
463 assert(IsNewMember);
464 assert(NewFD != -1 && "Must call getFD first");
465 return NewStatus;
466}
467
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000468template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000469void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
470 int Pos = -1) {
471 NewArchiveIterator NI(I, Name);
472 if (Pos == -1)
473 Members.push_back(NI);
474 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000475 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000476}
477
478namespace {
479class HasName {
480 StringRef Name;
481
482public:
483 HasName(StringRef Name) : Name(Name) {}
484 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
485};
486}
487
Rafael Espindola623c3d82013-07-22 15:11:51 +0000488enum InsertAction {
489 IA_AddOldMember,
490 IA_AddNewMeber,
491 IA_Delete,
492 IA_MoveOldMember,
493 IA_MoveNewMember
494};
495
496static InsertAction
497computeInsertAction(ArchiveOperation Operation,
498 object::Archive::child_iterator I, StringRef Name,
499 std::vector<std::string>::iterator &Pos) {
500 if (Operation == QuickAppend || Members.empty())
501 return IA_AddOldMember;
502
503 std::vector<std::string>::iterator MI =
504 std::find_if(Members.begin(), Members.end(), HasName(Name));
505
506 if (MI == Members.end())
507 return IA_AddOldMember;
508
509 Pos = MI;
510
511 if (Operation == Delete)
512 return IA_Delete;
513
514 if (Operation == Move)
515 return IA_MoveOldMember;
516
517 if (Operation == ReplaceOrInsert) {
518 StringRef PosName = sys::path::filename(RelPos);
519 if (!OnlyUpdate) {
520 if (PosName.empty())
521 return IA_AddNewMeber;
522 return IA_MoveNewMember;
523 }
524
525 // We could try to optimize this to a fstat, but it is not a common
526 // operation.
527 sys::fs::file_status Status;
528 failIfError(sys::fs::status(*MI, Status));
529 if (Status.getLastModificationTime() < I->getLastModified()) {
530 if (PosName.empty())
531 return IA_AddOldMember;
532 return IA_MoveOldMember;
533 }
534
535 if (PosName.empty())
536 return IA_AddNewMeber;
537 return IA_MoveNewMember;
538 }
539 llvm_unreachable("No such operation");
540}
541
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000542// We have to walk this twice and computing it is not trivial, so creating an
543// explicit std::vector is actually fairly efficient.
544static std::vector<NewArchiveIterator>
545computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000546 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000547 std::vector<NewArchiveIterator> Ret;
548 std::vector<NewArchiveIterator> Moved;
549 int InsertPos = -1;
550 StringRef PosName = sys::path::filename(RelPos);
551 if (OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000552 for (object::Archive::child_iterator I = OldArchive->child_begin(),
553 E = OldArchive->child_end();
Rafael Espindola9cd24352013-07-21 12:58:07 +0000554 I != E; ++I) {
555 int Pos = Ret.size();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000556 StringRef Name;
557 failIfError(I->getName(Name));
558 if (Name == PosName) {
559 assert(AddAfter || AddBefore);
560 if (AddBefore)
561 InsertPos = Pos;
562 else
563 InsertPos = Pos + 1;
564 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000565
566 std::vector<std::string>::iterator MemberI = Members.end();
567 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
568 switch (Action) {
569 case IA_AddOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000570 addMember(Ret, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000571 break;
572 case IA_AddNewMeber:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000573 addMember(Ret, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000574 break;
575 case IA_Delete:
576 break;
577 case IA_MoveOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000578 addMember(Moved, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000579 break;
580 case IA_MoveNewMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000581 addMember(Moved, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000582 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000583 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000584 if (MemberI != Members.end())
585 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000586 }
587 }
588
589 if (Operation == Delete)
590 return Ret;
591
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000592 if (!RelPos.empty() && InsertPos == -1)
593 fail("Insertion point not found");
594
Rafael Espindola623c3d82013-07-22 15:11:51 +0000595 if (RelPos.empty())
596 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000597
Rafael Espindola623c3d82013-07-22 15:11:51 +0000598 assert(unsigned(InsertPos) <= Ret.size());
599 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000600
Rafael Espindola623c3d82013-07-22 15:11:51 +0000601 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000602 int Pos = InsertPos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000603 for (std::vector<std::string>::iterator I = Members.begin(),
Rafael Espindola623c3d82013-07-22 15:11:51 +0000604 E = Members.end();
605 I != E; ++I, ++Pos) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000606 StringRef Name = sys::path::filename(*I);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000607 addMember(Ret, &*I, Name, Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000608 }
609
610 return Ret;
611}
612
613template <typename T>
Rafael Espindolaed900302014-01-14 17:02:09 +0000614static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
615 bool MayTruncate = false) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000616 uint64_t OldPos = OS.tell();
617 OS << Data;
618 unsigned SizeSoFar = OS.tell() - OldPos;
Rafael Espindolaed900302014-01-14 17:02:09 +0000619 if (Size > SizeSoFar) {
620 unsigned Remaining = Size - SizeSoFar;
621 for (unsigned I = 0; I < Remaining; ++I)
622 OS << ' ';
623 } else if (Size < SizeSoFar) {
624 assert(MayTruncate && "Data doesn't fit in Size");
625 // Some of the data this is used for (like UID) can be larger than the
626 // space available in the archive format. Truncate in that case.
627 OS.seek(OldPos + Size);
628 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000629}
630
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000631static void print32BE(raw_fd_ostream &Out, unsigned Val) {
632 for (int I = 3; I >= 0; --I) {
633 char V = (Val >> (8 * I)) & 0xff;
634 Out << V;
635 }
636}
637
638static void printRestOfMemberHeader(raw_fd_ostream &Out,
639 const sys::TimeValue &ModTime, unsigned UID,
640 unsigned GID, unsigned Perms,
641 unsigned Size) {
642 printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
Rafael Espindolaed900302014-01-14 17:02:09 +0000643 printWithSpacePadding(Out, UID, 6, true);
644 printWithSpacePadding(Out, GID, 6, true);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000645 printWithSpacePadding(Out, format("%o", Perms), 8);
646 printWithSpacePadding(Out, Size, 10);
647 Out << "`\n";
648}
649
650static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
651 const sys::TimeValue &ModTime, unsigned UID,
652 unsigned GID, unsigned Perms, unsigned Size) {
653 printWithSpacePadding(Out, Twine(Name) + "/", 16);
654 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
655}
656
657static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
658 const sys::TimeValue &ModTime, unsigned UID,
659 unsigned GID, unsigned Perms, unsigned Size) {
660 Out << '/';
661 printWithSpacePadding(Out, NameOffset, 15);
662 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
663}
664
665static void writeStringTable(raw_fd_ostream &Out,
666 ArrayRef<NewArchiveIterator> Members,
667 std::vector<unsigned> &StringMapIndexes) {
668 unsigned StartOffset = 0;
669 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
670 E = Members.end();
671 I != E; ++I) {
672 StringRef Name = I->getName();
673 if (Name.size() < 16)
674 continue;
675 if (StartOffset == 0) {
676 printWithSpacePadding(Out, "//", 58);
677 Out << "`\n";
678 StartOffset = Out.tell();
679 }
680 StringMapIndexes.push_back(Out.tell() - StartOffset);
681 Out << Name << "/\n";
682 }
683 if (StartOffset == 0)
684 return;
685 if (Out.tell() % 2)
686 Out << '\n';
687 int Pos = Out.tell();
688 Out.seek(StartOffset - 12);
689 printWithSpacePadding(Out, Pos - StartOffset, 10);
690 Out.seek(Pos);
691}
692
693static void writeSymbolTable(
694 raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
695 std::vector<std::pair<unsigned, unsigned> > &MemberOffsetRefs) {
696 unsigned StartOffset = 0;
697 unsigned MemberNum = 0;
698 std::vector<StringRef> SymNames;
Rafael Espindola188bfd22013-07-23 11:02:16 +0000699 std::vector<object::ObjectFile *> DeleteIt;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000700 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
701 E = Members.end();
702 I != E; ++I, ++MemberNum) {
703 object::ObjectFile *Obj;
704 if (I->isNewMember()) {
705 const char *Filename = I->getNew();
Rafael Espindolab6082a32014-01-22 16:43:45 +0000706 int FD = I->getFD();
707 const sys::fs::file_status &Status = I->getStatus();
708
709 OwningPtr<MemoryBuffer> File;
710 failIfError(MemoryBuffer::getOpenFile(FD, Filename, File,
711 Status.getSize(), false),
712 Filename);
713
Rafael Espindola51cc3602014-01-22 00:14:49 +0000714 if (ErrorOr<object::ObjectFile *> ObjOrErr =
Rafael Espindolab6082a32014-01-22 16:43:45 +0000715 object::ObjectFile::createObjectFile(File.take()))
Rafael Espindola51cc3602014-01-22 00:14:49 +0000716 Obj = ObjOrErr.get();
717 else
718 Obj = NULL;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000719 } else {
720 object::Archive::child_iterator OldMember = I->getOld();
721 OwningPtr<object::Binary> Binary;
722 error_code EC = OldMember->getAsBinary(Binary);
723 if (EC) { // FIXME: check only for "not an object file" errors.
724 Obj = NULL;
725 } else {
726 Obj = dyn_cast<object::ObjectFile>(Binary.get());
727 if (Obj)
728 Binary.take();
729 }
730 }
731 if (!Obj)
732 continue;
Rafael Espindola188bfd22013-07-23 11:02:16 +0000733 DeleteIt.push_back(Obj);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000734 if (!StartOffset) {
735 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
736 StartOffset = Out.tell();
737 print32BE(Out, 0);
738 }
739
740 error_code Err;
741 for (object::symbol_iterator I = Obj->begin_symbols(),
742 E = Obj->end_symbols();
743 I != E; I.increment(Err), failIfError(Err)) {
744 uint32_t Symflags;
745 failIfError(I->getFlags(Symflags));
746 if (Symflags & object::SymbolRef::SF_FormatSpecific)
747 continue;
748 if (!(Symflags & object::SymbolRef::SF_Global))
749 continue;
750 if (Symflags & object::SymbolRef::SF_Undefined)
751 continue;
752 StringRef Name;
753 failIfError(I->getName(Name));
754 SymNames.push_back(Name);
755 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
756 print32BE(Out, 0);
757 }
758 }
759 for (std::vector<StringRef>::iterator I = SymNames.begin(),
760 E = SymNames.end();
761 I != E; ++I) {
762 Out << *I;
763 Out << '\0';
764 }
765
Rafael Espindola188bfd22013-07-23 11:02:16 +0000766 for (std::vector<object::ObjectFile *>::iterator I = DeleteIt.begin(),
767 E = DeleteIt.end();
768 I != E; ++I) {
769 object::ObjectFile *O = *I;
770 delete O;
771 }
772
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000773 if (StartOffset == 0)
774 return;
775
776 if (Out.tell() % 2)
777 Out << '\0';
778
779 unsigned Pos = Out.tell();
780 Out.seek(StartOffset - 12);
781 printWithSpacePadding(Out, Pos - StartOffset, 10);
782 Out.seek(StartOffset);
783 print32BE(Out, SymNames.size());
784 Out.seek(Pos);
785}
786
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000787static void performWriteOperation(ArchiveOperation Operation,
788 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000789 SmallString<128> TmpArchive;
790 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
791 TmpArchiveFD, TmpArchive));
792
793 TemporaryOutput = TmpArchive.c_str();
794 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
795 raw_fd_ostream &Out = Output.os();
796 Out << "!<arch>\n";
797
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000798 std::vector<NewArchiveIterator> NewMembers =
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000799 computeNewArchiveMembers(Operation, OldArchive);
800
801 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
802
803 if (Symtab) {
804 writeSymbolTable(Out, NewMembers, MemberOffsetRefs);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000805 }
806
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000807 std::vector<unsigned> StringMapIndexes;
808 writeStringTable(Out, NewMembers, StringMapIndexes);
809
810 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
811 MemberOffsetRefs.begin();
812
813 unsigned MemberNum = 0;
814 unsigned LongNameMemberNum = 0;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000815 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
816 E = NewMembers.end();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000817 I != E; ++I, ++MemberNum) {
818
819 unsigned Pos = Out.tell();
820 while (MemberRefsI != MemberOffsetRefs.end() &&
821 MemberRefsI->second == MemberNum) {
822 Out.seek(MemberRefsI->first);
823 print32BE(Out, Pos);
824 ++MemberRefsI;
825 }
826 Out.seek(Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000827
828 if (I->isNewMember()) {
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000829 const char *FileName = I->getNew();
Rafael Espindolab6082a32014-01-22 16:43:45 +0000830 int FD = I->getFD();
831 const sys::fs::file_status &Status = I->getStatus();
NAKAMURA Takumi0d82bac2013-11-08 12:35:56 +0000832
Rafael Espindola07025fe2013-07-13 05:07:22 +0000833 OwningPtr<MemoryBuffer> File;
Rafael Espindola3d2ac2e2013-07-23 20:25:01 +0000834 failIfError(MemoryBuffer::getOpenFile(FD, FileName, File,
835 Status.getSize(), false),
836 FileName);
Rafael Espindola07025fe2013-07-13 05:07:22 +0000837
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000838 StringRef Name = sys::path::filename(FileName);
839 if (Name.size() < 16)
840 printMemberHeader(Out, Name, Status.getLastModificationTime(),
841 Status.getUser(), Status.getGroup(),
842 Status.permissions(), Status.getSize());
843 else
844 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
845 Status.getLastModificationTime(), Status.getUser(),
846 Status.getGroup(), Status.permissions(),
847 Status.getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000848 Out << File->getBuffer();
849 } else {
850 object::Archive::child_iterator OldMember = I->getOld();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000851 StringRef Name = I->getName();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000852
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000853 if (Name.size() < 16)
854 printMemberHeader(Out, Name, OldMember->getLastModified(),
855 OldMember->getUID(), OldMember->getGID(),
856 OldMember->getAccessMode(), OldMember->getSize());
857 else
858 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
859 OldMember->getLastModified(), OldMember->getUID(),
860 OldMember->getGID(), OldMember->getAccessMode(),
861 OldMember->getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000862 Out << OldMember->getBuffer();
863 }
864
865 if (Out.tell() % 2)
866 Out << '\n';
867 }
868 Output.keep();
869 Out.close();
870 sys::fs::rename(TemporaryOutput, ArchiveName);
871 TemporaryOutput = NULL;
872}
873
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000874static void createSymbolTable(object::Archive *OldArchive) {
875 // When an archive is created or modified, if the s option is given, the
876 // resulting archive will have a current symbol table. If the S option
877 // is given, it will have no symbol table.
878 // In summary, we only need to update the symbol table if we have none.
879 // This is actually very common because of broken build systems that think
880 // they have to run ranlib.
881 if (OldArchive->hasSymbolTable())
882 return;
883
884 performWriteOperation(CreateSymTab, OldArchive);
885}
886
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000887static void performOperation(ArchiveOperation Operation,
888 object::Archive *OldArchive) {
889 switch (Operation) {
890 case Print:
891 case DisplayTable:
892 case Extract:
893 performReadOperation(Operation, OldArchive);
894 return;
895
896 case Delete:
897 case Move:
898 case QuickAppend:
899 case ReplaceOrInsert:
900 performWriteOperation(Operation, OldArchive);
901 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000902 case CreateSymTab:
903 createSymbolTable(OldArchive);
904 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000905 }
906 llvm_unreachable("Unknown operation.");
907}
908
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000909static int ar_main(char **argv);
910static int ranlib_main();
911
Reid Spencer84a12bf2004-11-14 22:20:07 +0000912// main - main program for llvm-ar .. see comments in the code
Tanya Lattner57c70a62003-08-28 15:22:38 +0000913int main(int argc, char **argv) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000914 ToolName = argv[0];
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000915 // Print a stack trace if we signal out.
916 sys::PrintStackTraceOnErrorSignal();
917 PrettyStackTraceProgram X(argc, argv);
918 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer84a12bf2004-11-14 22:20:07 +0000919
Reid Spencer84a12bf2004-11-14 22:20:07 +0000920 // Have the command line options parsed and handle things
921 // like --help and --version.
922 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000923 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greife16561c2007-07-05 17:07:56 +0000924 " This program archives bitcode files into single libraries\n"
Reid Spencer84a12bf2004-11-14 22:20:07 +0000925 );
926
Rafael Espindola0642df32013-08-28 21:00:03 +0000927 StringRef Stem = sys::path::stem(ToolName);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000928 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000929 return ar_main(argv);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000930 if (Stem.find("ranlib") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000931 return ranlib_main();
932 fail("Not ranlib or ar!");
933}
934
935static int performOperation(ArchiveOperation Operation);
936
937int ranlib_main() {
938 if (RestOfArgs.size() != 1)
939 fail(ToolName + "takes just one archive as argument");
940 ArchiveName = RestOfArgs[0];
941 return performOperation(CreateSymTab);
942}
943
944int ar_main(char **argv) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000945 // Do our own parsing of the command line because the CommandLine utility
946 // can't handle the grouped positional parameters without a dash.
947 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000948 return performOperation(Operation);
949}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000950
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000951static int performOperation(ArchiveOperation Operation) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000952 // Create or open the archive object.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000953 OwningPtr<MemoryBuffer> Buf;
954 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
955 if (EC && EC != llvm::errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000956 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000957 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000958 return 1;
959 }
960
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000961 if (!EC) {
962 object::Archive Archive(Buf.take(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000963
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000964 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000965 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000966 << "': " << EC.message() << "!\n";
967 return 1;
968 }
969 performOperation(Operation, &Archive);
970 return 0;
971 }
972
973 assert(EC == llvm::errc::no_such_file_or_directory);
974
975 if (!shouldCreateArchive(Operation)) {
976 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
977 } else {
978 if (!Create) {
979 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000980 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000981 }
982 }
983
984 performOperation(Operation, NULL);
985 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000986}