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