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