blob: 40889ab03aaa09d9b522822ca239c9a59b01b699 [file] [log] [blame]
Chris Lattner97f752f2003-12-30 07:45:46 +00001//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-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 Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Tanya Lattner14baebf2003-08-28 15:22:38 +00009//
Misha Brukman3da94ae2005-04-22 00:00:37 +000010// Builds up (relatively) standard unix archive files (.a) containing LLVM
Gabor Greifa99be512007-07-05 17:07:56 +000011// bitcode or other files.
Tanya Lattner14baebf2003-08-28 15:22:38 +000012//
13//===----------------------------------------------------------------------===//
Brian Gaeke4fa9fd32003-10-10 18:47:08 +000014
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/LLVMContext.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/Module.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000017#include "llvm/Object/Archive.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000018#include "llvm/Support/CommandLine.h"
Michael J. Spencer54453f22011-01-10 02:34:23 +000019#include "llvm/Support/FileSystem.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000020#include "llvm/Support/Format.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000021#include "llvm/Support/ManagedStatic.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000023#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000024#include "llvm/Support/Signals.h"
Rafael Espindola34ac52d2013-07-12 20:21:39 +000025#include "llvm/Support/ToolOutputFile.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000026#include "llvm/Support/raw_ostream.h"
Reid Spencer3a1582b2004-11-14 22:20:07 +000027#include <algorithm>
Joerg Sonnenberger975bc072012-10-26 10:49:15 +000028#include <cstdlib>
Chandler Carruthf010c462012-12-04 10:44:52 +000029#include <memory>
Rafael Espindola11ca2e52013-06-20 20:56:14 +000030
31#if !defined(_MSC_VER) && !defined(__MINGW32__)
32#include <unistd.h>
33#else
34#include <io.h>
35#endif
36
Brian Gaeked0fde302003-11-11 22:41:34 +000037using namespace llvm;
38
Rafael Espindola34ac52d2013-07-12 20:21:39 +000039// The name this program was invoked as.
40static StringRef ToolName;
41
42static const char *TemporaryOutput;
Rafael Espindola95779b62013-07-16 16:00:32 +000043static int TmpArchiveFD = -1;
Rafael Espindola34ac52d2013-07-12 20:21:39 +000044
45// fail - Show the error message and exit.
46LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
47 outs() << ToolName << ": " << Error << ".\n";
Rafael Espindola95779b62013-07-16 16:00:32 +000048 if (TmpArchiveFD != -1)
49 close(TmpArchiveFD);
Rafael Espindola34ac52d2013-07-12 20:21:39 +000050 if (TemporaryOutput)
51 sys::fs::remove(TemporaryOutput);
52 exit(1);
53}
54
55static void failIfError(error_code EC, Twine Context = "") {
56 if (!EC)
57 return;
58
59 std::string ContextStr = Context.str();
60 if (ContextStr == "")
61 fail(EC.message());
62 fail(Context + ": " + EC.message());
63}
64
Dan Gohman82f209e2007-10-15 21:10:03 +000065// Option for compatibility with AIX, not used but must allow it to be present.
Misha Brukman3da94ae2005-04-22 00:00:37 +000066static cl::opt<bool>
67X32Option ("X32_64", cl::Hidden,
Reid Spencerbede5832004-11-16 06:41:09 +000068 cl::desc("Ignored option for compatibility with AIX"));
Tanya Lattner14baebf2003-08-28 15:22:38 +000069
Reid Spencerbede5832004-11-16 06:41:09 +000070// llvm-ar operation code and modifier flags. This must come first.
Misha Brukman3da94ae2005-04-22 00:00:37 +000071static cl::opt<std::string>
Reid Spencer3a1582b2004-11-14 22:20:07 +000072Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000073
Reid Spencerbede5832004-11-16 06:41:09 +000074// llvm-ar remaining positional arguments.
Misha Brukman3da94ae2005-04-22 00:00:37 +000075static cl::list<std::string>
76RestOfArgs(cl::Positional, cl::OneOrMore,
Reid Spencer3a1582b2004-11-14 22:20:07 +000077 cl::desc("[relpos] [count] <archive-file> [members]..."));
Tanya Lattner14baebf2003-08-28 15:22:38 +000078
Reid Spencerbede5832004-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 Brukman3da94ae2005-04-22 00:00:37 +000083 "\nOPERATIONS:\n"
Reid Spencerbede5832004-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 Espindola94bc2462012-08-10 01:57:52 +000088 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
Reid Spencerbede5832004-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 Spencerbede5832004-11-16 06:41:09 +000094 " [i] - put file(s) before [relpos] (same as [b])\n"
Reid Spencerbede5832004-11-16 06:41:09 +000095 " [N] - use instance [count] of name\n"
96 " [o] - preserve original dates\n"
Reid Spencerbede5832004-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 Spencerbede5832004-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 Spencerbede5832004-11-16 06:41:09 +0000103);
104
Reid Spencer3a1582b2004-11-14 22:20:07 +0000105// This enumeration delineates the kinds of operations on an archive
106// that are permitted.
107enum ArchiveOperation {
Reid Spencer3a1582b2004-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
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000114 Extract ///< Extract files back to file system
Tanya Lattner57bd7962003-12-06 23:01:25 +0000115};
Tanya Lattner14baebf2003-08-28 15:22:38 +0000116
Reid Spencer3a1582b2004-11-14 22:20:07 +0000117// Modifiers to follow operation to vary behavior
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000118static bool AddAfter = false; ///< 'a' modifier
119static bool AddBefore = false; ///< 'b' modifier
120static bool Create = false; ///< 'c' modifier
121static bool OriginalDates = false; ///< 'o' modifier
122static bool OnlyUpdate = false; ///< 'u' modifier
123static bool Verbose = false; ///< 'v' modifier
Tanya Lattner14baebf2003-08-28 15:22:38 +0000124
Reid Spencer3a1582b2004-11-14 22:20:07 +0000125// Relative Positional Argument (for insert/move). This variable holds
126// the name of the archive member to which the 'a', 'b' or 'i' modifier
127// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
128// one variable.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000129static std::string RelPos;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000130
Reid Spencer3a1582b2004-11-14 22:20:07 +0000131// This variable holds the name of the archive file as given on the
132// command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000133static std::string ArchiveName;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000134
Reid Spencer3a1582b2004-11-14 22:20:07 +0000135// This variable holds the list of member files to proecess, as given
136// on the command line.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000137static std::vector<std::string> Members;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000138
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000139// show_help - Show the error message, the help message and exit.
140LLVM_ATTRIBUTE_NORETURN static void
141show_help(const std::string &msg) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000142 errs() << ToolName << ": " << msg << "\n\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000143 cl::PrintHelpMessage();
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000144 std::exit(1);
145}
146
Reid Spencer3a1582b2004-11-14 22:20:07 +0000147// getRelPos - Extract the member filename from the command line for
148// the [relpos] argument associated with a, b, and i modifiers
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000149static void getRelPos() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000150 if(RestOfArgs.size() == 0)
151 show_help("Expected [relpos] for a, b, or i modifier");
152 RelPos = RestOfArgs[0];
153 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000154}
155
Reid Spencer3a1582b2004-11-14 22:20:07 +0000156// getArchive - Get the archive file name from the command line
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000157static void getArchive() {
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000158 if(RestOfArgs.size() == 0)
159 show_help("An archive name must be specified");
160 ArchiveName = RestOfArgs[0];
161 RestOfArgs.erase(RestOfArgs.begin());
Tanya Lattner57bd7962003-12-06 23:01:25 +0000162}
163
Reid Spencer3a1582b2004-11-14 22:20:07 +0000164// getMembers - Copy over remaining items in RestOfArgs to our Members vector
165// This is just for clarity.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000166static void getMembers() {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000167 if(RestOfArgs.size() > 0)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000168 Members = std::vector<std::string>(RestOfArgs);
Tanya Lattner57bd7962003-12-06 23:01:25 +0000169}
170
Reid Spencer3a1582b2004-11-14 22:20:07 +0000171// parseCommandLine - Parse the command line options as presented and return the
Misha Brukman3da94ae2005-04-22 00:00:37 +0000172// operation specified. Process all modifiers and check to make sure that
Reid Spencer3a1582b2004-11-14 22:20:07 +0000173// constraints on modifier/operation pairs have not been violated.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000174static ArchiveOperation parseCommandLine() {
Tanya Lattner57bd7962003-12-06 23:01:25 +0000175
Reid Spencer3a1582b2004-11-14 22:20:07 +0000176 // Keep track of number of operations. We can only specify one
177 // per execution.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000178 unsigned NumOperations = 0;
179
Reid Spencer3a1582b2004-11-14 22:20:07 +0000180 // Keep track of the number of positional modifiers (a,b,i). Only
181 // one can be specified.
182 unsigned NumPositional = 0;
183
184 // Keep track of which operation was requested
Rafael Espindola87b8a7f92013-07-05 12:12:43 +0000185 ArchiveOperation Operation;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000186
Tanya Lattner57bd7962003-12-06 23:01:25 +0000187 for(unsigned i=0; i<Options.size(); ++i) {
188 switch(Options[i]) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000189 case 'd': ++NumOperations; Operation = Delete; break;
190 case 'm': ++NumOperations; Operation = Move ; break;
191 case 'p': ++NumOperations; Operation = Print; break;
Seo Sanghyeondc32d192007-12-25 13:53:47 +0000192 case 'q': ++NumOperations; Operation = QuickAppend; break;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000193 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000194 case 't': ++NumOperations; Operation = DisplayTable; break;
195 case 'x': ++NumOperations; Operation = Extract; break;
196 case 'c': Create = true; break;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000197 case 'l': /* accepted but unused */ break;
198 case 'o': OriginalDates = true; break;
Rafael Espindola6f2c88a2013-06-20 13:00:30 +0000199 case 's': break; // Ignore for now.
200 case 'S': break; // Ignore for now.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000201 case 'u': OnlyUpdate = true; break;
202 case 'v': Verbose = true; break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000203 case 'a':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000204 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000205 AddAfter = true;
206 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000207 break;
208 case 'b':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000209 getRelPos();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000210 AddBefore = true;
211 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000212 break;
213 case 'i':
Tanya Lattner57bd7962003-12-06 23:01:25 +0000214 getRelPos();
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000215 AddBefore = true;
Reid Spencer3a1582b2004-11-14 22:20:07 +0000216 NumPositional++;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000217 break;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000218 default:
Reid Spencerbede5832004-11-16 06:41:09 +0000219 cl::PrintHelpMessage();
Tanya Lattner57bd7962003-12-06 23:01:25 +0000220 }
221 }
222
Misha Brukman3da94ae2005-04-22 00:00:37 +0000223 // At this point, the next thing on the command line must be
Reid Spencer3a1582b2004-11-14 22:20:07 +0000224 // the archive name.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000225 getArchive();
Reid Spencer3a1582b2004-11-14 22:20:07 +0000226
227 // Everything on the command line at this point is a member.
Tanya Lattner57bd7962003-12-06 23:01:25 +0000228 getMembers();
229
Reid Spencer3a1582b2004-11-14 22:20:07 +0000230 // Perform various checks on the operation/modifier specification
231 // to make sure we are dealing with a legal request.
232 if (NumOperations == 0)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000233 show_help("You must specify at least one of the operations");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000234 if (NumOperations > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000235 show_help("Only one operation may be specified");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000236 if (NumPositional > 1)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000237 show_help("You may only specify one of a, b, and i modifiers");
Rafael Espindola1b3e3ee2013-07-11 15:54:53 +0000238 if (AddAfter || AddBefore) {
Reid Spencer3a1582b2004-11-14 22:20:07 +0000239 if (Operation != Move && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000240 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
241 "the 'm' or 'r' operations");
242 }
Reid Spencer3a1582b2004-11-14 22:20:07 +0000243 if (OriginalDates && Operation != Extract)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000244 show_help("The 'o' modifier is only applicable to the 'x' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000245 if (OnlyUpdate && Operation != ReplaceOrInsert)
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000246 show_help("The 'u' modifier is only applicable to the 'r' operation");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000247
248 // Return the parsed operation to the caller
249 return Operation;
Tanya Lattner57bd7962003-12-06 23:01:25 +0000250}
Tanya Lattner14baebf2003-08-28 15:22:38 +0000251
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000252// Implements the 'p' operation. This function traverses the archive
253// looking for members that match the path list.
254static void doPrint(StringRef Name, object::Archive::child_iterator I) {
255 if (Verbose)
256 outs() << "Printing " << Name << "\n";
Rafael Espindola8fe960e2013-06-19 14:58:16 +0000257
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000258 StringRef Data = I->getBuffer();
259 outs().write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000260}
261
262// putMode - utility function for printing out the file mode when the 't'
263// operation is in verbose mode.
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000264static void printMode(unsigned mode) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000265 if (mode & 004)
Chris Lattner424a04e2010-11-29 23:02:20 +0000266 outs() << "r";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000267 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000268 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000269 if (mode & 002)
Chris Lattner424a04e2010-11-29 23:02:20 +0000270 outs() << "w";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000271 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000272 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000273 if (mode & 001)
Chris Lattner424a04e2010-11-29 23:02:20 +0000274 outs() << "x";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000275 else
Chris Lattner424a04e2010-11-29 23:02:20 +0000276 outs() << "-";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000277}
278
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000279// Implement the 't' operation. This function prints out just
Reid Spencer3a1582b2004-11-14 22:20:07 +0000280// the file names of each of the members. However, if verbose mode is requested
281// ('v' modifier) then the file type, permission mode, user, group, size, and
282// modification time are also printed.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000283static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
284 if (Verbose) {
285 sys::fs::perms Mode = I->getAccessMode();
286 printMode((Mode >> 6) & 007);
287 printMode((Mode >> 3) & 007);
288 printMode(Mode & 007);
289 outs() << ' ' << I->getUID();
290 outs() << '/' << I->getGID();
291 outs() << ' ' << format("%6llu", I->getSize());
292 outs() << ' ' << I->getLastModified().str();
293 outs() << ' ';
Reid Spencer3a1582b2004-11-14 22:20:07 +0000294 }
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000295 outs() << Name << "\n";
Reid Spencer3a1582b2004-11-14 22:20:07 +0000296}
297
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000298// Implement the 'x' operation. This function extracts files back to the file
299// system.
300static void doExtract(StringRef Name, object::Archive::child_iterator I) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000301 // Retain the original mode.
302 sys::fs::perms Mode = I->getAccessMode();
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000303 SmallString<128> Storage = Name;
Rafael Espindola35637fc2013-07-08 16:16:51 +0000304
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000305 int FD;
306 failIfError(
NAKAMURA Takumi946dbd82013-07-17 12:31:50 +0000307 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_Binary, Mode),
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000308 Storage.c_str());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000309
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000310 {
311 raw_fd_ostream file(FD, false);
Reid Spencer3a1582b2004-11-14 22:20:07 +0000312
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000313 // Get the data and its length
314 StringRef Data = I->getBuffer();
Rafael Espindola11ca2e52013-06-20 20:56:14 +0000315
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000316 // Write the data.
317 file.write(Data.data(), Data.size());
Reid Spencer3a1582b2004-11-14 22:20:07 +0000318 }
319
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000320 // If we're supposed to retain the original modification times, etc. do so
321 // now.
322 if (OriginalDates)
323 failIfError(
324 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
Reid Spencer3a1582b2004-11-14 22:20:07 +0000325
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000326 if (close(FD))
327 fail("Could not close the file");
Reid Spencer3a1582b2004-11-14 22:20:07 +0000328}
329
Rafael Espindola2494dfc2013-07-12 16:29:27 +0000330static bool shouldCreateArchive(ArchiveOperation Op) {
Rafael Espindola61de1422013-07-05 13:03:07 +0000331 switch (Op) {
332 case Print:
333 case Delete:
334 case Move:
335 case DisplayTable:
336 case Extract:
337 return false;
338
339 case QuickAppend:
340 case ReplaceOrInsert:
341 return true;
342 }
Michael Gottesman2be430d2013-07-06 02:39:51 +0000343
344 llvm_unreachable("Missing entry in covered switch.");
Rafael Espindola61de1422013-07-05 13:03:07 +0000345}
346
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000347static void performReadOperation(ArchiveOperation Operation,
348 object::Archive *OldArchive) {
349 for (object::Archive::child_iterator I = OldArchive->begin_children(),
350 E = OldArchive->end_children();
351 I != E; ++I) {
352 StringRef Name;
353 failIfError(I->getName(Name));
354
355 if (!Members.empty() &&
356 std::find(Members.begin(), Members.end(), Name) == Members.end())
357 continue;
358
359 switch (Operation) {
360 default:
361 llvm_unreachable("Not a read operation");
362 case Print:
363 doPrint(Name, I);
364 break;
365 case DisplayTable:
366 doDisplayTable(Name, I);
367 break;
368 case Extract:
369 doExtract(Name, I);
370 break;
371 }
372 }
373}
374
375namespace {
376class NewArchiveIterator {
377 bool IsNewMember;
378 SmallString<16> MemberName;
Rafael Espindola33ccfb22013-07-12 20:28:02 +0000379 object::Archive::child_iterator OldI;
Rafael Espindola51392a02013-07-22 15:11:51 +0000380 std::string NewFilename;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000381
382public:
383 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
Rafael Espindola51392a02013-07-22 15:11:51 +0000384 NewArchiveIterator(std::string *I, Twine Name);
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000385 NewArchiveIterator();
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000386 bool isNewMember() const;
387 object::Archive::child_iterator getOld() const;
Rafael Espindola289e2412013-07-16 03:30:10 +0000388 const char *getNew() const;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000389 StringRef getMemberName() const { return MemberName; }
390};
391}
392
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000393NewArchiveIterator::NewArchiveIterator() {}
394
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000395NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
396 Twine Name)
397 : IsNewMember(false), OldI(I) {
398 Name.toVector(MemberName);
399}
400
Rafael Espindola51392a02013-07-22 15:11:51 +0000401NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, Twine Name)
402 : IsNewMember(true), NewFilename(*NewFilename) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000403 Name.toVector(MemberName);
404}
405
406bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
407
408object::Archive::child_iterator NewArchiveIterator::getOld() const {
409 assert(!IsNewMember);
410 return OldI;
411}
412
Rafael Espindola289e2412013-07-16 03:30:10 +0000413const char *NewArchiveIterator::getNew() const {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000414 assert(IsNewMember);
Rafael Espindola51392a02013-07-22 15:11:51 +0000415 return NewFilename.c_str();
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000416}
417
418template <typename T>
419void addMember(std::vector<NewArchiveIterator> &Members,
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000420 std::string &StringTable, T I, StringRef Name, int Pos = -1) {
Rafael Espindola51392a02013-07-22 15:11:51 +0000421 if (Pos == -1) {
422 Pos = Members.size();
423 Members.resize(Pos + 1);
424 }
425
Rafael Espindolac9516512013-07-13 04:14:13 +0000426 if (Name.size() < 16) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000427 NewArchiveIterator NI(I, Twine(Name) + "/");
Rafael Espindola51392a02013-07-22 15:11:51 +0000428 Members[Pos] = NI;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000429 } else {
430 int MapIndex = StringTable.size();
431 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
Rafael Espindola51392a02013-07-22 15:11:51 +0000432 Members[Pos] = NI;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000433 StringTable += Name;
434 StringTable += "/\n";
435 }
436}
437
438namespace {
439class HasName {
440 StringRef Name;
441
442public:
443 HasName(StringRef Name) : Name(Name) {}
444 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
445};
446}
447
Rafael Espindola51392a02013-07-22 15:11:51 +0000448enum InsertAction {
449 IA_AddOldMember,
450 IA_AddNewMeber,
451 IA_Delete,
452 IA_MoveOldMember,
453 IA_MoveNewMember
454};
455
456static InsertAction
457computeInsertAction(ArchiveOperation Operation,
458 object::Archive::child_iterator I, StringRef Name,
459 std::vector<std::string>::iterator &Pos) {
460 if (Operation == QuickAppend || Members.empty())
461 return IA_AddOldMember;
462
463 std::vector<std::string>::iterator MI =
464 std::find_if(Members.begin(), Members.end(), HasName(Name));
465
466 if (MI == Members.end())
467 return IA_AddOldMember;
468
469 Pos = MI;
470
471 if (Operation == Delete)
472 return IA_Delete;
473
474 if (Operation == Move)
475 return IA_MoveOldMember;
476
477 if (Operation == ReplaceOrInsert) {
478 StringRef PosName = sys::path::filename(RelPos);
479 if (!OnlyUpdate) {
480 if (PosName.empty())
481 return IA_AddNewMeber;
482 return IA_MoveNewMember;
483 }
484
485 // We could try to optimize this to a fstat, but it is not a common
486 // operation.
487 sys::fs::file_status Status;
488 failIfError(sys::fs::status(*MI, Status));
489 if (Status.getLastModificationTime() < I->getLastModified()) {
490 if (PosName.empty())
491 return IA_AddOldMember;
492 return IA_MoveOldMember;
493 }
494
495 if (PosName.empty())
496 return IA_AddNewMeber;
497 return IA_MoveNewMember;
498 }
499 llvm_unreachable("No such operation");
500}
501
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000502// We have to walk this twice and computing it is not trivial, so creating an
503// explicit std::vector is actually fairly efficient.
504static std::vector<NewArchiveIterator>
505computeNewArchiveMembers(ArchiveOperation Operation,
506 object::Archive *OldArchive,
507 std::string &StringTable) {
508 std::vector<NewArchiveIterator> Ret;
509 std::vector<NewArchiveIterator> Moved;
510 int InsertPos = -1;
511 StringRef PosName = sys::path::filename(RelPos);
512 if (OldArchive) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000513 for (object::Archive::child_iterator I = OldArchive->begin_children(),
514 E = OldArchive->end_children();
Rafael Espindola02a13642013-07-21 12:58:07 +0000515 I != E; ++I) {
516 int Pos = Ret.size();
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000517 StringRef Name;
518 failIfError(I->getName(Name));
519 if (Name == PosName) {
520 assert(AddAfter || AddBefore);
521 if (AddBefore)
522 InsertPos = Pos;
523 else
524 InsertPos = Pos + 1;
525 }
Rafael Espindola51392a02013-07-22 15:11:51 +0000526
527 std::vector<std::string>::iterator MemberI = Members.end();
528 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
529 switch (Action) {
530 case IA_AddOldMember:
531 addMember(Ret, StringTable, I, Name);
532 break;
533 case IA_AddNewMeber:
534 addMember(Ret, StringTable, &*MemberI, Name);
535 break;
536 case IA_Delete:
537 break;
538 case IA_MoveOldMember:
539 addMember(Moved, StringTable, I, Name);
540 break;
541 case IA_MoveNewMember:
542 addMember(Moved, StringTable, &*MemberI, Name);
543 break;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000544 }
Rafael Espindola51392a02013-07-22 15:11:51 +0000545 if (MemberI != Members.end())
546 Members.erase(MemberI);
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000547 }
548 }
549
550 if (Operation == Delete)
551 return Ret;
552
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000553 if (!RelPos.empty() && InsertPos == -1)
554 fail("Insertion point not found");
555
Rafael Espindola51392a02013-07-22 15:11:51 +0000556 if (RelPos.empty())
557 InsertPos = Ret.size();
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000558
Rafael Espindola51392a02013-07-22 15:11:51 +0000559 assert(unsigned(InsertPos) <= Ret.size());
560 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000561
Rafael Espindola51392a02013-07-22 15:11:51 +0000562 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
Rafael Espindolab55dcfe2013-07-19 21:23:28 +0000563 int Pos = InsertPos;
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000564 for (std::vector<std::string>::iterator I = Members.begin(),
Rafael Espindola51392a02013-07-22 15:11:51 +0000565 E = Members.end();
566 I != E; ++I, ++Pos) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000567 StringRef Name = sys::path::filename(*I);
Rafael Espindola51392a02013-07-22 15:11:51 +0000568 addMember(Ret, StringTable, &*I, Name, Pos);
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000569 }
570
571 return Ret;
572}
573
574template <typename T>
575static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
576 uint64_t OldPos = OS.tell();
577 OS << Data;
578 unsigned SizeSoFar = OS.tell() - OldPos;
579 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
580 unsigned Remaining = Size - SizeSoFar;
581 for (unsigned I = 0; I < Remaining; ++I)
582 OS << ' ';
583}
584
585static void performWriteOperation(ArchiveOperation Operation,
586 object::Archive *OldArchive) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000587 SmallString<128> TmpArchive;
588 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
589 TmpArchiveFD, TmpArchive));
590
591 TemporaryOutput = TmpArchive.c_str();
592 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
593 raw_fd_ostream &Out = Output.os();
594 Out << "!<arch>\n";
595
596 std::string StringTable;
597 std::vector<NewArchiveIterator> NewMembers =
598 computeNewArchiveMembers(Operation, OldArchive, StringTable);
599 if (!StringTable.empty()) {
600 if (StringTable.size() % 2)
601 StringTable += '\n';
602 printWithSpacePadding(Out, "//", 48);
603 printWithSpacePadding(Out, StringTable.size(), 10);
604 Out << "`\n";
605 Out << StringTable;
606 }
607
608 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
609 E = NewMembers.end();
610 I != E; ++I) {
611 StringRef Name = I->getMemberName();
612 printWithSpacePadding(Out, Name, 16);
613
614 if (I->isNewMember()) {
Rafael Espindola289e2412013-07-16 03:30:10 +0000615 const char *FileName = I->getNew();
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000616
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000617 int FD;
618 failIfError(sys::fs::openFileForRead(FileName, FD), FileName);
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000619
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000620 sys::fs::file_status Status;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000621 failIfError(sys::fs::status(FD, Status), FileName);
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000622
Rafael Espindola718af782013-07-13 05:07:22 +0000623 OwningPtr<MemoryBuffer> File;
Rafael Espindolabd6cb262013-07-16 03:34:31 +0000624 failIfError(
625 MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
626 FileName);
Rafael Espindola718af782013-07-13 05:07:22 +0000627
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000628 uint64_t secondsSinceEpoch =
629 Status.getLastModificationTime().toEpochTime();
630 printWithSpacePadding(Out, secondsSinceEpoch, 12);
631
632 printWithSpacePadding(Out, Status.getUser(), 6);
633 printWithSpacePadding(Out, Status.getGroup(), 6);
634 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
635 printWithSpacePadding(Out, Status.getSize(), 10);
636 Out << "`\n";
637
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000638 Out << File->getBuffer();
639 } else {
640 object::Archive::child_iterator OldMember = I->getOld();
641
642 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
643 printWithSpacePadding(Out, secondsSinceEpoch, 12);
644
645 printWithSpacePadding(Out, OldMember->getUID(), 6);
646 printWithSpacePadding(Out, OldMember->getGID(), 6);
647 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
648 printWithSpacePadding(Out, OldMember->getSize(), 10);
649 Out << "`\n";
650
651 Out << OldMember->getBuffer();
652 }
653
654 if (Out.tell() % 2)
655 Out << '\n';
656 }
657 Output.keep();
658 Out.close();
659 sys::fs::rename(TemporaryOutput, ArchiveName);
660 TemporaryOutput = NULL;
661}
662
663static void performOperation(ArchiveOperation Operation,
664 object::Archive *OldArchive) {
665 switch (Operation) {
666 case Print:
667 case DisplayTable:
668 case Extract:
669 performReadOperation(Operation, OldArchive);
670 return;
671
672 case Delete:
673 case Move:
674 case QuickAppend:
675 case ReplaceOrInsert:
676 performWriteOperation(Operation, OldArchive);
677 return;
678 }
679 llvm_unreachable("Unknown operation.");
680}
681
Reid Spencer3a1582b2004-11-14 22:20:07 +0000682// main - main program for llvm-ar .. see comments in the code
Tanya Lattner14baebf2003-08-28 15:22:38 +0000683int main(int argc, char **argv) {
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000684 ToolName = argv[0];
Chris Lattnercc14d252009-03-06 05:34:10 +0000685 // Print a stack trace if we signal out.
686 sys::PrintStackTraceOnErrorSignal();
687 PrettyStackTraceProgram X(argc, argv);
688 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer3a1582b2004-11-14 22:20:07 +0000689
Reid Spencer3a1582b2004-11-14 22:20:07 +0000690 // Have the command line options parsed and handle things
691 // like --help and --version.
692 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000693 "LLVM Archiver (llvm-ar)\n\n"
Gabor Greifa99be512007-07-05 17:07:56 +0000694 " This program archives bitcode files into single libraries\n"
Reid Spencer3a1582b2004-11-14 22:20:07 +0000695 );
696
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000697 // Do our own parsing of the command line because the CommandLine utility
698 // can't handle the grouped positional parameters without a dash.
699 ArchiveOperation Operation = parseCommandLine();
Tanya Lattner14baebf2003-08-28 15:22:38 +0000700
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000701 // Create or open the archive object.
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000702 OwningPtr<MemoryBuffer> Buf;
703 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
704 if (EC && EC != llvm::errc::no_such_file_or_directory) {
705 errs() << argv[0] << ": error opening '" << ArchiveName
706 << "': " << EC.message() << "!\n";
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000707 return 1;
708 }
709
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000710 if (!EC) {
711 object::Archive Archive(Buf.take(), EC);
Joerg Sonnenberger975bc072012-10-26 10:49:15 +0000712
Rafael Espindola34ac52d2013-07-12 20:21:39 +0000713 if (EC) {
714 errs() << argv[0] << ": error loading '" << ArchiveName
715 << "': " << EC.message() << "!\n";
716 return 1;
717 }
718 performOperation(Operation, &Archive);
719 return 0;
720 }
721
722 assert(EC == llvm::errc::no_such_file_or_directory);
723
724 if (!shouldCreateArchive(Operation)) {
725 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
726 } else {
727 if (!Create) {
728 // Produce a warning if we should and we're creating the archive
729 errs() << argv[0] << ": creating " << ArchiveName << "\n";
730 }
731 }
732
733 performOperation(Operation, NULL);
734 return 0;
Tanya Lattner14baebf2003-08-28 15:22:38 +0000735}