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