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