llvm-ar.cpp revision d74ea2bbd8bb630331f35ead42d385249bd42af8
1//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// Builds up (relatively) standard unix archive files (.a) containing LLVM 11// bytecode or other files. 12// 13//===----------------------------------------------------------------------===// 14 15#include "llvm/Module.h" 16#include "llvm/Bytecode/Archive.h" 17#include "llvm/Support/CommandLine.h" 18#include "llvm/Support/Compressor.h" 19#include "llvm/System/Signals.h" 20#include <iostream> 21#include <algorithm> 22#include <iomanip> 23#include <memory> 24 25using namespace llvm; 26 27// Option for compatibility with ASIX, not used but must allow it to be present. 28static cl::opt<bool> 29X32Option ("X32_64", cl::Hidden, 30 cl::desc("Ignored option for compatibility with AIX")); 31 32// llvm-ar operation code and modifier flags. This must come first. 33static cl::opt<std::string> 34Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]...")); 35 36// llvm-ar remaining positional arguments. 37static cl::list<std::string> 38RestOfArgs(cl::Positional, cl::OneOrMore, 39 cl::desc("[relpos] [count] <archive-file> [members]...")); 40 41// MoreHelp - Provide additional help output explaining the operations and 42// modifiers of llvm-ar. This object instructs the CommandLine library 43// to print the text of the constructor when the --help option is given. 44static cl::extrahelp MoreHelp( 45 "\nOPERATIONS:\n" 46 " d[NsS] - delete file(s) from the archive\n" 47 " m[abiSs] - move file(s) in the archive\n" 48 " p[kN] - print file(s) found in the archive\n" 49 " q[ufsS] - quick append file(s) to the archive\n" 50 " r[abfiuzRsS] - replace or insert file(s) into the archive\n" 51 " t - display contents of archive\n" 52 " x[No] - extract file(s) from the archive\n" 53 "\nMODIFIERS (operation specific):\n" 54 " [a] - put file(s) after [relpos]\n" 55 " [b] - put file(s) before [relpos] (same as [i])\n" 56 " [f] - truncate inserted file names\n" 57 " [i] - put file(s) before [relpos] (same as [b])\n" 58 " [k] - always print bytecode files (default is to skip them)\n" 59 " [N] - use instance [count] of name\n" 60 " [o] - preserve original dates\n" 61 " [P] - use full path names when matching\n" 62 " [R] - recurse through directories when inserting\n" 63 " [s] - create an archive index (cf. ranlib)\n" 64 " [S] - do not build a symbol table\n" 65 " [u] - update only files newer than archive contents\n" 66 " [z] - compress files before inserting/extracting\n" 67 "\nMODIFIERS (generic):\n" 68 " [c] - do not warn if the library had to be created\n" 69 " [v] - be verbose about actions taken\n" 70 " [V] - be *really* verbose about actions taken\n" 71); 72 73// This enumeration delineates the kinds of operations on an archive 74// that are permitted. 75enum ArchiveOperation { 76 NoOperation, ///< An operation hasn't been specified 77 Print, ///< Print the contents of the archive 78 Delete, ///< Delete the specified members 79 Move, ///< Move members to end or as given by {a,b,i} modifiers 80 QuickAppend, ///< Quickly append to end of archive 81 ReplaceOrInsert, ///< Replace or Insert members 82 DisplayTable, ///< Display the table of contents 83 Extract ///< Extract files back to file system 84}; 85 86// Modifiers to follow operation to vary behavior 87bool AddAfter = false; ///< 'a' modifier 88bool AddBefore = false; ///< 'b' modifier 89bool Create = false; ///< 'c' modifier 90bool TruncateNames = false; ///< 'f' modifier 91bool InsertBefore = false; ///< 'i' modifier 92bool DontSkipBytecode = false; ///< 'k' modifier 93bool UseCount = false; ///< 'N' modifier 94bool OriginalDates = false; ///< 'o' modifier 95bool FullPath = false; ///< 'P' modifier 96bool RecurseDirectories = false; ///< 'R' modifier 97bool SymTable = true; ///< 's' & 'S' modifiers 98bool OnlyUpdate = false; ///< 'u' modifier 99bool Verbose = false; ///< 'v' modifier 100bool ReallyVerbose = false; ///< 'V' modifier 101bool Compression = false; ///< 'z' modifier 102 103// Relative Positional Argument (for insert/move). This variable holds 104// the name of the archive member to which the 'a', 'b' or 'i' modifier 105// refers. Only one of 'a', 'b' or 'i' can be specified so we only need 106// one variable. 107std::string RelPos; 108 109// Select which of multiple entries in the archive with the same name should be 110// used (specified with -N) for the delete and extract operations. 111int Count = 1; 112 113// This variable holds the name of the archive file as given on the 114// command line. 115std::string ArchiveName; 116 117// This variable holds the list of member files to proecess, as given 118// on the command line. 119std::vector<std::string> Members; 120 121// This variable holds the (possibly expanded) list of path objects that 122// correspond to files we will 123std::set<sys::Path> Paths; 124 125// The Archive object to which all the editing operations will be sent. 126Archive* TheArchive = 0; 127 128// getRelPos - Extract the member filename from the command line for 129// the [relpos] argument associated with a, b, and i modifiers 130void getRelPos() { 131 if(RestOfArgs.size() > 0) { 132 RelPos = RestOfArgs[0]; 133 RestOfArgs.erase(RestOfArgs.begin()); 134 } 135 else 136 throw "Expected [relpos] for a, b, or i modifier"; 137} 138 139// getCount - Extract the [count] argument associated with the N modifier 140// from the command line and check its value. 141void getCount() { 142 if(RestOfArgs.size() > 0) { 143 Count = atoi(RestOfArgs[0].c_str()); 144 RestOfArgs.erase(RestOfArgs.begin()); 145 } 146 else 147 throw "Expected [count] value with N modifier"; 148 149 // Non-positive counts are not allowed 150 if (Count < 1) 151 throw "Invalid [count] value (not a positive integer)"; 152} 153 154// getArchive - Get the archive file name from the command line 155void getArchive() { 156 if(RestOfArgs.size() > 0) { 157 ArchiveName = RestOfArgs[0]; 158 RestOfArgs.erase(RestOfArgs.begin()); 159 } 160 else 161 throw "An archive name must be specified."; 162} 163 164// getMembers - Copy over remaining items in RestOfArgs to our Members vector 165// This is just for clarity. 166void getMembers() { 167 if(RestOfArgs.size() > 0) 168 Members = std::vector<std::string>(RestOfArgs); 169} 170 171// parseCommandLine - Parse the command line options as presented and return the 172// operation specified. Process all modifiers and check to make sure that 173// constraints on modifier/operation pairs have not been violated. 174ArchiveOperation parseCommandLine() { 175 176 // Keep track of number of operations. We can only specify one 177 // per execution. 178 unsigned NumOperations = 0; 179 180 // Keep track of the number of positional modifiers (a,b,i). Only 181 // one can be specified. 182 unsigned NumPositional = 0; 183 184 // Keep track of which operation was requested 185 ArchiveOperation Operation = NoOperation; 186 187 for(unsigned i=0; i<Options.size(); ++i) { 188 switch(Options[i]) { 189 case 'd': ++NumOperations; Operation = Delete; break; 190 case 'm': ++NumOperations; Operation = Move ; break; 191 case 'p': ++NumOperations; Operation = Print; break; 192 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break; 193 case 't': ++NumOperations; Operation = DisplayTable; break; 194 case 'x': ++NumOperations; Operation = Extract; break; 195 case 'c': Create = true; break; 196 case 'f': TruncateNames = true; break; 197 case 'k': DontSkipBytecode = true; break; 198 case 'l': /* accepted but unused */ break; 199 case 'o': OriginalDates = true; break; 200 case 'P': FullPath = true; break; 201 case 'R': RecurseDirectories = true; break; 202 case 's': SymTable = true; break; 203 case 'S': SymTable = false; break; 204 case 'u': OnlyUpdate = true; break; 205 case 'v': Verbose = true; break; 206 case 'V': Verbose = ReallyVerbose = true; break; 207 case 'z': Compression = true; break; 208 case 'a': 209 getRelPos(); 210 AddAfter = true; 211 NumPositional++; 212 break; 213 case 'b': 214 getRelPos(); 215 AddBefore = true; 216 NumPositional++; 217 break; 218 case 'i': 219 getRelPos(); 220 InsertBefore = true; 221 NumPositional++; 222 break; 223 case 'N': 224 getCount(); 225 UseCount = true; 226 break; 227 default: 228 cl::PrintHelpMessage(); 229 } 230 } 231 232 // At this point, the next thing on the command line must be 233 // the archive name. 234 getArchive(); 235 236 // Everything on the command line at this point is a member. 237 getMembers(); 238 239 // Perform various checks on the operation/modifier specification 240 // to make sure we are dealing with a legal request. 241 if (NumOperations == 0) 242 throw "You must specify at least one of the operations"; 243 if (NumOperations > 1) 244 throw "Only one operation may be specified"; 245 if (NumPositional > 1) 246 throw "You may only specify one of a, b, and i modifiers"; 247 if (AddAfter || AddBefore || InsertBefore) 248 if (Operation != Move && Operation != ReplaceOrInsert) 249 throw "The 'a', 'b' and 'i' modifiers can only be specified with " 250 "the 'm' or 'r' operations"; 251 if (RecurseDirectories && Operation != ReplaceOrInsert) 252 throw "The 'R' modifiers is only applicabe to the 'r' operation"; 253 if (OriginalDates && Operation != Extract) 254 throw "The 'o' modifier is only applicable to the 'x' operation"; 255 if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert) 256 throw "The 'f' modifier is only applicable to the 'q' and 'r' operations"; 257 if (OnlyUpdate && Operation != ReplaceOrInsert) 258 throw "The 'u' modifier is only applicable to the 'r' operation"; 259 if (Compression && Operation!=ReplaceOrInsert && Operation!=Extract) 260 throw "The 'z' modifier is only applicable to the 'r' and 'x' operations"; 261 if (Count > 1 && Members.size() > 1) 262 throw "Only one member name may be specified with the 'N' modifier"; 263 264 // Return the parsed operation to the caller 265 return Operation; 266} 267 268// recurseDirectories - Implements the "R" modifier. This function scans through 269// the Paths vector (built by buildPaths, below) and replaces any directories it 270// finds with all the files in that directory (recursively). It uses the 271// sys::Path::getDirectoryContent method to perform the actual directory scans. 272std::set<sys::Path> recurseDirectories(const sys::Path& path) { 273 assert(path.isDirectory() && "Oops, can't recurse a file"); 274 std::set<sys::Path> result; 275 if (RecurseDirectories) { 276 std::set<sys::Path> content; 277 path.getDirectoryContents(content); 278 for (std::set<sys::Path>::iterator I = content.begin(), E = content.end(); 279 I != E; ++I) { 280 if (I->isDirectory()) { 281 std::set<sys::Path> moreResults = recurseDirectories(*I); 282 result.insert(moreResults.begin(), moreResults.end()); 283 } else { 284 result.insert(*I); 285 } 286 } 287 } 288 return result; 289} 290 291// buildPaths - Convert the strings in the Members vector to sys::Path objects 292// and make sure they are valid and exist exist. This check is only needed for 293// the operations that add/replace files to the archive ('q' and 'r') 294void buildPaths(bool checkExistence = true) { 295 for (unsigned i = 0; i < Members.size(); i++) { 296 sys::Path aPath; 297 if (!aPath.set(Members[i])) 298 throw std::string("File member name invalid: ") + Members[i]; 299 if (checkExistence) { 300 if (!aPath.exists()) 301 throw std::string("File does not exist: ") + Members[i]; 302 sys::Path::StatusInfo si; 303 aPath.getStatusInfo(si); 304 if (si.isDir) { 305 std::set<sys::Path> dirpaths = recurseDirectories(aPath); 306 Paths.insert(dirpaths.begin(),dirpaths.end()); 307 } else { 308 Paths.insert(aPath); 309 } 310 } else { 311 Paths.insert(aPath); 312 } 313 } 314} 315 316// printSymbolTable - print out the archive's symbol table. 317void printSymbolTable() { 318 std::cout << "\nArchive Symbol Table:\n"; 319 const Archive::SymTabType& symtab = TheArchive->getSymbolTable(); 320 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end(); 321 I != E; ++I ) { 322 unsigned offset = TheArchive->getFirstFileOffset() + I->second; 323 std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n"; 324 } 325} 326 327// doPrint - Implements the 'p' operation. This function traverses the archive 328// looking for members that match the path list. It is careful to uncompress 329// things that should be and to skip bytecode files unless the 'k' modifier was 330// given. 331void doPrint() { 332 buildPaths(false); 333 unsigned countDown = Count; 334 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 335 I != E; ++I ) { 336 if (Paths.empty() || 337 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) { 338 if (countDown == 1) { 339 const char* data = reinterpret_cast<const char*>(I->getData()); 340 341 // Skip things that don't make sense to print 342 if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() || 343 I->isBSD4SymbolTable() || (!DontSkipBytecode && 344 (I->isBytecode() || I->isCompressedBytecode()))) 345 continue; 346 347 if (Verbose) 348 std::cout << "Printing " << I->getPath().toString() << "\n"; 349 350 if (I->isCompressedBytecode()) 351 Compressor::decompressToStream(data+4,I->getSize()-4,std::cout); 352 else if (I->isCompressed()) { 353 Compressor::decompressToStream(data,I->getSize(),std::cout); 354 } else { 355 unsigned len = I->getSize(); 356 std::cout.write(data, len); 357 } 358 } else { 359 countDown--; 360 } 361 } 362 } 363} 364 365// putMode - utility function for printing out the file mode when the 't' 366// operation is in verbose mode. 367void printMode(unsigned mode) { 368 if (mode & 004) 369 std::cout << "r"; 370 else 371 std::cout << "-"; 372 if (mode & 002) 373 std::cout << "w"; 374 else 375 std::cout << "-"; 376 if (mode & 001) 377 std::cout << "x"; 378 else 379 std::cout << "-"; 380} 381 382// doDisplayTable - Implement the 't' operation. This function prints out just 383// the file names of each of the members. However, if verbose mode is requested 384// ('v' modifier) then the file type, permission mode, user, group, size, and 385// modification time are also printed. 386void doDisplayTable() { 387 buildPaths(false); 388 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 389 I != E; ++I ) { 390 if (Paths.empty() || 391 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) { 392 if (Verbose) { 393 // FIXME: Output should be this format: 394 // Zrw-r--r-- 500/ 500 525 Nov 8 17:42 2004 Makefile 395 if (I->isBytecode()) 396 std::cout << "b"; 397 else if (I->isCompressedBytecode()) 398 std::cout << "B"; 399 else if (I->isCompressed()) 400 std::cout << "Z"; 401 else 402 std::cout << " "; 403 unsigned mode = I->getMode(); 404 printMode((mode >> 6) & 007); 405 printMode((mode >> 3) & 007); 406 printMode(mode & 007); 407 std::cout << " " << std::setw(4) << I->getUser(); 408 std::cout << "/" << std::setw(4) << I->getGroup(); 409 std::cout << " " << std::setw(8) << I->getSize(); 410 std::cout << " " << std::setw(20) << 411 I->getModTime().toString().substr(4); 412 std::cout << " " << I->getPath().toString() << "\n"; 413 } else { 414 std::cout << I->getPath().toString() << "\n"; 415 } 416 } 417 } 418 if (ReallyVerbose) 419 printSymbolTable(); 420} 421 422// doExtract - Implement the 'x' operation. This function extracts files back to 423// the file system, making sure to uncompress any that were compressed. 424void doExtract() { 425 buildPaths(false); 426 unsigned countDown = Count; 427 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 428 I != E; ++I ) { 429 if (Paths.empty() || 430 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) { 431 432 // Make sure the intervening directories are created 433 if (I->hasPath()) { 434 sys::Path dirs(I->getPath()); 435 dirs.eraseComponent(); 436 dirs.createDirectoryOnDisk(/*create_parents=*/true); 437 } 438 439 // Open up a file stream for writing 440 std::ios::openmode io_mode = std::ios::out | std::ios::trunc | 441 std::ios::binary; 442 std::ofstream file(I->getPath().c_str(), io_mode); 443 444 // Get the data and its length 445 const char* data = reinterpret_cast<const char*>(I->getData()); 446 unsigned len = I->getSize(); 447 448 // Write the data, making sure to uncompress things first 449 if (I->isCompressed()) { 450 Compressor::decompressToStream(data,len,file); 451 } else { 452 file.write(data,len); 453 } 454 file.close(); 455 456 // If we're supposed to retain the original modification times, etc. do so 457 // now. 458 if (OriginalDates) 459 I->getPath().setStatusInfoOnDisk(I->getStatusInfo()); 460 } 461 } 462} 463 464// doDelete - Implement the delete operation. This function deletes zero or more 465// members from the archive. Note that if the count is specified, there should 466// be no more than one path in the Paths list or else this algorithm breaks. 467// That check is enforced in parseCommandLine (above). 468void doDelete() { 469 buildPaths(false); 470 if (Paths.empty()) return; 471 unsigned countDown = Count; 472 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 473 I != E; ) { 474 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) { 475 if (countDown == 1) { 476 Archive::iterator J = I; 477 ++I; 478 TheArchive->erase(J); 479 } else 480 countDown--; 481 } else { 482 ++I; 483 } 484 } 485 486 // We're done editting, reconstruct the archive. 487 TheArchive->writeToDisk(SymTable,TruncateNames,Compression); 488 if (ReallyVerbose) 489 printSymbolTable(); 490} 491 492// doMore - Implement the move operation. This function re-arranges just the 493// order of the archive members so that when the archive is written the move 494// of the members is accomplished. Note the use of the RelPos variable to 495// determine where the items should be moved to. 496void doMove() { 497 498 buildPaths(false); 499 500 // By default and convention the place to move members to is the end of the 501 // archive. 502 Archive::iterator moveto_spot = TheArchive->end(); 503 504 // However, if the relative positioning modifiers were used, we need to scan 505 // the archive to find the member in question. If we don't find it, its no 506 // crime, we just move to the end. 507 if (AddBefore || InsertBefore || AddAfter) { 508 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end(); 509 I != E; ++I ) { 510 if (RelPos == I->getPath().toString()) { 511 if (AddAfter) { 512 moveto_spot = I; 513 moveto_spot++; 514 } else { 515 moveto_spot = I; 516 } 517 break; 518 } 519 } 520 } 521 522 // Keep a list of the paths remaining to be moved 523 std::set<sys::Path> remaining(Paths); 524 525 // Scan the archive again, this time looking for the members to move to the 526 // moveto_spot. 527 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end(); 528 I != E && !remaining.empty(); ++I ) { 529 std::set<sys::Path>::iterator found = 530 std::find(remaining.begin(),remaining.end(),I->getPath()); 531 if (found != remaining.end()) { 532 if (I != moveto_spot) 533 TheArchive->splice(moveto_spot,*TheArchive,I); 534 remaining.erase(found); 535 } 536 } 537 538 // We're done editting, reconstruct the archive. 539 TheArchive->writeToDisk(SymTable,TruncateNames,Compression); 540 if (ReallyVerbose) 541 printSymbolTable(); 542} 543 544// doQuickAppend - Implements the 'q' operation. This function just 545// indiscriminantly adds the members to the archive and rebuilds it. 546void doQuickAppend() { 547 // Get the list of paths to append. 548 buildPaths(true); 549 if (Paths.empty()) return; 550 551 // Append them quickly. 552 for (std::set<sys::Path>::iterator PI = Paths.begin(), PE = Paths.end(); 553 PI != PE; ++PI) { 554 TheArchive->addFileBefore(*PI,TheArchive->end()); 555 } 556 557 // We're done editting, reconstruct the archive. 558 TheArchive->writeToDisk(SymTable,TruncateNames,Compression); 559 if (ReallyVerbose) 560 printSymbolTable(); 561} 562 563// doReplaceOrInsert - Implements the 'r' operation. This function will replace 564// any existing files or insert new ones into the archive. 565void doReplaceOrInsert() { 566 567 // Build the list of files to be added/replaced. 568 buildPaths(true); 569 if (Paths.empty()) return; 570 571 // Keep track of the paths that remain to be inserted. 572 std::set<sys::Path> remaining(Paths); 573 574 // Default the insertion spot to the end of the archive 575 Archive::iterator insert_spot = TheArchive->end(); 576 577 // Iterate over the archive contents 578 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 579 I != E && !remaining.empty(); ++I ) { 580 581 // Determine if this archive member matches one of the paths we're trying 582 // to replace. 583 584 std::set<sys::Path>::iterator found = remaining.end(); 585 for (std::set<sys::Path>::iterator RI = remaining.begin(), 586 RE = remaining.end(); RI != RE; ++RI ) { 587 std::string compare(RI->toString()); 588 if (TruncateNames && compare.length() > 15) { 589 const char* nm = compare.c_str(); 590 unsigned len = compare.length(); 591 size_t slashpos = compare.rfind('/'); 592 if (slashpos != std::string::npos) { 593 nm += slashpos + 1; 594 len -= slashpos +1; 595 } 596 if (len > 15) 597 len = 15; 598 compare.assign(nm,len); 599 } 600 if (compare == I->getPath().toString()) { 601 found = RI; 602 break; 603 } 604 } 605 606 if (found != remaining.end()) { 607 sys::Path::StatusInfo si; 608 found->getStatusInfo(si); 609 if (si.isDir) { 610 if (OnlyUpdate) { 611 // Replace the item only if it is newer. 612 if (si.modTime > I->getModTime()) 613 I->replaceWith(*found); 614 } else { 615 // Replace the item regardless of time stamp 616 I->replaceWith(*found); 617 } 618 } else { 619 // We purposefully ignore directories. 620 } 621 622 // Remove it from our "to do" list 623 remaining.erase(found); 624 } 625 626 // Determine if this is the place where we should insert 627 if ((AddBefore || InsertBefore) && (RelPos == I->getPath().toString())) 628 insert_spot = I; 629 else if (AddAfter && (RelPos == I->getPath().toString())) { 630 insert_spot = I; 631 insert_spot++; 632 } 633 } 634 635 // If we didn't replace all the members, some will remain and need to be 636 // inserted at the previously computed insert-spot. 637 if (!remaining.empty()) { 638 for (std::set<sys::Path>::iterator PI = remaining.begin(), 639 PE = remaining.end(); PI != PE; ++PI) { 640 TheArchive->addFileBefore(*PI,insert_spot); 641 } 642 } 643 644 // We're done editting, reconstruct the archive. 645 TheArchive->writeToDisk(SymTable,TruncateNames,Compression); 646 if (ReallyVerbose) 647 printSymbolTable(); 648} 649 650// main - main program for llvm-ar .. see comments in the code 651int main(int argc, char **argv) { 652 653 // Have the command line options parsed and handle things 654 // like --help and --version. 655 cl::ParseCommandLineOptions(argc, argv, 656 " LLVM Archiver (llvm-ar)\n\n" 657 " This program archives bytecode files into single libraries\n" 658 ); 659 660 // Print a stack trace if we signal out. 661 sys::PrintStackTraceOnErrorSignal(); 662 663 int exitCode = 0; 664 665 // Make sure we don't exit with "unhandled exception". 666 try { 667 // Do our own parsing of the command line because the CommandLine utility 668 // can't handle the grouped positional parameters without a dash. 669 ArchiveOperation Operation = parseCommandLine(); 670 671 // Check the path name of the archive 672 sys::Path ArchivePath; 673 if (!ArchivePath.set(ArchiveName)) 674 throw std::string("Archive name invalid: ") + ArchiveName; 675 676 // Create or open the archive object. 677 if (!ArchivePath.exists()) { 678 // Produce a warning if we should and we're creating the archive 679 if (!Create) 680 std::cerr << argv[0] << ": creating " << ArchivePath.toString() << "\n"; 681 TheArchive = Archive::CreateEmpty(ArchivePath); 682 } else { 683 std::string Error; 684 TheArchive = Archive::OpenAndLoad(ArchivePath, &Error); 685 if (TheArchive == 0) { 686 std::cerr << argv[0] << ": error loading '" << ArchivePath << "': " 687 << Error << "!\n"; 688 return 1; 689 } 690 } 691 692 // Make sure we're not fooling ourselves. 693 assert(TheArchive && "Unable to instantiate the archive"); 694 695 // Make sure we clean up the archive even on failure. 696 std::auto_ptr<Archive> AutoArchive(TheArchive); 697 698 // Perform the operation 699 switch (Operation) { 700 case Print: doPrint(); break; 701 case Delete: doDelete(); break; 702 case Move: doMove(); break; 703 case QuickAppend: /* FALL THROUGH */ 704 case ReplaceOrInsert: doReplaceOrInsert(); break; 705 case DisplayTable: doDisplayTable(); break; 706 case Extract: doExtract(); break; 707 case NoOperation: 708 std::cerr << argv[0] << ": No operation was selected.\n"; 709 break; 710 } 711 } catch (const char*msg) { 712 // These errors are usage errors, thrown only by the various checks in the 713 // code above. 714 std::cerr << argv[0] << ": " << msg << "\n\n"; 715 cl::PrintHelpMessage(); 716 exitCode = 1; 717 } catch (const std::string& msg) { 718 // These errors are thrown by LLVM libraries (e.g. lib System) and represent 719 // a more serious error so we bump the exitCode and don't print the usage. 720 std::cerr << argv[0] << ": " << msg << "\n"; 721 exitCode = 2; 722 } catch (...) { 723 // This really shouldn't happen, but just in case .... 724 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n"; 725 exitCode = 3; 726 } 727 728 // Return result code back to operating system. 729 return exitCode; 730} 731