blob: d4fe7d789c8bc55efc590315e5da9d4139943459 [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 Espindola023e6562013-07-12 20:28:02 +0000398 object::Archive::child_iterator OldI;
Rafael Espindola623c3d82013-07-22 15:11:51 +0000399 std::string NewFilename;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000400
401public:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000402 NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
403 NewArchiveIterator(std::string *I, StringRef Name);
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000404 NewArchiveIterator();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000405 bool isNewMember() const;
406 object::Archive::child_iterator getOld() const;
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000407 const char *getNew() const;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000408 StringRef getName() const;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000409};
410}
411
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000412NewArchiveIterator::NewArchiveIterator() {}
413
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000414NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000415 StringRef Name)
416 : IsNewMember(false), Name(Name), OldI(I) {}
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000417
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000418NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
419 : IsNewMember(true), Name(Name), NewFilename(*NewFilename) {}
420
421StringRef NewArchiveIterator::getName() const { return Name; }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000422
423bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
424
425object::Archive::child_iterator NewArchiveIterator::getOld() const {
426 assert(!IsNewMember);
427 return OldI;
428}
429
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000430const char *NewArchiveIterator::getNew() const {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000431 assert(IsNewMember);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000432 return NewFilename.c_str();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000433}
434
435template <typename T>
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000436void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
437 int Pos = -1) {
438 NewArchiveIterator NI(I, Name);
439 if (Pos == -1)
440 Members.push_back(NI);
441 else
Rafael Espindola623c3d82013-07-22 15:11:51 +0000442 Members[Pos] = NI;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000443}
444
445namespace {
446class HasName {
447 StringRef Name;
448
449public:
450 HasName(StringRef Name) : Name(Name) {}
451 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
452};
453}
454
Rafael Espindola623c3d82013-07-22 15:11:51 +0000455enum InsertAction {
456 IA_AddOldMember,
457 IA_AddNewMeber,
458 IA_Delete,
459 IA_MoveOldMember,
460 IA_MoveNewMember
461};
462
463static InsertAction
464computeInsertAction(ArchiveOperation Operation,
465 object::Archive::child_iterator I, StringRef Name,
466 std::vector<std::string>::iterator &Pos) {
467 if (Operation == QuickAppend || Members.empty())
468 return IA_AddOldMember;
469
470 std::vector<std::string>::iterator MI =
471 std::find_if(Members.begin(), Members.end(), HasName(Name));
472
473 if (MI == Members.end())
474 return IA_AddOldMember;
475
476 Pos = MI;
477
478 if (Operation == Delete)
479 return IA_Delete;
480
481 if (Operation == Move)
482 return IA_MoveOldMember;
483
484 if (Operation == ReplaceOrInsert) {
485 StringRef PosName = sys::path::filename(RelPos);
486 if (!OnlyUpdate) {
487 if (PosName.empty())
488 return IA_AddNewMeber;
489 return IA_MoveNewMember;
490 }
491
492 // We could try to optimize this to a fstat, but it is not a common
493 // operation.
494 sys::fs::file_status Status;
495 failIfError(sys::fs::status(*MI, Status));
496 if (Status.getLastModificationTime() < I->getLastModified()) {
497 if (PosName.empty())
498 return IA_AddOldMember;
499 return IA_MoveOldMember;
500 }
501
502 if (PosName.empty())
503 return IA_AddNewMeber;
504 return IA_MoveNewMember;
505 }
506 llvm_unreachable("No such operation");
507}
508
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000509// We have to walk this twice and computing it is not trivial, so creating an
510// explicit std::vector is actually fairly efficient.
511static std::vector<NewArchiveIterator>
512computeNewArchiveMembers(ArchiveOperation Operation,
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000513 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000514 std::vector<NewArchiveIterator> Ret;
515 std::vector<NewArchiveIterator> Moved;
516 int InsertPos = -1;
517 StringRef PosName = sys::path::filename(RelPos);
518 if (OldArchive) {
Rafael Espindola23a97502014-01-21 16:09:45 +0000519 for (object::Archive::child_iterator I = OldArchive->child_begin(),
520 E = OldArchive->child_end();
Rafael Espindola9cd24352013-07-21 12:58:07 +0000521 I != E; ++I) {
522 int Pos = Ret.size();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000523 StringRef Name;
524 failIfError(I->getName(Name));
525 if (Name == PosName) {
526 assert(AddAfter || AddBefore);
527 if (AddBefore)
528 InsertPos = Pos;
529 else
530 InsertPos = Pos + 1;
531 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000532
533 std::vector<std::string>::iterator MemberI = Members.end();
534 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
535 switch (Action) {
536 case IA_AddOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000537 addMember(Ret, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000538 break;
539 case IA_AddNewMeber:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000540 addMember(Ret, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000541 break;
542 case IA_Delete:
543 break;
544 case IA_MoveOldMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000545 addMember(Moved, I, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000546 break;
547 case IA_MoveNewMember:
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000548 addMember(Moved, &*MemberI, Name);
Rafael Espindola623c3d82013-07-22 15:11:51 +0000549 break;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000550 }
Rafael Espindola623c3d82013-07-22 15:11:51 +0000551 if (MemberI != Members.end())
552 Members.erase(MemberI);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000553 }
554 }
555
556 if (Operation == Delete)
557 return Ret;
558
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000559 if (!RelPos.empty() && InsertPos == -1)
560 fail("Insertion point not found");
561
Rafael Espindola623c3d82013-07-22 15:11:51 +0000562 if (RelPos.empty())
563 InsertPos = Ret.size();
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000564
Rafael Espindola623c3d82013-07-22 15:11:51 +0000565 assert(unsigned(InsertPos) <= Ret.size());
566 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000567
Rafael Espindola623c3d82013-07-22 15:11:51 +0000568 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolafcc3a1a2013-07-19 21:23:28 +0000569 int Pos = InsertPos;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000570 for (std::vector<std::string>::iterator I = Members.begin(),
Rafael Espindola623c3d82013-07-22 15:11:51 +0000571 E = Members.end();
572 I != E; ++I, ++Pos) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000573 StringRef Name = sys::path::filename(*I);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000574 addMember(Ret, &*I, Name, Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000575 }
576
577 return Ret;
578}
579
580template <typename T>
Rafael Espindolaed900302014-01-14 17:02:09 +0000581static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
582 bool MayTruncate = false) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000583 uint64_t OldPos = OS.tell();
584 OS << Data;
585 unsigned SizeSoFar = OS.tell() - OldPos;
Rafael Espindolaed900302014-01-14 17:02:09 +0000586 if (Size > SizeSoFar) {
587 unsigned Remaining = Size - SizeSoFar;
588 for (unsigned I = 0; I < Remaining; ++I)
589 OS << ' ';
590 } else if (Size < SizeSoFar) {
591 assert(MayTruncate && "Data doesn't fit in Size");
592 // Some of the data this is used for (like UID) can be larger than the
593 // space available in the archive format. Truncate in that case.
594 OS.seek(OldPos + Size);
595 }
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000596}
597
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000598static void print32BE(raw_fd_ostream &Out, unsigned Val) {
599 for (int I = 3; I >= 0; --I) {
600 char V = (Val >> (8 * I)) & 0xff;
601 Out << V;
602 }
603}
604
605static void printRestOfMemberHeader(raw_fd_ostream &Out,
606 const sys::TimeValue &ModTime, unsigned UID,
607 unsigned GID, unsigned Perms,
608 unsigned Size) {
609 printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
Rafael Espindolaed900302014-01-14 17:02:09 +0000610 printWithSpacePadding(Out, UID, 6, true);
611 printWithSpacePadding(Out, GID, 6, true);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000612 printWithSpacePadding(Out, format("%o", Perms), 8);
613 printWithSpacePadding(Out, Size, 10);
614 Out << "`\n";
615}
616
617static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
618 const sys::TimeValue &ModTime, unsigned UID,
619 unsigned GID, unsigned Perms, unsigned Size) {
620 printWithSpacePadding(Out, Twine(Name) + "/", 16);
621 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
622}
623
624static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
625 const sys::TimeValue &ModTime, unsigned UID,
626 unsigned GID, unsigned Perms, unsigned Size) {
627 Out << '/';
628 printWithSpacePadding(Out, NameOffset, 15);
629 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
630}
631
632static void writeStringTable(raw_fd_ostream &Out,
633 ArrayRef<NewArchiveIterator> Members,
634 std::vector<unsigned> &StringMapIndexes) {
635 unsigned StartOffset = 0;
636 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
637 E = Members.end();
638 I != E; ++I) {
639 StringRef Name = I->getName();
640 if (Name.size() < 16)
641 continue;
642 if (StartOffset == 0) {
643 printWithSpacePadding(Out, "//", 58);
644 Out << "`\n";
645 StartOffset = Out.tell();
646 }
647 StringMapIndexes.push_back(Out.tell() - StartOffset);
648 Out << Name << "/\n";
649 }
650 if (StartOffset == 0)
651 return;
652 if (Out.tell() % 2)
653 Out << '\n';
654 int Pos = Out.tell();
655 Out.seek(StartOffset - 12);
656 printWithSpacePadding(Out, Pos - StartOffset, 10);
657 Out.seek(Pos);
658}
659
660static void writeSymbolTable(
661 raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
662 std::vector<std::pair<unsigned, unsigned> > &MemberOffsetRefs) {
663 unsigned StartOffset = 0;
664 unsigned MemberNum = 0;
665 std::vector<StringRef> SymNames;
Rafael Espindola188bfd22013-07-23 11:02:16 +0000666 std::vector<object::ObjectFile *> DeleteIt;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000667 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
668 E = Members.end();
669 I != E; ++I, ++MemberNum) {
670 object::ObjectFile *Obj;
671 if (I->isNewMember()) {
672 const char *Filename = I->getNew();
Rafael Espindola51cc3602014-01-22 00:14:49 +0000673 if (ErrorOr<object::ObjectFile *> ObjOrErr =
674 object::ObjectFile::createObjectFile(Filename))
675 Obj = ObjOrErr.get();
676 else
677 Obj = NULL;
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000678 } else {
679 object::Archive::child_iterator OldMember = I->getOld();
680 OwningPtr<object::Binary> Binary;
681 error_code EC = OldMember->getAsBinary(Binary);
682 if (EC) { // FIXME: check only for "not an object file" errors.
683 Obj = NULL;
684 } else {
685 Obj = dyn_cast<object::ObjectFile>(Binary.get());
686 if (Obj)
687 Binary.take();
688 }
689 }
690 if (!Obj)
691 continue;
Rafael Espindola188bfd22013-07-23 11:02:16 +0000692 DeleteIt.push_back(Obj);
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000693 if (!StartOffset) {
694 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
695 StartOffset = Out.tell();
696 print32BE(Out, 0);
697 }
698
699 error_code Err;
700 for (object::symbol_iterator I = Obj->begin_symbols(),
701 E = Obj->end_symbols();
702 I != E; I.increment(Err), failIfError(Err)) {
703 uint32_t Symflags;
704 failIfError(I->getFlags(Symflags));
705 if (Symflags & object::SymbolRef::SF_FormatSpecific)
706 continue;
707 if (!(Symflags & object::SymbolRef::SF_Global))
708 continue;
709 if (Symflags & object::SymbolRef::SF_Undefined)
710 continue;
711 StringRef Name;
712 failIfError(I->getName(Name));
713 SymNames.push_back(Name);
714 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
715 print32BE(Out, 0);
716 }
717 }
718 for (std::vector<StringRef>::iterator I = SymNames.begin(),
719 E = SymNames.end();
720 I != E; ++I) {
721 Out << *I;
722 Out << '\0';
723 }
724
Rafael Espindola188bfd22013-07-23 11:02:16 +0000725 for (std::vector<object::ObjectFile *>::iterator I = DeleteIt.begin(),
726 E = DeleteIt.end();
727 I != E; ++I) {
728 object::ObjectFile *O = *I;
729 delete O;
730 }
731
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000732 if (StartOffset == 0)
733 return;
734
735 if (Out.tell() % 2)
736 Out << '\0';
737
738 unsigned Pos = Out.tell();
739 Out.seek(StartOffset - 12);
740 printWithSpacePadding(Out, Pos - StartOffset, 10);
741 Out.seek(StartOffset);
742 print32BE(Out, SymNames.size());
743 Out.seek(Pos);
744}
745
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000746static void performWriteOperation(ArchiveOperation Operation,
747 object::Archive *OldArchive) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000748 SmallString<128> TmpArchive;
749 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
750 TmpArchiveFD, TmpArchive));
751
752 TemporaryOutput = TmpArchive.c_str();
753 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
754 raw_fd_ostream &Out = Output.os();
755 Out << "!<arch>\n";
756
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000757 std::vector<NewArchiveIterator> NewMembers =
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000758 computeNewArchiveMembers(Operation, OldArchive);
759
760 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
761
762 if (Symtab) {
763 writeSymbolTable(Out, NewMembers, MemberOffsetRefs);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000764 }
765
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000766 std::vector<unsigned> StringMapIndexes;
767 writeStringTable(Out, NewMembers, StringMapIndexes);
768
769 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
770 MemberOffsetRefs.begin();
771
772 unsigned MemberNum = 0;
773 unsigned LongNameMemberNum = 0;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000774 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
775 E = NewMembers.end();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000776 I != E; ++I, ++MemberNum) {
777
778 unsigned Pos = Out.tell();
779 while (MemberRefsI != MemberOffsetRefs.end() &&
780 MemberRefsI->second == MemberNum) {
781 Out.seek(MemberRefsI->first);
782 print32BE(Out, Pos);
783 ++MemberRefsI;
784 }
785 Out.seek(Pos);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000786
787 if (I->isNewMember()) {
Rafael Espindola8c1ee472013-07-16 03:30:10 +0000788 const char *FileName = I->getNew();
Rafael Espindolaeed76902013-07-16 03:34:31 +0000789
Rafael Espindola6d354812013-07-16 19:44:17 +0000790 int FD;
791 failIfError(sys::fs::openFileForRead(FileName, FD), FileName);
Rafael Espindolaeed76902013-07-16 03:34:31 +0000792
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000793 sys::fs::file_status Status;
Rafael Espindolaeed76902013-07-16 03:34:31 +0000794 failIfError(sys::fs::status(FD, Status), FileName);
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000795
NAKAMURA Takumi0d82bac2013-11-08 12:35:56 +0000796 // Opening a directory doesn't make sense. Let it failed.
797 // Linux cannot open directories with open(2), although
798 // cygwin and *bsd can.
799 if (Status.type() == sys::fs::file_type::directory_file)
800 failIfError(error_code(errc::is_a_directory, posix_category()),
801 FileName);
802
Rafael Espindola07025fe2013-07-13 05:07:22 +0000803 OwningPtr<MemoryBuffer> File;
Rafael Espindola3d2ac2e2013-07-23 20:25:01 +0000804 failIfError(MemoryBuffer::getOpenFile(FD, FileName, File,
805 Status.getSize(), false),
806 FileName);
Rafael Espindola07025fe2013-07-13 05:07:22 +0000807
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000808 StringRef Name = sys::path::filename(FileName);
809 if (Name.size() < 16)
810 printMemberHeader(Out, Name, Status.getLastModificationTime(),
811 Status.getUser(), Status.getGroup(),
812 Status.permissions(), Status.getSize());
813 else
814 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
815 Status.getLastModificationTime(), Status.getUser(),
816 Status.getGroup(), Status.permissions(),
817 Status.getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000818 Out << File->getBuffer();
819 } else {
820 object::Archive::child_iterator OldMember = I->getOld();
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000821 StringRef Name = I->getName();
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000822
Rafael Espindolace7f52d2013-07-23 10:47:01 +0000823 if (Name.size() < 16)
824 printMemberHeader(Out, Name, OldMember->getLastModified(),
825 OldMember->getUID(), OldMember->getGID(),
826 OldMember->getAccessMode(), OldMember->getSize());
827 else
828 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
829 OldMember->getLastModified(), OldMember->getUID(),
830 OldMember->getGID(), OldMember->getAccessMode(),
831 OldMember->getSize());
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000832 Out << OldMember->getBuffer();
833 }
834
835 if (Out.tell() % 2)
836 Out << '\n';
837 }
838 Output.keep();
839 Out.close();
840 sys::fs::rename(TemporaryOutput, ArchiveName);
841 TemporaryOutput = NULL;
842}
843
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000844static void createSymbolTable(object::Archive *OldArchive) {
845 // When an archive is created or modified, if the s option is given, the
846 // resulting archive will have a current symbol table. If the S option
847 // is given, it will have no symbol table.
848 // In summary, we only need to update the symbol table if we have none.
849 // This is actually very common because of broken build systems that think
850 // they have to run ranlib.
851 if (OldArchive->hasSymbolTable())
852 return;
853
854 performWriteOperation(CreateSymTab, OldArchive);
855}
856
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000857static void performOperation(ArchiveOperation Operation,
858 object::Archive *OldArchive) {
859 switch (Operation) {
860 case Print:
861 case DisplayTable:
862 case Extract:
863 performReadOperation(Operation, OldArchive);
864 return;
865
866 case Delete:
867 case Move:
868 case QuickAppend:
869 case ReplaceOrInsert:
870 performWriteOperation(Operation, OldArchive);
871 return;
Rafael Espindolab6b5f52e2013-07-29 12:40:31 +0000872 case CreateSymTab:
873 createSymbolTable(OldArchive);
874 return;
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000875 }
876 llvm_unreachable("Unknown operation.");
877}
878
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000879static int ar_main(char **argv);
880static int ranlib_main();
881
Reid Spencer84a12bf2004-11-14 22:20:07 +0000882// main - main program for llvm-ar .. see comments in the code
Tanya Lattner57c70a62003-08-28 15:22:38 +0000883int main(int argc, char **argv) {
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000884 ToolName = argv[0];
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000885 // Print a stack trace if we signal out.
886 sys::PrintStackTraceOnErrorSignal();
887 PrettyStackTraceProgram X(argc, argv);
888 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer84a12bf2004-11-14 22:20:07 +0000889
Reid Spencer84a12bf2004-11-14 22:20:07 +0000890 // Have the command line options parsed and handle things
891 // like --help and --version.
892 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000893 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greife16561c2007-07-05 17:07:56 +0000894 " This program archives bitcode files into single libraries\n"
Reid Spencer84a12bf2004-11-14 22:20:07 +0000895 );
896
Rafael Espindola0642df32013-08-28 21:00:03 +0000897 StringRef Stem = sys::path::stem(ToolName);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000898 if (Stem.find("ar") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000899 return ar_main(argv);
Rafael Espindolae804b1a2013-10-29 14:25:43 +0000900 if (Stem.find("ranlib") != StringRef::npos)
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000901 return ranlib_main();
902 fail("Not ranlib or ar!");
903}
904
905static int performOperation(ArchiveOperation Operation);
906
907int ranlib_main() {
908 if (RestOfArgs.size() != 1)
909 fail(ToolName + "takes just one archive as argument");
910 ArchiveName = RestOfArgs[0];
911 return performOperation(CreateSymTab);
912}
913
914int ar_main(char **argv) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000915 // Do our own parsing of the command line because the CommandLine utility
916 // can't handle the grouped positional parameters without a dash.
917 ArchiveOperation Operation = parseCommandLine();
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000918 return performOperation(Operation);
919}
Tanya Lattner57c70a62003-08-28 15:22:38 +0000920
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000921static int performOperation(ArchiveOperation Operation) {
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000922 // Create or open the archive object.
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000923 OwningPtr<MemoryBuffer> Buf;
924 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
925 if (EC && EC != llvm::errc::no_such_file_or_directory) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000926 errs() << ToolName << ": error opening '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000927 << "': " << EC.message() << "!\n";
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000928 return 1;
929 }
930
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000931 if (!EC) {
932 object::Archive Archive(Buf.take(), EC);
Joerg Sonnenberger4a0f7be2012-10-26 10:49:15 +0000933
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000934 if (EC) {
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000935 errs() << ToolName << ": error loading '" << ArchiveName
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000936 << "': " << EC.message() << "!\n";
937 return 1;
938 }
939 performOperation(Operation, &Archive);
940 return 0;
941 }
942
943 assert(EC == llvm::errc::no_such_file_or_directory);
944
945 if (!shouldCreateArchive(Operation)) {
946 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
947 } else {
948 if (!Create) {
949 // Produce a warning if we should and we're creating the archive
Rafael Espindola0c8a3522013-08-28 16:22:16 +0000950 errs() << ToolName << ": creating " << ArchiveName << "\n";
Rafael Espindola3e2b21c2013-07-12 20:21:39 +0000951 }
952 }
953
954 performOperation(Operation, NULL);
955 return 0;
Tanya Lattner57c70a62003-08-28 15:22:38 +0000956}