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 object::Archive::Kind getDefaultForHost() {
884   Triple HostTriple(sys::getProcessTriple());
885   return HostTriple.isOSDarwin()
886              ? object::Archive::K_DARWIN
887              : (HostTriple.isOSAIX() ? object::Archive::K_AIXBIG
888                                      : object::Archive::K_GNU);
889 }
890 
891 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
892   auto MemBufferRef = Member.Buf->getMemBufferRef();
893   Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
894       object::ObjectFile::createObjectFile(MemBufferRef);
895 
896   if (OptionalObject)
897     return isa<object::MachOObjectFile>(**OptionalObject)
898                ? object::Archive::K_DARWIN
899                : (isa<object::XCOFFObjectFile>(**OptionalObject)
900                       ? object::Archive::K_AIXBIG
901                       : object::Archive::K_GNU);
902 
903   // squelch the error in case we had a non-object file
904   consumeError(OptionalObject.takeError());
905 
906   // If we're adding a bitcode file to the archive, detect the Archive kind
907   // based on the target triple.
908   LLVMContext Context;
909   if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
910     if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
911             MemBufferRef, file_magic::bitcode, &Context)) {
912       auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
913       return Triple(IRObject.getTargetTriple()).isOSDarwin()
914                  ? object::Archive::K_DARWIN
915                  : object::Archive::K_GNU;
916     } else {
917       // Squelch the error in case this was not a SymbolicFile.
918       consumeError(ObjOrErr.takeError());
919     }
920   }
921 
922   return getDefaultForHost();
923 }
924 
925 static void performWriteOperation(ArchiveOperation Operation,
926                                   object::Archive *OldArchive,
927                                   std::unique_ptr<MemoryBuffer> OldArchiveBuf,
928                                   std::vector<NewArchiveMember> *NewMembersP) {
929   if (OldArchive) {
930     if (Thin && !OldArchive->isThin())
931       fail("cannot convert a regular archive to a thin one");
932 
933     if (OldArchive->isThin())
934       Thin = true;
935   }
936 
937   std::vector<NewArchiveMember> NewMembers;
938   if (!NewMembersP)
939     NewMembers = computeNewArchiveMembers(Operation, OldArchive);
940 
941   object::Archive::Kind Kind;
942   switch (FormatType) {
943   case Default:
944     if (Thin)
945       Kind = object::Archive::K_GNU;
946     else if (OldArchive)
947       Kind = OldArchive->kind();
948     else if (NewMembersP)
949       Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
950                                    : getDefaultForHost();
951     else
952       Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
953                                  : getDefaultForHost();
954     break;
955   case GNU:
956     Kind = object::Archive::K_GNU;
957     break;
958   case BSD:
959     if (Thin)
960       fail("only the gnu format has a thin mode");
961     Kind = object::Archive::K_BSD;
962     break;
963   case DARWIN:
964     if (Thin)
965       fail("only the gnu format has a thin mode");
966     Kind = object::Archive::K_DARWIN;
967     break;
968   case BIGARCHIVE:
969     if (Thin)
970       fail("only the gnu format has a thin mode");
971     Kind = object::Archive::K_AIXBIG;
972     break;
973   case Unknown:
974     llvm_unreachable("");
975   }
976 
977   Error E =
978       writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
979                    Kind, Deterministic, Thin, std::move(OldArchiveBuf));
980   failIfError(std::move(E), ArchiveName);
981 }
982 
983 static void createSymbolTable(object::Archive *OldArchive) {
984   // When an archive is created or modified, if the s option is given, the
985   // resulting archive will have a current symbol table. If the S option
986   // is given, it will have no symbol table.
987   // In summary, we only need to update the symbol table if we have none.
988   // This is actually very common because of broken build systems that think
989   // they have to run ranlib.
990   if (OldArchive->hasSymbolTable())
991     return;
992 
993   if (OldArchive->isThin())
994     Thin = true;
995   performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
996 }
997 
998 static void performOperation(ArchiveOperation Operation,
999                              object::Archive *OldArchive,
1000                              std::unique_ptr<MemoryBuffer> OldArchiveBuf,
1001                              std::vector<NewArchiveMember> *NewMembers) {
1002   switch (Operation) {
1003   case Print:
1004   case DisplayTable:
1005   case Extract:
1006     performReadOperation(Operation, OldArchive);
1007     return;
1008 
1009   case Delete:
1010   case Move:
1011   case QuickAppend:
1012   case ReplaceOrInsert:
1013     performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
1014                           NewMembers);
1015     return;
1016   case CreateSymTab:
1017     createSymbolTable(OldArchive);
1018     return;
1019   }
1020   llvm_unreachable("Unknown operation.");
1021 }
1022 
1023 static int performOperation(ArchiveOperation Operation,
1024                             std::vector<NewArchiveMember> *NewMembers) {
1025   // Create or open the archive object.
1026   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
1027       ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1028   std::error_code EC = Buf.getError();
1029   if (EC && EC != errc::no_such_file_or_directory)
1030     fail("unable to open '" + ArchiveName + "': " + EC.message());
1031 
1032   if (!EC) {
1033     Expected<std::unique_ptr<object::Archive>> ArchiveOrError =
1034         object::Archive::create(Buf.get()->getMemBufferRef());
1035     if (!ArchiveOrError)
1036       failIfError(ArchiveOrError.takeError(),
1037                   "unable to load '" + ArchiveName + "'");
1038 
1039     std::unique_ptr<object::Archive> Archive = std::move(ArchiveOrError.get());
1040     if (Archive->isThin())
1041       CompareFullPath = true;
1042     performOperation(Operation, Archive.get(), std::move(Buf.get()),
1043                      NewMembers);
1044     return 0;
1045   }
1046 
1047   assert(EC == errc::no_such_file_or_directory);
1048 
1049   if (!shouldCreateArchive(Operation)) {
1050     failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
1051   } else {
1052     if (!Create) {
1053       // Produce a warning if we should and we're creating the archive
1054       WithColor::warning(errs(), ToolName)
1055           << "creating " << ArchiveName << "\n";
1056     }
1057   }
1058 
1059   performOperation(Operation, nullptr, nullptr, NewMembers);
1060   return 0;
1061 }
1062 
1063 static void runMRIScript() {
1064   enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1065 
1066   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1067   failIfError(Buf.getError());
1068   const MemoryBuffer &Ref = *Buf.get();
1069   bool Saved = false;
1070   std::vector<NewArchiveMember> NewMembers;
1071   ParsingMRIScript = true;
1072 
1073   for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1074     ++MRILineNumber;
1075     StringRef Line = *I;
1076     Line = Line.split(';').first;
1077     Line = Line.split('*').first;
1078     Line = Line.trim();
1079     if (Line.empty())
1080       continue;
1081     StringRef CommandStr, Rest;
1082     std::tie(CommandStr, Rest) = Line.split(' ');
1083     Rest = Rest.trim();
1084     if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
1085       Rest = Rest.drop_front().drop_back();
1086     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
1087                        .Case("addlib", MRICommand::AddLib)
1088                        .Case("addmod", MRICommand::AddMod)
1089                        .Case("create", MRICommand::Create)
1090                        .Case("createthin", MRICommand::CreateThin)
1091                        .Case("delete", MRICommand::Delete)
1092                        .Case("save", MRICommand::Save)
1093                        .Case("end", MRICommand::End)
1094                        .Default(MRICommand::Invalid);
1095 
1096     switch (Command) {
1097     case MRICommand::AddLib: {
1098       object::Archive &Lib = readLibrary(Rest);
1099       {
1100         Error Err = Error::success();
1101         for (auto &Member : Lib.children(Err))
1102           addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1103         failIfError(std::move(Err));
1104       }
1105       break;
1106     }
1107     case MRICommand::AddMod:
1108       addMember(NewMembers, Rest);
1109       break;
1110     case MRICommand::CreateThin:
1111       Thin = true;
1112       LLVM_FALLTHROUGH;
1113     case MRICommand::Create:
1114       Create = true;
1115       if (!ArchiveName.empty())
1116         fail("editing multiple archives not supported");
1117       if (Saved)
1118         fail("file already saved");
1119       ArchiveName = std::string(Rest);
1120       break;
1121     case MRICommand::Delete: {
1122       llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1123         return comparePaths(M.MemberName, Rest);
1124       });
1125       break;
1126     }
1127     case MRICommand::Save:
1128       Saved = true;
1129       break;
1130     case MRICommand::End:
1131       break;
1132     case MRICommand::Invalid:
1133       fail("unknown command: " + CommandStr);
1134     }
1135   }
1136 
1137   ParsingMRIScript = false;
1138 
1139   // Nothing to do if not saved.
1140   if (Saved)
1141     performOperation(ReplaceOrInsert, /*OldArchive=*/nullptr,
1142                      /*OldArchiveBuf=*/ nullptr, &NewMembers);
1143   exit(0);
1144 }
1145 
1146 static bool handleGenericOption(StringRef arg) {
1147   if (arg == "--help" || arg == "-h") {
1148     printHelpMessage();
1149     return true;
1150   }
1151   if (arg == "--version") {
1152     cl::PrintVersionMessage();
1153     return true;
1154   }
1155   return false;
1156 }
1157 
1158 static const char *matchFlagWithArg(StringRef Expected,
1159                                     ArrayRef<const char *>::iterator &ArgIt,
1160                                     ArrayRef<const char *> Args) {
1161   StringRef Arg = *ArgIt;
1162 
1163   if (Arg.startswith("--"))
1164     Arg = Arg.substr(2);
1165 
1166   size_t len = Expected.size();
1167   if (Arg == Expected) {
1168     if (++ArgIt == Args.end())
1169       fail(std::string(Expected) + " requires an argument");
1170 
1171     return *ArgIt;
1172   }
1173   if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
1174     return Arg.data() + len + 1;
1175 
1176   return nullptr;
1177 }
1178 
1179 static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) {
1180   cl::TokenizerCallback Ret =
1181       Triple(sys::getProcessTriple()).getOS() == Triple::Win32
1182           ? cl::TokenizeWindowsCommandLine
1183           : cl::TokenizeGNUCommandLine;
1184 
1185   for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin();
1186        ArgIt != ArgsArr.end(); ++ArgIt) {
1187     if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) {
1188       StringRef MatchRef = Match;
1189       if (MatchRef == "posix")
1190         Ret = cl::TokenizeGNUCommandLine;
1191       else if (MatchRef == "windows")
1192         Ret = cl::TokenizeWindowsCommandLine;
1193       else
1194         fail(std::string("Invalid response file quoting style ") + Match);
1195     }
1196   }
1197 
1198   return Ret;
1199 }
1200 
1201 static int ar_main(int argc, char **argv) {
1202   SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
1203   StringSaver Saver(Alloc);
1204 
1205   cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
1206 
1207   for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
1208        ArgIt != Argv.end(); ++ArgIt) {
1209     const char *Match = nullptr;
1210 
1211     if (handleGenericOption(*ArgIt))
1212       return 0;
1213     if (strcmp(*ArgIt, "--") == 0) {
1214       ++ArgIt;
1215       for (; ArgIt != Argv.end(); ++ArgIt)
1216         PositionalArgs.push_back(*ArgIt);
1217       break;
1218     }
1219 
1220     if (*ArgIt[0] != '-') {
1221       if (Options.empty())
1222         Options += *ArgIt;
1223       else
1224         PositionalArgs.push_back(*ArgIt);
1225       continue;
1226     }
1227 
1228     if (strcmp(*ArgIt, "-M") == 0) {
1229       MRI = true;
1230       continue;
1231     }
1232 
1233     if (strcmp(*ArgIt, "--thin") == 0) {
1234       Thin = true;
1235       continue;
1236     }
1237 
1238     Match = matchFlagWithArg("format", ArgIt, Argv);
1239     if (Match) {
1240       FormatType = StringSwitch<Format>(Match)
1241                        .Case("default", Default)
1242                        .Case("gnu", GNU)
1243                        .Case("darwin", DARWIN)
1244                        .Case("bsd", BSD)
1245                        .Case("bigarchive", BIGARCHIVE)
1246                        .Default(Unknown);
1247       if (FormatType == Unknown)
1248         fail(std::string("Invalid format ") + Match);
1249       continue;
1250     }
1251 
1252     if (matchFlagWithArg("plugin", ArgIt, Argv) ||
1253         matchFlagWithArg("rsp-quoting", ArgIt, Argv))
1254       continue;
1255 
1256     Options += *ArgIt + 1;
1257   }
1258 
1259   ArchiveOperation Operation = parseCommandLine();
1260   return performOperation(Operation, nullptr);
1261 }
1262 
1263 static int ranlib_main(int argc, char **argv) {
1264   bool ArchiveSpecified = false;
1265   for (int i = 1; i < argc; ++i) {
1266     StringRef arg(argv[i]);
1267     if (handleGenericOption(arg)) {
1268       return 0;
1269     } else if (arg.consume_front("-")) {
1270       // Handle the -D/-U flag
1271       while (!arg.empty()) {
1272         if (arg.front() == 'D') {
1273           Deterministic = true;
1274         } else if (arg.front() == 'U') {
1275           Deterministic = false;
1276         } else if (arg.front() == 'h') {
1277           printHelpMessage();
1278           return 0;
1279         } else if (arg.front() == 'v') {
1280           cl::PrintVersionMessage();
1281           return 0;
1282         } else {
1283           // TODO: GNU ranlib also supports a -t flag
1284           fail("Invalid option: '-" + arg + "'");
1285         }
1286         arg = arg.drop_front(1);
1287       }
1288     } else {
1289       if (ArchiveSpecified)
1290         fail("exactly one archive should be specified");
1291       ArchiveSpecified = true;
1292       ArchiveName = arg.str();
1293     }
1294   }
1295   if (!ArchiveSpecified) {
1296     badUsage("an archive name must be specified");
1297   }
1298   return performOperation(CreateSymTab, nullptr);
1299 }
1300 
1301 int main(int argc, char **argv) {
1302   InitLLVM X(argc, argv);
1303   ToolName = argv[0];
1304 
1305   llvm::InitializeAllTargetInfos();
1306   llvm::InitializeAllTargetMCs();
1307   llvm::InitializeAllAsmParsers();
1308 
1309   Stem = sys::path::stem(ToolName);
1310   auto Is = [](StringRef Tool) {
1311     // We need to recognize the following filenames.
1312     //
1313     // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
1314     // dlltool.exe -> dlltool
1315     // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
1316     auto I = Stem.rfind_insensitive(Tool);
1317     return I != StringRef::npos &&
1318            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
1319   };
1320 
1321   if (Is("dlltool"))
1322     return dlltoolDriverMain(makeArrayRef(argv, argc));
1323   if (Is("ranlib"))
1324     return ranlib_main(argc, argv);
1325   if (Is("lib"))
1326     return libDriverMain(makeArrayRef(argv, argc));
1327   if (Is("ar"))
1328     return ar_main(argc, argv);
1329 
1330   fail("not ranlib, ar, lib or dlltool");
1331 }
1332