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);
686 static void writeSymbolTable(
687 raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
688 ArrayRef<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 std::vector<object::SymbolicFile *> DeleteIt;
696 LLVMContext &Context = getGlobalContext();
697 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
699 I != E; ++I, ++MemberNum) {
700 MemoryBuffer *MemberBuffer = Buffers[MemberNum];
701 ErrorOr<object::SymbolicFile *> ObjOrErr =
702 object::SymbolicFile::createSymbolicFile(
703 MemberBuffer, false, sys::fs::file_magic::unknown, &Context);
705 continue; // FIXME: check only for "not an object file" errors.
706 object::SymbolicFile *Obj = ObjOrErr.get();
708 DeleteIt.push_back(Obj);
710 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
711 StartOffset = Out.tell();
715 for (object::basic_symbol_iterator I = Obj->symbol_begin(),
716 E = Obj->symbol_end();
718 uint32_t Symflags = I->getFlags();
719 if (Symflags & object::SymbolRef::SF_FormatSpecific)
721 if (!(Symflags & object::SymbolRef::SF_Global))
723 if (Symflags & object::SymbolRef::SF_Undefined)
725 failIfError(I->printName(NameOS));
728 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
734 for (std::vector<object::SymbolicFile *>::iterator I = DeleteIt.begin(),
737 object::SymbolicFile *O = *I;
741 if (StartOffset == 0)
747 unsigned Pos = Out.tell();
748 Out.seek(StartOffset - 12);
749 printWithSpacePadding(Out, Pos - StartOffset, 10);
750 Out.seek(StartOffset);
751 print32BE(Out, NumSyms);
755 static void performWriteOperation(ArchiveOperation Operation,
756 object::Archive *OldArchive) {
757 SmallString<128> TmpArchive;
758 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
759 TmpArchiveFD, TmpArchive));
761 TemporaryOutput = TmpArchive.c_str();
762 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
763 raw_fd_ostream &Out = Output.os();
766 std::vector<NewArchiveIterator> NewMembers =
767 computeNewArchiveMembers(Operation, OldArchive);
769 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
771 std::vector<MemoryBuffer *> MemberBuffers;
772 MemberBuffers.resize(NewMembers.size());
774 for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
775 std::unique_ptr<MemoryBuffer> MemberBuffer;
776 NewArchiveIterator &Member = NewMembers[I];
778 if (Member.isNewMember()) {
779 const char *Filename = Member.getNew();
780 int FD = Member.getFD();
781 const sys::fs::file_status &Status = Member.getStatus();
782 failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
783 Status.getSize(), false),
787 object::Archive::child_iterator OldMember = Member.getOld();
788 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
789 OldMember->getMemoryBuffer();
790 failIfError(MemberBufferOrErr.getError());
791 MemberBuffer = std::move(MemberBufferOrErr.get());
793 MemberBuffers[I] = MemberBuffer.release();
797 writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
800 std::vector<unsigned> StringMapIndexes;
801 writeStringTable(Out, NewMembers, StringMapIndexes);
803 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
804 MemberOffsetRefs.begin();
806 unsigned MemberNum = 0;
807 unsigned LongNameMemberNum = 0;
808 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
809 E = NewMembers.end();
810 I != E; ++I, ++MemberNum) {
812 unsigned Pos = Out.tell();
813 while (MemberRefsI != MemberOffsetRefs.end() &&
814 MemberRefsI->second == MemberNum) {
815 Out.seek(MemberRefsI->first);
821 const MemoryBuffer *File = MemberBuffers[MemberNum];
822 if (I->isNewMember()) {
823 const char *FileName = I->getNew();
824 const sys::fs::file_status &Status = I->getStatus();
826 StringRef Name = sys::path::filename(FileName);
827 if (Name.size() < 16)
828 printMemberHeader(Out, Name, Status.getLastModificationTime(),
829 Status.getUser(), Status.getGroup(),
830 Status.permissions(), Status.getSize());
832 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
833 Status.getLastModificationTime(), Status.getUser(),
834 Status.getGroup(), Status.permissions(),
837 object::Archive::child_iterator OldMember = I->getOld();
838 StringRef Name = I->getName();
840 if (Name.size() < 16)
841 printMemberHeader(Out, Name, OldMember->getLastModified(),
842 OldMember->getUID(), OldMember->getGID(),
843 OldMember->getAccessMode(), OldMember->getSize());
845 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
846 OldMember->getLastModified(), OldMember->getUID(),
847 OldMember->getGID(), OldMember->getAccessMode(),
848 OldMember->getSize());
851 Out << File->getBuffer();
857 for (unsigned I = 0, N = MemberBuffers.size(); I < N; ++I) {
858 delete MemberBuffers[I];
863 sys::fs::rename(TemporaryOutput, ArchiveName);
864 TemporaryOutput = nullptr;
867 static void createSymbolTable(object::Archive *OldArchive) {
868 // When an archive is created or modified, if the s option is given, the
869 // resulting archive will have a current symbol table. If the S option
870 // is given, it will have no symbol table.
871 // In summary, we only need to update the symbol table if we have none.
872 // This is actually very common because of broken build systems that think
873 // they have to run ranlib.
874 if (OldArchive->hasSymbolTable())
877 performWriteOperation(CreateSymTab, OldArchive);
880 static void performOperation(ArchiveOperation Operation,
881 object::Archive *OldArchive) {
886 performReadOperation(Operation, OldArchive);
892 case ReplaceOrInsert:
893 performWriteOperation(Operation, OldArchive);
896 createSymbolTable(OldArchive);
899 llvm_unreachable("Unknown operation.");
902 static int ar_main(char **argv);
903 static int ranlib_main();
905 // main - main program for llvm-ar .. see comments in the code
906 int main(int argc, char **argv) {
908 // Print a stack trace if we signal out.
909 sys::PrintStackTraceOnErrorSignal();
910 PrettyStackTraceProgram X(argc, argv);
911 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
913 // Have the command line options parsed and handle things
914 // like --help and --version.
915 cl::ParseCommandLineOptions(argc, argv,
916 "LLVM Archiver (llvm-ar)\n\n"
917 " This program archives bitcode files into single libraries\n"
920 StringRef Stem = sys::path::stem(ToolName);
921 if (Stem.find("ar") != StringRef::npos)
922 return ar_main(argv);
923 if (Stem.find("ranlib") != StringRef::npos)
924 return ranlib_main();
925 fail("Not ranlib or ar!");
928 static int performOperation(ArchiveOperation Operation);
931 if (RestOfArgs.size() != 1)
932 fail(ToolName + "takes just one archive as argument");
933 ArchiveName = RestOfArgs[0];
934 return performOperation(CreateSymTab);
937 int ar_main(char **argv) {
938 // Do our own parsing of the command line because the CommandLine utility
939 // can't handle the grouped positional parameters without a dash.
940 ArchiveOperation Operation = parseCommandLine();
941 return performOperation(Operation);
944 static int performOperation(ArchiveOperation Operation) {
945 // Create or open the archive object.
946 std::unique_ptr<MemoryBuffer> Buf;
947 std::error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
948 if (EC && EC != errc::no_such_file_or_directory) {
949 errs() << ToolName << ": error opening '" << ArchiveName
950 << "': " << EC.message() << "!\n";
955 object::Archive Archive(Buf.release(), EC);
958 errs() << ToolName << ": error loading '" << ArchiveName
959 << "': " << EC.message() << "!\n";
962 performOperation(Operation, &Archive);
966 assert(EC == errc::no_such_file_or_directory);
968 if (!shouldCreateArchive(Operation)) {
969 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
972 // Produce a warning if we should and we're creating the archive
973 errs() << ToolName << ": creating " << ArchiveName << "\n";
977 performOperation(Operation, nullptr);