Simplify memory management with std::unique_ptr.
[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/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"
29 #include <algorithm>
30 #include <cstdlib>
31 #include <memory>
32
33 #if !defined(_MSC_VER) && !defined(__MINGW32__)
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 #endif
38
39 using namespace llvm;
40
41 // The name this program was invoked as.
42 static StringRef ToolName;
43
44 static const char *TemporaryOutput;
45 static int TmpArchiveFD = -1;
46
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)
51     close(TmpArchiveFD);
52   if (TemporaryOutput)
53     sys::fs::remove(TemporaryOutput);
54   exit(1);
55 }
56
57 static void failIfError(std::error_code EC, Twine Context = "") {
58   if (!EC)
59     return;
60
61   std::string ContextStr = Context.str();
62   if (ContextStr == "")
63     fail(EC.message());
64   fail(Context + ": " + EC.message());
65 }
66
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]..."));
71
72 std::string Options;
73
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(
78   "\nOPERATIONS:\n"
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"
98 );
99
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
111 };
112
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
121
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
125 // one variable.
126 static std::string RelPos;
127
128 // This variable holds the name of the archive file as given on the
129 // command line.
130 static std::string ArchiveName;
131
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;
135
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();
141   std::exit(1);
142 }
143
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());
151 }
152
153 static void getOptions() {
154   if(RestOfArgs.size() == 0)
155     show_help("Expected options");
156   Options = RestOfArgs[0];
157   RestOfArgs.erase(RestOfArgs.begin());
158 }
159
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());
166 }
167
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);
173 }
174
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() {
179   getOptions();
180
181   // Keep track of number of operations. We can only specify one
182   // per execution.
183   unsigned NumOperations = 0;
184
185   // Keep track of the number of positional modifiers (a,b,i). Only
186   // one can be specified.
187   unsigned NumPositional = 0;
188
189   // Keep track of which operation was requested
190   ArchiveOperation Operation;
191
192   bool MaybeJustCreateSymTab = false;
193
194   for(unsigned i=0; i<Options.size(); ++i) {
195     switch(Options[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;
206     case 's':
207       Symtab = true;
208       MaybeJustCreateSymTab = true;
209       break;
210     case 'S':
211       Symtab = false;
212       break;
213     case 'u': OnlyUpdate = true; break;
214     case 'v': Verbose = true; break;
215     case 'a':
216       getRelPos();
217       AddAfter = true;
218       NumPositional++;
219       break;
220     case 'b':
221       getRelPos();
222       AddBefore = true;
223       NumPositional++;
224       break;
225     case 'i':
226       getRelPos();
227       AddBefore = true;
228       NumPositional++;
229       break;
230     default:
231       cl::PrintHelpMessage();
232     }
233   }
234
235   // At this point, the next thing on the command line must be
236   // the archive name.
237   getArchive();
238
239   // Everything on the command line at this point is a member.
240   getMembers();
241
242  if (NumOperations == 0 && MaybeJustCreateSymTab) {
243     NumOperations = 1;
244     Operation = CreateSymTab;
245     if (!Members.empty())
246       show_help("The s operation takes only an archive as argument");
247   }
248
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");
261   }
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");
266
267   // Return the parsed operation to the caller
268   return Operation;
269 }
270
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) {
274   if (Verbose)
275     outs() << "Printing " << Name << "\n";
276
277   StringRef Data = I->getBuffer();
278   outs().write(Data.data(), Data.size());
279 }
280
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) {
284   if (mode & 004)
285     outs() << "r";
286   else
287     outs() << "-";
288   if (mode & 002)
289     outs() << "w";
290   else
291     outs() << "-";
292   if (mode & 001)
293     outs() << "x";
294   else
295     outs() << "-";
296 }
297
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) {
303   if (Verbose) {
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();
312     outs() << ' ';
313   }
314   outs() << Name << "\n";
315 }
316
317 // Implement the 'x' operation. This function extracts files back to the file
318 // system.
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;
323
324   int FD;
325   failIfError(
326       sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
327       Storage.c_str());
328
329   {
330     raw_fd_ostream file(FD, false);
331
332     // Get the data and its length
333     StringRef Data = I->getBuffer();
334
335     // Write the data.
336     file.write(Data.data(), Data.size());
337   }
338
339   // If we're supposed to retain the original modification times, etc. do so
340   // now.
341   if (OriginalDates)
342     failIfError(
343         sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
344
345   if (close(FD))
346     fail("Could not close the file");
347 }
348
349 static bool shouldCreateArchive(ArchiveOperation Op) {
350   switch (Op) {
351   case Print:
352   case Delete:
353   case Move:
354   case DisplayTable:
355   case Extract:
356   case CreateSymTab:
357     return false;
358
359   case QuickAppend:
360   case ReplaceOrInsert:
361     return true;
362   }
363
364   llvm_unreachable("Missing entry in covered switch.");
365 }
366
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();
371        I != E; ++I) {
372     ErrorOr<StringRef> NameOrErr = I->getName();
373     failIfError(NameOrErr.getError());
374     StringRef Name = NameOrErr.get();
375
376     if (!Members.empty() &&
377         std::find(Members.begin(), Members.end(), Name) == Members.end())
378       continue;
379
380     switch (Operation) {
381     default:
382       llvm_unreachable("Not a read operation");
383     case Print:
384       doPrint(Name, I);
385       break;
386     case DisplayTable:
387       doDisplayTable(Name, I);
388       break;
389     case Extract:
390       doExtract(Name, I);
391       break;
392     }
393   }
394 }
395
396 namespace {
397 class NewArchiveIterator {
398   bool IsNewMember;
399   StringRef Name;
400
401   object::Archive::child_iterator OldI;
402
403   std::string NewFilename;
404   mutable int NewFD;
405   mutable sys::fs::file_status NewStatus;
406
407 public:
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;
413
414   object::Archive::child_iterator getOld() const;
415
416   const char *getNew() const;
417   int getFD() const;
418   const sys::fs::file_status &getStatus() const;
419 };
420 }
421
422 NewArchiveIterator::NewArchiveIterator() {}
423
424 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
425                                        StringRef Name)
426     : IsNewMember(false), Name(Name), OldI(I) {}
427
428 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
429     : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
430
431 StringRef NewArchiveIterator::getName() const { return Name; }
432
433 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
434
435 object::Archive::child_iterator NewArchiveIterator::getOld() const {
436   assert(!IsNewMember);
437   return OldI;
438 }
439
440 const char *NewArchiveIterator::getNew() const {
441   assert(IsNewMember);
442   return NewFilename.c_str();
443 }
444
445 int NewArchiveIterator::getFD() const {
446   assert(IsNewMember);
447   if (NewFD != -1)
448     return NewFD;
449   failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
450   assert(NewFD != -1);
451
452   failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
453
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);
459
460   return NewFD;
461 }
462
463 const sys::fs::file_status &NewArchiveIterator::getStatus() const {
464   assert(IsNewMember);
465   assert(NewFD != -1 && "Must call getFD first");
466   return NewStatus;
467 }
468
469 template <typename T>
470 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
471                int Pos = -1) {
472   NewArchiveIterator NI(I, Name);
473   if (Pos == -1)
474     Members.push_back(NI);
475   else
476     Members[Pos] = NI;
477 }
478
479 enum InsertAction {
480   IA_AddOldMember,
481   IA_AddNewMeber,
482   IA_Delete,
483   IA_MoveOldMember,
484   IA_MoveNewMember
485 };
486
487 static InsertAction
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;
493
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); });
497
498   if (MI == Members.end())
499     return IA_AddOldMember;
500
501   Pos = MI;
502
503   if (Operation == Delete)
504     return IA_Delete;
505
506   if (Operation == Move)
507     return IA_MoveOldMember;
508
509   if (Operation == ReplaceOrInsert) {
510     StringRef PosName = sys::path::filename(RelPos);
511     if (!OnlyUpdate) {
512       if (PosName.empty())
513         return IA_AddNewMeber;
514       return IA_MoveNewMember;
515     }
516
517     // We could try to optimize this to a fstat, but it is not a common
518     // operation.
519     sys::fs::file_status Status;
520     failIfError(sys::fs::status(*MI, Status), *MI);
521     if (Status.getLastModificationTime() < I->getLastModified()) {
522       if (PosName.empty())
523         return IA_AddOldMember;
524       return IA_MoveOldMember;
525     }
526
527     if (PosName.empty())
528       return IA_AddNewMeber;
529     return IA_MoveNewMember;
530   }
531   llvm_unreachable("No such operation");
532 }
533
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;
541   int InsertPos = -1;
542   StringRef PosName = sys::path::filename(RelPos);
543   if (OldArchive) {
544     for (object::Archive::child_iterator I = OldArchive->child_begin(),
545                                          E = OldArchive->child_end();
546          I != E; ++I) {
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);
553         if (AddBefore)
554           InsertPos = Pos;
555         else
556           InsertPos = Pos + 1;
557       }
558
559       std::vector<std::string>::iterator MemberI = Members.end();
560       InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
561       switch (Action) {
562       case IA_AddOldMember:
563         addMember(Ret, I, Name);
564         break;
565       case IA_AddNewMeber:
566         addMember(Ret, &*MemberI, Name);
567         break;
568       case IA_Delete:
569         break;
570       case IA_MoveOldMember:
571         addMember(Moved, I, Name);
572         break;
573       case IA_MoveNewMember:
574         addMember(Moved, &*MemberI, Name);
575         break;
576       }
577       if (MemberI != Members.end())
578         Members.erase(MemberI);
579     }
580   }
581
582   if (Operation == Delete)
583     return Ret;
584
585   if (!RelPos.empty() && InsertPos == -1)
586     fail("Insertion point not found");
587
588   if (RelPos.empty())
589     InsertPos = Ret.size();
590
591   assert(unsigned(InsertPos) <= Ret.size());
592   Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
593
594   Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
595   int Pos = InsertPos;
596   for (std::vector<std::string>::iterator I = Members.begin(),
597          E = Members.end();
598        I != E; ++I, ++Pos) {
599     StringRef Name = sys::path::filename(*I);
600     addMember(Ret, &*I, Name, Pos);
601   }
602
603   return Ret;
604 }
605
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();
610   OS << Data;
611   unsigned SizeSoFar = OS.tell() - OldPos;
612   if (Size > SizeSoFar) {
613     unsigned Remaining = Size - SizeSoFar;
614     for (unsigned I = 0; I < Remaining; ++I)
615       OS << ' ';
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);
621   }
622 }
623
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;
627     Out << V;
628   }
629 }
630
631 static void printRestOfMemberHeader(raw_fd_ostream &Out,
632                                     const sys::TimeValue &ModTime, unsigned UID,
633                                     unsigned GID, unsigned Perms,
634                                     unsigned Size) {
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);
640   Out << "`\n";
641 }
642
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);
648 }
649
650 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
651                               const sys::TimeValue &ModTime, unsigned UID,
652                               unsigned GID, unsigned Perms, unsigned Size) {
653   Out << '/';
654   printWithSpacePadding(Out, NameOffset, 15);
655   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
656 }
657
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(),
663                                               E = Members.end();
664        I != E; ++I) {
665     StringRef Name = I->getName();
666     if (Name.size() < 16)
667       continue;
668     if (StartOffset == 0) {
669       printWithSpacePadding(Out, "//", 58);
670       Out << "`\n";
671       StartOffset = Out.tell();
672     }
673     StringMapIndexes.push_back(Out.tell() - StartOffset);
674     Out << Name << "/\n";
675   }
676   if (StartOffset == 0)
677     return;
678   if (Out.tell() % 2)
679     Out << '\n';
680   int Pos = Out.tell();
681   Out.seek(StartOffset - 12);
682   printWithSpacePadding(Out, Pos - StartOffset, 10);
683   Out.seek(Pos);
684 }
685
686 static void
687 writeSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
688                  ArrayRef<std::unique_ptr<MemoryBuffer>> Buffers,
689                  std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
690   unsigned StartOffset = 0;
691   unsigned MemberNum = 0;
692   std::string NameBuf;
693   raw_string_ostream NameOS(NameBuf);
694   unsigned NumSyms = 0;
695   LLVMContext &Context = getGlobalContext();
696   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
697                                               E = Members.end();
698        I != E; ++I, ++MemberNum) {
699     MemoryBuffer *MemberBuffer = Buffers[MemberNum].get();
700     ErrorOr<object::SymbolicFile *> ObjOrErr =
701         object::SymbolicFile::createSymbolicFile(
702             MemberBuffer, false, sys::fs::file_magic::unknown, &Context);
703     if (!ObjOrErr)
704       continue;  // FIXME: check only for "not an object file" errors.
705     std::unique_ptr<object::SymbolicFile> Obj(ObjOrErr.get());
706
707     if (!StartOffset) {
708       printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
709       StartOffset = Out.tell();
710       print32BE(Out, 0);
711     }
712
713     for (const object::BasicSymbolRef &S : Obj->symbols()) {
714       uint32_t Symflags = S.getFlags();
715       if (Symflags & object::SymbolRef::SF_FormatSpecific)
716         continue;
717       if (!(Symflags & object::SymbolRef::SF_Global))
718         continue;
719       if (Symflags & object::SymbolRef::SF_Undefined)
720         continue;
721       failIfError(S.printName(NameOS));
722       NameOS << '\0';
723       ++NumSyms;
724       MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
725       print32BE(Out, 0);
726     }
727   }
728   Out << NameOS.str();
729
730   if (StartOffset == 0)
731     return;
732
733   if (Out.tell() % 2)
734     Out << '\0';
735
736   unsigned Pos = Out.tell();
737   Out.seek(StartOffset - 12);
738   printWithSpacePadding(Out, Pos - StartOffset, 10);
739   Out.seek(StartOffset);
740   print32BE(Out, NumSyms);
741   Out.seek(Pos);
742 }
743
744 static void performWriteOperation(ArchiveOperation Operation,
745                                   object::Archive *OldArchive) {
746   SmallString<128> TmpArchive;
747   failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
748                                         TmpArchiveFD, TmpArchive));
749
750   TemporaryOutput = TmpArchive.c_str();
751   tool_output_file Output(TemporaryOutput, TmpArchiveFD);
752   raw_fd_ostream &Out = Output.os();
753   Out << "!<arch>\n";
754
755   std::vector<NewArchiveIterator> NewMembers =
756       computeNewArchiveMembers(Operation, OldArchive);
757
758   std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
759
760   std::vector<std::unique_ptr<MemoryBuffer>> MemberBuffers;
761   MemberBuffers.resize(NewMembers.size());
762
763   for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
764     std::unique_ptr<MemoryBuffer> MemberBuffer;
765     NewArchiveIterator &Member = NewMembers[I];
766
767     if (Member.isNewMember()) {
768       const char *Filename = Member.getNew();
769       int FD = Member.getFD();
770       const sys::fs::file_status &Status = Member.getStatus();
771       failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
772                                             Status.getSize(), false),
773                   Filename);
774
775     } else {
776       object::Archive::child_iterator OldMember = Member.getOld();
777       ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
778           OldMember->getMemoryBuffer();
779       failIfError(MemberBufferOrErr.getError());
780       MemberBuffer = std::move(MemberBufferOrErr.get());
781     }
782     MemberBuffers[I].reset(MemberBuffer.release());
783   }
784
785   if (Symtab) {
786     writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
787   }
788
789   std::vector<unsigned> StringMapIndexes;
790   writeStringTable(Out, NewMembers, StringMapIndexes);
791
792   std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
793       MemberOffsetRefs.begin();
794
795   unsigned MemberNum = 0;
796   unsigned LongNameMemberNum = 0;
797   for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
798                                                  E = NewMembers.end();
799        I != E; ++I, ++MemberNum) {
800
801     unsigned Pos = Out.tell();
802     while (MemberRefsI != MemberOffsetRefs.end() &&
803            MemberRefsI->second == MemberNum) {
804       Out.seek(MemberRefsI->first);
805       print32BE(Out, Pos);
806       ++MemberRefsI;
807     }
808     Out.seek(Pos);
809
810     const MemoryBuffer *File = MemberBuffers[MemberNum].get();
811     if (I->isNewMember()) {
812       const char *FileName = I->getNew();
813       const sys::fs::file_status &Status = I->getStatus();
814
815       StringRef Name = sys::path::filename(FileName);
816       if (Name.size() < 16)
817         printMemberHeader(Out, Name, Status.getLastModificationTime(),
818                           Status.getUser(), Status.getGroup(),
819                           Status.permissions(), Status.getSize());
820       else
821         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
822                           Status.getLastModificationTime(), Status.getUser(),
823                           Status.getGroup(), Status.permissions(),
824                           Status.getSize());
825     } else {
826       object::Archive::child_iterator OldMember = I->getOld();
827       StringRef Name = I->getName();
828
829       if (Name.size() < 16)
830         printMemberHeader(Out, Name, OldMember->getLastModified(),
831                           OldMember->getUID(), OldMember->getGID(),
832                           OldMember->getAccessMode(), OldMember->getSize());
833       else
834         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
835                           OldMember->getLastModified(), OldMember->getUID(),
836                           OldMember->getGID(), OldMember->getAccessMode(),
837                           OldMember->getSize());
838     }
839
840     Out << File->getBuffer();
841
842     if (Out.tell() % 2)
843       Out << '\n';
844   }
845
846   Output.keep();
847   Out.close();
848   sys::fs::rename(TemporaryOutput, ArchiveName);
849   TemporaryOutput = nullptr;
850 }
851
852 static void createSymbolTable(object::Archive *OldArchive) {
853   // When an archive is created or modified, if the s option is given, the
854   // resulting archive will have a current symbol table. If the S option
855   // is given, it will have no symbol table.
856   // In summary, we only need to update the symbol table if we have none.
857   // This is actually very common because of broken build systems that think
858   // they have to run ranlib.
859   if (OldArchive->hasSymbolTable())
860     return;
861
862   performWriteOperation(CreateSymTab, OldArchive);
863 }
864
865 static void performOperation(ArchiveOperation Operation,
866                              object::Archive *OldArchive) {
867   switch (Operation) {
868   case Print:
869   case DisplayTable:
870   case Extract:
871     performReadOperation(Operation, OldArchive);
872     return;
873
874   case Delete:
875   case Move:
876   case QuickAppend:
877   case ReplaceOrInsert:
878     performWriteOperation(Operation, OldArchive);
879     return;
880   case CreateSymTab:
881     createSymbolTable(OldArchive);
882     return;
883   }
884   llvm_unreachable("Unknown operation.");
885 }
886
887 static int ar_main(char **argv);
888 static int ranlib_main();
889
890 // main - main program for llvm-ar .. see comments in the code
891 int main(int argc, char **argv) {
892   ToolName = argv[0];
893   // Print a stack trace if we signal out.
894   sys::PrintStackTraceOnErrorSignal();
895   PrettyStackTraceProgram X(argc, argv);
896   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
897
898   // Have the command line options parsed and handle things
899   // like --help and --version.
900   cl::ParseCommandLineOptions(argc, argv,
901     "LLVM Archiver (llvm-ar)\n\n"
902     "  This program archives bitcode files into single libraries\n"
903   );
904
905   StringRef Stem = sys::path::stem(ToolName);
906   if (Stem.find("ar") != StringRef::npos)
907     return ar_main(argv);
908   if (Stem.find("ranlib") != StringRef::npos)
909     return ranlib_main();
910   fail("Not ranlib or ar!");
911 }
912
913 static int performOperation(ArchiveOperation Operation);
914
915 int ranlib_main() {
916   if (RestOfArgs.size() != 1)
917     fail(ToolName + "takes just one archive as argument");
918   ArchiveName = RestOfArgs[0];
919   return performOperation(CreateSymTab);
920 }
921
922 int ar_main(char **argv) {
923   // Do our own parsing of the command line because the CommandLine utility
924   // can't handle the grouped positional parameters without a dash.
925   ArchiveOperation Operation = parseCommandLine();
926   return performOperation(Operation);
927 }
928
929 static int performOperation(ArchiveOperation Operation) {
930   // Create or open the archive object.
931   std::unique_ptr<MemoryBuffer> Buf;
932   std::error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
933   if (EC && EC != errc::no_such_file_or_directory) {
934     errs() << ToolName << ": error opening '" << ArchiveName
935            << "': " << EC.message() << "!\n";
936     return 1;
937   }
938
939   if (!EC) {
940     object::Archive Archive(Buf.release(), EC);
941
942     if (EC) {
943       errs() << ToolName << ": error loading '" << ArchiveName
944              << "': " << EC.message() << "!\n";
945       return 1;
946     }
947     performOperation(Operation, &Archive);
948     return 0;
949   }
950
951   assert(EC == errc::no_such_file_or_directory);
952
953   if (!shouldCreateArchive(Operation)) {
954     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
955   } else {
956     if (!Create) {
957       // Produce a warning if we should and we're creating the archive
958       errs() << ToolName << ": creating " << ArchiveName << "\n";
959     }
960   }
961
962   performOperation(Operation, nullptr);
963   return 0;
964 }