d65f9ecc9fe51a8b784bf554f353f37ee433744d
[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/Support/CommandLine.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/Signals.h"
25 #include "llvm/Support/ToolOutputFile.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cstdlib>
29 #include <fcntl.h>
30 #include <memory>
31
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 #endif
37
38 using namespace llvm;
39
40 // The name this program was invoked as.
41 static StringRef ToolName;
42
43 static const char *TemporaryOutput;
44 static int TmpArchiveFD = -1;
45
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)
50     close(TmpArchiveFD);
51   if (TemporaryOutput)
52     sys::fs::remove(TemporaryOutput);
53   exit(1);
54 }
55
56 static void failIfError(error_code EC, Twine Context = "") {
57   if (!EC)
58     return;
59
60   std::string ContextStr = Context.str();
61   if (ContextStr == "")
62     fail(EC.message());
63   fail(Context + ": " + EC.message());
64 }
65
66 // Option for compatibility with AIX, not used but must allow it to be present.
67 static cl::opt<bool>
68 X32Option ("X32_64", cl::Hidden,
69             cl::desc("Ignored option for compatibility with AIX"));
70
71 // llvm-ar operation code and modifier flags. This must come first.
72 static cl::opt<std::string>
73 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
74
75 // llvm-ar remaining positional arguments.
76 static cl::list<std::string>
77 RestOfArgs(cl::Positional, cl::OneOrMore,
78     cl::desc("[relpos] [count] <archive-file> [members]..."));
79
80 // MoreHelp - Provide additional help output explaining the operations and
81 // modifiers of llvm-ar. This object instructs the CommandLine library
82 // to print the text of the constructor when the --help option is given.
83 static cl::extrahelp MoreHelp(
84   "\nOPERATIONS:\n"
85   "  d[NsS]       - delete file(s) from the archive\n"
86   "  m[abiSs]     - move file(s) in the archive\n"
87   "  p[kN]        - print file(s) found in the archive\n"
88   "  q[ufsS]      - quick append file(s) to the archive\n"
89   "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
90   "  t            - display contents of archive\n"
91   "  x[No]        - extract file(s) from the archive\n"
92   "\nMODIFIERS (operation specific):\n"
93   "  [a] - put file(s) after [relpos]\n"
94   "  [b] - put file(s) before [relpos] (same as [i])\n"
95   "  [i] - put file(s) before [relpos] (same as [b])\n"
96   "  [N] - use instance [count] of name\n"
97   "  [o] - preserve original dates\n"
98   "  [s] - create an archive index (cf. ranlib)\n"
99   "  [S] - do not build a symbol table\n"
100   "  [u] - update only files newer than archive contents\n"
101   "\nMODIFIERS (generic):\n"
102   "  [c] - do not warn if the library had to be created\n"
103   "  [v] - be verbose about actions taken\n"
104 );
105
106 // This enumeration delineates the kinds of operations on an archive
107 // that are permitted.
108 enum ArchiveOperation {
109   Print,            ///< Print the contents of the archive
110   Delete,           ///< Delete the specified members
111   Move,             ///< Move members to end or as given by {a,b,i} modifiers
112   QuickAppend,      ///< Quickly append to end of archive
113   ReplaceOrInsert,  ///< Replace or Insert members
114   DisplayTable,     ///< Display the table of contents
115   Extract           ///< Extract files back to file system
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
126 // Relative Positional Argument (for insert/move). This variable holds
127 // the name of the archive member to which the 'a', 'b' or 'i' modifier
128 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
129 // one variable.
130 static std::string RelPos;
131
132 // This variable holds the name of the archive file as given on the
133 // command line.
134 static std::string ArchiveName;
135
136 // This variable holds the list of member files to proecess, as given
137 // on the command line.
138 static std::vector<std::string> Members;
139
140 // show_help - Show the error message, the help message and exit.
141 LLVM_ATTRIBUTE_NORETURN static void
142 show_help(const std::string &msg) {
143   errs() << ToolName << ": " << msg << "\n\n";
144   cl::PrintHelpMessage();
145   std::exit(1);
146 }
147
148 // getRelPos - Extract the member filename from the command line for
149 // the [relpos] argument associated with a, b, and i modifiers
150 static void getRelPos() {
151   if(RestOfArgs.size() == 0)
152     show_help("Expected [relpos] for a, b, or i modifier");
153   RelPos = RestOfArgs[0];
154   RestOfArgs.erase(RestOfArgs.begin());
155 }
156
157 // getArchive - Get the archive file name from the command line
158 static void getArchive() {
159   if(RestOfArgs.size() == 0)
160     show_help("An archive name must be specified");
161   ArchiveName = RestOfArgs[0];
162   RestOfArgs.erase(RestOfArgs.begin());
163 }
164
165 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
166 // This is just for clarity.
167 static void getMembers() {
168   if(RestOfArgs.size() > 0)
169     Members = std::vector<std::string>(RestOfArgs);
170 }
171
172 // parseCommandLine - Parse the command line options as presented and return the
173 // operation specified. Process all modifiers and check to make sure that
174 // constraints on modifier/operation pairs have not been violated.
175 static ArchiveOperation parseCommandLine() {
176
177   // Keep track of number of operations. We can only specify one
178   // per execution.
179   unsigned NumOperations = 0;
180
181   // Keep track of the number of positional modifiers (a,b,i). Only
182   // one can be specified.
183   unsigned NumPositional = 0;
184
185   // Keep track of which operation was requested
186   ArchiveOperation Operation;
187
188   for(unsigned i=0; i<Options.size(); ++i) {
189     switch(Options[i]) {
190     case 'd': ++NumOperations; Operation = Delete; break;
191     case 'm': ++NumOperations; Operation = Move ; break;
192     case 'p': ++NumOperations; Operation = Print; break;
193     case 'q': ++NumOperations; Operation = QuickAppend; break;
194     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
195     case 't': ++NumOperations; Operation = DisplayTable; break;
196     case 'x': ++NumOperations; Operation = Extract; break;
197     case 'c': Create = true; break;
198     case 'l': /* accepted but unused */ break;
199     case 'o': OriginalDates = true; break;
200     case 's': break; // Ignore for now.
201     case 'S': break; // Ignore for now.
202     case 'u': OnlyUpdate = true; break;
203     case 'v': Verbose = true; break;
204     case 'a':
205       getRelPos();
206       AddAfter = true;
207       NumPositional++;
208       break;
209     case 'b':
210       getRelPos();
211       AddBefore = true;
212       NumPositional++;
213       break;
214     case 'i':
215       getRelPos();
216       AddBefore = true;
217       NumPositional++;
218       break;
219     default:
220       cl::PrintHelpMessage();
221     }
222   }
223
224   // At this point, the next thing on the command line must be
225   // the archive name.
226   getArchive();
227
228   // Everything on the command line at this point is a member.
229   getMembers();
230
231   // Perform various checks on the operation/modifier specification
232   // to make sure we are dealing with a legal request.
233   if (NumOperations == 0)
234     show_help("You must specify at least one of the operations");
235   if (NumOperations > 1)
236     show_help("Only one operation may be specified");
237   if (NumPositional > 1)
238     show_help("You may only specify one of a, b, and i modifiers");
239   if (AddAfter || AddBefore) {
240     if (Operation != Move && Operation != ReplaceOrInsert)
241       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
242             "the 'm' or 'r' operations");
243   }
244   if (OriginalDates && Operation != Extract)
245     show_help("The 'o' modifier is only applicable to the 'x' operation");
246   if (OnlyUpdate && Operation != ReplaceOrInsert)
247     show_help("The 'u' modifier is only applicable to the 'r' operation");
248
249   // Return the parsed operation to the caller
250   return Operation;
251 }
252
253 // Implements the 'p' operation. This function traverses the archive
254 // looking for members that match the path list.
255 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
256   if (Verbose)
257     outs() << "Printing " << Name << "\n";
258
259   StringRef Data = I->getBuffer();
260   outs().write(Data.data(), Data.size());
261 }
262
263 // putMode - utility function for printing out the file mode when the 't'
264 // operation is in verbose mode.
265 static void printMode(unsigned mode) {
266   if (mode & 004)
267     outs() << "r";
268   else
269     outs() << "-";
270   if (mode & 002)
271     outs() << "w";
272   else
273     outs() << "-";
274   if (mode & 001)
275     outs() << "x";
276   else
277     outs() << "-";
278 }
279
280 // Implement the 't' operation. This function prints out just
281 // the file names of each of the members. However, if verbose mode is requested
282 // ('v' modifier) then the file type, permission mode, user, group, size, and
283 // modification time are also printed.
284 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
285   if (Verbose) {
286     sys::fs::perms Mode = I->getAccessMode();
287     printMode((Mode >> 6) & 007);
288     printMode((Mode >> 3) & 007);
289     printMode(Mode & 007);
290     outs() << ' ' << I->getUID();
291     outs() << '/' << I->getGID();
292     outs() << ' ' << format("%6llu", I->getSize());
293     outs() << ' ' << I->getLastModified().str();
294     outs() << ' ';
295   }
296   outs() << Name << "\n";
297 }
298
299 // Implement the 'x' operation. This function extracts files back to the file
300 // system.
301 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
302   // Open up a file stream for writing
303   // FIXME: we should abstract this, O_BINARY in particular.
304   int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
305 #ifdef O_BINARY
306   OpenFlags |= O_BINARY;
307 #endif
308
309   // Retain the original mode.
310   sys::fs::perms Mode = I->getAccessMode();
311
312   int FD = open(Name.str().c_str(), OpenFlags, Mode);
313   if (FD < 0)
314     fail("Could not open output file");
315
316   {
317     raw_fd_ostream file(FD, false);
318
319     // Get the data and its length
320     StringRef Data = I->getBuffer();
321
322     // Write the data.
323     file.write(Data.data(), Data.size());
324   }
325
326   // If we're supposed to retain the original modification times, etc. do so
327   // now.
328   if (OriginalDates)
329     failIfError(
330         sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
331
332   if (close(FD))
333     fail("Could not close the file");
334 }
335
336 static bool shouldCreateArchive(ArchiveOperation Op) {
337   switch (Op) {
338   case Print:
339   case Delete:
340   case Move:
341   case DisplayTable:
342   case Extract:
343     return false;
344
345   case QuickAppend:
346   case ReplaceOrInsert:
347     return true;
348   }
349
350   llvm_unreachable("Missing entry in covered switch.");
351 }
352
353 static void performReadOperation(ArchiveOperation Operation,
354                                  object::Archive *OldArchive) {
355   for (object::Archive::child_iterator I = OldArchive->begin_children(),
356                                        E = OldArchive->end_children();
357        I != E; ++I) {
358     StringRef Name;
359     failIfError(I->getName(Name));
360
361     if (!Members.empty() &&
362         std::find(Members.begin(), Members.end(), Name) == Members.end())
363       continue;
364
365     switch (Operation) {
366     default:
367       llvm_unreachable("Not a read operation");
368     case Print:
369       doPrint(Name, I);
370       break;
371     case DisplayTable:
372       doDisplayTable(Name, I);
373       break;
374     case Extract:
375       doExtract(Name, I);
376       break;
377     }
378   }
379 }
380
381 namespace {
382 class NewArchiveIterator {
383   bool IsNewMember;
384   SmallString<16> MemberName;
385   object::Archive::child_iterator OldI;
386   std::vector<std::string>::const_iterator NewI;
387
388 public:
389   NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
390   NewArchiveIterator(std::vector<std::string>::const_iterator I, Twine Name);
391   bool isNewMember() const;
392   object::Archive::child_iterator getOld() const;
393   const char *getNew() const;
394   StringRef getMemberName() const { return MemberName; }
395 };
396 }
397
398 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
399                                        Twine Name)
400     : IsNewMember(false), OldI(I) {
401   Name.toVector(MemberName);
402 }
403
404 NewArchiveIterator::NewArchiveIterator(
405     std::vector<std::string>::const_iterator I, Twine Name)
406     : IsNewMember(true), NewI(I) {
407   Name.toVector(MemberName);
408 }
409
410 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
411
412 object::Archive::child_iterator NewArchiveIterator::getOld() const {
413   assert(!IsNewMember);
414   return OldI;
415 }
416
417 const char *NewArchiveIterator::getNew() const {
418   assert(IsNewMember);
419   return NewI->c_str();
420 }
421
422 template <typename T>
423 void addMember(std::vector<NewArchiveIterator> &Members,
424                std::string &StringTable, T I, StringRef Name) {
425   if (Name.size() < 16) {
426     NewArchiveIterator NI(I, Twine(Name) + "/");
427     Members.push_back(NI);
428   } else {
429     int MapIndex = StringTable.size();
430     NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
431     Members.push_back(NI);
432     StringTable += Name;
433     StringTable += "/\n";
434   }
435 }
436
437 namespace {
438 class HasName {
439   StringRef Name;
440
441 public:
442   HasName(StringRef Name) : Name(Name) {}
443   bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
444 };
445 }
446
447 // We have to walk this twice and computing it is not trivial, so creating an
448 // explicit std::vector is actually fairly efficient.
449 static std::vector<NewArchiveIterator>
450 computeNewArchiveMembers(ArchiveOperation Operation,
451                          object::Archive *OldArchive,
452                          std::string &StringTable) {
453   std::vector<NewArchiveIterator> Ret;
454   std::vector<NewArchiveIterator> Moved;
455   int InsertPos = -1;
456   StringRef PosName = sys::path::filename(RelPos);
457   if (OldArchive) {
458     int Pos = 0;
459     for (object::Archive::child_iterator I = OldArchive->begin_children(),
460                                          E = OldArchive->end_children();
461          I != E; ++I, ++Pos) {
462       StringRef Name;
463       failIfError(I->getName(Name));
464       if (Name == PosName) {
465         assert(AddAfter || AddBefore);
466         if (AddBefore)
467           InsertPos = Pos;
468         else
469           InsertPos = Pos + 1;
470       }
471       if (Operation != QuickAppend && !Members.empty()) {
472         std::vector<std::string>::iterator MI =
473             std::find_if(Members.begin(), Members.end(), HasName(Name));
474         if (MI != Members.end()) {
475           if (Operation == Move) {
476             addMember(Moved, StringTable, I, Name);
477             continue;
478           }
479           if (Operation != ReplaceOrInsert || !OnlyUpdate)
480             continue;
481           // Ignore if the file if it is older than the member.
482           sys::fs::file_status Status;
483           failIfError(sys::fs::status(*MI, Status));
484           if (Status.getLastModificationTime() < I->getLastModified())
485             Members.erase(MI);
486           else
487             continue;
488         }
489       }
490       addMember(Ret, StringTable, I, Name);
491     }
492   }
493
494   if (Operation == Delete)
495     return Ret;
496
497   if (Operation == Move) {
498     if (RelPos.empty()) {
499       Ret.insert(Ret.end(), Moved.begin(), Moved.end());
500       return Ret;
501     }
502     if (InsertPos == -1)
503       fail("Insertion point not found");
504     assert(unsigned(InsertPos) <= Ret.size());
505     Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
506     return Ret;
507   }
508
509   for (std::vector<std::string>::iterator I = Members.begin(),
510                                           E = Members.end();
511        I != E; ++I) {
512     StringRef Name = sys::path::filename(*I);
513     addMember(Ret, StringTable, I, Name);
514   }
515
516   return Ret;
517 }
518
519 template <typename T>
520 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
521   uint64_t OldPos = OS.tell();
522   OS << Data;
523   unsigned SizeSoFar = OS.tell() - OldPos;
524   assert(Size >= SizeSoFar && "Data doesn't fit in Size");
525   unsigned Remaining = Size - SizeSoFar;
526   for (unsigned I = 0; I < Remaining; ++I)
527     OS << ' ';
528 }
529
530 static void performWriteOperation(ArchiveOperation Operation,
531                                   object::Archive *OldArchive) {
532   SmallString<128> TmpArchive;
533   failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
534                                         TmpArchiveFD, TmpArchive));
535
536   TemporaryOutput = TmpArchive.c_str();
537   tool_output_file Output(TemporaryOutput, TmpArchiveFD);
538   raw_fd_ostream &Out = Output.os();
539   Out << "!<arch>\n";
540
541   std::string StringTable;
542   std::vector<NewArchiveIterator> NewMembers =
543       computeNewArchiveMembers(Operation, OldArchive, StringTable);
544   if (!StringTable.empty()) {
545     if (StringTable.size() % 2)
546       StringTable += '\n';
547     printWithSpacePadding(Out, "//", 48);
548     printWithSpacePadding(Out, StringTable.size(), 10);
549     Out << "`\n";
550     Out << StringTable;
551   }
552
553   for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
554                                                  E = NewMembers.end();
555        I != E; ++I) {
556     StringRef Name = I->getMemberName();
557     printWithSpacePadding(Out, Name, 16);
558
559     if (I->isNewMember()) {
560       const char *FileName = I->getNew();
561
562       int OpenFlags = O_RDONLY;
563 #ifdef O_BINARY
564       OpenFlags |= O_BINARY;
565 #endif
566       int FD = ::open(FileName, OpenFlags);
567       if (FD == -1)
568         return failIfError(error_code(errno, posix_category()), FileName);
569
570       sys::fs::file_status Status;
571       failIfError(sys::fs::status(FD, Status), FileName);
572
573       OwningPtr<MemoryBuffer> File;
574       failIfError(
575           MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
576           FileName);
577
578       uint64_t secondsSinceEpoch =
579           Status.getLastModificationTime().toEpochTime();
580       printWithSpacePadding(Out, secondsSinceEpoch, 12);
581
582       printWithSpacePadding(Out, Status.getUser(), 6);
583       printWithSpacePadding(Out, Status.getGroup(), 6);
584       printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
585       printWithSpacePadding(Out, Status.getSize(), 10);
586       Out << "`\n";
587
588       Out << File->getBuffer();
589     } else {
590       object::Archive::child_iterator OldMember = I->getOld();
591
592       uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
593       printWithSpacePadding(Out, secondsSinceEpoch, 12);
594
595       printWithSpacePadding(Out, OldMember->getUID(), 6);
596       printWithSpacePadding(Out, OldMember->getGID(), 6);
597       printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
598       printWithSpacePadding(Out, OldMember->getSize(), 10);
599       Out << "`\n";
600
601       Out << OldMember->getBuffer();
602     }
603
604     if (Out.tell() % 2)
605       Out << '\n';
606   }
607   Output.keep();
608   Out.close();
609   sys::fs::rename(TemporaryOutput, ArchiveName);
610   TemporaryOutput = NULL;
611 }
612
613 static void performOperation(ArchiveOperation Operation,
614                              object::Archive *OldArchive) {
615   switch (Operation) {
616   case Print:
617   case DisplayTable:
618   case Extract:
619     performReadOperation(Operation, OldArchive);
620     return;
621
622   case Delete:
623   case Move:
624   case QuickAppend:
625   case ReplaceOrInsert:
626     performWriteOperation(Operation, OldArchive);
627     return;
628   }
629   llvm_unreachable("Unknown operation.");
630 }
631
632 // main - main program for llvm-ar .. see comments in the code
633 int main(int argc, char **argv) {
634   ToolName = argv[0];
635   // Print a stack trace if we signal out.
636   sys::PrintStackTraceOnErrorSignal();
637   PrettyStackTraceProgram X(argc, argv);
638   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
639
640   // Have the command line options parsed and handle things
641   // like --help and --version.
642   cl::ParseCommandLineOptions(argc, argv,
643     "LLVM Archiver (llvm-ar)\n\n"
644     "  This program archives bitcode files into single libraries\n"
645   );
646
647   // Do our own parsing of the command line because the CommandLine utility
648   // can't handle the grouped positional parameters without a dash.
649   ArchiveOperation Operation = parseCommandLine();
650
651   // Create or open the archive object.
652   OwningPtr<MemoryBuffer> Buf;
653   error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
654   if (EC && EC != llvm::errc::no_such_file_or_directory) {
655     errs() << argv[0] << ": error opening '" << ArchiveName
656            << "': " << EC.message() << "!\n";
657     return 1;
658   }
659
660   if (!EC) {
661     object::Archive Archive(Buf.take(), EC);
662
663     if (EC) {
664       errs() << argv[0] << ": error loading '" << ArchiveName
665              << "': " << EC.message() << "!\n";
666       return 1;
667     }
668     performOperation(Operation, &Archive);
669     return 0;
670   }
671
672   assert(EC == llvm::errc::no_such_file_or_directory);
673
674   if (!shouldCreateArchive(Operation)) {
675     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
676   } else {
677     if (!Create) {
678       // Produce a warning if we should and we're creating the archive
679       errs() << argv[0] << ": creating " << ArchiveName << "\n";
680     }
681   }
682
683   performOperation(Operation, NULL);
684   return 0;
685 }