785cabd08ff87ab814e35102ed09dc0939a499cb
[oota-llvm.git] / tools / llvm-ar / llvm-ar.cpp
1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up (relatively) standard unix archive files (.a) containing LLVM
11 // bitcode or other files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/ObjectFile.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Errc.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/LineIterator.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/ToolOutputFile.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cstdlib>
34 #include <memory>
35
36 #if !defined(_MSC_VER) && !defined(__MINGW32__)
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 #endif
41
42 using namespace llvm;
43
44 // The name this program was invoked as.
45 static StringRef ToolName;
46
47 static const char *TemporaryOutput;
48 static int TmpArchiveFD = -1;
49
50 // fail - Show the error message and exit.
51 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
52   outs() << ToolName << ": " << Error << ".\n";
53   if (TmpArchiveFD != -1)
54     close(TmpArchiveFD);
55   if (TemporaryOutput)
56     sys::fs::remove(TemporaryOutput);
57   exit(1);
58 }
59
60 static void failIfError(std::error_code EC, Twine Context = "") {
61   if (!EC)
62     return;
63
64   std::string ContextStr = Context.str();
65   if (ContextStr == "")
66     fail(EC.message());
67   fail(Context + ": " + EC.message());
68 }
69
70 // llvm-ar/llvm-ranlib remaining positional arguments.
71 static cl::list<std::string>
72     RestOfArgs(cl::Positional, cl::ZeroOrMore,
73                cl::desc("[relpos] [count] <archive-file> [members]..."));
74
75 static cl::opt<bool> MRI("M", cl::desc(""));
76
77 std::string Options;
78
79 // MoreHelp - Provide additional help output explaining the operations and
80 // modifiers of llvm-ar. This object instructs the CommandLine library
81 // to print the text of the constructor when the --help option is given.
82 static cl::extrahelp MoreHelp(
83   "\nOPERATIONS:\n"
84   "  d[NsS]       - delete file(s) from the archive\n"
85   "  m[abiSs]     - move file(s) in the archive\n"
86   "  p[kN]        - print file(s) found in the archive\n"
87   "  q[ufsS]      - quick append file(s) to the archive\n"
88   "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
89   "  t            - display contents of archive\n"
90   "  x[No]        - extract file(s) from the archive\n"
91   "\nMODIFIERS (operation specific):\n"
92   "  [a] - put file(s) after [relpos]\n"
93   "  [b] - put file(s) before [relpos] (same as [i])\n"
94   "  [i] - put file(s) before [relpos] (same as [b])\n"
95   "  [N] - use instance [count] of name\n"
96   "  [o] - preserve original dates\n"
97   "  [s] - create an archive index (cf. ranlib)\n"
98   "  [S] - do not build a symbol table\n"
99   "  [u] - update only files newer than archive contents\n"
100   "\nMODIFIERS (generic):\n"
101   "  [c] - do not warn if the library had to be created\n"
102   "  [v] - be verbose about actions taken\n"
103 );
104
105 // This enumeration delineates the kinds of operations on an archive
106 // that are permitted.
107 enum ArchiveOperation {
108   Print,            ///< Print the contents of the archive
109   Delete,           ///< Delete the specified members
110   Move,             ///< Move members to end or as given by {a,b,i} modifiers
111   QuickAppend,      ///< Quickly append to end of archive
112   ReplaceOrInsert,  ///< Replace or Insert members
113   DisplayTable,     ///< Display the table of contents
114   Extract,          ///< Extract files back to file system
115   CreateSymTab      ///< Create a symbol table in an existing archive
116 };
117
118 // Modifiers to follow operation to vary behavior
119 static bool AddAfter = false;      ///< 'a' modifier
120 static bool AddBefore = false;     ///< 'b' modifier
121 static bool Create = false;        ///< 'c' modifier
122 static bool OriginalDates = false; ///< 'o' modifier
123 static bool OnlyUpdate = false;    ///< 'u' modifier
124 static bool Verbose = false;       ///< 'v' modifier
125 static bool Symtab = true;         ///< 's' modifier
126
127 // Relative Positional Argument (for insert/move). This variable holds
128 // the name of the archive member to which the 'a', 'b' or 'i' modifier
129 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
130 // one variable.
131 static std::string RelPos;
132
133 // This variable holds the name of the archive file as given on the
134 // command line.
135 static std::string ArchiveName;
136
137 // This variable holds the list of member files to proecess, as given
138 // on the command line.
139 static std::vector<std::string> Members;
140
141 // show_help - Show the error message, the help message and exit.
142 LLVM_ATTRIBUTE_NORETURN static void
143 show_help(const std::string &msg) {
144   errs() << ToolName << ": " << msg << "\n\n";
145   cl::PrintHelpMessage();
146   std::exit(1);
147 }
148
149 // getRelPos - Extract the member filename from the command line for
150 // the [relpos] argument associated with a, b, and i modifiers
151 static void getRelPos() {
152   if(RestOfArgs.size() == 0)
153     show_help("Expected [relpos] for a, b, or i modifier");
154   RelPos = RestOfArgs[0];
155   RestOfArgs.erase(RestOfArgs.begin());
156 }
157
158 static void getOptions() {
159   if(RestOfArgs.size() == 0)
160     show_help("Expected options");
161   Options = RestOfArgs[0];
162   RestOfArgs.erase(RestOfArgs.begin());
163 }
164
165 // getArchive - Get the archive file name from the command line
166 static void getArchive() {
167   if(RestOfArgs.size() == 0)
168     show_help("An archive name must be specified");
169   ArchiveName = RestOfArgs[0];
170   RestOfArgs.erase(RestOfArgs.begin());
171 }
172
173 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
174 // This is just for clarity.
175 static void getMembers() {
176   if(RestOfArgs.size() > 0)
177     Members = std::vector<std::string>(RestOfArgs);
178 }
179
180 namespace {
181 enum class MRICommand { AddMod, Create, Save, End, Invalid };
182 }
183
184 static ArchiveOperation parseMRIScript() {
185   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
186   failIfError(Buf.getError());
187   const MemoryBuffer &Ref = *Buf.get();
188   bool Saved = false;
189
190   for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
191     StringRef Line = *I;
192     StringRef CommandStr, Rest;
193     std::tie(CommandStr, Rest) = Line.split(' ');
194     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
195                        .Case("addmod", MRICommand::AddMod)
196                        .Case("create", MRICommand::Create)
197                        .Case("save", MRICommand::Save)
198                        .Case("end", MRICommand::End)
199                        .Default(MRICommand::Invalid);
200
201     switch (Command) {
202     case MRICommand::AddMod:
203       Members.push_back(Rest);
204       break;
205     case MRICommand::Create:
206       Create = true;
207       if (!ArchiveName.empty())
208         fail("Editing multiple archives not supported");
209       if (Saved)
210         fail("File already saved");
211       ArchiveName = Rest;
212       break;
213     case MRICommand::Save:
214       Saved = true;
215       break;
216     case MRICommand::End:
217       break;
218     case MRICommand::Invalid:
219       fail("Unknown command: " + CommandStr);
220     }
221   }
222
223   // Nothing to do if not saved.
224   if (!Saved)
225     exit(0);
226   return ReplaceOrInsert;
227 }
228
229 // parseCommandLine - Parse the command line options as presented and return the
230 // operation specified. Process all modifiers and check to make sure that
231 // constraints on modifier/operation pairs have not been violated.
232 static ArchiveOperation parseCommandLine() {
233   if (MRI) {
234     if (!RestOfArgs.empty())
235       fail("Cannot mix -M and other options");
236     return parseMRIScript();
237   }
238
239   getOptions();
240
241   // Keep track of number of operations. We can only specify one
242   // per execution.
243   unsigned NumOperations = 0;
244
245   // Keep track of the number of positional modifiers (a,b,i). Only
246   // one can be specified.
247   unsigned NumPositional = 0;
248
249   // Keep track of which operation was requested
250   ArchiveOperation Operation;
251
252   bool MaybeJustCreateSymTab = false;
253
254   for(unsigned i=0; i<Options.size(); ++i) {
255     switch(Options[i]) {
256     case 'd': ++NumOperations; Operation = Delete; break;
257     case 'm': ++NumOperations; Operation = Move ; break;
258     case 'p': ++NumOperations; Operation = Print; break;
259     case 'q': ++NumOperations; Operation = QuickAppend; break;
260     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
261     case 't': ++NumOperations; Operation = DisplayTable; break;
262     case 'x': ++NumOperations; Operation = Extract; break;
263     case 'c': Create = true; break;
264     case 'l': /* accepted but unused */ break;
265     case 'o': OriginalDates = true; break;
266     case 's':
267       Symtab = true;
268       MaybeJustCreateSymTab = true;
269       break;
270     case 'S':
271       Symtab = false;
272       break;
273     case 'u': OnlyUpdate = true; break;
274     case 'v': Verbose = true; break;
275     case 'a':
276       getRelPos();
277       AddAfter = true;
278       NumPositional++;
279       break;
280     case 'b':
281       getRelPos();
282       AddBefore = true;
283       NumPositional++;
284       break;
285     case 'i':
286       getRelPos();
287       AddBefore = true;
288       NumPositional++;
289       break;
290     default:
291       cl::PrintHelpMessage();
292     }
293   }
294
295   // At this point, the next thing on the command line must be
296   // the archive name.
297   getArchive();
298
299   // Everything on the command line at this point is a member.
300   getMembers();
301
302  if (NumOperations == 0 && MaybeJustCreateSymTab) {
303     NumOperations = 1;
304     Operation = CreateSymTab;
305     if (!Members.empty())
306       show_help("The s operation takes only an archive as argument");
307   }
308
309   // Perform various checks on the operation/modifier specification
310   // to make sure we are dealing with a legal request.
311   if (NumOperations == 0)
312     show_help("You must specify at least one of the operations");
313   if (NumOperations > 1)
314     show_help("Only one operation may be specified");
315   if (NumPositional > 1)
316     show_help("You may only specify one of a, b, and i modifiers");
317   if (AddAfter || AddBefore) {
318     if (Operation != Move && Operation != ReplaceOrInsert)
319       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
320             "the 'm' or 'r' operations");
321   }
322   if (OriginalDates && Operation != Extract)
323     show_help("The 'o' modifier is only applicable to the 'x' operation");
324   if (OnlyUpdate && Operation != ReplaceOrInsert)
325     show_help("The 'u' modifier is only applicable to the 'r' operation");
326
327   // Return the parsed operation to the caller
328   return Operation;
329 }
330
331 // Implements the 'p' operation. This function traverses the archive
332 // looking for members that match the path list.
333 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
334   if (Verbose)
335     outs() << "Printing " << Name << "\n";
336
337   StringRef Data = I->getBuffer();
338   outs().write(Data.data(), Data.size());
339 }
340
341 // putMode - utility function for printing out the file mode when the 't'
342 // operation is in verbose mode.
343 static void printMode(unsigned mode) {
344   if (mode & 004)
345     outs() << "r";
346   else
347     outs() << "-";
348   if (mode & 002)
349     outs() << "w";
350   else
351     outs() << "-";
352   if (mode & 001)
353     outs() << "x";
354   else
355     outs() << "-";
356 }
357
358 // Implement the 't' operation. This function prints out just
359 // the file names of each of the members. However, if verbose mode is requested
360 // ('v' modifier) then the file type, permission mode, user, group, size, and
361 // modification time are also printed.
362 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
363   if (Verbose) {
364     sys::fs::perms Mode = I->getAccessMode();
365     printMode((Mode >> 6) & 007);
366     printMode((Mode >> 3) & 007);
367     printMode(Mode & 007);
368     outs() << ' ' << I->getUID();
369     outs() << '/' << I->getGID();
370     outs() << ' ' << format("%6llu", I->getSize());
371     outs() << ' ' << I->getLastModified().str();
372     outs() << ' ';
373   }
374   outs() << Name << "\n";
375 }
376
377 // Implement the 'x' operation. This function extracts files back to the file
378 // system.
379 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
380   // Retain the original mode.
381   sys::fs::perms Mode = I->getAccessMode();
382   SmallString<128> Storage = Name;
383
384   int FD;
385   failIfError(
386       sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
387       Storage.c_str());
388
389   {
390     raw_fd_ostream file(FD, false);
391
392     // Get the data and its length
393     StringRef Data = I->getBuffer();
394
395     // Write the data.
396     file.write(Data.data(), Data.size());
397   }
398
399   // If we're supposed to retain the original modification times, etc. do so
400   // now.
401   if (OriginalDates)
402     failIfError(
403         sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
404
405   if (close(FD))
406     fail("Could not close the file");
407 }
408
409 static bool shouldCreateArchive(ArchiveOperation Op) {
410   switch (Op) {
411   case Print:
412   case Delete:
413   case Move:
414   case DisplayTable:
415   case Extract:
416   case CreateSymTab:
417     return false;
418
419   case QuickAppend:
420   case ReplaceOrInsert:
421     return true;
422   }
423
424   llvm_unreachable("Missing entry in covered switch.");
425 }
426
427 static void performReadOperation(ArchiveOperation Operation,
428                                  object::Archive *OldArchive) {
429   for (object::Archive::child_iterator I = OldArchive->child_begin(),
430                                        E = OldArchive->child_end();
431        I != E; ++I) {
432     ErrorOr<StringRef> NameOrErr = I->getName();
433     failIfError(NameOrErr.getError());
434     StringRef Name = NameOrErr.get();
435
436     if (!Members.empty() &&
437         std::find(Members.begin(), Members.end(), Name) == Members.end())
438       continue;
439
440     switch (Operation) {
441     default:
442       llvm_unreachable("Not a read operation");
443     case Print:
444       doPrint(Name, I);
445       break;
446     case DisplayTable:
447       doDisplayTable(Name, I);
448       break;
449     case Extract:
450       doExtract(Name, I);
451       break;
452     }
453   }
454 }
455
456 namespace {
457 class NewArchiveIterator {
458   bool IsNewMember;
459   StringRef Name;
460
461   object::Archive::child_iterator OldI;
462
463   std::string NewFilename;
464   mutable int NewFD;
465   mutable sys::fs::file_status NewStatus;
466
467 public:
468   NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
469   NewArchiveIterator(std::string *I, StringRef Name);
470   NewArchiveIterator();
471   bool isNewMember() const;
472   StringRef getName() const;
473
474   object::Archive::child_iterator getOld() const;
475
476   const char *getNew() const;
477   int getFD() const;
478   const sys::fs::file_status &getStatus() const;
479 };
480 }
481
482 NewArchiveIterator::NewArchiveIterator() {}
483
484 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
485                                        StringRef Name)
486     : IsNewMember(false), Name(Name), OldI(I) {}
487
488 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
489     : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
490
491 StringRef NewArchiveIterator::getName() const { return Name; }
492
493 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
494
495 object::Archive::child_iterator NewArchiveIterator::getOld() const {
496   assert(!IsNewMember);
497   return OldI;
498 }
499
500 const char *NewArchiveIterator::getNew() const {
501   assert(IsNewMember);
502   return NewFilename.c_str();
503 }
504
505 int NewArchiveIterator::getFD() const {
506   assert(IsNewMember);
507   if (NewFD != -1)
508     return NewFD;
509   failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
510   assert(NewFD != -1);
511
512   failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
513
514   // Opening a directory doesn't make sense. Let it fail.
515   // Linux cannot open directories with open(2), although
516   // cygwin and *bsd can.
517   if (NewStatus.type() == sys::fs::file_type::directory_file)
518     failIfError(make_error_code(errc::is_a_directory), NewFilename);
519
520   return NewFD;
521 }
522
523 const sys::fs::file_status &NewArchiveIterator::getStatus() const {
524   assert(IsNewMember);
525   assert(NewFD != -1 && "Must call getFD first");
526   return NewStatus;
527 }
528
529 template <typename T>
530 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
531                int Pos = -1) {
532   NewArchiveIterator NI(I, Name);
533   if (Pos == -1)
534     Members.push_back(NI);
535   else
536     Members[Pos] = NI;
537 }
538
539 enum InsertAction {
540   IA_AddOldMember,
541   IA_AddNewMeber,
542   IA_Delete,
543   IA_MoveOldMember,
544   IA_MoveNewMember
545 };
546
547 static InsertAction
548 computeInsertAction(ArchiveOperation Operation,
549                     object::Archive::child_iterator I, StringRef Name,
550                     std::vector<std::string>::iterator &Pos) {
551   if (Operation == QuickAppend || Members.empty())
552     return IA_AddOldMember;
553
554   std::vector<std::string>::iterator MI = std::find_if(
555       Members.begin(), Members.end(),
556       [Name](StringRef Path) { return Name == sys::path::filename(Path); });
557
558   if (MI == Members.end())
559     return IA_AddOldMember;
560
561   Pos = MI;
562
563   if (Operation == Delete)
564     return IA_Delete;
565
566   if (Operation == Move)
567     return IA_MoveOldMember;
568
569   if (Operation == ReplaceOrInsert) {
570     StringRef PosName = sys::path::filename(RelPos);
571     if (!OnlyUpdate) {
572       if (PosName.empty())
573         return IA_AddNewMeber;
574       return IA_MoveNewMember;
575     }
576
577     // We could try to optimize this to a fstat, but it is not a common
578     // operation.
579     sys::fs::file_status Status;
580     failIfError(sys::fs::status(*MI, Status), *MI);
581     if (Status.getLastModificationTime() < I->getLastModified()) {
582       if (PosName.empty())
583         return IA_AddOldMember;
584       return IA_MoveOldMember;
585     }
586
587     if (PosName.empty())
588       return IA_AddNewMeber;
589     return IA_MoveNewMember;
590   }
591   llvm_unreachable("No such operation");
592 }
593
594 // We have to walk this twice and computing it is not trivial, so creating an
595 // explicit std::vector is actually fairly efficient.
596 static std::vector<NewArchiveIterator>
597 computeNewArchiveMembers(ArchiveOperation Operation,
598                          object::Archive *OldArchive) {
599   std::vector<NewArchiveIterator> Ret;
600   std::vector<NewArchiveIterator> Moved;
601   int InsertPos = -1;
602   StringRef PosName = sys::path::filename(RelPos);
603   if (OldArchive) {
604     for (object::Archive::child_iterator I = OldArchive->child_begin(),
605                                          E = OldArchive->child_end();
606          I != E; ++I) {
607       int Pos = Ret.size();
608       ErrorOr<StringRef> NameOrErr = I->getName();
609       failIfError(NameOrErr.getError());
610       StringRef Name = NameOrErr.get();
611       if (Name == PosName) {
612         assert(AddAfter || AddBefore);
613         if (AddBefore)
614           InsertPos = Pos;
615         else
616           InsertPos = Pos + 1;
617       }
618
619       std::vector<std::string>::iterator MemberI = Members.end();
620       InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
621       switch (Action) {
622       case IA_AddOldMember:
623         addMember(Ret, I, Name);
624         break;
625       case IA_AddNewMeber:
626         addMember(Ret, &*MemberI, Name);
627         break;
628       case IA_Delete:
629         break;
630       case IA_MoveOldMember:
631         addMember(Moved, I, Name);
632         break;
633       case IA_MoveNewMember:
634         addMember(Moved, &*MemberI, Name);
635         break;
636       }
637       if (MemberI != Members.end())
638         Members.erase(MemberI);
639     }
640   }
641
642   if (Operation == Delete)
643     return Ret;
644
645   if (!RelPos.empty() && InsertPos == -1)
646     fail("Insertion point not found");
647
648   if (RelPos.empty())
649     InsertPos = Ret.size();
650
651   assert(unsigned(InsertPos) <= Ret.size());
652   Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
653
654   Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
655   int Pos = InsertPos;
656   for (std::vector<std::string>::iterator I = Members.begin(),
657          E = Members.end();
658        I != E; ++I, ++Pos) {
659     StringRef Name = sys::path::filename(*I);
660     addMember(Ret, &*I, Name, Pos);
661   }
662
663   return Ret;
664 }
665
666 template <typename T>
667 static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
668                                   bool MayTruncate = false) {
669   uint64_t OldPos = OS.tell();
670   OS << Data;
671   unsigned SizeSoFar = OS.tell() - OldPos;
672   if (Size > SizeSoFar) {
673     unsigned Remaining = Size - SizeSoFar;
674     for (unsigned I = 0; I < Remaining; ++I)
675       OS << ' ';
676   } else if (Size < SizeSoFar) {
677     assert(MayTruncate && "Data doesn't fit in Size");
678     // Some of the data this is used for (like UID) can be larger than the
679     // space available in the archive format. Truncate in that case.
680     OS.seek(OldPos + Size);
681   }
682 }
683
684 static void print32BE(raw_fd_ostream &Out, unsigned Val) {
685   for (int I = 3; I >= 0; --I) {
686     char V = (Val >> (8 * I)) & 0xff;
687     Out << V;
688   }
689 }
690
691 static void printRestOfMemberHeader(raw_fd_ostream &Out,
692                                     const sys::TimeValue &ModTime, unsigned UID,
693                                     unsigned GID, unsigned Perms,
694                                     unsigned Size) {
695   printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
696   printWithSpacePadding(Out, UID, 6, true);
697   printWithSpacePadding(Out, GID, 6, true);
698   printWithSpacePadding(Out, format("%o", Perms), 8);
699   printWithSpacePadding(Out, Size, 10);
700   Out << "`\n";
701 }
702
703 static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
704                               const sys::TimeValue &ModTime, unsigned UID,
705                               unsigned GID, unsigned Perms, unsigned Size) {
706   printWithSpacePadding(Out, Twine(Name) + "/", 16);
707   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
708 }
709
710 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
711                               const sys::TimeValue &ModTime, unsigned UID,
712                               unsigned GID, unsigned Perms, unsigned Size) {
713   Out << '/';
714   printWithSpacePadding(Out, NameOffset, 15);
715   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
716 }
717
718 static void writeStringTable(raw_fd_ostream &Out,
719                              ArrayRef<NewArchiveIterator> Members,
720                              std::vector<unsigned> &StringMapIndexes) {
721   unsigned StartOffset = 0;
722   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
723                                               E = Members.end();
724        I != E; ++I) {
725     StringRef Name = I->getName();
726     if (Name.size() < 16)
727       continue;
728     if (StartOffset == 0) {
729       printWithSpacePadding(Out, "//", 58);
730       Out << "`\n";
731       StartOffset = Out.tell();
732     }
733     StringMapIndexes.push_back(Out.tell() - StartOffset);
734     Out << Name << "/\n";
735   }
736   if (StartOffset == 0)
737     return;
738   if (Out.tell() % 2)
739     Out << '\n';
740   int Pos = Out.tell();
741   Out.seek(StartOffset - 12);
742   printWithSpacePadding(Out, Pos - StartOffset, 10);
743   Out.seek(Pos);
744 }
745
746 static void
747 writeSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
748                  ArrayRef<MemoryBufferRef> Buffers,
749                  std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
750   unsigned StartOffset = 0;
751   unsigned MemberNum = 0;
752   std::string NameBuf;
753   raw_string_ostream NameOS(NameBuf);
754   unsigned NumSyms = 0;
755   LLVMContext &Context = getGlobalContext();
756   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
757                                               E = Members.end();
758        I != E; ++I, ++MemberNum) {
759     MemoryBufferRef MemberBuffer = Buffers[MemberNum];
760     ErrorOr<std::unique_ptr<object::SymbolicFile>> ObjOrErr =
761         object::SymbolicFile::createSymbolicFile(
762             MemberBuffer, sys::fs::file_magic::unknown, &Context);
763     if (!ObjOrErr)
764       continue;  // FIXME: check only for "not an object file" errors.
765     object::SymbolicFile &Obj = *ObjOrErr.get();
766
767     if (!StartOffset) {
768       printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
769       StartOffset = Out.tell();
770       print32BE(Out, 0);
771     }
772
773     for (const object::BasicSymbolRef &S : Obj.symbols()) {
774       uint32_t Symflags = S.getFlags();
775       if (Symflags & object::SymbolRef::SF_FormatSpecific)
776         continue;
777       if (!(Symflags & object::SymbolRef::SF_Global))
778         continue;
779       if (Symflags & object::SymbolRef::SF_Undefined)
780         continue;
781       failIfError(S.printName(NameOS));
782       NameOS << '\0';
783       ++NumSyms;
784       MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
785       print32BE(Out, 0);
786     }
787   }
788   Out << NameOS.str();
789
790   if (StartOffset == 0)
791     return;
792
793   if (Out.tell() % 2)
794     Out << '\0';
795
796   unsigned Pos = Out.tell();
797   Out.seek(StartOffset - 12);
798   printWithSpacePadding(Out, Pos - StartOffset, 10);
799   Out.seek(StartOffset);
800   print32BE(Out, NumSyms);
801   Out.seek(Pos);
802 }
803
804 static void performWriteOperation(ArchiveOperation Operation,
805                                   object::Archive *OldArchive) {
806   SmallString<128> TmpArchive;
807   failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
808                                         TmpArchiveFD, TmpArchive));
809
810   TemporaryOutput = TmpArchive.c_str();
811   tool_output_file Output(TemporaryOutput, TmpArchiveFD);
812   raw_fd_ostream &Out = Output.os();
813   Out << "!<arch>\n";
814
815   std::vector<NewArchiveIterator> NewMembers =
816       computeNewArchiveMembers(Operation, OldArchive);
817
818   std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
819
820   std::vector<std::unique_ptr<MemoryBuffer>> Buffers;
821   std::vector<MemoryBufferRef> Members;
822
823   for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
824     NewArchiveIterator &Member = NewMembers[I];
825     MemoryBufferRef MemberRef;
826
827     if (Member.isNewMember()) {
828       const char *Filename = Member.getNew();
829       int FD = Member.getFD();
830       const sys::fs::file_status &Status = Member.getStatus();
831       ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
832           MemoryBuffer::getOpenFile(FD, Filename, Status.getSize(), false);
833       failIfError(MemberBufferOrErr.getError(), Filename);
834       Buffers.push_back(std::move(MemberBufferOrErr.get()));
835       MemberRef = Buffers.back()->getMemBufferRef();
836     } else {
837       object::Archive::child_iterator OldMember = Member.getOld();
838       ErrorOr<MemoryBufferRef> MemberBufferOrErr =
839           OldMember->getMemoryBufferRef();
840       failIfError(MemberBufferOrErr.getError());
841       MemberRef = MemberBufferOrErr.get();
842     }
843     Members.push_back(MemberRef);
844   }
845
846   if (Symtab) {
847     writeSymbolTable(Out, NewMembers, Members, MemberOffsetRefs);
848   }
849
850   std::vector<unsigned> StringMapIndexes;
851   writeStringTable(Out, NewMembers, StringMapIndexes);
852
853   std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
854       MemberOffsetRefs.begin();
855
856   unsigned MemberNum = 0;
857   unsigned LongNameMemberNum = 0;
858   for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
859                                                  E = NewMembers.end();
860        I != E; ++I, ++MemberNum) {
861
862     unsigned Pos = Out.tell();
863     while (MemberRefsI != MemberOffsetRefs.end() &&
864            MemberRefsI->second == MemberNum) {
865       Out.seek(MemberRefsI->first);
866       print32BE(Out, Pos);
867       ++MemberRefsI;
868     }
869     Out.seek(Pos);
870
871     MemoryBufferRef File = Members[MemberNum];
872     if (I->isNewMember()) {
873       const char *FileName = I->getNew();
874       const sys::fs::file_status &Status = I->getStatus();
875
876       StringRef Name = sys::path::filename(FileName);
877       if (Name.size() < 16)
878         printMemberHeader(Out, Name, Status.getLastModificationTime(),
879                           Status.getUser(), Status.getGroup(),
880                           Status.permissions(), Status.getSize());
881       else
882         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
883                           Status.getLastModificationTime(), Status.getUser(),
884                           Status.getGroup(), Status.permissions(),
885                           Status.getSize());
886     } else {
887       object::Archive::child_iterator OldMember = I->getOld();
888       StringRef Name = I->getName();
889
890       if (Name.size() < 16)
891         printMemberHeader(Out, Name, OldMember->getLastModified(),
892                           OldMember->getUID(), OldMember->getGID(),
893                           OldMember->getAccessMode(), OldMember->getSize());
894       else
895         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
896                           OldMember->getLastModified(), OldMember->getUID(),
897                           OldMember->getGID(), OldMember->getAccessMode(),
898                           OldMember->getSize());
899     }
900
901     Out << File.getBuffer();
902
903     if (Out.tell() % 2)
904       Out << '\n';
905   }
906
907   Output.keep();
908   Out.close();
909   sys::fs::rename(TemporaryOutput, ArchiveName);
910   TemporaryOutput = nullptr;
911 }
912
913 static void createSymbolTable(object::Archive *OldArchive) {
914   // When an archive is created or modified, if the s option is given, the
915   // resulting archive will have a current symbol table. If the S option
916   // is given, it will have no symbol table.
917   // In summary, we only need to update the symbol table if we have none.
918   // This is actually very common because of broken build systems that think
919   // they have to run ranlib.
920   if (OldArchive->hasSymbolTable())
921     return;
922
923   performWriteOperation(CreateSymTab, OldArchive);
924 }
925
926 static void performOperation(ArchiveOperation Operation,
927                              object::Archive *OldArchive) {
928   switch (Operation) {
929   case Print:
930   case DisplayTable:
931   case Extract:
932     performReadOperation(Operation, OldArchive);
933     return;
934
935   case Delete:
936   case Move:
937   case QuickAppend:
938   case ReplaceOrInsert:
939     performWriteOperation(Operation, OldArchive);
940     return;
941   case CreateSymTab:
942     createSymbolTable(OldArchive);
943     return;
944   }
945   llvm_unreachable("Unknown operation.");
946 }
947
948 static int ar_main(char **argv);
949 static int ranlib_main();
950
951 // main - main program for llvm-ar .. see comments in the code
952 int main(int argc, char **argv) {
953   ToolName = argv[0];
954   // Print a stack trace if we signal out.
955   sys::PrintStackTraceOnErrorSignal();
956   PrettyStackTraceProgram X(argc, argv);
957   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
958
959   // Have the command line options parsed and handle things
960   // like --help and --version.
961   cl::ParseCommandLineOptions(argc, argv,
962     "LLVM Archiver (llvm-ar)\n\n"
963     "  This program archives bitcode files into single libraries\n"
964   );
965
966   llvm::InitializeAllTargetInfos();
967   llvm::InitializeAllTargetMCs();
968   llvm::InitializeAllAsmParsers();
969
970   StringRef Stem = sys::path::stem(ToolName);
971   if (Stem.find("ar") != StringRef::npos)
972     return ar_main(argv);
973   if (Stem.find("ranlib") != StringRef::npos)
974     return ranlib_main();
975   fail("Not ranlib or ar!");
976 }
977
978 static int performOperation(ArchiveOperation Operation);
979
980 int ranlib_main() {
981   if (RestOfArgs.size() != 1)
982     fail(ToolName + "takes just one archive as argument");
983   ArchiveName = RestOfArgs[0];
984   return performOperation(CreateSymTab);
985 }
986
987 int ar_main(char **argv) {
988   // Do our own parsing of the command line because the CommandLine utility
989   // can't handle the grouped positional parameters without a dash.
990   ArchiveOperation Operation = parseCommandLine();
991   return performOperation(Operation);
992 }
993
994 static int performOperation(ArchiveOperation Operation) {
995   // Create or open the archive object.
996   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
997       MemoryBuffer::getFile(ArchiveName, -1, false);
998   std::error_code EC = Buf.getError();
999   if (EC && EC != errc::no_such_file_or_directory) {
1000     errs() << ToolName << ": error opening '" << ArchiveName
1001            << "': " << EC.message() << "!\n";
1002     return 1;
1003   }
1004
1005   if (!EC) {
1006     object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
1007
1008     if (EC) {
1009       errs() << ToolName << ": error loading '" << ArchiveName
1010              << "': " << EC.message() << "!\n";
1011       return 1;
1012     }
1013     performOperation(Operation, &Archive);
1014     return 0;
1015   }
1016
1017   assert(EC == errc::no_such_file_or_directory);
1018
1019   if (!shouldCreateArchive(Operation)) {
1020     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
1021   } else {
1022     if (!Create) {
1023       // Produce a warning if we should and we're creating the archive
1024       errs() << ToolName << ": creating " << ArchiveName << "\n";
1025     }
1026   }
1027
1028   performOperation(Operation, nullptr);
1029   return 0;
1030 }