xref: /freebsd-src/contrib/llvm-project/llvm/tools/llvm-ar/llvm-ar.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Builds up (relatively) standard unix archive files (.a) containing LLVM
10 // bitcode or other files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/BinaryFormat/Magic.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/Object/Archive.h"
20 #include "llvm/Object/ArchiveWriter.h"
21 #include "llvm/Object/IRObjectFile.h"
22 #include "llvm/Object/MachO.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Object/SymbolicFile.h"
25 #include "llvm/Object/XCOFFObjectFile.h"
26 #include "llvm/Support/Chrono.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormatVariadic.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/InitLLVM.h"
35 #include "llvm/Support/LineIterator.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/StringSaver.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/WithColor.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
45 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
46 
47 #if !defined(_MSC_VER) && !defined(__MINGW32__)
48 #include <unistd.h>
49 #else
50 #include <io.h>
51 #endif
52 
53 #ifdef _WIN32
54 #include "llvm/Support/Windows/WindowsSupport.h"
55 #endif
56 
57 using namespace llvm;
58 
59 // The name this program was invoked as.
60 static StringRef ToolName;
61 
62 // The basename of this program.
63 static StringRef Stem;
64 
65 static void printRanLibHelp(StringRef ToolName) {
66   outs() << "OVERVIEW: LLVM Ranlib\n\n"
67          << "This program generates an index to speed access to archives\n\n"
68          << "USAGE: " + ToolName + " <archive-file>\n\n"
69          << "OPTIONS:\n"
70          << "  -h --help             - Display available options\n"
71          << "  -v --version          - Display the version of this program\n"
72          << "  -D                    - Use zero for timestamps and uids/gids "
73             "(default)\n"
74          << "  -U                    - Use actual timestamps and uids/gids\n";
75 }
76 
77 static void printArHelp(StringRef ToolName) {
78   const char ArOptions[] =
79       R"(OPTIONS:
80   --format              - archive format to create
81     =default            -   default
82     =gnu                -   gnu
83     =darwin             -   darwin
84     =bsd                -   bsd
85     =aix                -   aix (big archive)
86   --plugin=<string>     - ignored for compatibility
87   -h --help             - display this help and exit
88   --output              - the directory to extract archive members to
89   --rsp-quoting         - quoting style for response files
90     =posix              -   posix
91     =windows            -   windows
92   --thin                - create a thin archive
93   --version             - print the version and exit
94   @<file>               - read options from <file>
95 
96 OPERATIONS:
97   d - delete [files] from the archive
98   m - move [files] in the archive
99   p - print contents of [files] found in the archive
100   q - quick append [files] to the archive
101   r - replace or insert [files] into the archive
102   s - act as ranlib
103   t - display list of files in archive
104   x - extract [files] from the archive
105 
106 MODIFIERS:
107   [a] - put [files] after [relpos]
108   [b] - put [files] before [relpos] (same as [i])
109   [c] - do not warn if archive had to be created
110   [D] - use zero for timestamps and uids/gids (default)
111   [h] - display this help and exit
112   [i] - put [files] before [relpos] (same as [b])
113   [l] - ignored for compatibility
114   [L] - add archive's contents
115   [N] - use instance [count] of name
116   [o] - preserve original dates
117   [O] - display member offsets
118   [P] - use full names when matching (implied for thin archives)
119   [s] - create an archive index (cf. ranlib)
120   [S] - do not build a symbol table
121   [T] - deprecated, use --thin instead
122   [u] - update only [files] newer than archive contents
123   [U] - use actual timestamps and uids/gids
124   [v] - be verbose about actions taken
125   [V] - display the version and exit
126 )";
127 
128   outs() << "OVERVIEW: LLVM Archiver\n\n"
129          << "USAGE: " + ToolName +
130                 " [options] [-]<operation>[modifiers] [relpos] "
131                 "[count] <archive> [files]\n"
132          << "       " + ToolName + " -M [<mri-script]\n\n";
133 
134   outs() << ArOptions;
135 }
136 
137 static void printHelpMessage() {
138   if (Stem.contains_insensitive("ranlib"))
139     printRanLibHelp(Stem);
140   else if (Stem.contains_insensitive("ar"))
141     printArHelp(Stem);
142 }
143 
144 static unsigned MRILineNumber;
145 static bool ParsingMRIScript;
146 
147 // Show the error plus the usage message, and exit.
148 [[noreturn]] static void badUsage(Twine Error) {
149   WithColor::error(errs(), ToolName) << Error << "\n";
150   printHelpMessage();
151   exit(1);
152 }
153 
154 // Show the error message and exit.
155 [[noreturn]] static void fail(Twine Error) {
156   if (ParsingMRIScript) {
157     WithColor::error(errs(), ToolName)
158         << "script line " << MRILineNumber << ": " << Error << "\n";
159   } else {
160     WithColor::error(errs(), ToolName) << Error << "\n";
161   }
162   exit(1);
163 }
164 
165 static void failIfError(std::error_code EC, Twine Context = "") {
166   if (!EC)
167     return;
168 
169   std::string ContextStr = Context.str();
170   if (ContextStr.empty())
171     fail(EC.message());
172   fail(Context + ": " + EC.message());
173 }
174 
175 static void failIfError(Error E, Twine Context = "") {
176   if (!E)
177     return;
178 
179   handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
180     std::string ContextStr = Context.str();
181     if (ContextStr.empty())
182       fail(EIB.message());
183     fail(Context + ": " + EIB.message());
184   });
185 }
186 
187 static SmallVector<const char *, 256> PositionalArgs;
188 
189 static bool MRI;
190 
191 namespace {
192 enum Format { Default, GNU, BSD, DARWIN, BIGARCHIVE, Unknown };
193 }
194 
195 static Format FormatType = Default;
196 
197 static std::string Options;
198 
199 // This enumeration delineates the kinds of operations on an archive
200 // that are permitted.
201 enum ArchiveOperation {
202   Print,           ///< Print the contents of the archive
203   Delete,          ///< Delete the specified members
204   Move,            ///< Move members to end or as given by {a,b,i} modifiers
205   QuickAppend,     ///< Quickly append to end of archive
206   ReplaceOrInsert, ///< Replace or Insert members
207   DisplayTable,    ///< Display the table of contents
208   Extract,         ///< Extract files back to file system
209   CreateSymTab     ///< Create a symbol table in an existing archive
210 };
211 
212 // Modifiers to follow operation to vary behavior
213 static bool AddAfter = false;             ///< 'a' modifier
214 static bool AddBefore = false;            ///< 'b' modifier
215 static bool Create = false;               ///< 'c' modifier
216 static bool OriginalDates = false;        ///< 'o' modifier
217 static bool DisplayMemberOffsets = false; ///< 'O' modifier
218 static bool CompareFullPath = false;      ///< 'P' modifier
219 static bool OnlyUpdate = false;           ///< 'u' modifier
220 static bool Verbose = false;              ///< 'v' modifier
221 static bool Symtab = true;                ///< 's' modifier
222 static bool Deterministic = true;         ///< 'D' and 'U' modifiers
223 static bool Thin = false;                 ///< 'T' modifier
224 static bool AddLibrary = false;           ///< 'L' modifier
225 
226 // Relative Positional Argument (for insert/move). This variable holds
227 // the name of the archive member to which the 'a', 'b' or 'i' modifier
228 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
229 // one variable.
230 static std::string RelPos;
231 
232 // Count parameter for 'N' modifier. This variable specifies which file should
233 // match for extract/delete operations when there are multiple matches. This is
234 // 1-indexed. A value of 0 is invalid, and implies 'N' is not used.
235 static int CountParam = 0;
236 
237 // This variable holds the name of the archive file as given on the
238 // command line.
239 static std::string ArchiveName;
240 
241 // Output directory specified by --output.
242 static std::string OutputDir;
243 
244 static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
245 static std::vector<std::unique_ptr<object::Archive>> Archives;
246 
247 // This variable holds the list of member files to proecess, as given
248 // on the command line.
249 static std::vector<StringRef> Members;
250 
251 // Static buffer to hold StringRefs.
252 static BumpPtrAllocator Alloc;
253 
254 // Extract the member filename from the command line for the [relpos] argument
255 // associated with a, b, and i modifiers
256 static void getRelPos() {
257   if (PositionalArgs.empty())
258     fail("expected [relpos] for 'a', 'b', or 'i' modifier");
259   RelPos = PositionalArgs[0];
260   PositionalArgs.erase(PositionalArgs.begin());
261 }
262 
263 // Extract the parameter from the command line for the [count] argument
264 // associated with the N modifier
265 static void getCountParam() {
266   if (PositionalArgs.empty())
267     badUsage("expected [count] for 'N' modifier");
268   auto CountParamArg = StringRef(PositionalArgs[0]);
269   if (CountParamArg.getAsInteger(10, CountParam))
270     badUsage("value for [count] must be numeric, got: " + CountParamArg);
271   if (CountParam < 1)
272     badUsage("value for [count] must be positive, got: " + CountParamArg);
273   PositionalArgs.erase(PositionalArgs.begin());
274 }
275 
276 // Get the archive file name from the command line
277 static void getArchive() {
278   if (PositionalArgs.empty())
279     badUsage("an archive name must be specified");
280   ArchiveName = PositionalArgs[0];
281   PositionalArgs.erase(PositionalArgs.begin());
282 }
283 
284 static object::Archive &readLibrary(const Twine &Library) {
285   auto BufOrErr = MemoryBuffer::getFile(Library, /*IsText=*/false,
286                                         /*RequiresNullTerminator=*/false);
287   failIfError(BufOrErr.getError(), "could not open library " + Library);
288   ArchiveBuffers.push_back(std::move(*BufOrErr));
289   auto LibOrErr =
290       object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
291   failIfError(errorToErrorCode(LibOrErr.takeError()),
292               "could not parse library");
293   Archives.push_back(std::move(*LibOrErr));
294   return *Archives.back();
295 }
296 
297 static void runMRIScript();
298 
299 // Parse the command line options as presented and return the operation
300 // specified. Process all modifiers and check to make sure that constraints on
301 // modifier/operation pairs have not been violated.
302 static ArchiveOperation parseCommandLine() {
303   if (MRI) {
304     if (!PositionalArgs.empty() || !Options.empty())
305       badUsage("cannot mix -M and other options");
306     runMRIScript();
307   }
308 
309   // Keep track of number of operations. We can only specify one
310   // per execution.
311   unsigned NumOperations = 0;
312 
313   // Keep track of the number of positional modifiers (a,b,i). Only
314   // one can be specified.
315   unsigned NumPositional = 0;
316 
317   // Keep track of which operation was requested
318   ArchiveOperation Operation;
319 
320   bool MaybeJustCreateSymTab = false;
321 
322   for (unsigned i = 0; i < Options.size(); ++i) {
323     switch (Options[i]) {
324     case 'd':
325       ++NumOperations;
326       Operation = Delete;
327       break;
328     case 'm':
329       ++NumOperations;
330       Operation = Move;
331       break;
332     case 'p':
333       ++NumOperations;
334       Operation = Print;
335       break;
336     case 'q':
337       ++NumOperations;
338       Operation = QuickAppend;
339       break;
340     case 'r':
341       ++NumOperations;
342       Operation = ReplaceOrInsert;
343       break;
344     case 't':
345       ++NumOperations;
346       Operation = DisplayTable;
347       break;
348     case 'x':
349       ++NumOperations;
350       Operation = Extract;
351       break;
352     case 'c':
353       Create = true;
354       break;
355     case 'l': /* accepted but unused */
356       break;
357     case 'o':
358       OriginalDates = true;
359       break;
360     case 'O':
361       DisplayMemberOffsets = true;
362       break;
363     case 'P':
364       CompareFullPath = true;
365       break;
366     case 's':
367       Symtab = true;
368       MaybeJustCreateSymTab = true;
369       break;
370     case 'S':
371       Symtab = false;
372       break;
373     case 'u':
374       OnlyUpdate = true;
375       break;
376     case 'v':
377       Verbose = true;
378       break;
379     case 'a':
380       getRelPos();
381       AddAfter = true;
382       NumPositional++;
383       break;
384     case 'b':
385       getRelPos();
386       AddBefore = true;
387       NumPositional++;
388       break;
389     case 'i':
390       getRelPos();
391       AddBefore = true;
392       NumPositional++;
393       break;
394     case 'D':
395       Deterministic = true;
396       break;
397     case 'U':
398       Deterministic = false;
399       break;
400     case 'N':
401       getCountParam();
402       break;
403     case 'T':
404       Thin = true;
405       break;
406     case 'L':
407       AddLibrary = true;
408       break;
409     case 'V':
410       cl::PrintVersionMessage();
411       exit(0);
412     case 'h':
413       printHelpMessage();
414       exit(0);
415     default:
416       badUsage(std::string("unknown option ") + Options[i]);
417     }
418   }
419 
420   // Thin archives store path names, so P should be forced.
421   if (Thin)
422     CompareFullPath = true;
423 
424   // At this point, the next thing on the command line must be
425   // the archive name.
426   getArchive();
427 
428   // Everything on the command line at this point is a member.
429   Members.assign(PositionalArgs.begin(), PositionalArgs.end());
430 
431   if (NumOperations == 0 && MaybeJustCreateSymTab) {
432     NumOperations = 1;
433     Operation = CreateSymTab;
434     if (!Members.empty())
435       badUsage("the 's' operation takes only an archive as argument");
436   }
437 
438   // Perform various checks on the operation/modifier specification
439   // to make sure we are dealing with a legal request.
440   if (NumOperations == 0)
441     badUsage("you must specify at least one of the operations");
442   if (NumOperations > 1)
443     badUsage("only one operation may be specified");
444   if (NumPositional > 1)
445     badUsage("you may only specify one of 'a', 'b', and 'i' modifiers");
446   if (AddAfter || AddBefore)
447     if (Operation != Move && Operation != ReplaceOrInsert)
448       badUsage("the 'a', 'b' and 'i' modifiers can only be specified with "
449                "the 'm' or 'r' operations");
450   if (CountParam)
451     if (Operation != Extract && Operation != Delete)
452       badUsage("the 'N' modifier can only be specified with the 'x' or 'd' "
453                "operations");
454   if (OriginalDates && Operation != Extract)
455     badUsage("the 'o' modifier is only applicable to the 'x' operation");
456   if (OnlyUpdate && Operation != ReplaceOrInsert)
457     badUsage("the 'u' modifier is only applicable to the 'r' operation");
458   if (AddLibrary && Operation != QuickAppend)
459     badUsage("the 'L' modifier is only applicable to the 'q' operation");
460 
461   if (!OutputDir.empty()) {
462     if (Operation != Extract)
463       badUsage("--output is only applicable to the 'x' operation");
464     bool IsDir = false;
465     // If OutputDir is not a directory, create_directories may still succeed if
466     // all components of the path prefix are directories. Test is_directory as
467     // well.
468     if (!sys::fs::create_directories(OutputDir))
469       sys::fs::is_directory(OutputDir, IsDir);
470     if (!IsDir)
471       fail("'" + OutputDir + "' is not a directory");
472   }
473 
474   // Return the parsed operation to the caller
475   return Operation;
476 }
477 
478 // Implements the 'p' operation. This function traverses the archive
479 // looking for members that match the path list.
480 static void doPrint(StringRef Name, const object::Archive::Child &C) {
481   if (Verbose)
482     outs() << "Printing " << Name << "\n";
483 
484   Expected<StringRef> DataOrErr = C.getBuffer();
485   failIfError(DataOrErr.takeError());
486   StringRef Data = *DataOrErr;
487   outs().write(Data.data(), Data.size());
488 }
489 
490 // Utility function for printing out the file mode when the 't' operation is in
491 // verbose mode.
492 static void printMode(unsigned mode) {
493   outs() << ((mode & 004) ? "r" : "-");
494   outs() << ((mode & 002) ? "w" : "-");
495   outs() << ((mode & 001) ? "x" : "-");
496 }
497 
498 // Implement the 't' operation. This function prints out just
499 // the file names of each of the members. However, if verbose mode is requested
500 // ('v' modifier) then the file type, permission mode, user, group, size, and
501 // modification time are also printed.
502 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
503   if (Verbose) {
504     Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
505     failIfError(ModeOrErr.takeError());
506     sys::fs::perms Mode = ModeOrErr.get();
507     printMode((Mode >> 6) & 007);
508     printMode((Mode >> 3) & 007);
509     printMode(Mode & 007);
510     Expected<unsigned> UIDOrErr = C.getUID();
511     failIfError(UIDOrErr.takeError());
512     outs() << ' ' << UIDOrErr.get();
513     Expected<unsigned> GIDOrErr = C.getGID();
514     failIfError(GIDOrErr.takeError());
515     outs() << '/' << GIDOrErr.get();
516     Expected<uint64_t> Size = C.getSize();
517     failIfError(Size.takeError());
518     outs() << ' ' << format("%6llu", Size.get());
519     auto ModTimeOrErr = C.getLastModified();
520     failIfError(ModTimeOrErr.takeError());
521     // Note: formatv() only handles the default TimePoint<>, which is in
522     // nanoseconds.
523     // TODO: fix format_provider<TimePoint<>> to allow other units.
524     sys::TimePoint<> ModTimeInNs = ModTimeOrErr.get();
525     outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs);
526     outs() << ' ';
527   }
528 
529   if (C.getParent()->isThin()) {
530     if (!sys::path::is_absolute(Name)) {
531       StringRef ParentDir = sys::path::parent_path(ArchiveName);
532       if (!ParentDir.empty())
533         outs() << sys::path::convert_to_slash(ParentDir) << '/';
534     }
535     outs() << Name;
536   } else {
537     outs() << Name;
538     if (DisplayMemberOffsets)
539       outs() << " 0x" << utohexstr(C.getDataOffset(), true);
540   }
541   outs() << '\n';
542 }
543 
544 static std::string normalizePath(StringRef Path) {
545   return CompareFullPath ? sys::path::convert_to_slash(Path)
546                          : std::string(sys::path::filename(Path));
547 }
548 
549 static bool comparePaths(StringRef Path1, StringRef Path2) {
550 // When on Windows this function calls CompareStringOrdinal
551 // as Windows file paths are case-insensitive.
552 // CompareStringOrdinal compares two Unicode strings for
553 // binary equivalence and allows for case insensitivity.
554 #ifdef _WIN32
555   SmallVector<wchar_t, 128> WPath1, WPath2;
556   failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path1), WPath1));
557   failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path2), WPath2));
558 
559   return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(),
560                               WPath2.size(), true) == CSTR_EQUAL;
561 #else
562   return normalizePath(Path1) == normalizePath(Path2);
563 #endif
564 }
565 
566 // Implement the 'x' operation. This function extracts files back to the file
567 // system.
568 static void doExtract(StringRef Name, const object::Archive::Child &C) {
569   // Retain the original mode.
570   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
571   failIfError(ModeOrErr.takeError());
572   sys::fs::perms Mode = ModeOrErr.get();
573 
574   StringRef outputFilePath;
575   SmallString<128> path;
576   if (OutputDir.empty()) {
577     outputFilePath = sys::path::filename(Name);
578   } else {
579     sys::path::append(path, OutputDir, sys::path::filename(Name));
580     outputFilePath = path.str();
581   }
582 
583   if (Verbose)
584     outs() << "x - " << outputFilePath << '\n';
585 
586   int FD;
587   failIfError(sys::fs::openFileForWrite(outputFilePath, FD,
588                                         sys::fs::CD_CreateAlways,
589                                         sys::fs::OF_None, Mode),
590               Name);
591 
592   {
593     raw_fd_ostream file(FD, false);
594 
595     // Get the data and its length
596     Expected<StringRef> BufOrErr = C.getBuffer();
597     failIfError(BufOrErr.takeError());
598     StringRef Data = BufOrErr.get();
599 
600     // Write the data.
601     file.write(Data.data(), Data.size());
602   }
603 
604   // If we're supposed to retain the original modification times, etc. do so
605   // now.
606   if (OriginalDates) {
607     auto ModTimeOrErr = C.getLastModified();
608     failIfError(ModTimeOrErr.takeError());
609     failIfError(
610         sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get()));
611   }
612 
613   if (close(FD))
614     fail("Could not close the file");
615 }
616 
617 static bool shouldCreateArchive(ArchiveOperation Op) {
618   switch (Op) {
619   case Print:
620   case Delete:
621   case Move:
622   case DisplayTable:
623   case Extract:
624   case CreateSymTab:
625     return false;
626 
627   case QuickAppend:
628   case ReplaceOrInsert:
629     return true;
630   }
631 
632   llvm_unreachable("Missing entry in covered switch.");
633 }
634 
635 static void performReadOperation(ArchiveOperation Operation,
636                                  object::Archive *OldArchive) {
637   if (Operation == Extract && OldArchive->isThin())
638     fail("extracting from a thin archive is not supported");
639 
640   bool Filter = !Members.empty();
641   StringMap<int> MemberCount;
642   {
643     Error Err = Error::success();
644     for (auto &C : OldArchive->children(Err)) {
645       Expected<StringRef> NameOrErr = C.getName();
646       failIfError(NameOrErr.takeError());
647       StringRef Name = NameOrErr.get();
648 
649       if (Filter) {
650         auto I = find_if(Members, [Name](StringRef Path) {
651           return comparePaths(Name, Path);
652         });
653         if (I == Members.end())
654           continue;
655         if (CountParam && ++MemberCount[Name] != CountParam)
656           continue;
657         Members.erase(I);
658       }
659 
660       switch (Operation) {
661       default:
662         llvm_unreachable("Not a read operation");
663       case Print:
664         doPrint(Name, C);
665         break;
666       case DisplayTable:
667         doDisplayTable(Name, C);
668         break;
669       case Extract:
670         doExtract(Name, C);
671         break;
672       }
673     }
674     failIfError(std::move(Err));
675   }
676 
677   if (Members.empty())
678     return;
679   for (StringRef Name : Members)
680     WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n";
681   exit(1);
682 }
683 
684 static void addChildMember(std::vector<NewArchiveMember> &Members,
685                            const object::Archive::Child &M,
686                            bool FlattenArchive = false) {
687   Expected<NewArchiveMember> NMOrErr =
688       NewArchiveMember::getOldMember(M, Deterministic);
689   failIfError(NMOrErr.takeError());
690   // If the child member we're trying to add is thin, use the path relative to
691   // the archive it's in, so the file resolves correctly.
692   if (Thin && FlattenArchive) {
693     StringSaver Saver(Alloc);
694     Expected<std::string> FileNameOrErr(M.getName());
695     failIfError(FileNameOrErr.takeError());
696     if (sys::path::is_absolute(*FileNameOrErr)) {
697       NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr));
698     } else {
699       FileNameOrErr = M.getFullName();
700       failIfError(FileNameOrErr.takeError());
701       Expected<std::string> PathOrErr =
702           computeArchiveRelativePath(ArchiveName, *FileNameOrErr);
703       NMOrErr->MemberName = Saver.save(
704           PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr));
705     }
706   }
707   if (FlattenArchive &&
708       identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
709     Expected<std::string> FileNameOrErr = M.getFullName();
710     failIfError(FileNameOrErr.takeError());
711     object::Archive &Lib = readLibrary(*FileNameOrErr);
712     // When creating thin archives, only flatten if the member is also thin.
713     if (!Thin || Lib.isThin()) {
714       Error Err = Error::success();
715       // Only Thin archives are recursively flattened.
716       for (auto &Child : Lib.children(Err))
717         addChildMember(Members, Child, /*FlattenArchive=*/Thin);
718       failIfError(std::move(Err));
719       return;
720     }
721   }
722   Members.push_back(std::move(*NMOrErr));
723 }
724 
725 static void addMember(std::vector<NewArchiveMember> &Members,
726                       StringRef FileName, bool FlattenArchive = false) {
727   Expected<NewArchiveMember> NMOrErr =
728       NewArchiveMember::getFile(FileName, Deterministic);
729   failIfError(NMOrErr.takeError(), FileName);
730   StringSaver Saver(Alloc);
731   // For regular archives, use the basename of the object path for the member
732   // name. For thin archives, use the full relative paths so the file resolves
733   // correctly.
734   if (!Thin) {
735     NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
736   } else {
737     if (sys::path::is_absolute(FileName))
738       NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
739     else {
740       Expected<std::string> PathOrErr =
741           computeArchiveRelativePath(ArchiveName, FileName);
742       NMOrErr->MemberName = Saver.save(
743           PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
744     }
745   }
746 
747   if (FlattenArchive &&
748       identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
749     object::Archive &Lib = readLibrary(FileName);
750     // When creating thin archives, only flatten if the member is also thin.
751     if (!Thin || Lib.isThin()) {
752       Error Err = Error::success();
753       // Only Thin archives are recursively flattened.
754       for (auto &Child : Lib.children(Err))
755         addChildMember(Members, Child, /*FlattenArchive=*/Thin);
756       failIfError(std::move(Err));
757       return;
758     }
759   }
760   Members.push_back(std::move(*NMOrErr));
761 }
762 
763 enum InsertAction {
764   IA_AddOldMember,
765   IA_AddNewMember,
766   IA_Delete,
767   IA_MoveOldMember,
768   IA_MoveNewMember
769 };
770 
771 static InsertAction computeInsertAction(ArchiveOperation Operation,
772                                         const object::Archive::Child &Member,
773                                         StringRef Name,
774                                         std::vector<StringRef>::iterator &Pos,
775                                         StringMap<int> &MemberCount) {
776   if (Operation == QuickAppend || Members.empty())
777     return IA_AddOldMember;
778   auto MI = find_if(
779       Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
780 
781   if (MI == Members.end())
782     return IA_AddOldMember;
783 
784   Pos = MI;
785 
786   if (Operation == Delete) {
787     if (CountParam && ++MemberCount[Name] != CountParam)
788       return IA_AddOldMember;
789     return IA_Delete;
790   }
791 
792   if (Operation == Move)
793     return IA_MoveOldMember;
794 
795   if (Operation == ReplaceOrInsert) {
796     if (!OnlyUpdate) {
797       if (RelPos.empty())
798         return IA_AddNewMember;
799       return IA_MoveNewMember;
800     }
801 
802     // We could try to optimize this to a fstat, but it is not a common
803     // operation.
804     sys::fs::file_status Status;
805     failIfError(sys::fs::status(*MI, Status), *MI);
806     auto ModTimeOrErr = Member.getLastModified();
807     failIfError(ModTimeOrErr.takeError());
808     if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
809       if (RelPos.empty())
810         return IA_AddOldMember;
811       return IA_MoveOldMember;
812     }
813 
814     if (RelPos.empty())
815       return IA_AddNewMember;
816     return IA_MoveNewMember;
817   }
818   llvm_unreachable("No such operation");
819 }
820 
821 // We have to walk this twice and computing it is not trivial, so creating an
822 // explicit std::vector is actually fairly efficient.
823 static std::vector<NewArchiveMember>
824 computeNewArchiveMembers(ArchiveOperation Operation,
825                          object::Archive *OldArchive) {
826   std::vector<NewArchiveMember> Ret;
827   std::vector<NewArchiveMember> Moved;
828   int InsertPos = -1;
829   if (OldArchive) {
830     Error Err = Error::success();
831     StringMap<int> MemberCount;
832     for (auto &Child : OldArchive->children(Err)) {
833       int Pos = Ret.size();
834       Expected<StringRef> NameOrErr = Child.getName();
835       failIfError(NameOrErr.takeError());
836       std::string Name = std::string(NameOrErr.get());
837       if (comparePaths(Name, RelPos)) {
838         assert(AddAfter || AddBefore);
839         if (AddBefore)
840           InsertPos = Pos;
841         else
842           InsertPos = Pos + 1;
843       }
844 
845       std::vector<StringRef>::iterator MemberI = Members.end();
846       InsertAction Action =
847           computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
848       switch (Action) {
849       case IA_AddOldMember:
850         addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
851         break;
852       case IA_AddNewMember:
853         addMember(Ret, *MemberI);
854         break;
855       case IA_Delete:
856         break;
857       case IA_MoveOldMember:
858         addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
859         break;
860       case IA_MoveNewMember:
861         addMember(Moved, *MemberI);
862         break;
863       }
864       // When processing elements with the count param, we need to preserve the
865       // full members list when iterating over all archive members. For
866       // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
867       // file named member.o it sees; we are not done with member.o the first
868       // time we see it in the archive.
869       if (MemberI != Members.end() && !CountParam)
870         Members.erase(MemberI);
871     }
872     failIfError(std::move(Err));
873   }
874 
875   if (Operation == Delete)
876     return Ret;
877 
878   if (!RelPos.empty() && InsertPos == -1)
879     fail("insertion point not found");
880 
881   if (RelPos.empty())
882     InsertPos = Ret.size();
883 
884   assert(unsigned(InsertPos) <= Ret.size());
885   int Pos = InsertPos;
886   for (auto &M : Moved) {
887     Ret.insert(Ret.begin() + Pos, std::move(M));
888     ++Pos;
889   }
890 
891   if (AddLibrary) {
892     assert(Operation == QuickAppend);
893     for (auto &Member : Members)
894       addMember(Ret, Member, /*FlattenArchive=*/true);
895     return Ret;
896   }
897 
898   std::vector<NewArchiveMember> NewMembers;
899   for (auto &Member : Members)
900     addMember(NewMembers, Member, /*FlattenArchive=*/Thin);
901   Ret.reserve(Ret.size() + NewMembers.size());
902   std::move(NewMembers.begin(), NewMembers.end(),
903             std::inserter(Ret, std::next(Ret.begin(), InsertPos)));
904 
905   return Ret;
906 }
907 
908 static void performWriteOperation(ArchiveOperation Operation,
909                                   object::Archive *OldArchive,
910                                   std::unique_ptr<MemoryBuffer> OldArchiveBuf,
911                                   std::vector<NewArchiveMember> *NewMembersP) {
912   if (OldArchive) {
913     if (Thin && !OldArchive->isThin())
914       fail("cannot convert a regular archive to a thin one");
915 
916     if (OldArchive->isThin())
917       Thin = true;
918   }
919 
920   std::vector<NewArchiveMember> NewMembers;
921   if (!NewMembersP)
922     NewMembers = computeNewArchiveMembers(Operation, OldArchive);
923 
924   object::Archive::Kind Kind;
925   switch (FormatType) {
926   case Default:
927     if (Thin)
928       Kind = object::Archive::K_GNU;
929     else if (OldArchive) {
930       Kind = OldArchive->kind();
931       if (Kind == object::Archive::K_BSD) {
932         auto InferredKind = object::Archive::K_BSD;
933         if (NewMembersP && !NewMembersP->empty())
934           InferredKind = NewMembersP->front().detectKindFromObject();
935         else if (!NewMembers.empty())
936           InferredKind = NewMembers.front().detectKindFromObject();
937         if (InferredKind == object::Archive::K_DARWIN)
938           Kind = object::Archive::K_DARWIN;
939       }
940     } else if (NewMembersP)
941       Kind = !NewMembersP->empty() ? NewMembersP->front().detectKindFromObject()
942                                    : object::Archive::getDefaultKindForHost();
943     else
944       Kind = !NewMembers.empty() ? NewMembers.front().detectKindFromObject()
945                                  : object::Archive::getDefaultKindForHost();
946     break;
947   case GNU:
948     Kind = object::Archive::K_GNU;
949     break;
950   case BSD:
951     if (Thin)
952       fail("only the gnu format has a thin mode");
953     Kind = object::Archive::K_BSD;
954     break;
955   case DARWIN:
956     if (Thin)
957       fail("only the gnu format has a thin mode");
958     Kind = object::Archive::K_DARWIN;
959     break;
960   case BIGARCHIVE:
961     if (Thin)
962       fail("only the gnu format has a thin mode");
963     Kind = object::Archive::K_AIXBIG;
964     break;
965   case Unknown:
966     llvm_unreachable("");
967   }
968 
969   Error E =
970       writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
971                    Kind, Deterministic, Thin, std::move(OldArchiveBuf));
972   failIfError(std::move(E), ArchiveName);
973 }
974 
975 static void createSymbolTable(object::Archive *OldArchive) {
976   // When an archive is created or modified, if the s option is given, the
977   // resulting archive will have a current symbol table. If the S option
978   // is given, it will have no symbol table.
979   // In summary, we only need to update the symbol table if we have none.
980   // This is actually very common because of broken build systems that think
981   // they have to run ranlib.
982   if (OldArchive->hasSymbolTable())
983     return;
984 
985   if (OldArchive->isThin())
986     Thin = true;
987   performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
988 }
989 
990 static void performOperation(ArchiveOperation Operation,
991                              object::Archive *OldArchive,
992                              std::unique_ptr<MemoryBuffer> OldArchiveBuf,
993                              std::vector<NewArchiveMember> *NewMembers) {
994   switch (Operation) {
995   case Print:
996   case DisplayTable:
997   case Extract:
998     performReadOperation(Operation, OldArchive);
999     return;
1000 
1001   case Delete:
1002   case Move:
1003   case QuickAppend:
1004   case ReplaceOrInsert:
1005     performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
1006                           NewMembers);
1007     return;
1008   case CreateSymTab:
1009     createSymbolTable(OldArchive);
1010     return;
1011   }
1012   llvm_unreachable("Unknown operation.");
1013 }
1014 
1015 static int performOperation(ArchiveOperation Operation,
1016                             std::vector<NewArchiveMember> *NewMembers) {
1017   // Create or open the archive object.
1018   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
1019       ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1020   std::error_code EC = Buf.getError();
1021   if (EC && EC != errc::no_such_file_or_directory)
1022     fail("unable to open '" + ArchiveName + "': " + EC.message());
1023 
1024   if (!EC) {
1025     Expected<std::unique_ptr<object::Archive>> ArchiveOrError =
1026         object::Archive::create(Buf.get()->getMemBufferRef());
1027     if (!ArchiveOrError)
1028       failIfError(ArchiveOrError.takeError(),
1029                   "unable to load '" + ArchiveName + "'");
1030 
1031     std::unique_ptr<object::Archive> Archive = std::move(ArchiveOrError.get());
1032     if (Archive->isThin())
1033       CompareFullPath = true;
1034     performOperation(Operation, Archive.get(), std::move(Buf.get()),
1035                      NewMembers);
1036     return 0;
1037   }
1038 
1039   assert(EC == errc::no_such_file_or_directory);
1040 
1041   if (!shouldCreateArchive(Operation)) {
1042     failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
1043   } else {
1044     if (!Create) {
1045       // Produce a warning if we should and we're creating the archive
1046       WithColor::warning(errs(), ToolName)
1047           << "creating " << ArchiveName << "\n";
1048     }
1049   }
1050 
1051   performOperation(Operation, nullptr, nullptr, NewMembers);
1052   return 0;
1053 }
1054 
1055 static void runMRIScript() {
1056   enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1057 
1058   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1059   failIfError(Buf.getError());
1060   const MemoryBuffer &Ref = *Buf.get();
1061   bool Saved = false;
1062   std::vector<NewArchiveMember> NewMembers;
1063   ParsingMRIScript = true;
1064 
1065   for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1066     ++MRILineNumber;
1067     StringRef Line = *I;
1068     Line = Line.split(';').first;
1069     Line = Line.split('*').first;
1070     Line = Line.trim();
1071     if (Line.empty())
1072       continue;
1073     StringRef CommandStr, Rest;
1074     std::tie(CommandStr, Rest) = Line.split(' ');
1075     Rest = Rest.trim();
1076     if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
1077       Rest = Rest.drop_front().drop_back();
1078     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
1079                        .Case("addlib", MRICommand::AddLib)
1080                        .Case("addmod", MRICommand::AddMod)
1081                        .Case("create", MRICommand::Create)
1082                        .Case("createthin", MRICommand::CreateThin)
1083                        .Case("delete", MRICommand::Delete)
1084                        .Case("save", MRICommand::Save)
1085                        .Case("end", MRICommand::End)
1086                        .Default(MRICommand::Invalid);
1087 
1088     switch (Command) {
1089     case MRICommand::AddLib: {
1090       if (!Create)
1091         fail("no output archive has been opened");
1092       object::Archive &Lib = readLibrary(Rest);
1093       {
1094         if (Thin && !Lib.isThin())
1095           fail("cannot add a regular archive's contents to a thin archive");
1096         Error Err = Error::success();
1097         for (auto &Member : Lib.children(Err))
1098           addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1099         failIfError(std::move(Err));
1100       }
1101       break;
1102     }
1103     case MRICommand::AddMod:
1104       if (!Create)
1105         fail("no output archive has been opened");
1106       addMember(NewMembers, Rest);
1107       break;
1108     case MRICommand::CreateThin:
1109       Thin = true;
1110       LLVM_FALLTHROUGH;
1111     case MRICommand::Create:
1112       Create = true;
1113       if (!ArchiveName.empty())
1114         fail("editing multiple archives not supported");
1115       if (Saved)
1116         fail("file already saved");
1117       ArchiveName = std::string(Rest);
1118       if (ArchiveName.empty())
1119         fail("missing archive name");
1120       break;
1121     case MRICommand::Delete: {
1122       llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1123         return comparePaths(M.MemberName, Rest);
1124       });
1125       break;
1126     }
1127     case MRICommand::Save:
1128       Saved = true;
1129       break;
1130     case MRICommand::End:
1131       break;
1132     case MRICommand::Invalid:
1133       fail("unknown command: " + CommandStr);
1134     }
1135   }
1136 
1137   ParsingMRIScript = false;
1138 
1139   // Nothing to do if not saved.
1140   if (Saved)
1141     performOperation(ReplaceOrInsert, /*OldArchive=*/nullptr,
1142                      /*OldArchiveBuf=*/nullptr, &NewMembers);
1143   exit(0);
1144 }
1145 
1146 static bool handleGenericOption(StringRef arg) {
1147   if (arg == "--help" || arg == "-h") {
1148     printHelpMessage();
1149     return true;
1150   }
1151   if (arg == "--version") {
1152     cl::PrintVersionMessage();
1153     return true;
1154   }
1155   return false;
1156 }
1157 
1158 static const char *matchFlagWithArg(StringRef Expected,
1159                                     ArrayRef<const char *>::iterator &ArgIt,
1160                                     ArrayRef<const char *> Args) {
1161   StringRef Arg = *ArgIt;
1162 
1163   if (Arg.startswith("--"))
1164     Arg = Arg.substr(2);
1165 
1166   size_t len = Expected.size();
1167   if (Arg == Expected) {
1168     if (++ArgIt == Args.end())
1169       fail(std::string(Expected) + " requires an argument");
1170 
1171     return *ArgIt;
1172   }
1173   if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
1174     return Arg.data() + len + 1;
1175 
1176   return nullptr;
1177 }
1178 
1179 static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) {
1180   cl::TokenizerCallback Ret =
1181       Triple(sys::getProcessTriple()).getOS() == Triple::Win32
1182           ? cl::TokenizeWindowsCommandLine
1183           : cl::TokenizeGNUCommandLine;
1184 
1185   for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin();
1186        ArgIt != ArgsArr.end(); ++ArgIt) {
1187     if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) {
1188       StringRef MatchRef = Match;
1189       if (MatchRef == "posix")
1190         Ret = cl::TokenizeGNUCommandLine;
1191       else if (MatchRef == "windows")
1192         Ret = cl::TokenizeWindowsCommandLine;
1193       else
1194         fail(std::string("Invalid response file quoting style ") + Match);
1195     }
1196   }
1197 
1198   return Ret;
1199 }
1200 
1201 static int ar_main(int argc, char **argv) {
1202   SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
1203   StringSaver Saver(Alloc);
1204 
1205   cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
1206 
1207   for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
1208        ArgIt != Argv.end(); ++ArgIt) {
1209     const char *Match = nullptr;
1210 
1211     if (handleGenericOption(*ArgIt))
1212       return 0;
1213     if (strcmp(*ArgIt, "--") == 0) {
1214       ++ArgIt;
1215       for (; ArgIt != Argv.end(); ++ArgIt)
1216         PositionalArgs.push_back(*ArgIt);
1217       break;
1218     }
1219 
1220     if (*ArgIt[0] != '-') {
1221       if (Options.empty())
1222         Options += *ArgIt;
1223       else
1224         PositionalArgs.push_back(*ArgIt);
1225       continue;
1226     }
1227 
1228     if (strcmp(*ArgIt, "-M") == 0) {
1229       MRI = true;
1230       continue;
1231     }
1232 
1233     if (strcmp(*ArgIt, "--thin") == 0) {
1234       Thin = true;
1235       continue;
1236     }
1237 
1238     Match = matchFlagWithArg("format", ArgIt, Argv);
1239     if (Match) {
1240       FormatType = StringSwitch<Format>(Match)
1241                        .Case("default", Default)
1242                        .Case("gnu", GNU)
1243                        .Case("darwin", DARWIN)
1244                        .Case("bsd", BSD)
1245                        .Case("bigarchive", BIGARCHIVE)
1246                        .Default(Unknown);
1247       if (FormatType == Unknown)
1248         fail(std::string("Invalid format ") + Match);
1249       continue;
1250     }
1251 
1252     if ((Match = matchFlagWithArg("output", ArgIt, Argv))) {
1253       OutputDir = Match;
1254       continue;
1255     }
1256 
1257     if (matchFlagWithArg("plugin", ArgIt, Argv) ||
1258         matchFlagWithArg("rsp-quoting", ArgIt, Argv))
1259       continue;
1260 
1261     Options += *ArgIt + 1;
1262   }
1263 
1264   ArchiveOperation Operation = parseCommandLine();
1265   return performOperation(Operation, nullptr);
1266 }
1267 
1268 static int ranlib_main(int argc, char **argv) {
1269   bool ArchiveSpecified = false;
1270   for (int i = 1; i < argc; ++i) {
1271     StringRef arg(argv[i]);
1272     if (handleGenericOption(arg)) {
1273       return 0;
1274     } else if (arg.consume_front("-")) {
1275       // Handle the -D/-U flag
1276       while (!arg.empty()) {
1277         if (arg.front() == 'D') {
1278           Deterministic = true;
1279         } else if (arg.front() == 'U') {
1280           Deterministic = false;
1281         } else if (arg.front() == 'h') {
1282           printHelpMessage();
1283           return 0;
1284         } else if (arg.front() == 'v') {
1285           cl::PrintVersionMessage();
1286           return 0;
1287         } else {
1288           // TODO: GNU ranlib also supports a -t flag
1289           fail("Invalid option: '-" + arg + "'");
1290         }
1291         arg = arg.drop_front(1);
1292       }
1293     } else {
1294       if (ArchiveSpecified)
1295         fail("exactly one archive should be specified");
1296       ArchiveSpecified = true;
1297       ArchiveName = arg.str();
1298     }
1299   }
1300   if (!ArchiveSpecified) {
1301     badUsage("an archive name must be specified");
1302   }
1303   return performOperation(CreateSymTab, nullptr);
1304 }
1305 
1306 int llvm_ar_main(int argc, char **argv) {
1307   InitLLVM X(argc, argv);
1308   ToolName = argv[0];
1309 
1310   llvm::InitializeAllTargetInfos();
1311   llvm::InitializeAllTargetMCs();
1312   llvm::InitializeAllAsmParsers();
1313 
1314   Stem = sys::path::stem(ToolName);
1315   auto Is = [](StringRef Tool) {
1316     // We need to recognize the following filenames.
1317     //
1318     // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
1319     // dlltool.exe -> dlltool
1320     // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
1321     auto I = Stem.rfind_insensitive(Tool);
1322     return I != StringRef::npos &&
1323            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
1324   };
1325 
1326   if (Is("dlltool"))
1327     return dlltoolDriverMain(makeArrayRef(argv, argc));
1328   if (Is("ranlib"))
1329     return ranlib_main(argc, argv);
1330   if (Is("lib"))
1331     return libDriverMain(makeArrayRef(argv, argc));
1332   if (Is("ar"))
1333     return ar_main(argc, argv);
1334 
1335   fail("not ranlib, ar, lib or dlltool");
1336 }
1337