1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Builds up (relatively) standard unix archive files (.a) containing LLVM
10 // bitcode or other files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/ArchiveWriter.h"
19 #include "llvm/Object/MachO.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/Chrono.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormatVariadic.h"
27 #include "llvm/Support/InitLLVM.h"
28 #include "llvm/Support/LineIterator.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/StringSaver.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/WithColor.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
38 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
40 #if !defined(_MSC_VER) && !defined(__MINGW32__)
47 #define WIN32_LEAN_AND_MEAN
53 // The name this program was invoked as.
54 static StringRef ToolName
;
56 // The basename of this program.
57 static StringRef Stem
;
59 const char RanlibHelp
[] = R
"(
60 OVERVIEW: LLVM Ranlib (llvm-ranlib)
62 This program generates an index to speed access to archives
64 USAGE: llvm-ranlib <archive-file>
67 -help - Display available options
68 -version - Display the version of this program
71 const char ArHelp
[] = R
"(
72 OVERVIEW: LLVM Archiver
74 USAGE: llvm-ar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files]
75 llvm-ar -M [<mri-script]
78 --format - archive format to create
83 --plugin=<string> - ignored for compatibility
84 -h --help - display this help and exit
85 --version - print the version and exit
86 @<file> - read options from <file>
89 d - delete [files] from the archive
90 m - move [files] in the archive
91 p - print [files] found in the archive
92 q - quick append [files] to the archive
93 r - replace or insert [files] into the archive
95 t - display contents of archive
96 x - extract [files] from the archive
99 [a] - put [files] after [relpos]
100 [b] - put [files] before [relpos] (same as [i])
101 [c] - do not warn if archive had to be created
102 [D] - use zero for timestamps and uids/gids (default)
103 [h] - display this help and exit
104 [i] - put [files] before [relpos] (same as [b])
105 [l] - ignored for compatibility
106 [L] - add archive's contents
107 [N] - use instance [count] of name
108 [o] - preserve original dates
109 [O] - display member offsets
110 [P] - use full names when matching (implied for thin archives)
111 [s] - create an archive index (cf. ranlib)
112 [S] - do not build a symbol table
113 [T] - create a thin archive
114 [u] - update only [files] newer than archive contents
115 [U] - use actual timestamps and uids/gids
116 [v] - be verbose about actions taken
117 [V] - display the version and exit
120 void printHelpMessage() {
121 if (Stem
.contains_lower("ranlib"))
122 outs() << RanlibHelp
;
123 else if (Stem
.contains_lower("ar"))
127 static unsigned MRILineNumber
;
128 static bool ParsingMRIScript
;
130 // Show the error message and exit.
131 LLVM_ATTRIBUTE_NORETURN
static void fail(Twine Error
) {
132 if (ParsingMRIScript
) {
133 WithColor::error(errs(), ToolName
)
134 << "script line " << MRILineNumber
<< ": " << Error
<< "\n";
136 WithColor::error(errs(), ToolName
) << Error
<< "\n";
143 static void failIfError(std::error_code EC
, Twine Context
= "") {
147 std::string ContextStr
= Context
.str();
148 if (ContextStr
.empty())
150 fail(Context
+ ": " + EC
.message());
153 static void failIfError(Error E
, Twine Context
= "") {
157 handleAllErrors(std::move(E
), [&](const llvm::ErrorInfoBase
&EIB
) {
158 std::string ContextStr
= Context
.str();
159 if (ContextStr
.empty())
161 fail(Context
+ ": " + EIB
.message());
165 static SmallVector
<const char *, 256> PositionalArgs
;
170 enum Format
{ Default
, GNU
, BSD
, DARWIN
, Unknown
};
173 static Format FormatType
= Default
;
175 static std::string Options
;
177 // This enumeration delineates the kinds of operations on an archive
178 // that are permitted.
179 enum ArchiveOperation
{
180 Print
, ///< Print the contents of the archive
181 Delete
, ///< Delete the specified members
182 Move
, ///< Move members to end or as given by {a,b,i} modifiers
183 QuickAppend
, ///< Quickly append to end of archive
184 ReplaceOrInsert
, ///< Replace or Insert members
185 DisplayTable
, ///< Display the table of contents
186 Extract
, ///< Extract files back to file system
187 CreateSymTab
///< Create a symbol table in an existing archive
190 // Modifiers to follow operation to vary behavior
191 static bool AddAfter
= false; ///< 'a' modifier
192 static bool AddBefore
= false; ///< 'b' modifier
193 static bool Create
= false; ///< 'c' modifier
194 static bool OriginalDates
= false; ///< 'o' modifier
195 static bool DisplayMemberOffsets
= false; ///< 'O' modifier
196 static bool CompareFullPath
= false; ///< 'P' modifier
197 static bool OnlyUpdate
= false; ///< 'u' modifier
198 static bool Verbose
= false; ///< 'v' modifier
199 static bool Symtab
= true; ///< 's' modifier
200 static bool Deterministic
= true; ///< 'D' and 'U' modifiers
201 static bool Thin
= false; ///< 'T' modifier
202 static bool AddLibrary
= false; ///< 'L' modifier
204 // Relative Positional Argument (for insert/move). This variable holds
205 // the name of the archive member to which the 'a', 'b' or 'i' modifier
206 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
208 static std::string RelPos
;
210 // Count parameter for 'N' modifier. This variable specifies which file should
211 // match for extract/delete operations when there are multiple matches. This is
212 // 1-indexed. A value of 0 is invalid, and implies 'N' is not used.
213 static int CountParam
= 0;
215 // This variable holds the name of the archive file as given on the
217 static std::string ArchiveName
;
219 static std::vector
<std::unique_ptr
<MemoryBuffer
>> ArchiveBuffers
;
220 static std::vector
<std::unique_ptr
<object::Archive
>> Archives
;
222 // This variable holds the list of member files to proecess, as given
223 // on the command line.
224 static std::vector
<StringRef
> Members
;
226 // Static buffer to hold StringRefs.
227 static BumpPtrAllocator Alloc
;
229 // Extract the member filename from the command line for the [relpos] argument
230 // associated with a, b, and i modifiers
231 static void getRelPos() {
232 if (PositionalArgs
.empty())
233 fail("expected [relpos] for 'a', 'b', or 'i' modifier");
234 RelPos
= PositionalArgs
[0];
235 PositionalArgs
.erase(PositionalArgs
.begin());
238 // Extract the parameter from the command line for the [count] argument
239 // associated with the N modifier
240 static void getCountParam() {
241 if (PositionalArgs
.empty())
242 fail("expected [count] for 'N' modifier");
243 auto CountParamArg
= StringRef(PositionalArgs
[0]);
244 if (CountParamArg
.getAsInteger(10, CountParam
))
245 fail("value for [count] must be numeric, got: " + CountParamArg
);
247 fail("value for [count] must be positive, got: " + CountParamArg
);
248 PositionalArgs
.erase(PositionalArgs
.begin());
251 // Get the archive file name from the command line
252 static void getArchive() {
253 if (PositionalArgs
.empty())
254 fail("an archive name must be specified");
255 ArchiveName
= PositionalArgs
[0];
256 PositionalArgs
.erase(PositionalArgs
.begin());
259 static object::Archive
&readLibrary(const Twine
&Library
) {
260 auto BufOrErr
= MemoryBuffer::getFile(Library
, -1, false);
261 failIfError(BufOrErr
.getError(), "could not open library " + Library
);
262 ArchiveBuffers
.push_back(std::move(*BufOrErr
));
264 object::Archive::create(ArchiveBuffers
.back()->getMemBufferRef());
265 failIfError(errorToErrorCode(LibOrErr
.takeError()),
266 "could not parse library");
267 Archives
.push_back(std::move(*LibOrErr
));
268 return *Archives
.back();
271 static void runMRIScript();
273 // Parse the command line options as presented and return the operation
274 // specified. Process all modifiers and check to make sure that constraints on
275 // modifier/operation pairs have not been violated.
276 static ArchiveOperation
parseCommandLine() {
278 if (!PositionalArgs
.empty() || !Options
.empty())
279 fail("cannot mix -M and other options");
283 // Keep track of number of operations. We can only specify one
285 unsigned NumOperations
= 0;
287 // Keep track of the number of positional modifiers (a,b,i). Only
288 // one can be specified.
289 unsigned NumPositional
= 0;
291 // Keep track of which operation was requested
292 ArchiveOperation Operation
;
294 bool MaybeJustCreateSymTab
= false;
296 for (unsigned i
= 0; i
< Options
.size(); ++i
) {
297 switch (Options
[i
]) {
312 Operation
= QuickAppend
;
316 Operation
= ReplaceOrInsert
;
320 Operation
= DisplayTable
;
329 case 'l': /* accepted but unused */
332 OriginalDates
= true;
335 DisplayMemberOffsets
= true;
338 CompareFullPath
= true;
342 MaybeJustCreateSymTab
= true;
369 Deterministic
= true;
372 Deterministic
= false;
379 // Thin archives store path names, so P should be forced.
380 CompareFullPath
= true;
386 cl::PrintVersionMessage();
392 fail(std::string("unknown option ") + Options
[i
]);
396 // At this point, the next thing on the command line must be
400 // Everything on the command line at this point is a member.
401 Members
.assign(PositionalArgs
.begin(), PositionalArgs
.end());
403 if (NumOperations
== 0 && MaybeJustCreateSymTab
) {
405 Operation
= CreateSymTab
;
406 if (!Members
.empty())
407 fail("the 's' operation takes only an archive as argument");
410 // Perform various checks on the operation/modifier specification
411 // to make sure we are dealing with a legal request.
412 if (NumOperations
== 0)
413 fail("you must specify at least one of the operations");
414 if (NumOperations
> 1)
415 fail("only one operation may be specified");
416 if (NumPositional
> 1)
417 fail("you may only specify one of 'a', 'b', and 'i' modifiers");
418 if (AddAfter
|| AddBefore
)
419 if (Operation
!= Move
&& Operation
!= ReplaceOrInsert
)
420 fail("the 'a', 'b' and 'i' modifiers can only be specified with "
421 "the 'm' or 'r' operations");
423 if (Operation
!= Extract
&& Operation
!= Delete
)
424 fail("the 'N' modifier can only be specified with the 'x' or 'd' "
426 if (OriginalDates
&& Operation
!= Extract
)
427 fail("the 'o' modifier is only applicable to the 'x' operation");
428 if (OnlyUpdate
&& Operation
!= ReplaceOrInsert
)
429 fail("the 'u' modifier is only applicable to the 'r' operation");
430 if (AddLibrary
&& Operation
!= QuickAppend
)
431 fail("the 'L' modifier is only applicable to the 'q' operation");
433 // Return the parsed operation to the caller
437 // Implements the 'p' operation. This function traverses the archive
438 // looking for members that match the path list.
439 static void doPrint(StringRef Name
, const object::Archive::Child
&C
) {
441 outs() << "Printing " << Name
<< "\n";
443 Expected
<StringRef
> DataOrErr
= C
.getBuffer();
444 failIfError(DataOrErr
.takeError());
445 StringRef Data
= *DataOrErr
;
446 outs().write(Data
.data(), Data
.size());
449 // Utility function for printing out the file mode when the 't' operation is in
451 static void printMode(unsigned mode
) {
452 outs() << ((mode
& 004) ? "r" : "-");
453 outs() << ((mode
& 002) ? "w" : "-");
454 outs() << ((mode
& 001) ? "x" : "-");
457 // Implement the 't' operation. This function prints out just
458 // the file names of each of the members. However, if verbose mode is requested
459 // ('v' modifier) then the file type, permission mode, user, group, size, and
460 // modification time are also printed.
461 static void doDisplayTable(StringRef Name
, const object::Archive::Child
&C
) {
463 Expected
<sys::fs::perms
> ModeOrErr
= C
.getAccessMode();
464 failIfError(ModeOrErr
.takeError());
465 sys::fs::perms Mode
= ModeOrErr
.get();
466 printMode((Mode
>> 6) & 007);
467 printMode((Mode
>> 3) & 007);
468 printMode(Mode
& 007);
469 Expected
<unsigned> UIDOrErr
= C
.getUID();
470 failIfError(UIDOrErr
.takeError());
471 outs() << ' ' << UIDOrErr
.get();
472 Expected
<unsigned> GIDOrErr
= C
.getGID();
473 failIfError(GIDOrErr
.takeError());
474 outs() << '/' << GIDOrErr
.get();
475 Expected
<uint64_t> Size
= C
.getSize();
476 failIfError(Size
.takeError());
477 outs() << ' ' << format("%6llu", Size
.get());
478 auto ModTimeOrErr
= C
.getLastModified();
479 failIfError(ModTimeOrErr
.takeError());
480 // Note: formatv() only handles the default TimePoint<>, which is in
482 // TODO: fix format_provider<TimePoint<>> to allow other units.
483 sys::TimePoint
<> ModTimeInNs
= ModTimeOrErr
.get();
484 outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs
);
488 if (C
.getParent()->isThin()) {
489 if (!sys::path::is_absolute(Name
)) {
490 StringRef ParentDir
= sys::path::parent_path(ArchiveName
);
491 if (!ParentDir
.empty())
492 outs() << sys::path::convert_to_slash(ParentDir
) << '/';
497 if (DisplayMemberOffsets
)
498 outs() << " 0x" << utohexstr(C
.getDataOffset(), true);
503 static std::string
normalizePath(StringRef Path
) {
504 return CompareFullPath
? sys::path::convert_to_slash(Path
)
505 : std::string(sys::path::filename(Path
));
508 static bool comparePaths(StringRef Path1
, StringRef Path2
) {
509 // When on Windows this function calls CompareStringOrdinal
510 // as Windows file paths are case-insensitive.
511 // CompareStringOrdinal compares two Unicode strings for
512 // binary equivalence and allows for case insensitivity.
514 SmallVector
<wchar_t, 128> WPath1
, WPath2
;
515 failIfError(sys::path::widenPath(normalizePath(Path1
), WPath1
));
516 failIfError(sys::path::widenPath(normalizePath(Path2
), WPath2
));
518 return CompareStringOrdinal(WPath1
.data(), WPath1
.size(), WPath2
.data(),
519 WPath2
.size(), true) == CSTR_EQUAL
;
521 return normalizePath(Path1
) == normalizePath(Path2
);
525 // Implement the 'x' operation. This function extracts files back to the file
527 static void doExtract(StringRef Name
, const object::Archive::Child
&C
) {
528 // Retain the original mode.
529 Expected
<sys::fs::perms
> ModeOrErr
= C
.getAccessMode();
530 failIfError(ModeOrErr
.takeError());
531 sys::fs::perms Mode
= ModeOrErr
.get();
534 failIfError(sys::fs::openFileForWrite(sys::path::filename(Name
), FD
,
535 sys::fs::CD_CreateAlways
,
536 sys::fs::OF_None
, Mode
),
540 raw_fd_ostream
file(FD
, false);
542 // Get the data and its length
543 Expected
<StringRef
> BufOrErr
= C
.getBuffer();
544 failIfError(BufOrErr
.takeError());
545 StringRef Data
= BufOrErr
.get();
548 file
.write(Data
.data(), Data
.size());
551 // If we're supposed to retain the original modification times, etc. do so
554 auto ModTimeOrErr
= C
.getLastModified();
555 failIfError(ModTimeOrErr
.takeError());
557 sys::fs::setLastAccessAndModificationTime(FD
, ModTimeOrErr
.get()));
561 fail("Could not close the file");
564 static bool shouldCreateArchive(ArchiveOperation Op
) {
575 case ReplaceOrInsert
:
579 llvm_unreachable("Missing entry in covered switch.");
582 static void performReadOperation(ArchiveOperation Operation
,
583 object::Archive
*OldArchive
) {
584 if (Operation
== Extract
&& OldArchive
->isThin())
585 fail("extracting from a thin archive is not supported");
587 bool Filter
= !Members
.empty();
588 StringMap
<int> MemberCount
;
590 Error Err
= Error::success();
591 for (auto &C
: OldArchive
->children(Err
)) {
592 Expected
<StringRef
> NameOrErr
= C
.getName();
593 failIfError(NameOrErr
.takeError());
594 StringRef Name
= NameOrErr
.get();
597 auto I
= find_if(Members
, [Name
](StringRef Path
) {
598 return comparePaths(Name
, Path
);
600 if (I
== Members
.end())
602 if (CountParam
&& ++MemberCount
[Name
] != CountParam
)
609 llvm_unreachable("Not a read operation");
614 doDisplayTable(Name
, C
);
621 failIfError(std::move(Err
));
626 for (StringRef Name
: Members
)
627 WithColor::error(errs(), ToolName
) << "'" << Name
<< "' was not found\n";
631 static void addChildMember(std::vector
<NewArchiveMember
> &Members
,
632 const object::Archive::Child
&M
,
633 bool FlattenArchive
= false) {
634 if (Thin
&& !M
.getParent()->isThin())
635 fail("cannot convert a regular archive to a thin one");
636 Expected
<NewArchiveMember
> NMOrErr
=
637 NewArchiveMember::getOldMember(M
, Deterministic
);
638 failIfError(NMOrErr
.takeError());
639 // If the child member we're trying to add is thin, use the path relative to
640 // the archive it's in, so the file resolves correctly.
641 if (Thin
&& FlattenArchive
) {
642 StringSaver
Saver(Alloc
);
643 Expected
<std::string
> FileNameOrErr
= M
.getName();
644 failIfError(FileNameOrErr
.takeError());
645 if (sys::path::is_absolute(*FileNameOrErr
)) {
646 NMOrErr
->MemberName
= Saver
.save(sys::path::convert_to_slash(*FileNameOrErr
));
648 FileNameOrErr
= M
.getFullName();
649 failIfError(FileNameOrErr
.takeError());
650 Expected
<std::string
> PathOrErr
=
651 computeArchiveRelativePath(ArchiveName
, *FileNameOrErr
);
652 NMOrErr
->MemberName
= Saver
.save(
653 PathOrErr
? *PathOrErr
: sys::path::convert_to_slash(*FileNameOrErr
));
656 if (FlattenArchive
&&
657 identify_magic(NMOrErr
->Buf
->getBuffer()) == file_magic::archive
) {
658 Expected
<std::string
> FileNameOrErr
= M
.getFullName();
659 failIfError(FileNameOrErr
.takeError());
660 object::Archive
&Lib
= readLibrary(*FileNameOrErr
);
661 // When creating thin archives, only flatten if the member is also thin.
662 if (!Thin
|| Lib
.isThin()) {
663 Error Err
= Error::success();
664 // Only Thin archives are recursively flattened.
665 for (auto &Child
: Lib
.children(Err
))
666 addChildMember(Members
, Child
, /*FlattenArchive=*/Thin
);
667 failIfError(std::move(Err
));
671 Members
.push_back(std::move(*NMOrErr
));
674 static void addMember(std::vector
<NewArchiveMember
> &Members
,
675 StringRef FileName
, bool FlattenArchive
= false) {
676 Expected
<NewArchiveMember
> NMOrErr
=
677 NewArchiveMember::getFile(FileName
, Deterministic
);
678 failIfError(NMOrErr
.takeError(), FileName
);
679 StringSaver
Saver(Alloc
);
680 // For regular archives, use the basename of the object path for the member
681 // name. For thin archives, use the full relative paths so the file resolves
684 NMOrErr
->MemberName
= sys::path::filename(NMOrErr
->MemberName
);
686 if (sys::path::is_absolute(FileName
))
687 NMOrErr
->MemberName
= Saver
.save(sys::path::convert_to_slash(FileName
));
689 Expected
<std::string
> PathOrErr
=
690 computeArchiveRelativePath(ArchiveName
, FileName
);
691 NMOrErr
->MemberName
= Saver
.save(
692 PathOrErr
? *PathOrErr
: sys::path::convert_to_slash(FileName
));
696 if (FlattenArchive
&&
697 identify_magic(NMOrErr
->Buf
->getBuffer()) == file_magic::archive
) {
698 object::Archive
&Lib
= readLibrary(FileName
);
699 // When creating thin archives, only flatten if the member is also thin.
700 if (!Thin
|| Lib
.isThin()) {
701 Error Err
= Error::success();
702 // Only Thin archives are recursively flattened.
703 for (auto &Child
: Lib
.children(Err
))
704 addChildMember(Members
, Child
, /*FlattenArchive=*/Thin
);
705 failIfError(std::move(Err
));
709 Members
.push_back(std::move(*NMOrErr
));
720 static InsertAction
computeInsertAction(ArchiveOperation Operation
,
721 const object::Archive::Child
&Member
,
723 std::vector
<StringRef
>::iterator
&Pos
,
724 StringMap
<int> &MemberCount
) {
725 if (Operation
== QuickAppend
|| Members
.empty())
726 return IA_AddOldMember
;
728 Members
, [Name
](StringRef Path
) { return comparePaths(Name
, Path
); });
730 if (MI
== Members
.end())
731 return IA_AddOldMember
;
735 if (Operation
== Delete
) {
736 if (CountParam
&& ++MemberCount
[Name
] != CountParam
)
737 return IA_AddOldMember
;
741 if (Operation
== Move
)
742 return IA_MoveOldMember
;
744 if (Operation
== ReplaceOrInsert
) {
747 return IA_AddNewMember
;
748 return IA_MoveNewMember
;
751 // We could try to optimize this to a fstat, but it is not a common
753 sys::fs::file_status Status
;
754 failIfError(sys::fs::status(*MI
, Status
), *MI
);
755 auto ModTimeOrErr
= Member
.getLastModified();
756 failIfError(ModTimeOrErr
.takeError());
757 if (Status
.getLastModificationTime() < ModTimeOrErr
.get()) {
759 return IA_AddOldMember
;
760 return IA_MoveOldMember
;
764 return IA_AddNewMember
;
765 return IA_MoveNewMember
;
767 llvm_unreachable("No such operation");
770 // We have to walk this twice and computing it is not trivial, so creating an
771 // explicit std::vector is actually fairly efficient.
772 static std::vector
<NewArchiveMember
>
773 computeNewArchiveMembers(ArchiveOperation Operation
,
774 object::Archive
*OldArchive
) {
775 std::vector
<NewArchiveMember
> Ret
;
776 std::vector
<NewArchiveMember
> Moved
;
779 Error Err
= Error::success();
780 StringMap
<int> MemberCount
;
781 for (auto &Child
: OldArchive
->children(Err
)) {
782 int Pos
= Ret
.size();
783 Expected
<StringRef
> NameOrErr
= Child
.getName();
784 failIfError(NameOrErr
.takeError());
785 std::string Name
= NameOrErr
.get();
786 if (comparePaths(Name
, RelPos
)) {
787 assert(AddAfter
|| AddBefore
);
794 std::vector
<StringRef
>::iterator MemberI
= Members
.end();
795 InsertAction Action
=
796 computeInsertAction(Operation
, Child
, Name
, MemberI
, MemberCount
);
798 case IA_AddOldMember
:
799 addChildMember(Ret
, Child
, /*FlattenArchive=*/Thin
);
801 case IA_AddNewMember
:
802 addMember(Ret
, *MemberI
);
806 case IA_MoveOldMember
:
807 addChildMember(Moved
, Child
, /*FlattenArchive=*/Thin
);
809 case IA_MoveNewMember
:
810 addMember(Moved
, *MemberI
);
813 // When processing elements with the count param, we need to preserve the
814 // full members list when iterating over all archive members. For
815 // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
816 // file named member.o it sees; we are not done with member.o the first
817 // time we see it in the archive.
818 if (MemberI
!= Members
.end() && !CountParam
)
819 Members
.erase(MemberI
);
821 failIfError(std::move(Err
));
824 if (Operation
== Delete
)
827 if (!RelPos
.empty() && InsertPos
== -1)
828 fail("insertion point not found");
831 InsertPos
= Ret
.size();
833 assert(unsigned(InsertPos
) <= Ret
.size());
835 for (auto &M
: Moved
) {
836 Ret
.insert(Ret
.begin() + Pos
, std::move(M
));
841 assert(Operation
== QuickAppend
);
842 for (auto &Member
: Members
)
843 addMember(Ret
, Member
, /*FlattenArchive=*/true);
847 std::vector
<NewArchiveMember
> NewMembers
;
848 for (auto &Member
: Members
)
849 addMember(NewMembers
, Member
, /*FlattenArchive=*/Thin
);
850 Ret
.reserve(Ret
.size() + NewMembers
.size());
851 std::move(NewMembers
.begin(), NewMembers
.end(),
852 std::inserter(Ret
, std::next(Ret
.begin(), InsertPos
)));
857 static object::Archive::Kind
getDefaultForHost() {
858 return Triple(sys::getProcessTriple()).isOSDarwin()
859 ? object::Archive::K_DARWIN
860 : object::Archive::K_GNU
;
863 static object::Archive::Kind
getKindFromMember(const NewArchiveMember
&Member
) {
864 Expected
<std::unique_ptr
<object::ObjectFile
>> OptionalObject
=
865 object::ObjectFile::createObjectFile(Member
.Buf
->getMemBufferRef());
868 return isa
<object::MachOObjectFile
>(**OptionalObject
)
869 ? object::Archive::K_DARWIN
870 : object::Archive::K_GNU
;
872 // squelch the error in case we had a non-object file
873 consumeError(OptionalObject
.takeError());
874 return getDefaultForHost();
877 static void performWriteOperation(ArchiveOperation Operation
,
878 object::Archive
*OldArchive
,
879 std::unique_ptr
<MemoryBuffer
> OldArchiveBuf
,
880 std::vector
<NewArchiveMember
> *NewMembersP
) {
881 std::vector
<NewArchiveMember
> NewMembers
;
883 NewMembers
= computeNewArchiveMembers(Operation
, OldArchive
);
885 object::Archive::Kind Kind
;
886 switch (FormatType
) {
889 Kind
= object::Archive::K_GNU
;
891 Kind
= OldArchive
->kind();
892 else if (NewMembersP
)
893 Kind
= !NewMembersP
->empty() ? getKindFromMember(NewMembersP
->front())
894 : getDefaultForHost();
896 Kind
= !NewMembers
.empty() ? getKindFromMember(NewMembers
.front())
897 : getDefaultForHost();
900 Kind
= object::Archive::K_GNU
;
904 fail("only the gnu format has a thin mode");
905 Kind
= object::Archive::K_BSD
;
909 fail("only the gnu format has a thin mode");
910 Kind
= object::Archive::K_DARWIN
;
913 llvm_unreachable("");
917 writeArchive(ArchiveName
, NewMembersP
? *NewMembersP
: NewMembers
, Symtab
,
918 Kind
, Deterministic
, Thin
, std::move(OldArchiveBuf
));
919 failIfError(std::move(E
), ArchiveName
);
922 static void createSymbolTable(object::Archive
*OldArchive
) {
923 // When an archive is created or modified, if the s option is given, the
924 // resulting archive will have a current symbol table. If the S option
925 // is given, it will have no symbol table.
926 // In summary, we only need to update the symbol table if we have none.
927 // This is actually very common because of broken build systems that think
928 // they have to run ranlib.
929 if (OldArchive
->hasSymbolTable())
932 performWriteOperation(CreateSymTab
, OldArchive
, nullptr, nullptr);
935 static void performOperation(ArchiveOperation Operation
,
936 object::Archive
*OldArchive
,
937 std::unique_ptr
<MemoryBuffer
> OldArchiveBuf
,
938 std::vector
<NewArchiveMember
> *NewMembers
) {
943 performReadOperation(Operation
, OldArchive
);
949 case ReplaceOrInsert
:
950 performWriteOperation(Operation
, OldArchive
, std::move(OldArchiveBuf
),
954 createSymbolTable(OldArchive
);
957 llvm_unreachable("Unknown operation.");
960 static int performOperation(ArchiveOperation Operation
,
961 std::vector
<NewArchiveMember
> *NewMembers
) {
962 // Create or open the archive object.
963 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> Buf
=
964 MemoryBuffer::getFile(ArchiveName
, -1, false);
965 std::error_code EC
= Buf
.getError();
966 if (EC
&& EC
!= errc::no_such_file_or_directory
)
967 fail("error opening '" + ArchiveName
+ "': " + EC
.message());
970 Error Err
= Error::success();
971 object::Archive
Archive(Buf
.get()->getMemBufferRef(), Err
);
972 failIfError(std::move(Err
), "unable to load '" + ArchiveName
+ "'");
973 if (Archive
.isThin())
974 CompareFullPath
= true;
975 performOperation(Operation
, &Archive
, std::move(Buf
.get()), NewMembers
);
979 assert(EC
== errc::no_such_file_or_directory
);
981 if (!shouldCreateArchive(Operation
)) {
982 failIfError(EC
, Twine("error loading '") + ArchiveName
+ "'");
985 // Produce a warning if we should and we're creating the archive
986 WithColor::warning(errs(), ToolName
)
987 << "creating " << ArchiveName
<< "\n";
991 performOperation(Operation
, nullptr, nullptr, NewMembers
);
995 static void runMRIScript() {
996 enum class MRICommand
{ AddLib
, AddMod
, Create
, CreateThin
, Delete
, Save
, End
, Invalid
};
998 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> Buf
= MemoryBuffer::getSTDIN();
999 failIfError(Buf
.getError());
1000 const MemoryBuffer
&Ref
= *Buf
.get();
1002 std::vector
<NewArchiveMember
> NewMembers
;
1003 ParsingMRIScript
= true;
1005 for (line_iterator
I(Ref
, /*SkipBlanks*/ false), E
; I
!= E
; ++I
) {
1007 StringRef Line
= *I
;
1008 Line
= Line
.split(';').first
;
1009 Line
= Line
.split('*').first
;
1013 StringRef CommandStr
, Rest
;
1014 std::tie(CommandStr
, Rest
) = Line
.split(' ');
1016 if (!Rest
.empty() && Rest
.front() == '"' && Rest
.back() == '"')
1017 Rest
= Rest
.drop_front().drop_back();
1018 auto Command
= StringSwitch
<MRICommand
>(CommandStr
.lower())
1019 .Case("addlib", MRICommand::AddLib
)
1020 .Case("addmod", MRICommand::AddMod
)
1021 .Case("create", MRICommand::Create
)
1022 .Case("createthin", MRICommand::CreateThin
)
1023 .Case("delete", MRICommand::Delete
)
1024 .Case("save", MRICommand::Save
)
1025 .Case("end", MRICommand::End
)
1026 .Default(MRICommand::Invalid
);
1029 case MRICommand::AddLib
: {
1030 object::Archive
&Lib
= readLibrary(Rest
);
1032 Error Err
= Error::success();
1033 for (auto &Member
: Lib
.children(Err
))
1034 addChildMember(NewMembers
, Member
, /*FlattenArchive=*/Thin
);
1035 failIfError(std::move(Err
));
1039 case MRICommand::AddMod
:
1040 addMember(NewMembers
, Rest
);
1042 case MRICommand::CreateThin
:
1045 case MRICommand::Create
:
1047 if (!ArchiveName
.empty())
1048 fail("editing multiple archives not supported");
1050 fail("file already saved");
1053 case MRICommand::Delete
: {
1054 llvm::erase_if(NewMembers
, [=](NewArchiveMember
&M
) {
1055 return comparePaths(M
.MemberName
, Rest
);
1059 case MRICommand::Save
:
1062 case MRICommand::End
:
1064 case MRICommand::Invalid
:
1065 fail("unknown command: " + CommandStr
);
1069 ParsingMRIScript
= false;
1071 // Nothing to do if not saved.
1073 performOperation(ReplaceOrInsert
, &NewMembers
);
1077 static bool handleGenericOption(StringRef arg
) {
1078 if (arg
== "-help" || arg
== "--help") {
1082 if (arg
== "-version" || arg
== "--version") {
1083 cl::PrintVersionMessage();
1089 static int ar_main(int argc
, char **argv
) {
1090 SmallVector
<const char *, 0> Argv(argv
, argv
+ argc
);
1091 StringSaver
Saver(Alloc
);
1092 cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
);
1093 for (size_t i
= 1; i
< Argv
.size(); ++i
) {
1094 StringRef Arg
= Argv
[i
];
1096 auto MatchFlagWithArg
= [&](const char *expected
) {
1097 size_t len
= strlen(expected
);
1098 if (Arg
== expected
) {
1099 if (++i
>= Argv
.size())
1100 fail(std::string(expected
) + " requires an argument");
1104 if (Arg
.startswith(expected
) && Arg
.size() > len
&& Arg
[len
] == '=') {
1105 match
= Arg
.data() + len
+ 1;
1110 if (handleGenericOption(Argv
[i
]))
1113 for (; i
< Argv
.size(); ++i
)
1114 PositionalArgs
.push_back(Argv
[i
]);
1117 if (Arg
[0] == '-') {
1118 if (Arg
.startswith("--"))
1124 } else if (MatchFlagWithArg("format")) {
1125 FormatType
= StringSwitch
<Format
>(match
)
1126 .Case("default", Default
)
1128 .Case("darwin", DARWIN
)
1131 if (FormatType
== Unknown
)
1132 fail(std::string("Invalid format ") + match
);
1133 } else if (MatchFlagWithArg("plugin")) {
1136 Options
+= Argv
[i
] + 1;
1138 } else if (Options
.empty()) {
1141 PositionalArgs
.push_back(Argv
[i
]);
1144 ArchiveOperation Operation
= parseCommandLine();
1145 return performOperation(Operation
, nullptr);
1148 static int ranlib_main(int argc
, char **argv
) {
1149 bool ArchiveSpecified
= false;
1150 for (int i
= 1; i
< argc
; ++i
) {
1151 if (handleGenericOption(argv
[i
])) {
1154 if (ArchiveSpecified
)
1155 fail("exactly one archive should be specified");
1156 ArchiveSpecified
= true;
1157 ArchiveName
= argv
[i
];
1160 return performOperation(CreateSymTab
, nullptr);
1163 int main(int argc
, char **argv
) {
1164 InitLLVM
X(argc
, argv
);
1167 llvm::InitializeAllTargetInfos();
1168 llvm::InitializeAllTargetMCs();
1169 llvm::InitializeAllAsmParsers();
1171 Stem
= sys::path::stem(ToolName
);
1172 if (Stem
.contains_lower("dlltool"))
1173 return dlltoolDriverMain(makeArrayRef(argv
, argc
));
1175 if (Stem
.contains_lower("ranlib"))
1176 return ranlib_main(argc
, argv
);
1178 if (Stem
.contains_lower("lib"))
1179 return libDriverMain(makeArrayRef(argv
, argc
));
1181 if (Stem
.contains_lower("ar"))
1182 return ar_main(argc
, argv
);
1183 fail("not ranlib, ar, lib or dlltool");