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