1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Builds up (relatively) standard unix archive files (.a) containing LLVM
11 // bitcode or other files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Errc.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/ToolOutputFile.h"
28 #include "llvm/Support/raw_ostream.h"
33 #if !defined(_MSC_VER) && !defined(__MINGW32__)
41 // The name this program was invoked as.
42 static StringRef ToolName;
44 static const char *TemporaryOutput;
45 static int TmpArchiveFD = -1;
47 // fail - Show the error message and exit.
48 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
49 outs() << ToolName << ": " << Error << ".\n";
50 if (TmpArchiveFD != -1)
53 sys::fs::remove(TemporaryOutput);
57 static void failIfError(std::error_code EC, Twine Context = "") {
61 std::string ContextStr = Context.str();
64 fail(Context + ": " + EC.message());
67 // llvm-ar/llvm-ranlib remaining positional arguments.
68 static cl::list<std::string>
69 RestOfArgs(cl::Positional, cl::OneOrMore,
70 cl::desc("[relpos] [count] <archive-file> [members]..."));
74 // MoreHelp - Provide additional help output explaining the operations and
75 // modifiers of llvm-ar. This object instructs the CommandLine library
76 // to print the text of the constructor when the --help option is given.
77 static cl::extrahelp MoreHelp(
79 " d[NsS] - delete file(s) from the archive\n"
80 " m[abiSs] - move file(s) in the archive\n"
81 " p[kN] - print file(s) found in the archive\n"
82 " q[ufsS] - quick append file(s) to the archive\n"
83 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
84 " t - display contents of archive\n"
85 " x[No] - extract file(s) from the archive\n"
86 "\nMODIFIERS (operation specific):\n"
87 " [a] - put file(s) after [relpos]\n"
88 " [b] - put file(s) before [relpos] (same as [i])\n"
89 " [i] - put file(s) before [relpos] (same as [b])\n"
90 " [N] - use instance [count] of name\n"
91 " [o] - preserve original dates\n"
92 " [s] - create an archive index (cf. ranlib)\n"
93 " [S] - do not build a symbol table\n"
94 " [u] - update only files newer than archive contents\n"
95 "\nMODIFIERS (generic):\n"
96 " [c] - do not warn if the library had to be created\n"
97 " [v] - be verbose about actions taken\n"
100 // This enumeration delineates the kinds of operations on an archive
101 // that are permitted.
102 enum ArchiveOperation {
103 Print, ///< Print the contents of the archive
104 Delete, ///< Delete the specified members
105 Move, ///< Move members to end or as given by {a,b,i} modifiers
106 QuickAppend, ///< Quickly append to end of archive
107 ReplaceOrInsert, ///< Replace or Insert members
108 DisplayTable, ///< Display the table of contents
109 Extract, ///< Extract files back to file system
110 CreateSymTab ///< Create a symbol table in an existing archive
113 // Modifiers to follow operation to vary behavior
114 static bool AddAfter = false; ///< 'a' modifier
115 static bool AddBefore = false; ///< 'b' modifier
116 static bool Create = false; ///< 'c' modifier
117 static bool OriginalDates = false; ///< 'o' modifier
118 static bool OnlyUpdate = false; ///< 'u' modifier
119 static bool Verbose = false; ///< 'v' modifier
120 static bool Symtab = true; ///< 's' modifier
122 // Relative Positional Argument (for insert/move). This variable holds
123 // the name of the archive member to which the 'a', 'b' or 'i' modifier
124 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
126 static std::string RelPos;
128 // This variable holds the name of the archive file as given on the
130 static std::string ArchiveName;
132 // This variable holds the list of member files to proecess, as given
133 // on the command line.
134 static std::vector<std::string> Members;
136 // show_help - Show the error message, the help message and exit.
137 LLVM_ATTRIBUTE_NORETURN static void
138 show_help(const std::string &msg) {
139 errs() << ToolName << ": " << msg << "\n\n";
140 cl::PrintHelpMessage();
144 // getRelPos - Extract the member filename from the command line for
145 // the [relpos] argument associated with a, b, and i modifiers
146 static void getRelPos() {
147 if(RestOfArgs.size() == 0)
148 show_help("Expected [relpos] for a, b, or i modifier");
149 RelPos = RestOfArgs[0];
150 RestOfArgs.erase(RestOfArgs.begin());
153 static void getOptions() {
154 if(RestOfArgs.size() == 0)
155 show_help("Expected options");
156 Options = RestOfArgs[0];
157 RestOfArgs.erase(RestOfArgs.begin());
160 // getArchive - Get the archive file name from the command line
161 static void getArchive() {
162 if(RestOfArgs.size() == 0)
163 show_help("An archive name must be specified");
164 ArchiveName = RestOfArgs[0];
165 RestOfArgs.erase(RestOfArgs.begin());
168 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
169 // This is just for clarity.
170 static void getMembers() {
171 if(RestOfArgs.size() > 0)
172 Members = std::vector<std::string>(RestOfArgs);
175 // parseCommandLine - Parse the command line options as presented and return the
176 // operation specified. Process all modifiers and check to make sure that
177 // constraints on modifier/operation pairs have not been violated.
178 static ArchiveOperation parseCommandLine() {
181 // Keep track of number of operations. We can only specify one
183 unsigned NumOperations = 0;
185 // Keep track of the number of positional modifiers (a,b,i). Only
186 // one can be specified.
187 unsigned NumPositional = 0;
189 // Keep track of which operation was requested
190 ArchiveOperation Operation;
192 bool MaybeJustCreateSymTab = false;
194 for(unsigned i=0; i<Options.size(); ++i) {
196 case 'd': ++NumOperations; Operation = Delete; break;
197 case 'm': ++NumOperations; Operation = Move ; break;
198 case 'p': ++NumOperations; Operation = Print; break;
199 case 'q': ++NumOperations; Operation = QuickAppend; break;
200 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
201 case 't': ++NumOperations; Operation = DisplayTable; break;
202 case 'x': ++NumOperations; Operation = Extract; break;
203 case 'c': Create = true; break;
204 case 'l': /* accepted but unused */ break;
205 case 'o': OriginalDates = true; break;
208 MaybeJustCreateSymTab = true;
213 case 'u': OnlyUpdate = true; break;
214 case 'v': Verbose = true; break;
231 cl::PrintHelpMessage();
235 // At this point, the next thing on the command line must be
239 // Everything on the command line at this point is a member.
242 if (NumOperations == 0 && MaybeJustCreateSymTab) {
244 Operation = CreateSymTab;
245 if (!Members.empty())
246 show_help("The s operation takes only an archive as argument");
249 // Perform various checks on the operation/modifier specification
250 // to make sure we are dealing with a legal request.
251 if (NumOperations == 0)
252 show_help("You must specify at least one of the operations");
253 if (NumOperations > 1)
254 show_help("Only one operation may be specified");
255 if (NumPositional > 1)
256 show_help("You may only specify one of a, b, and i modifiers");
257 if (AddAfter || AddBefore) {
258 if (Operation != Move && Operation != ReplaceOrInsert)
259 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
260 "the 'm' or 'r' operations");
262 if (OriginalDates && Operation != Extract)
263 show_help("The 'o' modifier is only applicable to the 'x' operation");
264 if (OnlyUpdate && Operation != ReplaceOrInsert)
265 show_help("The 'u' modifier is only applicable to the 'r' operation");
267 // Return the parsed operation to the caller
271 // Implements the 'p' operation. This function traverses the archive
272 // looking for members that match the path list.
273 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
275 outs() << "Printing " << Name << "\n";
277 StringRef Data = I->getBuffer();
278 outs().write(Data.data(), Data.size());
281 // putMode - utility function for printing out the file mode when the 't'
282 // operation is in verbose mode.
283 static void printMode(unsigned mode) {
298 // Implement the 't' operation. This function prints out just
299 // the file names of each of the members. However, if verbose mode is requested
300 // ('v' modifier) then the file type, permission mode, user, group, size, and
301 // modification time are also printed.
302 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
304 sys::fs::perms Mode = I->getAccessMode();
305 printMode((Mode >> 6) & 007);
306 printMode((Mode >> 3) & 007);
307 printMode(Mode & 007);
308 outs() << ' ' << I->getUID();
309 outs() << '/' << I->getGID();
310 outs() << ' ' << format("%6llu", I->getSize());
311 outs() << ' ' << I->getLastModified().str();
314 outs() << Name << "\n";
317 // Implement the 'x' operation. This function extracts files back to the file
319 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
320 // Retain the original mode.
321 sys::fs::perms Mode = I->getAccessMode();
322 SmallString<128> Storage = Name;
326 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
330 raw_fd_ostream file(FD, false);
332 // Get the data and its length
333 StringRef Data = I->getBuffer();
336 file.write(Data.data(), Data.size());
339 // If we're supposed to retain the original modification times, etc. do so
343 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
346 fail("Could not close the file");
349 static bool shouldCreateArchive(ArchiveOperation Op) {
360 case ReplaceOrInsert:
364 llvm_unreachable("Missing entry in covered switch.");
367 static void performReadOperation(ArchiveOperation Operation,
368 object::Archive *OldArchive) {
369 for (object::Archive::child_iterator I = OldArchive->child_begin(),
370 E = OldArchive->child_end();
372 ErrorOr<StringRef> NameOrErr = I->getName();
373 failIfError(NameOrErr.getError());
374 StringRef Name = NameOrErr.get();
376 if (!Members.empty() &&
377 std::find(Members.begin(), Members.end(), Name) == Members.end())
382 llvm_unreachable("Not a read operation");
387 doDisplayTable(Name, I);
397 class NewArchiveIterator {
401 object::Archive::child_iterator OldI;
403 std::string NewFilename;
405 mutable sys::fs::file_status NewStatus;
408 NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
409 NewArchiveIterator(std::string *I, StringRef Name);
410 NewArchiveIterator();
411 bool isNewMember() const;
412 StringRef getName() const;
414 object::Archive::child_iterator getOld() const;
416 const char *getNew() const;
418 const sys::fs::file_status &getStatus() const;
422 NewArchiveIterator::NewArchiveIterator() {}
424 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
426 : IsNewMember(false), Name(Name), OldI(I) {}
428 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
429 : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
431 StringRef NewArchiveIterator::getName() const { return Name; }
433 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
435 object::Archive::child_iterator NewArchiveIterator::getOld() const {
436 assert(!IsNewMember);
440 const char *NewArchiveIterator::getNew() const {
442 return NewFilename.c_str();
445 int NewArchiveIterator::getFD() const {
449 failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
452 failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
454 // Opening a directory doesn't make sense. Let it fail.
455 // Linux cannot open directories with open(2), although
456 // cygwin and *bsd can.
457 if (NewStatus.type() == sys::fs::file_type::directory_file)
458 failIfError(make_error_code(errc::is_a_directory), NewFilename);
463 const sys::fs::file_status &NewArchiveIterator::getStatus() const {
465 assert(NewFD != -1 && "Must call getFD first");
469 template <typename T>
470 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
472 NewArchiveIterator NI(I, Name);
474 Members.push_back(NI);
488 computeInsertAction(ArchiveOperation Operation,
489 object::Archive::child_iterator I, StringRef Name,
490 std::vector<std::string>::iterator &Pos) {
491 if (Operation == QuickAppend || Members.empty())
492 return IA_AddOldMember;
494 std::vector<std::string>::iterator MI = std::find_if(
495 Members.begin(), Members.end(),
496 [Name](StringRef Path) { return Name == sys::path::filename(Path); });
498 if (MI == Members.end())
499 return IA_AddOldMember;
503 if (Operation == Delete)
506 if (Operation == Move)
507 return IA_MoveOldMember;
509 if (Operation == ReplaceOrInsert) {
510 StringRef PosName = sys::path::filename(RelPos);
513 return IA_AddNewMeber;
514 return IA_MoveNewMember;
517 // We could try to optimize this to a fstat, but it is not a common
519 sys::fs::file_status Status;
520 failIfError(sys::fs::status(*MI, Status), *MI);
521 if (Status.getLastModificationTime() < I->getLastModified()) {
523 return IA_AddOldMember;
524 return IA_MoveOldMember;
528 return IA_AddNewMeber;
529 return IA_MoveNewMember;
531 llvm_unreachable("No such operation");
534 // We have to walk this twice and computing it is not trivial, so creating an
535 // explicit std::vector is actually fairly efficient.
536 static std::vector<NewArchiveIterator>
537 computeNewArchiveMembers(ArchiveOperation Operation,
538 object::Archive *OldArchive) {
539 std::vector<NewArchiveIterator> Ret;
540 std::vector<NewArchiveIterator> Moved;
542 StringRef PosName = sys::path::filename(RelPos);
544 for (object::Archive::child_iterator I = OldArchive->child_begin(),
545 E = OldArchive->child_end();
547 int Pos = Ret.size();
548 ErrorOr<StringRef> NameOrErr = I->getName();
549 failIfError(NameOrErr.getError());
550 StringRef Name = NameOrErr.get();
551 if (Name == PosName) {
552 assert(AddAfter || AddBefore);
559 std::vector<std::string>::iterator MemberI = Members.end();
560 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
562 case IA_AddOldMember:
563 addMember(Ret, I, Name);
566 addMember(Ret, &*MemberI, Name);
570 case IA_MoveOldMember:
571 addMember(Moved, I, Name);
573 case IA_MoveNewMember:
574 addMember(Moved, &*MemberI, Name);
577 if (MemberI != Members.end())
578 Members.erase(MemberI);
582 if (Operation == Delete)
585 if (!RelPos.empty() && InsertPos == -1)
586 fail("Insertion point not found");
589 InsertPos = Ret.size();
591 assert(unsigned(InsertPos) <= Ret.size());
592 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
594 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
596 for (std::vector<std::string>::iterator I = Members.begin(),
598 I != E; ++I, ++Pos) {
599 StringRef Name = sys::path::filename(*I);
600 addMember(Ret, &*I, Name, Pos);
606 template <typename T>
607 static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
608 bool MayTruncate = false) {
609 uint64_t OldPos = OS.tell();
611 unsigned SizeSoFar = OS.tell() - OldPos;
612 if (Size > SizeSoFar) {
613 unsigned Remaining = Size - SizeSoFar;
614 for (unsigned I = 0; I < Remaining; ++I)
616 } else if (Size < SizeSoFar) {
617 assert(MayTruncate && "Data doesn't fit in Size");
618 // Some of the data this is used for (like UID) can be larger than the
619 // space available in the archive format. Truncate in that case.
620 OS.seek(OldPos + Size);
624 static void print32BE(raw_fd_ostream &Out, unsigned Val) {
625 for (int I = 3; I >= 0; --I) {
626 char V = (Val >> (8 * I)) & 0xff;
631 static void printRestOfMemberHeader(raw_fd_ostream &Out,
632 const sys::TimeValue &ModTime, unsigned UID,
633 unsigned GID, unsigned Perms,
635 printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
636 printWithSpacePadding(Out, UID, 6, true);
637 printWithSpacePadding(Out, GID, 6, true);
638 printWithSpacePadding(Out, format("%o", Perms), 8);
639 printWithSpacePadding(Out, Size, 10);
643 static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
644 const sys::TimeValue &ModTime, unsigned UID,
645 unsigned GID, unsigned Perms, unsigned Size) {
646 printWithSpacePadding(Out, Twine(Name) + "/", 16);
647 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
650 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
651 const sys::TimeValue &ModTime, unsigned UID,
652 unsigned GID, unsigned Perms, unsigned Size) {
654 printWithSpacePadding(Out, NameOffset, 15);
655 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
658 static void writeStringTable(raw_fd_ostream &Out,
659 ArrayRef<NewArchiveIterator> Members,
660 std::vector<unsigned> &StringMapIndexes) {
661 unsigned StartOffset = 0;
662 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
665 StringRef Name = I->getName();
666 if (Name.size() < 16)
668 if (StartOffset == 0) {
669 printWithSpacePadding(Out, "//", 58);
671 StartOffset = Out.tell();
673 StringMapIndexes.push_back(Out.tell() - StartOffset);
674 Out << Name << "/\n";
676 if (StartOffset == 0)
680 int Pos = Out.tell();
681 Out.seek(StartOffset - 12);
682 printWithSpacePadding(Out, Pos - StartOffset, 10);
687 writeSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
688 MutableArrayRef<std::unique_ptr<MemoryBuffer>> Buffers,
689 std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
690 unsigned StartOffset = 0;
691 unsigned MemberNum = 0;
693 raw_string_ostream NameOS(NameBuf);
694 unsigned NumSyms = 0;
695 LLVMContext &Context = getGlobalContext();
696 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
698 I != E; ++I, ++MemberNum) {
699 std::unique_ptr<MemoryBuffer> &MemberBuffer = Buffers[MemberNum];
700 ErrorOr<object::SymbolicFile *> ObjOrErr =
701 object::SymbolicFile::createSymbolicFile(
702 MemberBuffer, sys::fs::file_magic::unknown, &Context);
704 continue; // FIXME: check only for "not an object file" errors.
705 std::unique_ptr<object::SymbolicFile> Obj(ObjOrErr.get());
708 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
709 StartOffset = Out.tell();
713 for (const object::BasicSymbolRef &S : Obj->symbols()) {
714 uint32_t Symflags = S.getFlags();
715 if (Symflags & object::SymbolRef::SF_FormatSpecific)
717 if (!(Symflags & object::SymbolRef::SF_Global))
719 if (Symflags & object::SymbolRef::SF_Undefined)
721 failIfError(S.printName(NameOS));
724 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
727 MemberBuffer.reset(Obj->releaseBuffer());
731 if (StartOffset == 0)
737 unsigned Pos = Out.tell();
738 Out.seek(StartOffset - 12);
739 printWithSpacePadding(Out, Pos - StartOffset, 10);
740 Out.seek(StartOffset);
741 print32BE(Out, NumSyms);
745 static void performWriteOperation(ArchiveOperation Operation,
746 object::Archive *OldArchive) {
747 SmallString<128> TmpArchive;
748 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
749 TmpArchiveFD, TmpArchive));
751 TemporaryOutput = TmpArchive.c_str();
752 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
753 raw_fd_ostream &Out = Output.os();
756 std::vector<NewArchiveIterator> NewMembers =
757 computeNewArchiveMembers(Operation, OldArchive);
759 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
761 std::vector<std::unique_ptr<MemoryBuffer>> MemberBuffers;
762 MemberBuffers.resize(NewMembers.size());
764 for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
765 std::unique_ptr<MemoryBuffer> MemberBuffer;
766 NewArchiveIterator &Member = NewMembers[I];
768 if (Member.isNewMember()) {
769 const char *Filename = Member.getNew();
770 int FD = Member.getFD();
771 const sys::fs::file_status &Status = Member.getStatus();
772 failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
773 Status.getSize(), false),
777 object::Archive::child_iterator OldMember = Member.getOld();
778 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
779 OldMember->getMemoryBuffer();
780 failIfError(MemberBufferOrErr.getError());
781 MemberBuffer = std::move(MemberBufferOrErr.get());
783 MemberBuffers[I].reset(MemberBuffer.release());
787 writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
790 std::vector<unsigned> StringMapIndexes;
791 writeStringTable(Out, NewMembers, StringMapIndexes);
793 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
794 MemberOffsetRefs.begin();
796 unsigned MemberNum = 0;
797 unsigned LongNameMemberNum = 0;
798 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
799 E = NewMembers.end();
800 I != E; ++I, ++MemberNum) {
802 unsigned Pos = Out.tell();
803 while (MemberRefsI != MemberOffsetRefs.end() &&
804 MemberRefsI->second == MemberNum) {
805 Out.seek(MemberRefsI->first);
811 const MemoryBuffer *File = MemberBuffers[MemberNum].get();
812 if (I->isNewMember()) {
813 const char *FileName = I->getNew();
814 const sys::fs::file_status &Status = I->getStatus();
816 StringRef Name = sys::path::filename(FileName);
817 if (Name.size() < 16)
818 printMemberHeader(Out, Name, Status.getLastModificationTime(),
819 Status.getUser(), Status.getGroup(),
820 Status.permissions(), Status.getSize());
822 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
823 Status.getLastModificationTime(), Status.getUser(),
824 Status.getGroup(), Status.permissions(),
827 object::Archive::child_iterator OldMember = I->getOld();
828 StringRef Name = I->getName();
830 if (Name.size() < 16)
831 printMemberHeader(Out, Name, OldMember->getLastModified(),
832 OldMember->getUID(), OldMember->getGID(),
833 OldMember->getAccessMode(), OldMember->getSize());
835 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
836 OldMember->getLastModified(), OldMember->getUID(),
837 OldMember->getGID(), OldMember->getAccessMode(),
838 OldMember->getSize());
841 Out << File->getBuffer();
849 sys::fs::rename(TemporaryOutput, ArchiveName);
850 TemporaryOutput = nullptr;
853 static void createSymbolTable(object::Archive *OldArchive) {
854 // When an archive is created or modified, if the s option is given, the
855 // resulting archive will have a current symbol table. If the S option
856 // is given, it will have no symbol table.
857 // In summary, we only need to update the symbol table if we have none.
858 // This is actually very common because of broken build systems that think
859 // they have to run ranlib.
860 if (OldArchive->hasSymbolTable())
863 performWriteOperation(CreateSymTab, OldArchive);
866 static void performOperation(ArchiveOperation Operation,
867 object::Archive *OldArchive) {
872 performReadOperation(Operation, OldArchive);
878 case ReplaceOrInsert:
879 performWriteOperation(Operation, OldArchive);
882 createSymbolTable(OldArchive);
885 llvm_unreachable("Unknown operation.");
888 static int ar_main(char **argv);
889 static int ranlib_main();
891 // main - main program for llvm-ar .. see comments in the code
892 int main(int argc, char **argv) {
894 // Print a stack trace if we signal out.
895 sys::PrintStackTraceOnErrorSignal();
896 PrettyStackTraceProgram X(argc, argv);
897 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
899 // Have the command line options parsed and handle things
900 // like --help and --version.
901 cl::ParseCommandLineOptions(argc, argv,
902 "LLVM Archiver (llvm-ar)\n\n"
903 " This program archives bitcode files into single libraries\n"
906 StringRef Stem = sys::path::stem(ToolName);
907 if (Stem.find("ar") != StringRef::npos)
908 return ar_main(argv);
909 if (Stem.find("ranlib") != StringRef::npos)
910 return ranlib_main();
911 fail("Not ranlib or ar!");
914 static int performOperation(ArchiveOperation Operation);
917 if (RestOfArgs.size() != 1)
918 fail(ToolName + "takes just one archive as argument");
919 ArchiveName = RestOfArgs[0];
920 return performOperation(CreateSymTab);
923 int ar_main(char **argv) {
924 // Do our own parsing of the command line because the CommandLine utility
925 // can't handle the grouped positional parameters without a dash.
926 ArchiveOperation Operation = parseCommandLine();
927 return performOperation(Operation);
930 static int performOperation(ArchiveOperation Operation) {
931 // Create or open the archive object.
932 std::unique_ptr<MemoryBuffer> Buf;
933 std::error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
934 if (EC && EC != errc::no_such_file_or_directory) {
935 errs() << ToolName << ": error opening '" << ArchiveName
936 << "': " << EC.message() << "!\n";
941 object::Archive Archive(std::move(Buf), EC);
944 errs() << ToolName << ": error loading '" << ArchiveName
945 << "': " << EC.message() << "!\n";
948 performOperation(Operation, &Archive);
952 assert(EC == errc::no_such_file_or_directory);
954 if (!shouldCreateArchive(Operation)) {
955 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
958 // Produce a warning if we should and we're creating the archive
959 errs() << ToolName << ": creating " << ArchiveName << "\n";
963 performOperation(Operation, nullptr);