Use %llu to print a 64 bit number. Should fix the ARM bots.
[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 "Archive.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.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/PrettyStackTrace.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <cstdlib>
27 #include <fcntl.h>
28 #include <memory>
29
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
31 #include <unistd.h>
32 #else
33 #include <io.h>
34 #endif
35
36 using namespace llvm;
37
38 // Option for compatibility with AIX, not used but must allow it to be present.
39 static cl::opt<bool>
40 X32Option ("X32_64", cl::Hidden,
41             cl::desc("Ignored option for compatibility with AIX"));
42
43 // llvm-ar operation code and modifier flags. This must come first.
44 static cl::opt<std::string>
45 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
46
47 // llvm-ar remaining positional arguments.
48 static cl::list<std::string>
49 RestOfArgs(cl::Positional, cl::OneOrMore,
50     cl::desc("[relpos] [count] <archive-file> [members]..."));
51
52 // MoreHelp - Provide additional help output explaining the operations and
53 // modifiers of llvm-ar. This object instructs the CommandLine library
54 // to print the text of the constructor when the --help option is given.
55 static cl::extrahelp MoreHelp(
56   "\nOPERATIONS:\n"
57   "  d[NsS]       - delete file(s) from the archive\n"
58   "  m[abiSs]     - move file(s) in the archive\n"
59   "  p[kN]        - print file(s) found in the archive\n"
60   "  q[ufsS]      - quick append file(s) to the archive\n"
61   "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
62   "  t            - display contents of archive\n"
63   "  x[No]        - extract file(s) from the archive\n"
64   "\nMODIFIERS (operation specific):\n"
65   "  [a] - put file(s) after [relpos]\n"
66   "  [b] - put file(s) before [relpos] (same as [i])\n"
67   "  [i] - put file(s) before [relpos] (same as [b])\n"
68   "  [N] - use instance [count] of name\n"
69   "  [o] - preserve original dates\n"
70   "  [s] - create an archive index (cf. ranlib)\n"
71   "  [S] - do not build a symbol table\n"
72   "  [u] - update only files newer than archive contents\n"
73   "\nMODIFIERS (generic):\n"
74   "  [c] - do not warn if the library had to be created\n"
75   "  [v] - be verbose about actions taken\n"
76 );
77
78 // This enumeration delineates the kinds of operations on an archive
79 // that are permitted.
80 enum ArchiveOperation {
81   Print,            ///< Print the contents of the archive
82   Delete,           ///< Delete the specified members
83   Move,             ///< Move members to end or as given by {a,b,i} modifiers
84   QuickAppend,      ///< Quickly append to end of archive
85   ReplaceOrInsert,  ///< Replace or Insert members
86   DisplayTable,     ///< Display the table of contents
87   Extract           ///< Extract files back to file system
88 };
89
90 // Modifiers to follow operation to vary behavior
91 bool AddAfter = false;           ///< 'a' modifier
92 bool AddBefore = false;          ///< 'b' modifier
93 bool Create = false;             ///< 'c' modifier
94 bool OriginalDates = false;      ///< 'o' modifier
95 bool SymTable = true;            ///< 's' & 'S' modifiers
96 bool OnlyUpdate = false;         ///< 'u' modifier
97 bool Verbose = false;            ///< 'v' modifier
98
99 // Relative Positional Argument (for insert/move). This variable holds
100 // the name of the archive member to which the 'a', 'b' or 'i' modifier
101 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
102 // one variable.
103 std::string RelPos;
104
105 // This variable holds the name of the archive file as given on the
106 // command line.
107 std::string ArchiveName;
108
109 // This variable holds the list of member files to proecess, as given
110 // on the command line.
111 std::vector<std::string> Members;
112
113 // This variable holds the (possibly expanded) list of path objects that
114 // correspond to files we will
115 std::set<std::string> Paths;
116
117 // The Archive object to which all the editing operations will be sent.
118 Archive* TheArchive = 0;
119
120 // The name this program was invoked as.
121 static const char *program_name;
122
123 // show_help - Show the error message, the help message and exit.
124 LLVM_ATTRIBUTE_NORETURN static void
125 show_help(const std::string &msg) {
126   errs() << program_name << ": " << msg << "\n\n";
127   cl::PrintHelpMessage();
128   if (TheArchive)
129     delete TheArchive;
130   std::exit(1);
131 }
132
133 // fail - Show the error message and exit.
134 LLVM_ATTRIBUTE_NORETURN static void
135 fail(const std::string &msg) {
136   errs() << program_name << ": " << msg << "\n\n";
137   if (TheArchive)
138     delete TheArchive;
139   std::exit(1);
140 }
141
142 // getRelPos - Extract the member filename from the command line for
143 // the [relpos] argument associated with a, b, and i modifiers
144 void getRelPos() {
145   if(RestOfArgs.size() == 0)
146     show_help("Expected [relpos] for a, b, or i modifier");
147   RelPos = RestOfArgs[0];
148   RestOfArgs.erase(RestOfArgs.begin());
149 }
150
151 // getArchive - Get the archive file name from the command line
152 void getArchive() {
153   if(RestOfArgs.size() == 0)
154     show_help("An archive name must be specified");
155   ArchiveName = RestOfArgs[0];
156   RestOfArgs.erase(RestOfArgs.begin());
157 }
158
159 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
160 // This is just for clarity.
161 void getMembers() {
162   if(RestOfArgs.size() > 0)
163     Members = std::vector<std::string>(RestOfArgs);
164 }
165
166 // parseCommandLine - Parse the command line options as presented and return the
167 // operation specified. Process all modifiers and check to make sure that
168 // constraints on modifier/operation pairs have not been violated.
169 ArchiveOperation parseCommandLine() {
170
171   // Keep track of number of operations. We can only specify one
172   // per execution.
173   unsigned NumOperations = 0;
174
175   // Keep track of the number of positional modifiers (a,b,i). Only
176   // one can be specified.
177   unsigned NumPositional = 0;
178
179   // Keep track of which operation was requested
180   ArchiveOperation Operation;
181
182   for(unsigned i=0; i<Options.size(); ++i) {
183     switch(Options[i]) {
184     case 'd': ++NumOperations; Operation = Delete; break;
185     case 'm': ++NumOperations; Operation = Move ; break;
186     case 'p': ++NumOperations; Operation = Print; break;
187     case 'q': ++NumOperations; Operation = QuickAppend; break;
188     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
189     case 't': ++NumOperations; Operation = DisplayTable; break;
190     case 'x': ++NumOperations; Operation = Extract; break;
191     case 'c': Create = true; break;
192     case 'l': /* accepted but unused */ break;
193     case 'o': OriginalDates = true; break;
194     case 's': break; // Ignore for now.
195     case 'S': break; // Ignore for now.
196     case 'u': OnlyUpdate = true; break;
197     case 'v': Verbose = true; break;
198     case 'a':
199       getRelPos();
200       AddAfter = true;
201       NumPositional++;
202       break;
203     case 'b':
204       getRelPos();
205       AddBefore = true;
206       NumPositional++;
207       break;
208     case 'i':
209       getRelPos();
210       AddBefore = true;
211       NumPositional++;
212       break;
213     default:
214       cl::PrintHelpMessage();
215     }
216   }
217
218   // At this point, the next thing on the command line must be
219   // the archive name.
220   getArchive();
221
222   // Everything on the command line at this point is a member.
223   getMembers();
224
225   // Perform various checks on the operation/modifier specification
226   // to make sure we are dealing with a legal request.
227   if (NumOperations == 0)
228     show_help("You must specify at least one of the operations");
229   if (NumOperations > 1)
230     show_help("Only one operation may be specified");
231   if (NumPositional > 1)
232     show_help("You may only specify one of a, b, and i modifiers");
233   if (AddAfter || AddBefore) {
234     if (Operation != Move && Operation != ReplaceOrInsert)
235       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
236             "the 'm' or 'r' operations");
237   }
238   if (OriginalDates && Operation != Extract)
239     show_help("The 'o' modifier is only applicable to the 'x' operation");
240   if (OnlyUpdate && Operation != ReplaceOrInsert)
241     show_help("The 'u' modifier is only applicable to the 'r' operation");
242
243   // Return the parsed operation to the caller
244   return Operation;
245 }
246
247 // buildPaths - Convert the strings in the Members vector to sys::Path objects
248 // and make sure they are valid and exist exist. This check is only needed for
249 // the operations that add/replace files to the archive ('q' and 'r')
250 bool buildPaths(bool checkExistence, std::string* ErrMsg) {
251   for (unsigned i = 0; i < Members.size(); i++) {
252     std::string aPath = Members[i];
253     if (checkExistence) {
254       bool IsDirectory;
255       error_code EC = sys::fs::is_directory(aPath, IsDirectory);
256       if (EC)
257         fail(aPath + ": " + EC.message());
258       if (IsDirectory)
259         fail(aPath + " Is a directory");
260
261       Paths.insert(aPath);
262     } else {
263       Paths.insert(aPath);
264     }
265   }
266   return false;
267 }
268
269 // doPrint - Implements the 'p' operation. This function traverses the archive
270 // looking for members that match the path list. It is careful to uncompress
271 // things that should be and to skip bitcode files unless the 'k' modifier was
272 // given.
273 bool doPrint(std::string* ErrMsg) {
274   if (buildPaths(false, ErrMsg))
275     return true;
276   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
277        I != E; ++I ) {
278     if (Paths.empty() ||
279         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
280       const char *data = reinterpret_cast<const char *>(I->getData());
281
282       // Skip things that don't make sense to print
283       if (I->isSVR4SymbolTable() || I->isBSD4SymbolTable())
284         continue;
285
286       if (Verbose)
287         outs() << "Printing " << I->getPath().str() << "\n";
288
289       unsigned len = I->getSize();
290       outs().write(data, len);
291     }
292   }
293   return false;
294 }
295
296 // putMode - utility function for printing out the file mode when the 't'
297 // operation is in verbose mode.
298 void
299 printMode(unsigned mode) {
300   if (mode & 004)
301     outs() << "r";
302   else
303     outs() << "-";
304   if (mode & 002)
305     outs() << "w";
306   else
307     outs() << "-";
308   if (mode & 001)
309     outs() << "x";
310   else
311     outs() << "-";
312 }
313
314 // doDisplayTable - Implement the 't' operation. This function prints out just
315 // the file names of each of the members. However, if verbose mode is requested
316 // ('v' modifier) then the file type, permission mode, user, group, size, and
317 // modification time are also printed.
318 bool
319 doDisplayTable(std::string* ErrMsg) {
320   if (buildPaths(false, ErrMsg))
321     return true;
322   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
323        I != E; ++I ) {
324     if (Paths.empty() ||
325         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
326       if (Verbose) {
327         unsigned mode = I->getMode();
328         printMode((mode >> 6) & 007);
329         printMode((mode >> 3) & 007);
330         printMode(mode & 007);
331         outs() << ' ' << I->getUser();
332         outs() << "/" << I->getGroup();
333         outs() << ' ' << format("%6llu", I->getSize());
334         sys::TimeValue ModTime = I->getModTime();
335         outs() << " " << ModTime.str();
336         outs() << " " << I->getPath().str() << "\n";
337       } else {
338         outs() << I->getPath().str() << "\n";
339       }
340     }
341   }
342   return false;
343 }
344
345 // doExtract - Implement the 'x' operation. This function extracts files back to
346 // the file system.
347 bool
348 doExtract(std::string* ErrMsg) {
349   if (buildPaths(false, ErrMsg))
350     return true;
351   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
352        I != E; ++I ) {
353     if (Paths.empty() ||
354         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
355
356       // Open up a file stream for writing
357       int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
358 #ifdef O_BINARY
359       OpenFlags |= O_BINARY;
360 #endif
361
362       // Retain the original mode.
363       sys::fs::perms Mode = sys::fs::perms(I->getMode());
364
365       int FD = open(I->getPath().str().c_str(), OpenFlags, Mode);
366       if (FD < 0)
367         return true;
368
369       {
370         raw_fd_ostream file(FD, false);
371
372         // Get the data and its length
373         const char* data = reinterpret_cast<const char*>(I->getData());
374         unsigned len = I->getSize();
375
376         // Write the data.
377         file.write(data, len);
378       }
379
380       // If we're supposed to retain the original modification times, etc. do so
381       // now.
382       if (OriginalDates) {
383         error_code EC =
384             sys::fs::setLastModificationAndAccessTime(FD, I->getModTime());
385         if (EC)
386           fail(EC.message());
387       }
388       if (close(FD))
389         return true;
390     }
391   }
392   return false;
393 }
394
395 // doDelete - Implement the delete operation. This function deletes zero or more
396 // members from the archive. Note that if the count is specified, there should
397 // be no more than one path in the Paths list or else this algorithm breaks.
398 // That check is enforced in parseCommandLine (above).
399 bool
400 doDelete(std::string* ErrMsg) {
401   if (buildPaths(false, ErrMsg))
402     return true;
403   if (Paths.empty())
404     return false;
405   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
406        I != E; ) {
407     if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
408       Archive::iterator J = I;
409       ++I;
410       TheArchive->erase(J);
411     } else {
412       ++I;
413     }
414   }
415
416   // We're done editting, reconstruct the archive.
417   if (TheArchive->writeToDisk(ErrMsg))
418     return true;
419   return false;
420 }
421
422 // doMore - Implement the move operation. This function re-arranges just the
423 // order of the archive members so that when the archive is written the move
424 // of the members is accomplished. Note the use of the RelPos variable to
425 // determine where the items should be moved to.
426 bool
427 doMove(std::string* ErrMsg) {
428   if (buildPaths(false, ErrMsg))
429     return true;
430
431   // By default and convention the place to move members to is the end of the
432   // archive.
433   Archive::iterator moveto_spot = TheArchive->end();
434
435   // However, if the relative positioning modifiers were used, we need to scan
436   // the archive to find the member in question. If we don't find it, its no
437   // crime, we just move to the end.
438   if (AddBefore || AddAfter) {
439     for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
440          I != E; ++I ) {
441       if (RelPos == I->getPath().str()) {
442         if (AddAfter) {
443           moveto_spot = I;
444           moveto_spot++;
445         } else {
446           moveto_spot = I;
447         }
448         break;
449       }
450     }
451   }
452
453   // Keep a list of the paths remaining to be moved
454   std::set<std::string> remaining(Paths);
455
456   // Scan the archive again, this time looking for the members to move to the
457   // moveto_spot.
458   for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
459        I != E && !remaining.empty(); ++I ) {
460     std::set<std::string>::iterator found =
461       std::find(remaining.begin(),remaining.end(), I->getPath());
462     if (found != remaining.end()) {
463       if (I != moveto_spot)
464         TheArchive->splice(moveto_spot,*TheArchive,I);
465       remaining.erase(found);
466     }
467   }
468
469   // We're done editting, reconstruct the archive.
470   if (TheArchive->writeToDisk(ErrMsg))
471     return true;
472   return false;
473 }
474
475 // doQuickAppend - Implements the 'q' operation. This function just
476 // indiscriminantly adds the members to the archive and rebuilds it.
477 bool
478 doQuickAppend(std::string* ErrMsg) {
479   // Get the list of paths to append.
480   if (buildPaths(true, ErrMsg))
481     return true;
482   if (Paths.empty())
483     return false;
484
485   // Append them quickly.
486   for (std::set<std::string>::iterator PI = Paths.begin(), PE = Paths.end();
487        PI != PE; ++PI) {
488     if (TheArchive->addFileBefore(*PI, TheArchive->end(), ErrMsg))
489       return true;
490   }
491
492   // We're done editting, reconstruct the archive.
493   if (TheArchive->writeToDisk(ErrMsg))
494     return true;
495   return false;
496 }
497
498 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
499 // any existing files or insert new ones into the archive.
500 bool
501 doReplaceOrInsert(std::string* ErrMsg) {
502
503   // Build the list of files to be added/replaced.
504   if (buildPaths(true, ErrMsg))
505     return true;
506   if (Paths.empty())
507     return false;
508
509   // Keep track of the paths that remain to be inserted.
510   std::set<std::string> remaining(Paths);
511
512   // Default the insertion spot to the end of the archive
513   Archive::iterator insert_spot = TheArchive->end();
514
515   // Iterate over the archive contents
516   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
517        I != E && !remaining.empty(); ++I ) {
518
519     // Determine if this archive member matches one of the paths we're trying
520     // to replace.
521
522     std::set<std::string>::iterator found = remaining.end();
523     for (std::set<std::string>::iterator RI = remaining.begin(),
524          RE = remaining.end(); RI != RE; ++RI ) {
525       std::string compare(sys::path::filename(*RI));
526       if (compare == I->getPath().str()) {
527         found = RI;
528         break;
529       }
530     }
531
532     if (found != remaining.end()) {
533       sys::fs::file_status Status;
534       error_code EC = sys::fs::status(*found, Status);
535       if (EC)
536         return true;
537       if (!sys::fs::is_directory(Status)) {
538         if (OnlyUpdate) {
539           // Replace the item only if it is newer.
540           if (Status.getLastModificationTime() > I->getModTime())
541             if (I->replaceWith(*found, ErrMsg))
542               return true;
543         } else {
544           // Replace the item regardless of time stamp
545           if (I->replaceWith(*found, ErrMsg))
546             return true;
547         }
548       } else {
549         // We purposefully ignore directories.
550       }
551
552       // Remove it from our "to do" list
553       remaining.erase(found);
554     }
555
556     // Determine if this is the place where we should insert
557     if (AddBefore && RelPos == I->getPath().str())
558       insert_spot = I;
559     else if (AddAfter && RelPos == I->getPath().str()) {
560       insert_spot = I;
561       insert_spot++;
562     }
563   }
564
565   // If we didn't replace all the members, some will remain and need to be
566   // inserted at the previously computed insert-spot.
567   if (!remaining.empty()) {
568     for (std::set<std::string>::iterator PI = remaining.begin(),
569          PE = remaining.end(); PI != PE; ++PI) {
570       if (TheArchive->addFileBefore(*PI, insert_spot, ErrMsg))
571         return true;
572     }
573   }
574
575   // We're done editting, reconstruct the archive.
576   if (TheArchive->writeToDisk(ErrMsg))
577     return true;
578   return false;
579 }
580
581 bool shouldCreateArchive(ArchiveOperation Op) {
582   switch (Op) {
583   case Print:
584   case Delete:
585   case Move:
586   case DisplayTable:
587   case Extract:
588     return false;
589
590   case QuickAppend:
591   case ReplaceOrInsert:
592     return true;
593   }
594
595   llvm_unreachable("Missing entry in covered switch.");
596 }
597
598 // main - main program for llvm-ar .. see comments in the code
599 int main(int argc, char **argv) {
600   program_name = argv[0];
601   // Print a stack trace if we signal out.
602   sys::PrintStackTraceOnErrorSignal();
603   PrettyStackTraceProgram X(argc, argv);
604   LLVMContext &Context = getGlobalContext();
605   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
606
607   // Have the command line options parsed and handle things
608   // like --help and --version.
609   cl::ParseCommandLineOptions(argc, argv,
610     "LLVM Archiver (llvm-ar)\n\n"
611     "  This program archives bitcode files into single libraries\n"
612   );
613
614   int exitCode = 0;
615
616   // Do our own parsing of the command line because the CommandLine utility
617   // can't handle the grouped positional parameters without a dash.
618   ArchiveOperation Operation = parseCommandLine();
619
620   // Create or open the archive object.
621   if (shouldCreateArchive(Operation) && !llvm::sys::fs::exists(ArchiveName)) {
622     // Produce a warning if we should and we're creating the archive
623     if (!Create)
624       errs() << argv[0] << ": creating " << ArchiveName << "\n";
625     TheArchive = Archive::CreateEmpty(ArchiveName, Context);
626     TheArchive->writeToDisk();
627   }
628
629   if (!TheArchive) {
630     std::string Error;
631     TheArchive = Archive::OpenAndLoad(ArchiveName, Context, &Error);
632     if (TheArchive == 0) {
633       errs() << argv[0] << ": error loading '" << ArchiveName << "': "
634              << Error << "!\n";
635       return 1;
636     }
637   }
638
639   // Make sure we're not fooling ourselves.
640   assert(TheArchive && "Unable to instantiate the archive");
641
642   // Perform the operation
643   std::string ErrMsg;
644   bool haveError = false;
645   switch (Operation) {
646     case Print:           haveError = doPrint(&ErrMsg); break;
647     case Delete:          haveError = doDelete(&ErrMsg); break;
648     case Move:            haveError = doMove(&ErrMsg); break;
649     case QuickAppend:     haveError = doQuickAppend(&ErrMsg); break;
650     case ReplaceOrInsert: haveError = doReplaceOrInsert(&ErrMsg); break;
651     case DisplayTable:    haveError = doDisplayTable(&ErrMsg); break;
652     case Extract:         haveError = doExtract(&ErrMsg); break;
653   }
654   if (haveError) {
655     errs() << argv[0] << ": " << ErrMsg << "\n";
656     return 1;
657   }
658
659   delete TheArchive;
660   TheArchive = 0;
661
662   // Return result code back to operating system.
663   return exitCode;
664 }