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