llvm-ar.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/IR/LLVMContext.h"
  17. #include "llvm/IR/Module.h"
  18. #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
  19. #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
  20. #include "llvm/Object/Archive.h"
  21. #include "llvm/Object/ArchiveWriter.h"
  22. #include "llvm/Object/MachO.h"
  23. #include "llvm/Object/ObjectFile.h"
  24. #include "llvm/Support/Chrono.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/Errc.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/Format.h"
  29. #include "llvm/Support/LineIterator.h"
  30. #include "llvm/Support/ManagedStatic.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/Path.h"
  33. #include "llvm/Support/PrettyStackTrace.h"
  34. #include "llvm/Support/Signals.h"
  35. #include "llvm/Support/TargetSelect.h"
  36. #include "llvm/Support/ToolOutputFile.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <algorithm>
  39. #include <cstdlib>
  40. #include <memory>
  41. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  42. #include <unistd.h>
  43. #else
  44. #include <io.h>
  45. #endif
  46. using namespace llvm;
  47. // The name this program was invoked as.
  48. static StringRef ToolName;
  49. // Show the error message and exit.
  50. LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
  51. errs() << ToolName << ": " << Error << ".\n";
  52. exit(1);
  53. }
  54. static void failIfError(std::error_code EC, Twine Context = "") {
  55. if (!EC)
  56. return;
  57. std::string ContextStr = Context.str();
  58. if (ContextStr == "")
  59. fail(EC.message());
  60. fail(Context + ": " + EC.message());
  61. }
  62. static void failIfError(Error E, Twine Context = "") {
  63. if (!E)
  64. return;
  65. handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
  66. std::string ContextStr = Context.str();
  67. if (ContextStr == "")
  68. fail(EIB.message());
  69. fail(Context + ": " + EIB.message());
  70. });
  71. }
  72. // llvm-ar/llvm-ranlib remaining positional arguments.
  73. static cl::list<std::string>
  74. RestOfArgs(cl::Positional, cl::ZeroOrMore,
  75. cl::desc("[relpos] [count] <archive-file> [members]..."));
  76. static cl::opt<bool> MRI("M", cl::desc(""));
  77. static cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
  78. namespace {
  79. enum Format { Default, GNU, BSD, DARWIN };
  80. }
  81. static cl::opt<Format>
  82. FormatOpt("format", cl::desc("Archive format to create"),
  83. cl::values(clEnumValN(Default, "default", "default"),
  84. clEnumValN(GNU, "gnu", "gnu"),
  85. clEnumValN(DARWIN, "darwin", "darwin"),
  86. clEnumValN(BSD, "bsd", "bsd")));
  87. static std::string Options;
  88. // Provide additional help output explaining the operations and modifiers of
  89. // llvm-ar. This object instructs the CommandLine library to print the text of
  90. // the constructor when the --help option is given.
  91. static cl::extrahelp MoreHelp(
  92. "\nOPERATIONS:\n"
  93. " d[NsS] - delete file(s) from the archive\n"
  94. " m[abiSs] - move file(s) in the archive\n"
  95. " p[kN] - print file(s) found in the archive\n"
  96. " q[ufsS] - quick append file(s) to the archive\n"
  97. " r[abfiuRsS] - replace or insert file(s) into the archive\n"
  98. " t - display contents of archive\n"
  99. " x[No] - extract file(s) from the archive\n"
  100. "\nMODIFIERS (operation specific):\n"
  101. " [a] - put file(s) after [relpos]\n"
  102. " [b] - put file(s) before [relpos] (same as [i])\n"
  103. " [i] - put file(s) before [relpos] (same as [b])\n"
  104. " [o] - preserve original dates\n"
  105. " [s] - create an archive index (cf. ranlib)\n"
  106. " [S] - do not build a symbol table\n"
  107. " [T] - create a thin archive\n"
  108. " [u] - update only files newer than archive contents\n"
  109. "\nMODIFIERS (generic):\n"
  110. " [c] - do not warn if the library had to be created\n"
  111. " [v] - be verbose about actions taken\n"
  112. );
  113. // This enumeration delineates the kinds of operations on an archive
  114. // that are permitted.
  115. enum ArchiveOperation {
  116. Print, ///< Print the contents of the archive
  117. Delete, ///< Delete the specified members
  118. Move, ///< Move members to end or as given by {a,b,i} modifiers
  119. QuickAppend, ///< Quickly append to end of archive
  120. ReplaceOrInsert, ///< Replace or Insert members
  121. DisplayTable, ///< Display the table of contents
  122. Extract, ///< Extract files back to file system
  123. CreateSymTab ///< Create a symbol table in an existing archive
  124. };
  125. // Modifiers to follow operation to vary behavior
  126. static bool AddAfter = false; ///< 'a' modifier
  127. static bool AddBefore = false; ///< 'b' modifier
  128. static bool Create = false; ///< 'c' modifier
  129. static bool OriginalDates = false; ///< 'o' modifier
  130. static bool OnlyUpdate = false; ///< 'u' modifier
  131. static bool Verbose = false; ///< 'v' modifier
  132. static bool Symtab = true; ///< 's' modifier
  133. static bool Deterministic = true; ///< 'D' and 'U' modifiers
  134. static bool Thin = false; ///< 'T' modifier
  135. // Relative Positional Argument (for insert/move). This variable holds
  136. // the name of the archive member to which the 'a', 'b' or 'i' modifier
  137. // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
  138. // one variable.
  139. static std::string RelPos;
  140. // This variable holds the name of the archive file as given on the
  141. // command line.
  142. static std::string ArchiveName;
  143. // This variable holds the list of member files to proecess, as given
  144. // on the command line.
  145. static std::vector<StringRef> Members;
  146. // Show the error message, the help message and exit.
  147. LLVM_ATTRIBUTE_NORETURN static void
  148. show_help(const std::string &msg) {
  149. errs() << ToolName << ": " << msg << "\n\n";
  150. cl::PrintHelpMessage();
  151. exit(1);
  152. }
  153. // Extract the member filename from the command line for the [relpos] argument
  154. // associated with a, b, and i modifiers
  155. static void getRelPos() {
  156. if(RestOfArgs.size() == 0)
  157. show_help("Expected [relpos] for a, b, or i modifier");
  158. RelPos = RestOfArgs[0];
  159. RestOfArgs.erase(RestOfArgs.begin());
  160. }
  161. static void getOptions() {
  162. if(RestOfArgs.size() == 0)
  163. show_help("Expected options");
  164. Options = RestOfArgs[0];
  165. RestOfArgs.erase(RestOfArgs.begin());
  166. }
  167. // Get the archive file name from the command line
  168. static void getArchive() {
  169. if(RestOfArgs.size() == 0)
  170. show_help("An archive name must be specified");
  171. ArchiveName = RestOfArgs[0];
  172. RestOfArgs.erase(RestOfArgs.begin());
  173. }
  174. // Copy over remaining items in RestOfArgs to our Members vector
  175. static void getMembers() {
  176. for (auto &Arg : RestOfArgs)
  177. Members.push_back(Arg);
  178. }
  179. static void runMRIScript();
  180. // Parse the command line options as presented and return the operation
  181. // specified. Process all modifiers and check to make sure that constraints on
  182. // modifier/operation pairs have not been violated.
  183. static ArchiveOperation parseCommandLine() {
  184. if (MRI) {
  185. if (!RestOfArgs.empty())
  186. fail("Cannot mix -M and other options");
  187. runMRIScript();
  188. }
  189. getOptions();
  190. // Keep track of number of operations. We can only specify one
  191. // per execution.
  192. unsigned NumOperations = 0;
  193. // Keep track of the number of positional modifiers (a,b,i). Only
  194. // one can be specified.
  195. unsigned NumPositional = 0;
  196. // Keep track of which operation was requested
  197. ArchiveOperation Operation;
  198. bool MaybeJustCreateSymTab = false;
  199. for(unsigned i=0; i<Options.size(); ++i) {
  200. switch(Options[i]) {
  201. case 'd': ++NumOperations; Operation = Delete; break;
  202. case 'm': ++NumOperations; Operation = Move ; break;
  203. case 'p': ++NumOperations; Operation = Print; break;
  204. case 'q': ++NumOperations; Operation = QuickAppend; break;
  205. case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
  206. case 't': ++NumOperations; Operation = DisplayTable; break;
  207. case 'x': ++NumOperations; Operation = Extract; break;
  208. case 'c': Create = true; break;
  209. case 'l': /* accepted but unused */ break;
  210. case 'o': OriginalDates = true; break;
  211. case 's':
  212. Symtab = true;
  213. MaybeJustCreateSymTab = true;
  214. break;
  215. case 'S':
  216. Symtab = false;
  217. break;
  218. case 'u': OnlyUpdate = true; break;
  219. case 'v': Verbose = true; break;
  220. case 'a':
  221. getRelPos();
  222. AddAfter = true;
  223. NumPositional++;
  224. break;
  225. case 'b':
  226. getRelPos();
  227. AddBefore = true;
  228. NumPositional++;
  229. break;
  230. case 'i':
  231. getRelPos();
  232. AddBefore = true;
  233. NumPositional++;
  234. break;
  235. case 'D':
  236. Deterministic = true;
  237. break;
  238. case 'U':
  239. Deterministic = false;
  240. break;
  241. case 'T':
  242. Thin = true;
  243. break;
  244. default:
  245. cl::PrintHelpMessage();
  246. }
  247. }
  248. // At this point, the next thing on the command line must be
  249. // the archive name.
  250. getArchive();
  251. // Everything on the command line at this point is a member.
  252. getMembers();
  253. if (NumOperations == 0 && MaybeJustCreateSymTab) {
  254. NumOperations = 1;
  255. Operation = CreateSymTab;
  256. if (!Members.empty())
  257. show_help("The s operation takes only an archive as argument");
  258. }
  259. // Perform various checks on the operation/modifier specification
  260. // to make sure we are dealing with a legal request.
  261. if (NumOperations == 0)
  262. show_help("You must specify at least one of the operations");
  263. if (NumOperations > 1)
  264. show_help("Only one operation may be specified");
  265. if (NumPositional > 1)
  266. show_help("You may only specify one of a, b, and i modifiers");
  267. if (AddAfter || AddBefore) {
  268. if (Operation != Move && Operation != ReplaceOrInsert)
  269. show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
  270. "the 'm' or 'r' operations");
  271. }
  272. if (OriginalDates && Operation != Extract)
  273. show_help("The 'o' modifier is only applicable to the 'x' operation");
  274. if (OnlyUpdate && Operation != ReplaceOrInsert)
  275. show_help("The 'u' modifier is only applicable to the 'r' operation");
  276. // Return the parsed operation to the caller
  277. return Operation;
  278. }
  279. // Implements the 'p' operation. This function traverses the archive
  280. // looking for members that match the path list.
  281. static void doPrint(StringRef Name, const object::Archive::Child &C) {
  282. if (Verbose)
  283. outs() << "Printing " << Name << "\n";
  284. Expected<StringRef> DataOrErr = C.getBuffer();
  285. failIfError(DataOrErr.takeError());
  286. StringRef Data = *DataOrErr;
  287. outs().write(Data.data(), Data.size());
  288. }
  289. // Utility function for printing out the file mode when the 't' operation is in
  290. // verbose mode.
  291. static void printMode(unsigned mode) {
  292. outs() << ((mode & 004) ? "r" : "-");
  293. outs() << ((mode & 002) ? "w" : "-");
  294. outs() << ((mode & 001) ? "x" : "-");
  295. }
  296. // Implement the 't' operation. This function prints out just
  297. // the file names of each of the members. However, if verbose mode is requested
  298. // ('v' modifier) then the file type, permission mode, user, group, size, and
  299. // modification time are also printed.
  300. static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
  301. if (Verbose) {
  302. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  303. failIfError(ModeOrErr.takeError());
  304. sys::fs::perms Mode = ModeOrErr.get();
  305. printMode((Mode >> 6) & 007);
  306. printMode((Mode >> 3) & 007);
  307. printMode(Mode & 007);
  308. Expected<unsigned> UIDOrErr = C.getUID();
  309. failIfError(UIDOrErr.takeError());
  310. outs() << ' ' << UIDOrErr.get();
  311. Expected<unsigned> GIDOrErr = C.getGID();
  312. failIfError(GIDOrErr.takeError());
  313. outs() << '/' << GIDOrErr.get();
  314. Expected<uint64_t> Size = C.getSize();
  315. failIfError(Size.takeError());
  316. outs() << ' ' << format("%6llu", Size.get());
  317. auto ModTimeOrErr = C.getLastModified();
  318. failIfError(ModTimeOrErr.takeError());
  319. outs() << ' ' << ModTimeOrErr.get();
  320. outs() << ' ';
  321. }
  322. if (C.getParent()->isThin()) {
  323. outs() << sys::path::parent_path(ArchiveName);
  324. outs() << '/';
  325. }
  326. outs() << Name << "\n";
  327. }
  328. // Implement the 'x' operation. This function extracts files back to the file
  329. // system.
  330. static void doExtract(StringRef Name, const object::Archive::Child &C) {
  331. // Retain the original mode.
  332. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  333. failIfError(ModeOrErr.takeError());
  334. sys::fs::perms Mode = ModeOrErr.get();
  335. int FD;
  336. failIfError(sys::fs::openFileForWrite(sys::path::filename(Name), FD,
  337. sys::fs::F_None, Mode),
  338. Name);
  339. {
  340. raw_fd_ostream file(FD, false);
  341. // Get the data and its length
  342. Expected<StringRef> BufOrErr = C.getBuffer();
  343. failIfError(BufOrErr.takeError());
  344. StringRef Data = BufOrErr.get();
  345. // Write the data.
  346. file.write(Data.data(), Data.size());
  347. }
  348. // If we're supposed to retain the original modification times, etc. do so
  349. // now.
  350. if (OriginalDates) {
  351. auto ModTimeOrErr = C.getLastModified();
  352. failIfError(ModTimeOrErr.takeError());
  353. failIfError(
  354. sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
  355. }
  356. if (close(FD))
  357. fail("Could not close the file");
  358. }
  359. static bool shouldCreateArchive(ArchiveOperation Op) {
  360. switch (Op) {
  361. case Print:
  362. case Delete:
  363. case Move:
  364. case DisplayTable:
  365. case Extract:
  366. case CreateSymTab:
  367. return false;
  368. case QuickAppend:
  369. case ReplaceOrInsert:
  370. return true;
  371. }
  372. llvm_unreachable("Missing entry in covered switch.");
  373. }
  374. static void performReadOperation(ArchiveOperation Operation,
  375. object::Archive *OldArchive) {
  376. if (Operation == Extract && OldArchive->isThin())
  377. fail("extracting from a thin archive is not supported");
  378. bool Filter = !Members.empty();
  379. {
  380. Error Err = Error::success();
  381. for (auto &C : OldArchive->children(Err)) {
  382. Expected<StringRef> NameOrErr = C.getName();
  383. failIfError(NameOrErr.takeError());
  384. StringRef Name = NameOrErr.get();
  385. if (Filter) {
  386. auto I = find(Members, Name);
  387. if (I == Members.end())
  388. continue;
  389. Members.erase(I);
  390. }
  391. switch (Operation) {
  392. default:
  393. llvm_unreachable("Not a read operation");
  394. case Print:
  395. doPrint(Name, C);
  396. break;
  397. case DisplayTable:
  398. doDisplayTable(Name, C);
  399. break;
  400. case Extract:
  401. doExtract(Name, C);
  402. break;
  403. }
  404. }
  405. failIfError(std::move(Err));
  406. }
  407. if (Members.empty())
  408. return;
  409. for (StringRef Name : Members)
  410. errs() << Name << " was not found\n";
  411. exit(1);
  412. }
  413. static void addMember(std::vector<NewArchiveMember> &Members,
  414. StringRef FileName, int Pos = -1) {
  415. Expected<NewArchiveMember> NMOrErr =
  416. NewArchiveMember::getFile(FileName, Deterministic);
  417. failIfError(NMOrErr.takeError(), FileName);
  418. // Use the basename of the object path for the member name.
  419. NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
  420. if (Pos == -1)
  421. Members.push_back(std::move(*NMOrErr));
  422. else
  423. Members[Pos] = std::move(*NMOrErr);
  424. }
  425. static void addMember(std::vector<NewArchiveMember> &Members,
  426. const object::Archive::Child &M, int Pos = -1) {
  427. if (Thin && !M.getParent()->isThin())
  428. fail("Cannot convert a regular archive to a thin one");
  429. Expected<NewArchiveMember> NMOrErr =
  430. NewArchiveMember::getOldMember(M, Deterministic);
  431. failIfError(NMOrErr.takeError());
  432. if (Pos == -1)
  433. Members.push_back(std::move(*NMOrErr));
  434. else
  435. Members[Pos] = std::move(*NMOrErr);
  436. }
  437. enum InsertAction {
  438. IA_AddOldMember,
  439. IA_AddNewMember,
  440. IA_Delete,
  441. IA_MoveOldMember,
  442. IA_MoveNewMember
  443. };
  444. static InsertAction computeInsertAction(ArchiveOperation Operation,
  445. const object::Archive::Child &Member,
  446. StringRef Name,
  447. std::vector<StringRef>::iterator &Pos) {
  448. if (Operation == QuickAppend || Members.empty())
  449. return IA_AddOldMember;
  450. auto MI = find_if(Members, [Name](StringRef Path) {
  451. return Name == sys::path::filename(Path);
  452. });
  453. if (MI == Members.end())
  454. return IA_AddOldMember;
  455. Pos = MI;
  456. if (Operation == Delete)
  457. return IA_Delete;
  458. if (Operation == Move)
  459. return IA_MoveOldMember;
  460. if (Operation == ReplaceOrInsert) {
  461. StringRef PosName = sys::path::filename(RelPos);
  462. if (!OnlyUpdate) {
  463. if (PosName.empty())
  464. return IA_AddNewMember;
  465. return IA_MoveNewMember;
  466. }
  467. // We could try to optimize this to a fstat, but it is not a common
  468. // operation.
  469. sys::fs::file_status Status;
  470. failIfError(sys::fs::status(*MI, Status), *MI);
  471. auto ModTimeOrErr = Member.getLastModified();
  472. failIfError(ModTimeOrErr.takeError());
  473. if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
  474. if (PosName.empty())
  475. return IA_AddOldMember;
  476. return IA_MoveOldMember;
  477. }
  478. if (PosName.empty())
  479. return IA_AddNewMember;
  480. return IA_MoveNewMember;
  481. }
  482. llvm_unreachable("No such operation");
  483. }
  484. // We have to walk this twice and computing it is not trivial, so creating an
  485. // explicit std::vector is actually fairly efficient.
  486. static std::vector<NewArchiveMember>
  487. computeNewArchiveMembers(ArchiveOperation Operation,
  488. object::Archive *OldArchive) {
  489. std::vector<NewArchiveMember> Ret;
  490. std::vector<NewArchiveMember> Moved;
  491. int InsertPos = -1;
  492. StringRef PosName = sys::path::filename(RelPos);
  493. if (OldArchive) {
  494. Error Err = Error::success();
  495. for (auto &Child : OldArchive->children(Err)) {
  496. int Pos = Ret.size();
  497. Expected<StringRef> NameOrErr = Child.getName();
  498. failIfError(NameOrErr.takeError());
  499. StringRef Name = NameOrErr.get();
  500. if (Name == PosName) {
  501. assert(AddAfter || AddBefore);
  502. if (AddBefore)
  503. InsertPos = Pos;
  504. else
  505. InsertPos = Pos + 1;
  506. }
  507. std::vector<StringRef>::iterator MemberI = Members.end();
  508. InsertAction Action =
  509. computeInsertAction(Operation, Child, Name, MemberI);
  510. switch (Action) {
  511. case IA_AddOldMember:
  512. addMember(Ret, Child);
  513. break;
  514. case IA_AddNewMember:
  515. addMember(Ret, *MemberI);
  516. break;
  517. case IA_Delete:
  518. break;
  519. case IA_MoveOldMember:
  520. addMember(Moved, Child);
  521. break;
  522. case IA_MoveNewMember:
  523. addMember(Moved, *MemberI);
  524. break;
  525. }
  526. if (MemberI != Members.end())
  527. Members.erase(MemberI);
  528. }
  529. failIfError(std::move(Err));
  530. }
  531. if (Operation == Delete)
  532. return Ret;
  533. if (!RelPos.empty() && InsertPos == -1)
  534. fail("Insertion point not found");
  535. if (RelPos.empty())
  536. InsertPos = Ret.size();
  537. assert(unsigned(InsertPos) <= Ret.size());
  538. int Pos = InsertPos;
  539. for (auto &M : Moved) {
  540. Ret.insert(Ret.begin() + Pos, std::move(M));
  541. ++Pos;
  542. }
  543. for (unsigned I = 0; I != Members.size(); ++I)
  544. Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
  545. Pos = InsertPos;
  546. for (auto &Member : Members) {
  547. addMember(Ret, Member, Pos);
  548. ++Pos;
  549. }
  550. return Ret;
  551. }
  552. static object::Archive::Kind getDefaultForHost() {
  553. return Triple(sys::getProcessTriple()).isOSDarwin()
  554. ? object::Archive::K_DARWIN
  555. : object::Archive::K_GNU;
  556. }
  557. static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
  558. Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
  559. object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
  560. if (OptionalObject)
  561. return isa<object::MachOObjectFile>(**OptionalObject)
  562. ? object::Archive::K_DARWIN
  563. : object::Archive::K_GNU;
  564. // squelch the error in case we had a non-object file
  565. consumeError(OptionalObject.takeError());
  566. return getDefaultForHost();
  567. }
  568. static void
  569. performWriteOperation(ArchiveOperation Operation,
  570. object::Archive *OldArchive,
  571. std::unique_ptr<MemoryBuffer> OldArchiveBuf,
  572. std::vector<NewArchiveMember> *NewMembersP) {
  573. std::vector<NewArchiveMember> NewMembers;
  574. if (!NewMembersP)
  575. NewMembers = computeNewArchiveMembers(Operation, OldArchive);
  576. object::Archive::Kind Kind;
  577. switch (FormatOpt) {
  578. case Default:
  579. if (Thin)
  580. Kind = object::Archive::K_GNU;
  581. else if (OldArchive)
  582. Kind = OldArchive->kind();
  583. else if (NewMembersP)
  584. Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
  585. : getDefaultForHost();
  586. else
  587. Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
  588. : getDefaultForHost();
  589. break;
  590. case GNU:
  591. Kind = object::Archive::K_GNU;
  592. break;
  593. case BSD:
  594. if (Thin)
  595. fail("Only the gnu format has a thin mode");
  596. Kind = object::Archive::K_BSD;
  597. break;
  598. case DARWIN:
  599. if (Thin)
  600. fail("Only the gnu format has a thin mode");
  601. Kind = object::Archive::K_DARWIN;
  602. break;
  603. }
  604. std::error_code EC =
  605. writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
  606. Kind, Deterministic, Thin, std::move(OldArchiveBuf));
  607. failIfError(EC, ArchiveName);
  608. }
  609. static void createSymbolTable(object::Archive *OldArchive) {
  610. // When an archive is created or modified, if the s option is given, the
  611. // resulting archive will have a current symbol table. If the S option
  612. // is given, it will have no symbol table.
  613. // In summary, we only need to update the symbol table if we have none.
  614. // This is actually very common because of broken build systems that think
  615. // they have to run ranlib.
  616. if (OldArchive->hasSymbolTable())
  617. return;
  618. performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
  619. }
  620. static void performOperation(ArchiveOperation Operation,
  621. object::Archive *OldArchive,
  622. std::unique_ptr<MemoryBuffer> OldArchiveBuf,
  623. std::vector<NewArchiveMember> *NewMembers) {
  624. switch (Operation) {
  625. case Print:
  626. case DisplayTable:
  627. case Extract:
  628. performReadOperation(Operation, OldArchive);
  629. return;
  630. case Delete:
  631. case Move:
  632. case QuickAppend:
  633. case ReplaceOrInsert:
  634. performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
  635. NewMembers);
  636. return;
  637. case CreateSymTab:
  638. createSymbolTable(OldArchive);
  639. return;
  640. }
  641. llvm_unreachable("Unknown operation.");
  642. }
  643. static int performOperation(ArchiveOperation Operation,
  644. std::vector<NewArchiveMember> *NewMembers) {
  645. // Create or open the archive object.
  646. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
  647. MemoryBuffer::getFile(ArchiveName, -1, false);
  648. std::error_code EC = Buf.getError();
  649. if (EC && EC != errc::no_such_file_or_directory)
  650. fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
  651. if (!EC) {
  652. Error Err = Error::success();
  653. object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
  654. EC = errorToErrorCode(std::move(Err));
  655. failIfError(EC,
  656. "error loading '" + ArchiveName + "': " + EC.message() + "!");
  657. performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
  658. return 0;
  659. }
  660. assert(EC == errc::no_such_file_or_directory);
  661. if (!shouldCreateArchive(Operation)) {
  662. failIfError(EC, Twine("error loading '") + ArchiveName + "'");
  663. } else {
  664. if (!Create) {
  665. // Produce a warning if we should and we're creating the archive
  666. errs() << ToolName << ": creating " << ArchiveName << "\n";
  667. }
  668. }
  669. performOperation(Operation, nullptr, nullptr, NewMembers);
  670. return 0;
  671. }
  672. static void runMRIScript() {
  673. enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
  674. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
  675. failIfError(Buf.getError());
  676. const MemoryBuffer &Ref = *Buf.get();
  677. bool Saved = false;
  678. std::vector<NewArchiveMember> NewMembers;
  679. std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
  680. std::vector<std::unique_ptr<object::Archive>> Archives;
  681. for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
  682. StringRef Line = *I;
  683. StringRef CommandStr, Rest;
  684. std::tie(CommandStr, Rest) = Line.split(' ');
  685. Rest = Rest.trim();
  686. if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
  687. Rest = Rest.drop_front().drop_back();
  688. auto Command = StringSwitch<MRICommand>(CommandStr.lower())
  689. .Case("addlib", MRICommand::AddLib)
  690. .Case("addmod", MRICommand::AddMod)
  691. .Case("create", MRICommand::Create)
  692. .Case("save", MRICommand::Save)
  693. .Case("end", MRICommand::End)
  694. .Default(MRICommand::Invalid);
  695. switch (Command) {
  696. case MRICommand::AddLib: {
  697. auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
  698. failIfError(BufOrErr.getError(), "Could not open library");
  699. ArchiveBuffers.push_back(std::move(*BufOrErr));
  700. auto LibOrErr =
  701. object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
  702. failIfError(errorToErrorCode(LibOrErr.takeError()),
  703. "Could not parse library");
  704. Archives.push_back(std::move(*LibOrErr));
  705. object::Archive &Lib = *Archives.back();
  706. {
  707. Error Err = Error::success();
  708. for (auto &Member : Lib.children(Err))
  709. addMember(NewMembers, Member);
  710. failIfError(std::move(Err));
  711. }
  712. break;
  713. }
  714. case MRICommand::AddMod:
  715. addMember(NewMembers, Rest);
  716. break;
  717. case MRICommand::Create:
  718. Create = true;
  719. if (!ArchiveName.empty())
  720. fail("Editing multiple archives not supported");
  721. if (Saved)
  722. fail("File already saved");
  723. ArchiveName = Rest;
  724. break;
  725. case MRICommand::Save:
  726. Saved = true;
  727. break;
  728. case MRICommand::End:
  729. break;
  730. case MRICommand::Invalid:
  731. fail("Unknown command: " + CommandStr);
  732. }
  733. }
  734. // Nothing to do if not saved.
  735. if (Saved)
  736. performOperation(ReplaceOrInsert, &NewMembers);
  737. exit(0);
  738. }
  739. static int ar_main() {
  740. // Do our own parsing of the command line because the CommandLine utility
  741. // can't handle the grouped positional parameters without a dash.
  742. ArchiveOperation Operation = parseCommandLine();
  743. return performOperation(Operation, nullptr);
  744. }
  745. static int ranlib_main() {
  746. if (RestOfArgs.size() != 1)
  747. fail(ToolName + " takes just one archive as an argument");
  748. ArchiveName = RestOfArgs[0];
  749. return performOperation(CreateSymTab, nullptr);
  750. }
  751. int main(int argc, char **argv) {
  752. ToolName = argv[0];
  753. // Print a stack trace if we signal out.
  754. sys::PrintStackTraceOnErrorSignal(argv[0]);
  755. PrettyStackTraceProgram X(argc, argv);
  756. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  757. llvm::InitializeAllTargetInfos();
  758. llvm::InitializeAllTargetMCs();
  759. llvm::InitializeAllAsmParsers();
  760. StringRef Stem = sys::path::stem(ToolName);
  761. if (Stem.find("dlltool") != StringRef::npos)
  762. return dlltoolDriverMain(makeArrayRef(argv, argc));
  763. if (Stem.find("ranlib") == StringRef::npos &&
  764. Stem.find("lib") != StringRef::npos)
  765. return libDriverMain(makeArrayRef(argv, argc));
  766. // Have the command line options parsed and handle things
  767. // like --help and --version.
  768. cl::ParseCommandLineOptions(argc, argv,
  769. "LLVM Archiver (llvm-ar)\n\n"
  770. " This program archives bitcode files into single libraries\n"
  771. );
  772. if (Stem.find("ranlib") != StringRef::npos)
  773. return ranlib_main();
  774. if (Stem.find("ar") != StringRef::npos)
  775. return ar_main();
  776. fail("Not ranlib, ar, lib or dlltool!");
  777. }