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