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/FileSystem.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/Signals.h"
26 #include "llvm/Support/ToolOutputFile.h"
27 #include "llvm/Support/raw_ostream.h"
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
40 // The name this program was invoked as.
41 static StringRef ToolName;
43 static const char *TemporaryOutput;
44 static int TmpArchiveFD = -1;
46 // fail - Show the error message and exit.
47 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
48 outs() << ToolName << ": " << Error << ".\n";
49 if (TmpArchiveFD != -1)
52 sys::fs::remove(TemporaryOutput);
56 static void failIfError(error_code EC, Twine Context = "") {
60 std::string ContextStr = Context.str();
63 fail(Context + ": " + EC.message());
66 // llvm-ar/llvm-ranlib remaining positional arguments.
67 static cl::list<std::string>
68 RestOfArgs(cl::Positional, cl::OneOrMore,
69 cl::desc("[relpos] [count] <archive-file> [members]..."));
73 // MoreHelp - Provide additional help output explaining the operations and
74 // modifiers of llvm-ar. This object instructs the CommandLine library
75 // to print the text of the constructor when the --help option is given.
76 static cl::extrahelp MoreHelp(
78 " d[NsS] - delete file(s) from the archive\n"
79 " m[abiSs] - move file(s) in the archive\n"
80 " p[kN] - print file(s) found in the archive\n"
81 " q[ufsS] - quick append file(s) to the archive\n"
82 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
83 " t - display contents of archive\n"
84 " x[No] - extract file(s) from the archive\n"
85 "\nMODIFIERS (operation specific):\n"
86 " [a] - put file(s) after [relpos]\n"
87 " [b] - put file(s) before [relpos] (same as [i])\n"
88 " [i] - put file(s) before [relpos] (same as [b])\n"
89 " [N] - use instance [count] of name\n"
90 " [o] - preserve original dates\n"
91 " [s] - create an archive index (cf. ranlib)\n"
92 " [S] - do not build a symbol table\n"
93 " [u] - update only files newer than archive contents\n"
94 "\nMODIFIERS (generic):\n"
95 " [c] - do not warn if the library had to be created\n"
96 " [v] - be verbose about actions taken\n"
99 // This enumeration delineates the kinds of operations on an archive
100 // that are permitted.
101 enum ArchiveOperation {
102 Print, ///< Print the contents of the archive
103 Delete, ///< Delete the specified members
104 Move, ///< Move members to end or as given by {a,b,i} modifiers
105 QuickAppend, ///< Quickly append to end of archive
106 ReplaceOrInsert, ///< Replace or Insert members
107 DisplayTable, ///< Display the table of contents
108 Extract, ///< Extract files back to file system
109 CreateSymTab ///< Create a symbol table in an existing archive
112 // Modifiers to follow operation to vary behavior
113 static bool AddAfter = false; ///< 'a' modifier
114 static bool AddBefore = false; ///< 'b' modifier
115 static bool Create = false; ///< 'c' modifier
116 static bool OriginalDates = false; ///< 'o' modifier
117 static bool OnlyUpdate = false; ///< 'u' modifier
118 static bool Verbose = false; ///< 'v' modifier
119 static bool Symtab = true; ///< 's' modifier
121 // Relative Positional Argument (for insert/move). This variable holds
122 // the name of the archive member to which the 'a', 'b' or 'i' modifier
123 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
125 static std::string RelPos;
127 // This variable holds the name of the archive file as given on the
129 static std::string ArchiveName;
131 // This variable holds the list of member files to proecess, as given
132 // on the command line.
133 static std::vector<std::string> Members;
135 // show_help - Show the error message, the help message and exit.
136 LLVM_ATTRIBUTE_NORETURN static void
137 show_help(const std::string &msg) {
138 errs() << ToolName << ": " << msg << "\n\n";
139 cl::PrintHelpMessage();
143 // getRelPos - Extract the member filename from the command line for
144 // the [relpos] argument associated with a, b, and i modifiers
145 static void getRelPos() {
146 if(RestOfArgs.size() == 0)
147 show_help("Expected [relpos] for a, b, or i modifier");
148 RelPos = RestOfArgs[0];
149 RestOfArgs.erase(RestOfArgs.begin());
152 static void getOptions() {
153 if(RestOfArgs.size() == 0)
154 show_help("Expected options");
155 Options = RestOfArgs[0];
156 RestOfArgs.erase(RestOfArgs.begin());
159 // getArchive - Get the archive file name from the command line
160 static void getArchive() {
161 if(RestOfArgs.size() == 0)
162 show_help("An archive name must be specified");
163 ArchiveName = RestOfArgs[0];
164 RestOfArgs.erase(RestOfArgs.begin());
167 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
168 // This is just for clarity.
169 static void getMembers() {
170 if(RestOfArgs.size() > 0)
171 Members = std::vector<std::string>(RestOfArgs);
174 // parseCommandLine - Parse the command line options as presented and return the
175 // operation specified. Process all modifiers and check to make sure that
176 // constraints on modifier/operation pairs have not been violated.
177 static ArchiveOperation parseCommandLine() {
180 // Keep track of number of operations. We can only specify one
182 unsigned NumOperations = 0;
184 // Keep track of the number of positional modifiers (a,b,i). Only
185 // one can be specified.
186 unsigned NumPositional = 0;
188 // Keep track of which operation was requested
189 ArchiveOperation Operation;
191 bool MaybeJustCreateSymTab = false;
193 for(unsigned i=0; i<Options.size(); ++i) {
195 case 'd': ++NumOperations; Operation = Delete; break;
196 case 'm': ++NumOperations; Operation = Move ; break;
197 case 'p': ++NumOperations; Operation = Print; break;
198 case 'q': ++NumOperations; Operation = QuickAppend; break;
199 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
200 case 't': ++NumOperations; Operation = DisplayTable; break;
201 case 'x': ++NumOperations; Operation = Extract; break;
202 case 'c': Create = true; break;
203 case 'l': /* accepted but unused */ break;
204 case 'o': OriginalDates = true; break;
207 MaybeJustCreateSymTab = true;
212 case 'u': OnlyUpdate = true; break;
213 case 'v': Verbose = true; break;
230 cl::PrintHelpMessage();
234 // At this point, the next thing on the command line must be
238 // Everything on the command line at this point is a member.
241 if (NumOperations == 0 && MaybeJustCreateSymTab) {
243 Operation = CreateSymTab;
244 if (!Members.empty())
245 show_help("The s operation takes only an archive as argument");
248 // Perform various checks on the operation/modifier specification
249 // to make sure we are dealing with a legal request.
250 if (NumOperations == 0)
251 show_help("You must specify at least one of the operations");
252 if (NumOperations > 1)
253 show_help("Only one operation may be specified");
254 if (NumPositional > 1)
255 show_help("You may only specify one of a, b, and i modifiers");
256 if (AddAfter || AddBefore) {
257 if (Operation != Move && Operation != ReplaceOrInsert)
258 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
259 "the 'm' or 'r' operations");
261 if (OriginalDates && Operation != Extract)
262 show_help("The 'o' modifier is only applicable to the 'x' operation");
263 if (OnlyUpdate && Operation != ReplaceOrInsert)
264 show_help("The 'u' modifier is only applicable to the 'r' operation");
266 // Return the parsed operation to the caller
270 // Implements the 'p' operation. This function traverses the archive
271 // looking for members that match the path list.
272 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
274 outs() << "Printing " << Name << "\n";
276 StringRef Data = I->getBuffer();
277 outs().write(Data.data(), Data.size());
280 // putMode - utility function for printing out the file mode when the 't'
281 // operation is in verbose mode.
282 static void printMode(unsigned mode) {
297 // Implement the 't' operation. This function prints out just
298 // the file names of each of the members. However, if verbose mode is requested
299 // ('v' modifier) then the file type, permission mode, user, group, size, and
300 // modification time are also printed.
301 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
303 sys::fs::perms Mode = I->getAccessMode();
304 printMode((Mode >> 6) & 007);
305 printMode((Mode >> 3) & 007);
306 printMode(Mode & 007);
307 outs() << ' ' << I->getUID();
308 outs() << '/' << I->getGID();
309 outs() << ' ' << format("%6llu", I->getSize());
310 outs() << ' ' << I->getLastModified().str();
313 outs() << Name << "\n";
316 // Implement the 'x' operation. This function extracts files back to the file
318 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
319 // Retain the original mode.
320 sys::fs::perms Mode = I->getAccessMode();
321 SmallString<128> Storage = Name;
325 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_Binary, Mode),
329 raw_fd_ostream file(FD, false);
331 // Get the data and its length
332 StringRef Data = I->getBuffer();
335 file.write(Data.data(), Data.size());
338 // If we're supposed to retain the original modification times, etc. do so
342 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
345 fail("Could not close the file");
348 static bool shouldCreateArchive(ArchiveOperation Op) {
359 case ReplaceOrInsert:
363 llvm_unreachable("Missing entry in covered switch.");
366 static void performReadOperation(ArchiveOperation Operation,
367 object::Archive *OldArchive) {
368 for (object::Archive::child_iterator I = OldArchive->child_begin(),
369 E = OldArchive->child_end();
372 failIfError(I->getName(Name));
374 if (!Members.empty() &&
375 std::find(Members.begin(), Members.end(), Name) == Members.end())
380 llvm_unreachable("Not a read operation");
385 doDisplayTable(Name, I);
395 class NewArchiveIterator {
399 object::Archive::child_iterator OldI;
401 std::string NewFilename;
403 mutable sys::fs::file_status NewStatus;
406 NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
407 NewArchiveIterator(std::string *I, StringRef Name);
408 NewArchiveIterator();
409 bool isNewMember() const;
410 StringRef getName() const;
412 object::Archive::child_iterator getOld() const;
414 const char *getNew() const;
416 const sys::fs::file_status &getStatus() const;
420 NewArchiveIterator::NewArchiveIterator() {}
422 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
424 : IsNewMember(false), Name(Name), OldI(I) {}
426 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
427 : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
429 StringRef NewArchiveIterator::getName() const { return Name; }
431 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
433 object::Archive::child_iterator NewArchiveIterator::getOld() const {
434 assert(!IsNewMember);
438 const char *NewArchiveIterator::getNew() const {
440 return NewFilename.c_str();
443 int NewArchiveIterator::getFD() const {
447 failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
450 failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
452 // Opening a directory doesn't make sense. Let it fail.
453 // Linux cannot open directories with open(2), although
454 // cygwin and *bsd can.
455 if (NewStatus.type() == sys::fs::file_type::directory_file)
456 failIfError(error_code(errc::is_a_directory, posix_category()),
462 const sys::fs::file_status &NewArchiveIterator::getStatus() const {
464 assert(NewFD != -1 && "Must call getFD first");
468 template <typename T>
469 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
471 NewArchiveIterator NI(I, Name);
473 Members.push_back(NI);
483 HasName(StringRef Name) : Name(Name) {}
484 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
497 computeInsertAction(ArchiveOperation Operation,
498 object::Archive::child_iterator I, StringRef Name,
499 std::vector<std::string>::iterator &Pos) {
500 if (Operation == QuickAppend || Members.empty())
501 return IA_AddOldMember;
503 std::vector<std::string>::iterator MI =
504 std::find_if(Members.begin(), Members.end(), HasName(Name));
506 if (MI == Members.end())
507 return IA_AddOldMember;
511 if (Operation == Delete)
514 if (Operation == Move)
515 return IA_MoveOldMember;
517 if (Operation == ReplaceOrInsert) {
518 StringRef PosName = sys::path::filename(RelPos);
521 return IA_AddNewMeber;
522 return IA_MoveNewMember;
525 // We could try to optimize this to a fstat, but it is not a common
527 sys::fs::file_status Status;
528 failIfError(sys::fs::status(*MI, Status));
529 if (Status.getLastModificationTime() < I->getLastModified()) {
531 return IA_AddOldMember;
532 return IA_MoveOldMember;
536 return IA_AddNewMeber;
537 return IA_MoveNewMember;
539 llvm_unreachable("No such operation");
542 // We have to walk this twice and computing it is not trivial, so creating an
543 // explicit std::vector is actually fairly efficient.
544 static std::vector<NewArchiveIterator>
545 computeNewArchiveMembers(ArchiveOperation Operation,
546 object::Archive *OldArchive) {
547 std::vector<NewArchiveIterator> Ret;
548 std::vector<NewArchiveIterator> Moved;
550 StringRef PosName = sys::path::filename(RelPos);
552 for (object::Archive::child_iterator I = OldArchive->child_begin(),
553 E = OldArchive->child_end();
555 int Pos = Ret.size();
557 failIfError(I->getName(Name));
558 if (Name == PosName) {
559 assert(AddAfter || AddBefore);
566 std::vector<std::string>::iterator MemberI = Members.end();
567 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
569 case IA_AddOldMember:
570 addMember(Ret, I, Name);
573 addMember(Ret, &*MemberI, Name);
577 case IA_MoveOldMember:
578 addMember(Moved, I, Name);
580 case IA_MoveNewMember:
581 addMember(Moved, &*MemberI, Name);
584 if (MemberI != Members.end())
585 Members.erase(MemberI);
589 if (Operation == Delete)
592 if (!RelPos.empty() && InsertPos == -1)
593 fail("Insertion point not found");
596 InsertPos = Ret.size();
598 assert(unsigned(InsertPos) <= Ret.size());
599 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
601 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
603 for (std::vector<std::string>::iterator I = Members.begin(),
605 I != E; ++I, ++Pos) {
606 StringRef Name = sys::path::filename(*I);
607 addMember(Ret, &*I, Name, Pos);
613 template <typename T>
614 static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
615 bool MayTruncate = false) {
616 uint64_t OldPos = OS.tell();
618 unsigned SizeSoFar = OS.tell() - OldPos;
619 if (Size > SizeSoFar) {
620 unsigned Remaining = Size - SizeSoFar;
621 for (unsigned I = 0; I < Remaining; ++I)
623 } else if (Size < SizeSoFar) {
624 assert(MayTruncate && "Data doesn't fit in Size");
625 // Some of the data this is used for (like UID) can be larger than the
626 // space available in the archive format. Truncate in that case.
627 OS.seek(OldPos + Size);
631 static void print32BE(raw_fd_ostream &Out, unsigned Val) {
632 for (int I = 3; I >= 0; --I) {
633 char V = (Val >> (8 * I)) & 0xff;
638 static void printRestOfMemberHeader(raw_fd_ostream &Out,
639 const sys::TimeValue &ModTime, unsigned UID,
640 unsigned GID, unsigned Perms,
642 printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
643 printWithSpacePadding(Out, UID, 6, true);
644 printWithSpacePadding(Out, GID, 6, true);
645 printWithSpacePadding(Out, format("%o", Perms), 8);
646 printWithSpacePadding(Out, Size, 10);
650 static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
651 const sys::TimeValue &ModTime, unsigned UID,
652 unsigned GID, unsigned Perms, unsigned Size) {
653 printWithSpacePadding(Out, Twine(Name) + "/", 16);
654 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
657 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
658 const sys::TimeValue &ModTime, unsigned UID,
659 unsigned GID, unsigned Perms, unsigned Size) {
661 printWithSpacePadding(Out, NameOffset, 15);
662 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
665 static void writeStringTable(raw_fd_ostream &Out,
666 ArrayRef<NewArchiveIterator> Members,
667 std::vector<unsigned> &StringMapIndexes) {
668 unsigned StartOffset = 0;
669 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
672 StringRef Name = I->getName();
673 if (Name.size() < 16)
675 if (StartOffset == 0) {
676 printWithSpacePadding(Out, "//", 58);
678 StartOffset = Out.tell();
680 StringMapIndexes.push_back(Out.tell() - StartOffset);
681 Out << Name << "/\n";
683 if (StartOffset == 0)
687 int Pos = Out.tell();
688 Out.seek(StartOffset - 12);
689 printWithSpacePadding(Out, Pos - StartOffset, 10);
693 static void writeSymbolTable(
694 raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
695 ArrayRef<MemoryBuffer *> Buffers,
696 std::vector<std::pair<unsigned, unsigned> > &MemberOffsetRefs) {
697 unsigned StartOffset = 0;
698 unsigned MemberNum = 0;
699 std::vector<StringRef> SymNames;
700 std::vector<object::ObjectFile *> DeleteIt;
701 for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
703 I != E; ++I, ++MemberNum) {
704 MemoryBuffer *MemberBuffer = Buffers[MemberNum];
705 ErrorOr<object::ObjectFile *> ObjOrErr =
706 object::ObjectFile::createObjectFile(MemberBuffer, false,
707 sys::fs::file_magic::unknown);
709 continue; // FIXME: check only for "not an object file" errors.
710 object::ObjectFile *Obj = ObjOrErr.get();
712 DeleteIt.push_back(Obj);
714 printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
715 StartOffset = Out.tell();
719 for (object::symbol_iterator I = Obj->begin_symbols(),
720 E = Obj->end_symbols();
723 failIfError(I->getFlags(Symflags));
724 if (Symflags & object::SymbolRef::SF_FormatSpecific)
726 if (!(Symflags & object::SymbolRef::SF_Global))
728 if (Symflags & object::SymbolRef::SF_Undefined)
731 failIfError(I->getName(Name));
732 SymNames.push_back(Name);
733 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
737 for (std::vector<StringRef>::iterator I = SymNames.begin(),
744 for (std::vector<object::ObjectFile *>::iterator I = DeleteIt.begin(),
747 object::ObjectFile *O = *I;
751 if (StartOffset == 0)
757 unsigned Pos = Out.tell();
758 Out.seek(StartOffset - 12);
759 printWithSpacePadding(Out, Pos - StartOffset, 10);
760 Out.seek(StartOffset);
761 print32BE(Out, SymNames.size());
765 static void performWriteOperation(ArchiveOperation Operation,
766 object::Archive *OldArchive) {
767 SmallString<128> TmpArchive;
768 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
769 TmpArchiveFD, TmpArchive));
771 TemporaryOutput = TmpArchive.c_str();
772 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
773 raw_fd_ostream &Out = Output.os();
776 std::vector<NewArchiveIterator> NewMembers =
777 computeNewArchiveMembers(Operation, OldArchive);
779 std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
781 std::vector<MemoryBuffer *> MemberBuffers;
782 MemberBuffers.resize(NewMembers.size());
784 for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
785 OwningPtr<MemoryBuffer> MemberBuffer;
786 NewArchiveIterator &Member = NewMembers[I];
788 if (Member.isNewMember()) {
789 const char *Filename = Member.getNew();
790 int FD = Member.getFD();
791 const sys::fs::file_status &Status = Member.getStatus();
792 failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
793 Status.getSize(), false),
797 object::Archive::child_iterator OldMember = Member.getOld();
798 failIfError(OldMember->getMemoryBuffer(MemberBuffer));
800 MemberBuffers[I] = MemberBuffer.take();
804 writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
807 std::vector<unsigned> StringMapIndexes;
808 writeStringTable(Out, NewMembers, StringMapIndexes);
810 std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
811 MemberOffsetRefs.begin();
813 unsigned MemberNum = 0;
814 unsigned LongNameMemberNum = 0;
815 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
816 E = NewMembers.end();
817 I != E; ++I, ++MemberNum) {
819 unsigned Pos = Out.tell();
820 while (MemberRefsI != MemberOffsetRefs.end() &&
821 MemberRefsI->second == MemberNum) {
822 Out.seek(MemberRefsI->first);
828 const MemoryBuffer *File = MemberBuffers[MemberNum];
829 if (I->isNewMember()) {
830 const char *FileName = I->getNew();
831 const sys::fs::file_status &Status = I->getStatus();
833 StringRef Name = sys::path::filename(FileName);
834 if (Name.size() < 16)
835 printMemberHeader(Out, Name, Status.getLastModificationTime(),
836 Status.getUser(), Status.getGroup(),
837 Status.permissions(), Status.getSize());
839 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
840 Status.getLastModificationTime(), Status.getUser(),
841 Status.getGroup(), Status.permissions(),
844 object::Archive::child_iterator OldMember = I->getOld();
845 StringRef Name = I->getName();
847 if (Name.size() < 16)
848 printMemberHeader(Out, Name, OldMember->getLastModified(),
849 OldMember->getUID(), OldMember->getGID(),
850 OldMember->getAccessMode(), OldMember->getSize());
852 printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
853 OldMember->getLastModified(), OldMember->getUID(),
854 OldMember->getGID(), OldMember->getAccessMode(),
855 OldMember->getSize());
858 Out << File->getBuffer();
864 for (unsigned I = 0, N = MemberBuffers.size(); I < N; ++I) {
865 delete MemberBuffers[I];
870 sys::fs::rename(TemporaryOutput, ArchiveName);
871 TemporaryOutput = NULL;
874 static void createSymbolTable(object::Archive *OldArchive) {
875 // When an archive is created or modified, if the s option is given, the
876 // resulting archive will have a current symbol table. If the S option
877 // is given, it will have no symbol table.
878 // In summary, we only need to update the symbol table if we have none.
879 // This is actually very common because of broken build systems that think
880 // they have to run ranlib.
881 if (OldArchive->hasSymbolTable())
884 performWriteOperation(CreateSymTab, OldArchive);
887 static void performOperation(ArchiveOperation Operation,
888 object::Archive *OldArchive) {
893 performReadOperation(Operation, OldArchive);
899 case ReplaceOrInsert:
900 performWriteOperation(Operation, OldArchive);
903 createSymbolTable(OldArchive);
906 llvm_unreachable("Unknown operation.");
909 static int ar_main(char **argv);
910 static int ranlib_main();
912 // main - main program for llvm-ar .. see comments in the code
913 int main(int argc, char **argv) {
915 // Print a stack trace if we signal out.
916 sys::PrintStackTraceOnErrorSignal();
917 PrettyStackTraceProgram X(argc, argv);
918 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
920 // Have the command line options parsed and handle things
921 // like --help and --version.
922 cl::ParseCommandLineOptions(argc, argv,
923 "LLVM Archiver (llvm-ar)\n\n"
924 " This program archives bitcode files into single libraries\n"
927 StringRef Stem = sys::path::stem(ToolName);
928 if (Stem.find("ar") != StringRef::npos)
929 return ar_main(argv);
930 if (Stem.find("ranlib") != StringRef::npos)
931 return ranlib_main();
932 fail("Not ranlib or ar!");
935 static int performOperation(ArchiveOperation Operation);
938 if (RestOfArgs.size() != 1)
939 fail(ToolName + "takes just one archive as argument");
940 ArchiveName = RestOfArgs[0];
941 return performOperation(CreateSymTab);
944 int ar_main(char **argv) {
945 // Do our own parsing of the command line because the CommandLine utility
946 // can't handle the grouped positional parameters without a dash.
947 ArchiveOperation Operation = parseCommandLine();
948 return performOperation(Operation);
951 static int performOperation(ArchiveOperation Operation) {
952 // Create or open the archive object.
953 OwningPtr<MemoryBuffer> Buf;
954 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
955 if (EC && EC != llvm::errc::no_such_file_or_directory) {
956 errs() << ToolName << ": error opening '" << ArchiveName
957 << "': " << EC.message() << "!\n";
962 object::Archive Archive(Buf.take(), EC);
965 errs() << ToolName << ": error loading '" << ArchiveName
966 << "': " << EC.message() << "!\n";
969 performOperation(Operation, &Archive);
973 assert(EC == llvm::errc::no_such_file_or_directory);
975 if (!shouldCreateArchive(Operation)) {
976 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
979 // Produce a warning if we should and we're creating the archive
980 errs() << ToolName << ": creating " << ArchiveName << "\n";
984 performOperation(Operation, NULL);