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 
658   // Avoid converting an existing thin archive to a regular one.
659   if (!AddLibrary && M.getParent()->isThin())
660     Thin = true;
661 
662   Expected<NewArchiveMember> NMOrErr =
663       NewArchiveMember::getOldMember(M, Deterministic);
664   failIfError(NMOrErr.takeError());
665   // If the child member we're trying to add is thin, use the path relative to
666   // the archive it's in, so the file resolves correctly.
667   if (Thin && FlattenArchive) {
668     StringSaver Saver(Alloc);
669     Expected<std::string> FileNameOrErr(M.getName());
670     failIfError(FileNameOrErr.takeError());
671     if (sys::path::is_absolute(*FileNameOrErr)) {
672       NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr));
673     } else {
674       FileNameOrErr = M.getFullName();
675       failIfError(FileNameOrErr.takeError());
676       Expected<std::string> PathOrErr =
677           computeArchiveRelativePath(ArchiveName, *FileNameOrErr);
678       NMOrErr->MemberName = Saver.save(
679           PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr));
680     }
681   }
682   if (FlattenArchive &&
683       identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
684     Expected<std::string> FileNameOrErr = M.getFullName();
685     failIfError(FileNameOrErr.takeError());
686     object::Archive &Lib = readLibrary(*FileNameOrErr);
687     // When creating thin archives, only flatten if the member is also thin.
688     if (!Thin || Lib.isThin()) {
689       Error Err = Error::success();
690       // Only Thin archives are recursively flattened.
691       for (auto &Child : Lib.children(Err))
692         addChildMember(Members, Child, /*FlattenArchive=*/Thin);
693       failIfError(std::move(Err));
694       return;
695     }
696   }
697   Members.push_back(std::move(*NMOrErr));
698 }
699 
700 static void addMember(std::vector<NewArchiveMember> &Members,
701                       StringRef FileName, bool FlattenArchive = false) {
702   Expected<NewArchiveMember> NMOrErr =
703       NewArchiveMember::getFile(FileName, Deterministic);
704   failIfError(NMOrErr.takeError(), FileName);
705   StringSaver Saver(Alloc);
706   // For regular archives, use the basename of the object path for the member
707   // name. For thin archives, use the full relative paths so the file resolves
708   // correctly.
709   if (!Thin) {
710     NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
711   } else {
712     if (sys::path::is_absolute(FileName))
713       NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
714     else {
715       Expected<std::string> PathOrErr =
716           computeArchiveRelativePath(ArchiveName, FileName);
717       NMOrErr->MemberName = Saver.save(
718           PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
719     }
720   }
721 
722   if (FlattenArchive &&
723       identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
724     object::Archive &Lib = readLibrary(FileName);
725     // When creating thin archives, only flatten if the member is also thin.
726     if (!Thin || Lib.isThin()) {
727       Error Err = Error::success();
728       // Only Thin archives are recursively flattened.
729       for (auto &Child : Lib.children(Err))
730         addChildMember(Members, Child, /*FlattenArchive=*/Thin);
731       failIfError(std::move(Err));
732       return;
733     }
734   }
735   Members.push_back(std::move(*NMOrErr));
736 }
737 
738 enum InsertAction {
739   IA_AddOldMember,
740   IA_AddNewMember,
741   IA_Delete,
742   IA_MoveOldMember,
743   IA_MoveNewMember
744 };
745 
746 static InsertAction computeInsertAction(ArchiveOperation Operation,
747                                         const object::Archive::Child &Member,
748                                         StringRef Name,
749                                         std::vector<StringRef>::iterator &Pos,
750                                         StringMap<int> &MemberCount) {
751   if (Operation == QuickAppend || Members.empty())
752     return IA_AddOldMember;
753   auto MI = find_if(
754       Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
755 
756   if (MI == Members.end())
757     return IA_AddOldMember;
758 
759   Pos = MI;
760 
761   if (Operation == Delete) {
762     if (CountParam && ++MemberCount[Name] != CountParam)
763       return IA_AddOldMember;
764     return IA_Delete;
765   }
766 
767   if (Operation == Move)
768     return IA_MoveOldMember;
769 
770   if (Operation == ReplaceOrInsert) {
771     if (!OnlyUpdate) {
772       if (RelPos.empty())
773         return IA_AddNewMember;
774       return IA_MoveNewMember;
775     }
776 
777     // We could try to optimize this to a fstat, but it is not a common
778     // operation.
779     sys::fs::file_status Status;
780     failIfError(sys::fs::status(*MI, Status), *MI);
781     auto ModTimeOrErr = Member.getLastModified();
782     failIfError(ModTimeOrErr.takeError());
783     if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
784       if (RelPos.empty())
785         return IA_AddOldMember;
786       return IA_MoveOldMember;
787     }
788 
789     if (RelPos.empty())
790       return IA_AddNewMember;
791     return IA_MoveNewMember;
792   }
793   llvm_unreachable("No such operation");
794 }
795 
796 // We have to walk this twice and computing it is not trivial, so creating an
797 // explicit std::vector is actually fairly efficient.
798 static std::vector<NewArchiveMember>
799 computeNewArchiveMembers(ArchiveOperation Operation,
800                          object::Archive *OldArchive) {
801   std::vector<NewArchiveMember> Ret;
802   std::vector<NewArchiveMember> Moved;
803   int InsertPos = -1;
804   if (OldArchive) {
805     Error Err = Error::success();
806     StringMap<int> MemberCount;
807     for (auto &Child : OldArchive->children(Err)) {
808       int Pos = Ret.size();
809       Expected<StringRef> NameOrErr = Child.getName();
810       failIfError(NameOrErr.takeError());
811       std::string Name = std::string(NameOrErr.get());
812       if (comparePaths(Name, RelPos)) {
813         assert(AddAfter || AddBefore);
814         if (AddBefore)
815           InsertPos = Pos;
816         else
817           InsertPos = Pos + 1;
818       }
819 
820       std::vector<StringRef>::iterator MemberI = Members.end();
821       InsertAction Action =
822           computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
823       switch (Action) {
824       case IA_AddOldMember:
825         addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
826         break;
827       case IA_AddNewMember:
828         addMember(Ret, *MemberI);
829         break;
830       case IA_Delete:
831         break;
832       case IA_MoveOldMember:
833         addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
834         break;
835       case IA_MoveNewMember:
836         addMember(Moved, *MemberI);
837         break;
838       }
839       // When processing elements with the count param, we need to preserve the
840       // full members list when iterating over all archive members. For
841       // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
842       // file named member.o it sees; we are not done with member.o the first
843       // time we see it in the archive.
844       if (MemberI != Members.end() && !CountParam)
845         Members.erase(MemberI);
846     }
847     failIfError(std::move(Err));
848   }
849 
850   if (Operation == Delete)
851     return Ret;
852 
853   if (!RelPos.empty() && InsertPos == -1)
854     fail("insertion point not found");
855 
856   if (RelPos.empty())
857     InsertPos = Ret.size();
858 
859   assert(unsigned(InsertPos) <= Ret.size());
860   int Pos = InsertPos;
861   for (auto &M : Moved) {
862     Ret.insert(Ret.begin() + Pos, std::move(M));
863     ++Pos;
864   }
865 
866   if (AddLibrary) {
867     assert(Operation == QuickAppend);
868     for (auto &Member : Members)
869       addMember(Ret, Member, /*FlattenArchive=*/true);
870     return Ret;
871   }
872 
873   std::vector<NewArchiveMember> NewMembers;
874   for (auto &Member : Members)
875     addMember(NewMembers, Member, /*FlattenArchive=*/Thin);
876   Ret.reserve(Ret.size() + NewMembers.size());
877   std::move(NewMembers.begin(), NewMembers.end(),
878             std::inserter(Ret, std::next(Ret.begin(), InsertPos)));
879 
880   return Ret;
881 }
882 
883 static object::Archive::Kind getDefaultForHost() {
884   return Triple(sys::getProcessTriple()).isOSDarwin()
885              ? object::Archive::K_DARWIN
886              : object::Archive::K_GNU;
887 }
888 
889 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
890   auto MemBufferRef = Member.Buf->getMemBufferRef();
891   Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
892       object::ObjectFile::createObjectFile(MemBufferRef);
893 
894   if (OptionalObject)
895     return isa<object::MachOObjectFile>(**OptionalObject)
896                ? object::Archive::K_DARWIN
897                : object::Archive::K_GNU;
898 
899   // squelch the error in case we had a non-object file
900   consumeError(OptionalObject.takeError());
901 
902   // If we're adding a bitcode file to the archive, detect the Archive kind
903   // based on the target triple.
904   LLVMContext Context;
905   if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
906     if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
907             MemBufferRef, file_magic::bitcode, &Context)) {
908       auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
909       return Triple(IRObject.getTargetTriple()).isOSDarwin()
910                  ? object::Archive::K_DARWIN
911                  : object::Archive::K_GNU;
912     } else {
913       // Squelch the error in case this was not a SymbolicFile.
914       consumeError(ObjOrErr.takeError());
915     }
916   }
917 
918   return getDefaultForHost();
919 }
920 
921 static void performWriteOperation(ArchiveOperation Operation,
922                                   object::Archive *OldArchive,
923                                   std::unique_ptr<MemoryBuffer> OldArchiveBuf,
924                                   std::vector<NewArchiveMember> *NewMembersP) {
925   std::vector<NewArchiveMember> NewMembers;
926   if (!NewMembersP)
927     NewMembers = computeNewArchiveMembers(Operation, OldArchive);
928 
929   object::Archive::Kind Kind;
930   switch (FormatType) {
931   case Default:
932     if (Thin)
933       Kind = object::Archive::K_GNU;
934     else if (OldArchive)
935       Kind = OldArchive->kind();
936     else if (NewMembersP)
937       Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
938                                    : getDefaultForHost();
939     else
940       Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
941                                  : getDefaultForHost();
942     break;
943   case GNU:
944     Kind = object::Archive::K_GNU;
945     break;
946   case BSD:
947     if (Thin)
948       fail("only the gnu format has a thin mode");
949     Kind = object::Archive::K_BSD;
950     break;
951   case DARWIN:
952     if (Thin)
953       fail("only the gnu format has a thin mode");
954     Kind = object::Archive::K_DARWIN;
955     break;
956   case Unknown:
957     llvm_unreachable("");
958   }
959 
960   Error E =
961       writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
962                    Kind, Deterministic, Thin, std::move(OldArchiveBuf));
963   failIfError(std::move(E), ArchiveName);
964 }
965 
966 static void createSymbolTable(object::Archive *OldArchive) {
967   // When an archive is created or modified, if the s option is given, the
968   // resulting archive will have a current symbol table. If the S option
969   // is given, it will have no symbol table.
970   // In summary, we only need to update the symbol table if we have none.
971   // This is actually very common because of broken build systems that think
972   // they have to run ranlib.
973   if (OldArchive->hasSymbolTable())
974     return;
975 
976   if (OldArchive->isThin())
977     Thin = true;
978   performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
979 }
980 
981 static void performOperation(ArchiveOperation Operation,
982                              object::Archive *OldArchive,
983                              std::unique_ptr<MemoryBuffer> OldArchiveBuf,
984                              std::vector<NewArchiveMember> *NewMembers) {
985   switch (Operation) {
986   case Print:
987   case DisplayTable:
988   case Extract:
989     performReadOperation(Operation, OldArchive);
990     return;
991 
992   case Delete:
993   case Move:
994   case QuickAppend:
995   case ReplaceOrInsert:
996     performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
997                           NewMembers);
998     return;
999   case CreateSymTab:
1000     createSymbolTable(OldArchive);
1001     return;
1002   }
1003   llvm_unreachable("Unknown operation.");
1004 }
1005 
1006 static int performOperation(ArchiveOperation Operation,
1007                             std::vector<NewArchiveMember> *NewMembers) {
1008   // Create or open the archive object.
1009   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
1010       ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1011   std::error_code EC = Buf.getError();
1012   if (EC && EC != errc::no_such_file_or_directory)
1013     fail("unable to open '" + ArchiveName + "': " + EC.message());
1014 
1015   if (!EC) {
1016     Expected<std::unique_ptr<object::Archive>> ArchiveOrError =
1017         object::Archive::create(Buf.get()->getMemBufferRef());
1018     if (!ArchiveOrError)
1019       failIfError(ArchiveOrError.takeError(),
1020                   "unable to load '" + ArchiveName + "'");
1021 
1022     std::unique_ptr<object::Archive> Archive = std::move(ArchiveOrError.get());
1023     if (Archive->isThin())
1024       CompareFullPath = true;
1025     performOperation(Operation, Archive.get(), std::move(Buf.get()),
1026                      NewMembers);
1027     return 0;
1028   }
1029 
1030   assert(EC == errc::no_such_file_or_directory);
1031 
1032   if (!shouldCreateArchive(Operation)) {
1033     failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
1034   } else {
1035     if (!Create) {
1036       // Produce a warning if we should and we're creating the archive
1037       WithColor::warning(errs(), ToolName)
1038           << "creating " << ArchiveName << "\n";
1039     }
1040   }
1041 
1042   performOperation(Operation, nullptr, nullptr, NewMembers);
1043   return 0;
1044 }
1045 
1046 static void runMRIScript() {
1047   enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1048 
1049   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1050   failIfError(Buf.getError());
1051   const MemoryBuffer &Ref = *Buf.get();
1052   bool Saved = false;
1053   std::vector<NewArchiveMember> NewMembers;
1054   ParsingMRIScript = true;
1055 
1056   for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1057     ++MRILineNumber;
1058     StringRef Line = *I;
1059     Line = Line.split(';').first;
1060     Line = Line.split('*').first;
1061     Line = Line.trim();
1062     if (Line.empty())
1063       continue;
1064     StringRef CommandStr, Rest;
1065     std::tie(CommandStr, Rest) = Line.split(' ');
1066     Rest = Rest.trim();
1067     if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
1068       Rest = Rest.drop_front().drop_back();
1069     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
1070                        .Case("addlib", MRICommand::AddLib)
1071                        .Case("addmod", MRICommand::AddMod)
1072                        .Case("create", MRICommand::Create)
1073                        .Case("createthin", MRICommand::CreateThin)
1074                        .Case("delete", MRICommand::Delete)
1075                        .Case("save", MRICommand::Save)
1076                        .Case("end", MRICommand::End)
1077                        .Default(MRICommand::Invalid);
1078 
1079     switch (Command) {
1080     case MRICommand::AddLib: {
1081       object::Archive &Lib = readLibrary(Rest);
1082       {
1083         Error Err = Error::success();
1084         for (auto &Member : Lib.children(Err))
1085           addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1086         failIfError(std::move(Err));
1087       }
1088       break;
1089     }
1090     case MRICommand::AddMod:
1091       addMember(NewMembers, Rest);
1092       break;
1093     case MRICommand::CreateThin:
1094       Thin = true;
1095       LLVM_FALLTHROUGH;
1096     case MRICommand::Create:
1097       Create = true;
1098       if (!ArchiveName.empty())
1099         fail("editing multiple archives not supported");
1100       if (Saved)
1101         fail("file already saved");
1102       ArchiveName = std::string(Rest);
1103       break;
1104     case MRICommand::Delete: {
1105       llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1106         return comparePaths(M.MemberName, Rest);
1107       });
1108       break;
1109     }
1110     case MRICommand::Save:
1111       Saved = true;
1112       break;
1113     case MRICommand::End:
1114       break;
1115     case MRICommand::Invalid:
1116       fail("unknown command: " + CommandStr);
1117     }
1118   }
1119 
1120   ParsingMRIScript = false;
1121 
1122   // Nothing to do if not saved.
1123   if (Saved)
1124     performOperation(ReplaceOrInsert, &NewMembers);
1125   exit(0);
1126 }
1127 
1128 static bool handleGenericOption(StringRef arg) {
1129   if (arg == "--help" || arg == "-h") {
1130     printHelpMessage();
1131     return true;
1132   }
1133   if (arg == "--version") {
1134     cl::PrintVersionMessage();
1135     return true;
1136   }
1137   return false;
1138 }
1139 
1140 static const char *matchFlagWithArg(StringRef Expected,
1141                                     ArrayRef<const char *>::iterator &ArgIt,
1142                                     ArrayRef<const char *> Args) {
1143   StringRef Arg = *ArgIt;
1144 
1145   if (Arg.startswith("--"))
1146     Arg = Arg.substr(2);
1147 
1148   size_t len = Expected.size();
1149   if (Arg == Expected) {
1150     if (++ArgIt == Args.end())
1151       fail(std::string(Expected) + " requires an argument");
1152 
1153     return *ArgIt;
1154   }
1155   if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
1156     return Arg.data() + len + 1;
1157 
1158   return nullptr;
1159 }
1160 
1161 static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) {
1162   cl::TokenizerCallback Ret =
1163       Triple(sys::getProcessTriple()).getOS() == Triple::Win32
1164           ? cl::TokenizeWindowsCommandLine
1165           : cl::TokenizeGNUCommandLine;
1166 
1167   for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin();
1168        ArgIt != ArgsArr.end(); ++ArgIt) {
1169     if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) {
1170       StringRef MatchRef = Match;
1171       if (MatchRef == "posix")
1172         Ret = cl::TokenizeGNUCommandLine;
1173       else if (MatchRef == "windows")
1174         Ret = cl::TokenizeWindowsCommandLine;
1175       else
1176         fail(std::string("Invalid response file quoting style ") + Match);
1177     }
1178   }
1179 
1180   return Ret;
1181 }
1182 
1183 static int ar_main(int argc, char **argv) {
1184   SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
1185   StringSaver Saver(Alloc);
1186 
1187   cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
1188 
1189   for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
1190        ArgIt != Argv.end(); ++ArgIt) {
1191     const char *Match = nullptr;
1192 
1193     if (handleGenericOption(*ArgIt))
1194       return 0;
1195     if (strcmp(*ArgIt, "--") == 0) {
1196       ++ArgIt;
1197       for (; ArgIt != Argv.end(); ++ArgIt)
1198         PositionalArgs.push_back(*ArgIt);
1199       break;
1200     }
1201 
1202     if (*ArgIt[0] != '-') {
1203       if (Options.empty())
1204         Options += *ArgIt;
1205       else
1206         PositionalArgs.push_back(*ArgIt);
1207       continue;
1208     }
1209 
1210     if (strcmp(*ArgIt, "-M") == 0) {
1211       MRI = true;
1212       continue;
1213     }
1214 
1215     if (strcmp(*ArgIt, "--thin") == 0) {
1216       Thin = true;
1217       continue;
1218     }
1219 
1220     Match = matchFlagWithArg("format", ArgIt, Argv);
1221     if (Match) {
1222       FormatType = StringSwitch<Format>(Match)
1223                        .Case("default", Default)
1224                        .Case("gnu", GNU)
1225                        .Case("darwin", DARWIN)
1226                        .Case("bsd", BSD)
1227                        .Default(Unknown);
1228       if (FormatType == Unknown)
1229         fail(std::string("Invalid format ") + Match);
1230       continue;
1231     }
1232 
1233     if (matchFlagWithArg("plugin", ArgIt, Argv) ||
1234         matchFlagWithArg("rsp-quoting", ArgIt, Argv))
1235       continue;
1236 
1237     Options += *ArgIt + 1;
1238   }
1239 
1240   ArchiveOperation Operation = parseCommandLine();
1241   return performOperation(Operation, nullptr);
1242 }
1243 
1244 static int ranlib_main(int argc, char **argv) {
1245   bool ArchiveSpecified = false;
1246   for (int i = 1; i < argc; ++i) {
1247     StringRef arg(argv[i]);
1248     if (handleGenericOption(arg)) {
1249       return 0;
1250     } else if (arg.consume_front("-")) {
1251       // Handle the -D/-U flag
1252       while (!arg.empty()) {
1253         if (arg.front() == 'D') {
1254           Deterministic = true;
1255         } else if (arg.front() == 'U') {
1256           Deterministic = false;
1257         } else if (arg.front() == 'h') {
1258           printHelpMessage();
1259           return 0;
1260         } else if (arg.front() == 'v') {
1261           cl::PrintVersionMessage();
1262           return 0;
1263         } else {
1264           // TODO: GNU ranlib also supports a -t flag
1265           fail("Invalid option: '-" + arg + "'");
1266         }
1267         arg = arg.drop_front(1);
1268       }
1269     } else {
1270       if (ArchiveSpecified)
1271         fail("exactly one archive should be specified");
1272       ArchiveSpecified = true;
1273       ArchiveName = arg.str();
1274     }
1275   }
1276   if (!ArchiveSpecified) {
1277     badUsage("an archive name must be specified");
1278   }
1279   return performOperation(CreateSymTab, nullptr);
1280 }
1281 
1282 int main(int argc, char **argv) {
1283   InitLLVM X(argc, argv);
1284   ToolName = argv[0];
1285 
1286   llvm::InitializeAllTargetInfos();
1287   llvm::InitializeAllTargetMCs();
1288   llvm::InitializeAllAsmParsers();
1289 
1290   Stem = sys::path::stem(ToolName);
1291   auto Is = [](StringRef Tool) {
1292     // We need to recognize the following filenames.
1293     //
1294     // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
1295     // dlltool.exe -> dlltool
1296     // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
1297     auto I = Stem.rfind_insensitive(Tool);
1298     return I != StringRef::npos &&
1299            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
1300   };
1301 
1302   if (Is("dlltool"))
1303     return dlltoolDriverMain(makeArrayRef(argv, argc));
1304   if (Is("ranlib"))
1305     return ranlib_main(argc, argv);
1306   if (Is("lib"))
1307     return libDriverMain(makeArrayRef(argv, argc));
1308   if (Is("ar"))
1309     return ar_main(argc, argv);
1310 
1311   fail("not ranlib, ar, lib or dlltool");
1312 }
1313