llvm-ar.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Builds up (relatively) standard unix archive files (.a) containing LLVM
  10. // bitcode or other files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/StringExtras.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/BinaryFormat/Magic.h"
  17. #include "llvm/IR/LLVMContext.h"
  18. #include "llvm/Object/Archive.h"
  19. #include "llvm/Object/ArchiveWriter.h"
  20. #include "llvm/Object/IRObjectFile.h"
  21. #include "llvm/Object/MachO.h"
  22. #include "llvm/Object/ObjectFile.h"
  23. #include "llvm/Object/SymbolicFile.h"
  24. #include "llvm/Support/Chrono.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/ConvertUTF.h"
  27. #include "llvm/Support/Errc.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/Format.h"
  30. #include "llvm/Support/FormatVariadic.h"
  31. #include "llvm/Support/Host.h"
  32. #include "llvm/Support/InitLLVM.h"
  33. #include "llvm/Support/LineIterator.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/Path.h"
  36. #include "llvm/Support/Process.h"
  37. #include "llvm/Support/StringSaver.h"
  38. #include "llvm/Support/TargetSelect.h"
  39. #include "llvm/Support/ToolOutputFile.h"
  40. #include "llvm/Support/WithColor.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
  43. #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
  44. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  45. #include <unistd.h>
  46. #else
  47. #include <io.h>
  48. #endif
  49. #ifdef _WIN32
  50. #include "llvm/Support/Windows/WindowsSupport.h"
  51. #endif
  52. using namespace llvm;
  53. // The name this program was invoked as.
  54. static StringRef ToolName;
  55. // The basename of this program.
  56. static StringRef Stem;
  57. const char RanlibHelp[] = R"(OVERVIEW: LLVM Ranlib (llvm-ranlib)
  58. This program generates an index to speed access to archives
  59. USAGE: llvm-ranlib <archive-file>
  60. OPTIONS:
  61. -h --help - Display available options
  62. -v --version - Display the version of this program
  63. -D - Use zero for timestamps and uids/gids (default)
  64. -U - Use actual timestamps and uids/gids
  65. )";
  66. const char ArHelp[] = R"(OVERVIEW: LLVM Archiver
  67. USAGE: llvm-ar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files]
  68. llvm-ar -M [<mri-script]
  69. OPTIONS:
  70. --format - archive format to create
  71. =default - default
  72. =gnu - gnu
  73. =darwin - darwin
  74. =bsd - bsd
  75. --plugin=<string> - ignored for compatibility
  76. -h --help - display this help and exit
  77. --rsp-quoting - quoting style for response files
  78. =posix - posix
  79. =windows - windows
  80. --version - print the version and exit
  81. @<file> - read options from <file>
  82. OPERATIONS:
  83. d - delete [files] from the archive
  84. m - move [files] in the archive
  85. p - print [files] found in the archive
  86. q - quick append [files] to the archive
  87. r - replace or insert [files] into the archive
  88. s - act as ranlib
  89. t - display contents of archive
  90. x - extract [files] from the archive
  91. MODIFIERS:
  92. [a] - put [files] after [relpos]
  93. [b] - put [files] before [relpos] (same as [i])
  94. [c] - do not warn if archive had to be created
  95. [D] - use zero for timestamps and uids/gids (default)
  96. [h] - display this help and exit
  97. [i] - put [files] before [relpos] (same as [b])
  98. [l] - ignored for compatibility
  99. [L] - add archive's contents
  100. [N] - use instance [count] of name
  101. [o] - preserve original dates
  102. [O] - display member offsets
  103. [P] - use full names when matching (implied for thin archives)
  104. [s] - create an archive index (cf. ranlib)
  105. [S] - do not build a symbol table
  106. [T] - create a thin archive
  107. [u] - update only [files] newer than archive contents
  108. [U] - use actual timestamps and uids/gids
  109. [v] - be verbose about actions taken
  110. [V] - display the version and exit
  111. )";
  112. static void printHelpMessage() {
  113. if (Stem.contains_lower("ranlib"))
  114. outs() << RanlibHelp;
  115. else if (Stem.contains_lower("ar"))
  116. outs() << ArHelp;
  117. }
  118. static unsigned MRILineNumber;
  119. static bool ParsingMRIScript;
  120. // Show the error plus the usage message, and exit.
  121. LLVM_ATTRIBUTE_NORETURN static void badUsage(Twine Error) {
  122. WithColor::error(errs(), ToolName) << Error << "\n";
  123. printHelpMessage();
  124. exit(1);
  125. }
  126. // Show the error message and exit.
  127. LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
  128. if (ParsingMRIScript) {
  129. WithColor::error(errs(), ToolName)
  130. << "script line " << MRILineNumber << ": " << Error << "\n";
  131. } else {
  132. WithColor::error(errs(), ToolName) << Error << "\n";
  133. }
  134. exit(1);
  135. }
  136. static void failIfError(std::error_code EC, Twine Context = "") {
  137. if (!EC)
  138. return;
  139. std::string ContextStr = Context.str();
  140. if (ContextStr.empty())
  141. fail(EC.message());
  142. fail(Context + ": " + EC.message());
  143. }
  144. static void failIfError(Error E, Twine Context = "") {
  145. if (!E)
  146. return;
  147. handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
  148. std::string ContextStr = Context.str();
  149. if (ContextStr.empty())
  150. fail(EIB.message());
  151. fail(Context + ": " + EIB.message());
  152. });
  153. }
  154. static SmallVector<const char *, 256> PositionalArgs;
  155. static bool MRI;
  156. namespace {
  157. enum Format { Default, GNU, BSD, DARWIN, Unknown };
  158. }
  159. static Format FormatType = Default;
  160. static std::string Options;
  161. // This enumeration delineates the kinds of operations on an archive
  162. // that are permitted.
  163. enum ArchiveOperation {
  164. Print, ///< Print the contents of the archive
  165. Delete, ///< Delete the specified members
  166. Move, ///< Move members to end or as given by {a,b,i} modifiers
  167. QuickAppend, ///< Quickly append to end of archive
  168. ReplaceOrInsert, ///< Replace or Insert members
  169. DisplayTable, ///< Display the table of contents
  170. Extract, ///< Extract files back to file system
  171. CreateSymTab ///< Create a symbol table in an existing archive
  172. };
  173. // Modifiers to follow operation to vary behavior
  174. static bool AddAfter = false; ///< 'a' modifier
  175. static bool AddBefore = false; ///< 'b' modifier
  176. static bool Create = false; ///< 'c' modifier
  177. static bool OriginalDates = false; ///< 'o' modifier
  178. static bool DisplayMemberOffsets = false; ///< 'O' modifier
  179. static bool CompareFullPath = false; ///< 'P' modifier
  180. static bool OnlyUpdate = false; ///< 'u' modifier
  181. static bool Verbose = false; ///< 'v' modifier
  182. static bool Symtab = true; ///< 's' modifier
  183. static bool Deterministic = true; ///< 'D' and 'U' modifiers
  184. static bool Thin = false; ///< 'T' modifier
  185. static bool AddLibrary = false; ///< 'L' modifier
  186. // Relative Positional Argument (for insert/move). This variable holds
  187. // the name of the archive member to which the 'a', 'b' or 'i' modifier
  188. // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
  189. // one variable.
  190. static std::string RelPos;
  191. // Count parameter for 'N' modifier. This variable specifies which file should
  192. // match for extract/delete operations when there are multiple matches. This is
  193. // 1-indexed. A value of 0 is invalid, and implies 'N' is not used.
  194. static int CountParam = 0;
  195. // This variable holds the name of the archive file as given on the
  196. // command line.
  197. static std::string ArchiveName;
  198. static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
  199. static std::vector<std::unique_ptr<object::Archive>> Archives;
  200. // This variable holds the list of member files to proecess, as given
  201. // on the command line.
  202. static std::vector<StringRef> Members;
  203. // Static buffer to hold StringRefs.
  204. static BumpPtrAllocator Alloc;
  205. // Extract the member filename from the command line for the [relpos] argument
  206. // associated with a, b, and i modifiers
  207. static void getRelPos() {
  208. if (PositionalArgs.empty())
  209. fail("expected [relpos] for 'a', 'b', or 'i' modifier");
  210. RelPos = PositionalArgs[0];
  211. PositionalArgs.erase(PositionalArgs.begin());
  212. }
  213. // Extract the parameter from the command line for the [count] argument
  214. // associated with the N modifier
  215. static void getCountParam() {
  216. if (PositionalArgs.empty())
  217. badUsage("expected [count] for 'N' modifier");
  218. auto CountParamArg = StringRef(PositionalArgs[0]);
  219. if (CountParamArg.getAsInteger(10, CountParam))
  220. badUsage("value for [count] must be numeric, got: " + CountParamArg);
  221. if (CountParam < 1)
  222. badUsage("value for [count] must be positive, got: " + CountParamArg);
  223. PositionalArgs.erase(PositionalArgs.begin());
  224. }
  225. // Get the archive file name from the command line
  226. static void getArchive() {
  227. if (PositionalArgs.empty())
  228. badUsage("an archive name must be specified");
  229. ArchiveName = PositionalArgs[0];
  230. PositionalArgs.erase(PositionalArgs.begin());
  231. }
  232. static object::Archive &readLibrary(const Twine &Library) {
  233. auto BufOrErr = MemoryBuffer::getFile(Library, -1, false);
  234. failIfError(BufOrErr.getError(), "could not open library " + Library);
  235. ArchiveBuffers.push_back(std::move(*BufOrErr));
  236. auto LibOrErr =
  237. object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
  238. failIfError(errorToErrorCode(LibOrErr.takeError()),
  239. "could not parse library");
  240. Archives.push_back(std::move(*LibOrErr));
  241. return *Archives.back();
  242. }
  243. static void runMRIScript();
  244. // Parse the command line options as presented and return the operation
  245. // specified. Process all modifiers and check to make sure that constraints on
  246. // modifier/operation pairs have not been violated.
  247. static ArchiveOperation parseCommandLine() {
  248. if (MRI) {
  249. if (!PositionalArgs.empty() || !Options.empty())
  250. badUsage("cannot mix -M and other options");
  251. runMRIScript();
  252. }
  253. // Keep track of number of operations. We can only specify one
  254. // per execution.
  255. unsigned NumOperations = 0;
  256. // Keep track of the number of positional modifiers (a,b,i). Only
  257. // one can be specified.
  258. unsigned NumPositional = 0;
  259. // Keep track of which operation was requested
  260. ArchiveOperation Operation;
  261. bool MaybeJustCreateSymTab = false;
  262. for (unsigned i = 0; i < Options.size(); ++i) {
  263. switch (Options[i]) {
  264. case 'd':
  265. ++NumOperations;
  266. Operation = Delete;
  267. break;
  268. case 'm':
  269. ++NumOperations;
  270. Operation = Move;
  271. break;
  272. case 'p':
  273. ++NumOperations;
  274. Operation = Print;
  275. break;
  276. case 'q':
  277. ++NumOperations;
  278. Operation = QuickAppend;
  279. break;
  280. case 'r':
  281. ++NumOperations;
  282. Operation = ReplaceOrInsert;
  283. break;
  284. case 't':
  285. ++NumOperations;
  286. Operation = DisplayTable;
  287. break;
  288. case 'x':
  289. ++NumOperations;
  290. Operation = Extract;
  291. break;
  292. case 'c':
  293. Create = true;
  294. break;
  295. case 'l': /* accepted but unused */
  296. break;
  297. case 'o':
  298. OriginalDates = true;
  299. break;
  300. case 'O':
  301. DisplayMemberOffsets = true;
  302. break;
  303. case 'P':
  304. CompareFullPath = true;
  305. break;
  306. case 's':
  307. Symtab = true;
  308. MaybeJustCreateSymTab = true;
  309. break;
  310. case 'S':
  311. Symtab = false;
  312. break;
  313. case 'u':
  314. OnlyUpdate = true;
  315. break;
  316. case 'v':
  317. Verbose = true;
  318. break;
  319. case 'a':
  320. getRelPos();
  321. AddAfter = true;
  322. NumPositional++;
  323. break;
  324. case 'b':
  325. getRelPos();
  326. AddBefore = true;
  327. NumPositional++;
  328. break;
  329. case 'i':
  330. getRelPos();
  331. AddBefore = true;
  332. NumPositional++;
  333. break;
  334. case 'D':
  335. Deterministic = true;
  336. break;
  337. case 'U':
  338. Deterministic = false;
  339. break;
  340. case 'N':
  341. getCountParam();
  342. break;
  343. case 'T':
  344. Thin = true;
  345. // Thin archives store path names, so P should be forced.
  346. CompareFullPath = true;
  347. break;
  348. case 'L':
  349. AddLibrary = true;
  350. break;
  351. case 'V':
  352. cl::PrintVersionMessage();
  353. exit(0);
  354. case 'h':
  355. printHelpMessage();
  356. exit(0);
  357. default:
  358. badUsage(std::string("unknown option ") + Options[i]);
  359. }
  360. }
  361. // At this point, the next thing on the command line must be
  362. // the archive name.
  363. getArchive();
  364. // Everything on the command line at this point is a member.
  365. Members.assign(PositionalArgs.begin(), PositionalArgs.end());
  366. if (NumOperations == 0 && MaybeJustCreateSymTab) {
  367. NumOperations = 1;
  368. Operation = CreateSymTab;
  369. if (!Members.empty())
  370. badUsage("the 's' operation takes only an archive as argument");
  371. }
  372. // Perform various checks on the operation/modifier specification
  373. // to make sure we are dealing with a legal request.
  374. if (NumOperations == 0)
  375. badUsage("you must specify at least one of the operations");
  376. if (NumOperations > 1)
  377. badUsage("only one operation may be specified");
  378. if (NumPositional > 1)
  379. badUsage("you may only specify one of 'a', 'b', and 'i' modifiers");
  380. if (AddAfter || AddBefore)
  381. if (Operation != Move && Operation != ReplaceOrInsert)
  382. badUsage("the 'a', 'b' and 'i' modifiers can only be specified with "
  383. "the 'm' or 'r' operations");
  384. if (CountParam)
  385. if (Operation != Extract && Operation != Delete)
  386. badUsage("the 'N' modifier can only be specified with the 'x' or 'd' "
  387. "operations");
  388. if (OriginalDates && Operation != Extract)
  389. badUsage("the 'o' modifier is only applicable to the 'x' operation");
  390. if (OnlyUpdate && Operation != ReplaceOrInsert)
  391. badUsage("the 'u' modifier is only applicable to the 'r' operation");
  392. if (AddLibrary && Operation != QuickAppend)
  393. badUsage("the 'L' modifier is only applicable to the 'q' operation");
  394. // Return the parsed operation to the caller
  395. return Operation;
  396. }
  397. // Implements the 'p' operation. This function traverses the archive
  398. // looking for members that match the path list.
  399. static void doPrint(StringRef Name, const object::Archive::Child &C) {
  400. if (Verbose)
  401. outs() << "Printing " << Name << "\n";
  402. Expected<StringRef> DataOrErr = C.getBuffer();
  403. failIfError(DataOrErr.takeError());
  404. StringRef Data = *DataOrErr;
  405. outs().write(Data.data(), Data.size());
  406. }
  407. // Utility function for printing out the file mode when the 't' operation is in
  408. // verbose mode.
  409. static void printMode(unsigned mode) {
  410. outs() << ((mode & 004) ? "r" : "-");
  411. outs() << ((mode & 002) ? "w" : "-");
  412. outs() << ((mode & 001) ? "x" : "-");
  413. }
  414. // Implement the 't' operation. This function prints out just
  415. // the file names of each of the members. However, if verbose mode is requested
  416. // ('v' modifier) then the file type, permission mode, user, group, size, and
  417. // modification time are also printed.
  418. static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
  419. if (Verbose) {
  420. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  421. failIfError(ModeOrErr.takeError());
  422. sys::fs::perms Mode = ModeOrErr.get();
  423. printMode((Mode >> 6) & 007);
  424. printMode((Mode >> 3) & 007);
  425. printMode(Mode & 007);
  426. Expected<unsigned> UIDOrErr = C.getUID();
  427. failIfError(UIDOrErr.takeError());
  428. outs() << ' ' << UIDOrErr.get();
  429. Expected<unsigned> GIDOrErr = C.getGID();
  430. failIfError(GIDOrErr.takeError());
  431. outs() << '/' << GIDOrErr.get();
  432. Expected<uint64_t> Size = C.getSize();
  433. failIfError(Size.takeError());
  434. outs() << ' ' << format("%6llu", Size.get());
  435. auto ModTimeOrErr = C.getLastModified();
  436. failIfError(ModTimeOrErr.takeError());
  437. // Note: formatv() only handles the default TimePoint<>, which is in
  438. // nanoseconds.
  439. // TODO: fix format_provider<TimePoint<>> to allow other units.
  440. sys::TimePoint<> ModTimeInNs = ModTimeOrErr.get();
  441. outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs);
  442. outs() << ' ';
  443. }
  444. if (C.getParent()->isThin()) {
  445. if (!sys::path::is_absolute(Name)) {
  446. StringRef ParentDir = sys::path::parent_path(ArchiveName);
  447. if (!ParentDir.empty())
  448. outs() << sys::path::convert_to_slash(ParentDir) << '/';
  449. }
  450. outs() << Name;
  451. } else {
  452. outs() << Name;
  453. if (DisplayMemberOffsets)
  454. outs() << " 0x" << utohexstr(C.getDataOffset(), true);
  455. }
  456. outs() << '\n';
  457. }
  458. static std::string normalizePath(StringRef Path) {
  459. return CompareFullPath ? sys::path::convert_to_slash(Path)
  460. : std::string(sys::path::filename(Path));
  461. }
  462. static bool comparePaths(StringRef Path1, StringRef Path2) {
  463. // When on Windows this function calls CompareStringOrdinal
  464. // as Windows file paths are case-insensitive.
  465. // CompareStringOrdinal compares two Unicode strings for
  466. // binary equivalence and allows for case insensitivity.
  467. #ifdef _WIN32
  468. SmallVector<wchar_t, 128> WPath1, WPath2;
  469. failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path1), WPath1));
  470. failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path2), WPath2));
  471. return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(),
  472. WPath2.size(), true) == CSTR_EQUAL;
  473. #else
  474. return normalizePath(Path1) == normalizePath(Path2);
  475. #endif
  476. }
  477. // Implement the 'x' operation. This function extracts files back to the file
  478. // system.
  479. static void doExtract(StringRef Name, const object::Archive::Child &C) {
  480. // Retain the original mode.
  481. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  482. failIfError(ModeOrErr.takeError());
  483. sys::fs::perms Mode = ModeOrErr.get();
  484. llvm::StringRef outputFilePath = sys::path::filename(Name);
  485. if (Verbose)
  486. outs() << "x - " << outputFilePath << '\n';
  487. int FD;
  488. failIfError(sys::fs::openFileForWrite(outputFilePath, FD,
  489. sys::fs::CD_CreateAlways,
  490. sys::fs::OF_None, Mode),
  491. Name);
  492. {
  493. raw_fd_ostream file(FD, false);
  494. // Get the data and its length
  495. Expected<StringRef> BufOrErr = C.getBuffer();
  496. failIfError(BufOrErr.takeError());
  497. StringRef Data = BufOrErr.get();
  498. // Write the data.
  499. file.write(Data.data(), Data.size());
  500. }
  501. // If we're supposed to retain the original modification times, etc. do so
  502. // now.
  503. if (OriginalDates) {
  504. auto ModTimeOrErr = C.getLastModified();
  505. failIfError(ModTimeOrErr.takeError());
  506. failIfError(
  507. sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get()));
  508. }
  509. if (close(FD))
  510. fail("Could not close the file");
  511. }
  512. static bool shouldCreateArchive(ArchiveOperation Op) {
  513. switch (Op) {
  514. case Print:
  515. case Delete:
  516. case Move:
  517. case DisplayTable:
  518. case Extract:
  519. case CreateSymTab:
  520. return false;
  521. case QuickAppend:
  522. case ReplaceOrInsert:
  523. return true;
  524. }
  525. llvm_unreachable("Missing entry in covered switch.");
  526. }
  527. static void performReadOperation(ArchiveOperation Operation,
  528. object::Archive *OldArchive) {
  529. if (Operation == Extract && OldArchive->isThin())
  530. fail("extracting from a thin archive is not supported");
  531. bool Filter = !Members.empty();
  532. StringMap<int> MemberCount;
  533. {
  534. Error Err = Error::success();
  535. for (auto &C : OldArchive->children(Err)) {
  536. Expected<StringRef> NameOrErr = C.getName();
  537. failIfError(NameOrErr.takeError());
  538. StringRef Name = NameOrErr.get();
  539. if (Filter) {
  540. auto I = find_if(Members, [Name](StringRef Path) {
  541. return comparePaths(Name, Path);
  542. });
  543. if (I == Members.end())
  544. continue;
  545. if (CountParam && ++MemberCount[Name] != CountParam)
  546. continue;
  547. Members.erase(I);
  548. }
  549. switch (Operation) {
  550. default:
  551. llvm_unreachable("Not a read operation");
  552. case Print:
  553. doPrint(Name, C);
  554. break;
  555. case DisplayTable:
  556. doDisplayTable(Name, C);
  557. break;
  558. case Extract:
  559. doExtract(Name, C);
  560. break;
  561. }
  562. }
  563. failIfError(std::move(Err));
  564. }
  565. if (Members.empty())
  566. return;
  567. for (StringRef Name : Members)
  568. WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n";
  569. exit(1);
  570. }
  571. static void addChildMember(std::vector<NewArchiveMember> &Members,
  572. const object::Archive::Child &M,
  573. bool FlattenArchive = false) {
  574. if (Thin && !M.getParent()->isThin())
  575. fail("cannot convert a regular archive to a thin one");
  576. Expected<NewArchiveMember> NMOrErr =
  577. NewArchiveMember::getOldMember(M, Deterministic);
  578. failIfError(NMOrErr.takeError());
  579. // If the child member we're trying to add is thin, use the path relative to
  580. // the archive it's in, so the file resolves correctly.
  581. if (Thin && FlattenArchive) {
  582. StringSaver Saver(Alloc);
  583. Expected<std::string> FileNameOrErr(M.getName());
  584. failIfError(FileNameOrErr.takeError());
  585. if (sys::path::is_absolute(*FileNameOrErr)) {
  586. NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr));
  587. } else {
  588. FileNameOrErr = M.getFullName();
  589. failIfError(FileNameOrErr.takeError());
  590. Expected<std::string> PathOrErr =
  591. computeArchiveRelativePath(ArchiveName, *FileNameOrErr);
  592. NMOrErr->MemberName = Saver.save(
  593. PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr));
  594. }
  595. }
  596. if (FlattenArchive &&
  597. identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
  598. Expected<std::string> FileNameOrErr = M.getFullName();
  599. failIfError(FileNameOrErr.takeError());
  600. object::Archive &Lib = readLibrary(*FileNameOrErr);
  601. // When creating thin archives, only flatten if the member is also thin.
  602. if (!Thin || Lib.isThin()) {
  603. Error Err = Error::success();
  604. // Only Thin archives are recursively flattened.
  605. for (auto &Child : Lib.children(Err))
  606. addChildMember(Members, Child, /*FlattenArchive=*/Thin);
  607. failIfError(std::move(Err));
  608. return;
  609. }
  610. }
  611. Members.push_back(std::move(*NMOrErr));
  612. }
  613. static void addMember(std::vector<NewArchiveMember> &Members,
  614. StringRef FileName, bool FlattenArchive = false) {
  615. Expected<NewArchiveMember> NMOrErr =
  616. NewArchiveMember::getFile(FileName, Deterministic);
  617. failIfError(NMOrErr.takeError(), FileName);
  618. StringSaver Saver(Alloc);
  619. // For regular archives, use the basename of the object path for the member
  620. // name. For thin archives, use the full relative paths so the file resolves
  621. // correctly.
  622. if (!Thin) {
  623. NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
  624. } else {
  625. if (sys::path::is_absolute(FileName))
  626. NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
  627. else {
  628. Expected<std::string> PathOrErr =
  629. computeArchiveRelativePath(ArchiveName, FileName);
  630. NMOrErr->MemberName = Saver.save(
  631. PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
  632. }
  633. }
  634. if (FlattenArchive &&
  635. identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
  636. object::Archive &Lib = readLibrary(FileName);
  637. // When creating thin archives, only flatten if the member is also thin.
  638. if (!Thin || Lib.isThin()) {
  639. Error Err = Error::success();
  640. // Only Thin archives are recursively flattened.
  641. for (auto &Child : Lib.children(Err))
  642. addChildMember(Members, Child, /*FlattenArchive=*/Thin);
  643. failIfError(std::move(Err));
  644. return;
  645. }
  646. }
  647. Members.push_back(std::move(*NMOrErr));
  648. }
  649. enum InsertAction {
  650. IA_AddOldMember,
  651. IA_AddNewMember,
  652. IA_Delete,
  653. IA_MoveOldMember,
  654. IA_MoveNewMember
  655. };
  656. static InsertAction computeInsertAction(ArchiveOperation Operation,
  657. const object::Archive::Child &Member,
  658. StringRef Name,
  659. std::vector<StringRef>::iterator &Pos,
  660. StringMap<int> &MemberCount) {
  661. if (Operation == QuickAppend || Members.empty())
  662. return IA_AddOldMember;
  663. auto MI = find_if(
  664. Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
  665. if (MI == Members.end())
  666. return IA_AddOldMember;
  667. Pos = MI;
  668. if (Operation == Delete) {
  669. if (CountParam && ++MemberCount[Name] != CountParam)
  670. return IA_AddOldMember;
  671. return IA_Delete;
  672. }
  673. if (Operation == Move)
  674. return IA_MoveOldMember;
  675. if (Operation == ReplaceOrInsert) {
  676. if (!OnlyUpdate) {
  677. if (RelPos.empty())
  678. return IA_AddNewMember;
  679. return IA_MoveNewMember;
  680. }
  681. // We could try to optimize this to a fstat, but it is not a common
  682. // operation.
  683. sys::fs::file_status Status;
  684. failIfError(sys::fs::status(*MI, Status), *MI);
  685. auto ModTimeOrErr = Member.getLastModified();
  686. failIfError(ModTimeOrErr.takeError());
  687. if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
  688. if (RelPos.empty())
  689. return IA_AddOldMember;
  690. return IA_MoveOldMember;
  691. }
  692. if (RelPos.empty())
  693. return IA_AddNewMember;
  694. return IA_MoveNewMember;
  695. }
  696. llvm_unreachable("No such operation");
  697. }
  698. // We have to walk this twice and computing it is not trivial, so creating an
  699. // explicit std::vector is actually fairly efficient.
  700. static std::vector<NewArchiveMember>
  701. computeNewArchiveMembers(ArchiveOperation Operation,
  702. object::Archive *OldArchive) {
  703. std::vector<NewArchiveMember> Ret;
  704. std::vector<NewArchiveMember> Moved;
  705. int InsertPos = -1;
  706. if (OldArchive) {
  707. Error Err = Error::success();
  708. StringMap<int> MemberCount;
  709. for (auto &Child : OldArchive->children(Err)) {
  710. int Pos = Ret.size();
  711. Expected<StringRef> NameOrErr = Child.getName();
  712. failIfError(NameOrErr.takeError());
  713. std::string Name = std::string(NameOrErr.get());
  714. if (comparePaths(Name, RelPos)) {
  715. assert(AddAfter || AddBefore);
  716. if (AddBefore)
  717. InsertPos = Pos;
  718. else
  719. InsertPos = Pos + 1;
  720. }
  721. std::vector<StringRef>::iterator MemberI = Members.end();
  722. InsertAction Action =
  723. computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
  724. switch (Action) {
  725. case IA_AddOldMember:
  726. addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
  727. break;
  728. case IA_AddNewMember:
  729. addMember(Ret, *MemberI);
  730. break;
  731. case IA_Delete:
  732. break;
  733. case IA_MoveOldMember:
  734. addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
  735. break;
  736. case IA_MoveNewMember:
  737. addMember(Moved, *MemberI);
  738. break;
  739. }
  740. // When processing elements with the count param, we need to preserve the
  741. // full members list when iterating over all archive members. For
  742. // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
  743. // file named member.o it sees; we are not done with member.o the first
  744. // time we see it in the archive.
  745. if (MemberI != Members.end() && !CountParam)
  746. Members.erase(MemberI);
  747. }
  748. failIfError(std::move(Err));
  749. }
  750. if (Operation == Delete)
  751. return Ret;
  752. if (!RelPos.empty() && InsertPos == -1)
  753. fail("insertion point not found");
  754. if (RelPos.empty())
  755. InsertPos = Ret.size();
  756. assert(unsigned(InsertPos) <= Ret.size());
  757. int Pos = InsertPos;
  758. for (auto &M : Moved) {
  759. Ret.insert(Ret.begin() + Pos, std::move(M));
  760. ++Pos;
  761. }
  762. if (AddLibrary) {
  763. assert(Operation == QuickAppend);
  764. for (auto &Member : Members)
  765. addMember(Ret, Member, /*FlattenArchive=*/true);
  766. return Ret;
  767. }
  768. std::vector<NewArchiveMember> NewMembers;
  769. for (auto &Member : Members)
  770. addMember(NewMembers, Member, /*FlattenArchive=*/Thin);
  771. Ret.reserve(Ret.size() + NewMembers.size());
  772. std::move(NewMembers.begin(), NewMembers.end(),
  773. std::inserter(Ret, std::next(Ret.begin(), InsertPos)));
  774. return Ret;
  775. }
  776. static object::Archive::Kind getDefaultForHost() {
  777. return Triple(sys::getProcessTriple()).isOSDarwin()
  778. ? object::Archive::K_DARWIN
  779. : object::Archive::K_GNU;
  780. }
  781. static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
  782. auto MemBufferRef = Member.Buf->getMemBufferRef();
  783. Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
  784. object::ObjectFile::createObjectFile(MemBufferRef);
  785. if (OptionalObject)
  786. return isa<object::MachOObjectFile>(**OptionalObject)
  787. ? object::Archive::K_DARWIN
  788. : object::Archive::K_GNU;
  789. // squelch the error in case we had a non-object file
  790. consumeError(OptionalObject.takeError());
  791. // If we're adding a bitcode file to the archive, detect the Archive kind
  792. // based on the target triple.
  793. LLVMContext Context;
  794. if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
  795. if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
  796. MemBufferRef, file_magic::bitcode, &Context)) {
  797. auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
  798. return Triple(IRObject.getTargetTriple()).isOSDarwin()
  799. ? object::Archive::K_DARWIN
  800. : object::Archive::K_GNU;
  801. } else {
  802. // Squelch the error in case this was not a SymbolicFile.
  803. consumeError(ObjOrErr.takeError());
  804. }
  805. }
  806. return getDefaultForHost();
  807. }
  808. static void performWriteOperation(ArchiveOperation Operation,
  809. object::Archive *OldArchive,
  810. std::unique_ptr<MemoryBuffer> OldArchiveBuf,
  811. std::vector<NewArchiveMember> *NewMembersP) {
  812. std::vector<NewArchiveMember> NewMembers;
  813. if (!NewMembersP)
  814. NewMembers = computeNewArchiveMembers(Operation, OldArchive);
  815. object::Archive::Kind Kind;
  816. switch (FormatType) {
  817. case Default:
  818. if (Thin)
  819. Kind = object::Archive::K_GNU;
  820. else if (OldArchive)
  821. Kind = OldArchive->kind();
  822. else if (NewMembersP)
  823. Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
  824. : getDefaultForHost();
  825. else
  826. Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
  827. : getDefaultForHost();
  828. break;
  829. case GNU:
  830. Kind = object::Archive::K_GNU;
  831. break;
  832. case BSD:
  833. if (Thin)
  834. fail("only the gnu format has a thin mode");
  835. Kind = object::Archive::K_BSD;
  836. break;
  837. case DARWIN:
  838. if (Thin)
  839. fail("only the gnu format has a thin mode");
  840. Kind = object::Archive::K_DARWIN;
  841. break;
  842. case Unknown:
  843. llvm_unreachable("");
  844. }
  845. Error E =
  846. writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
  847. Kind, Deterministic, Thin, std::move(OldArchiveBuf));
  848. failIfError(std::move(E), ArchiveName);
  849. }
  850. static void createSymbolTable(object::Archive *OldArchive) {
  851. // When an archive is created or modified, if the s option is given, the
  852. // resulting archive will have a current symbol table. If the S option
  853. // is given, it will have no symbol table.
  854. // In summary, we only need to update the symbol table if we have none.
  855. // This is actually very common because of broken build systems that think
  856. // they have to run ranlib.
  857. if (OldArchive->hasSymbolTable())
  858. return;
  859. performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
  860. }
  861. static void performOperation(ArchiveOperation Operation,
  862. object::Archive *OldArchive,
  863. std::unique_ptr<MemoryBuffer> OldArchiveBuf,
  864. std::vector<NewArchiveMember> *NewMembers) {
  865. switch (Operation) {
  866. case Print:
  867. case DisplayTable:
  868. case Extract:
  869. performReadOperation(Operation, OldArchive);
  870. return;
  871. case Delete:
  872. case Move:
  873. case QuickAppend:
  874. case ReplaceOrInsert:
  875. performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
  876. NewMembers);
  877. return;
  878. case CreateSymTab:
  879. createSymbolTable(OldArchive);
  880. return;
  881. }
  882. llvm_unreachable("Unknown operation.");
  883. }
  884. static int performOperation(ArchiveOperation Operation,
  885. std::vector<NewArchiveMember> *NewMembers) {
  886. // Create or open the archive object.
  887. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
  888. MemoryBuffer::getFile(ArchiveName, -1, false);
  889. std::error_code EC = Buf.getError();
  890. if (EC && EC != errc::no_such_file_or_directory)
  891. fail("unable to open '" + ArchiveName + "': " + EC.message());
  892. if (!EC) {
  893. Error Err = Error::success();
  894. object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
  895. failIfError(std::move(Err), "unable to load '" + ArchiveName + "'");
  896. if (Archive.isThin())
  897. CompareFullPath = true;
  898. performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
  899. return 0;
  900. }
  901. assert(EC == errc::no_such_file_or_directory);
  902. if (!shouldCreateArchive(Operation)) {
  903. failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
  904. } else {
  905. if (!Create) {
  906. // Produce a warning if we should and we're creating the archive
  907. WithColor::warning(errs(), ToolName)
  908. << "creating " << ArchiveName << "\n";
  909. }
  910. }
  911. performOperation(Operation, nullptr, nullptr, NewMembers);
  912. return 0;
  913. }
  914. static void runMRIScript() {
  915. enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
  916. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
  917. failIfError(Buf.getError());
  918. const MemoryBuffer &Ref = *Buf.get();
  919. bool Saved = false;
  920. std::vector<NewArchiveMember> NewMembers;
  921. ParsingMRIScript = true;
  922. for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
  923. ++MRILineNumber;
  924. StringRef Line = *I;
  925. Line = Line.split(';').first;
  926. Line = Line.split('*').first;
  927. Line = Line.trim();
  928. if (Line.empty())
  929. continue;
  930. StringRef CommandStr, Rest;
  931. std::tie(CommandStr, Rest) = Line.split(' ');
  932. Rest = Rest.trim();
  933. if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
  934. Rest = Rest.drop_front().drop_back();
  935. auto Command = StringSwitch<MRICommand>(CommandStr.lower())
  936. .Case("addlib", MRICommand::AddLib)
  937. .Case("addmod", MRICommand::AddMod)
  938. .Case("create", MRICommand::Create)
  939. .Case("createthin", MRICommand::CreateThin)
  940. .Case("delete", MRICommand::Delete)
  941. .Case("save", MRICommand::Save)
  942. .Case("end", MRICommand::End)
  943. .Default(MRICommand::Invalid);
  944. switch (Command) {
  945. case MRICommand::AddLib: {
  946. object::Archive &Lib = readLibrary(Rest);
  947. {
  948. Error Err = Error::success();
  949. for (auto &Member : Lib.children(Err))
  950. addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
  951. failIfError(std::move(Err));
  952. }
  953. break;
  954. }
  955. case MRICommand::AddMod:
  956. addMember(NewMembers, Rest);
  957. break;
  958. case MRICommand::CreateThin:
  959. Thin = true;
  960. LLVM_FALLTHROUGH;
  961. case MRICommand::Create:
  962. Create = true;
  963. if (!ArchiveName.empty())
  964. fail("editing multiple archives not supported");
  965. if (Saved)
  966. fail("file already saved");
  967. ArchiveName = std::string(Rest);
  968. break;
  969. case MRICommand::Delete: {
  970. llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
  971. return comparePaths(M.MemberName, Rest);
  972. });
  973. break;
  974. }
  975. case MRICommand::Save:
  976. Saved = true;
  977. break;
  978. case MRICommand::End:
  979. break;
  980. case MRICommand::Invalid:
  981. fail("unknown command: " + CommandStr);
  982. }
  983. }
  984. ParsingMRIScript = false;
  985. // Nothing to do if not saved.
  986. if (Saved)
  987. performOperation(ReplaceOrInsert, &NewMembers);
  988. exit(0);
  989. }
  990. static bool handleGenericOption(StringRef arg) {
  991. if (arg == "-help" || arg == "--help" || arg == "-h") {
  992. printHelpMessage();
  993. return true;
  994. }
  995. if (arg == "-version" || arg == "--version") {
  996. cl::PrintVersionMessage();
  997. return true;
  998. }
  999. return false;
  1000. }
  1001. static const char *matchFlagWithArg(StringRef Expected,
  1002. ArrayRef<const char *>::iterator &ArgIt,
  1003. ArrayRef<const char *> Args) {
  1004. StringRef Arg = *ArgIt;
  1005. if (Arg.startswith("--"))
  1006. Arg = Arg.substr(2);
  1007. else if (Arg.startswith("-"))
  1008. Arg = Arg.substr(1);
  1009. size_t len = Expected.size();
  1010. if (Arg == Expected) {
  1011. if (++ArgIt == Args.end())
  1012. fail(std::string(Expected) + " requires an argument");
  1013. return *ArgIt;
  1014. }
  1015. if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
  1016. return Arg.data() + len + 1;
  1017. return nullptr;
  1018. }
  1019. static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) {
  1020. cl::TokenizerCallback Ret =
  1021. Triple(sys::getProcessTriple()).getOS() == Triple::Win32
  1022. ? cl::TokenizeWindowsCommandLine
  1023. : cl::TokenizeGNUCommandLine;
  1024. for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin();
  1025. ArgIt != ArgsArr.end(); ++ArgIt) {
  1026. if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) {
  1027. StringRef MatchRef = Match;
  1028. if (MatchRef == "posix")
  1029. Ret = cl::TokenizeGNUCommandLine;
  1030. else if (MatchRef == "windows")
  1031. Ret = cl::TokenizeWindowsCommandLine;
  1032. else
  1033. fail(std::string("Invalid response file quoting style ") + Match);
  1034. }
  1035. }
  1036. return Ret;
  1037. }
  1038. static int ar_main(int argc, char **argv) {
  1039. SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
  1040. StringSaver Saver(Alloc);
  1041. cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
  1042. for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
  1043. ArgIt != Argv.end(); ++ArgIt) {
  1044. const char *Match = nullptr;
  1045. if (handleGenericOption(*ArgIt))
  1046. return 0;
  1047. if (strcmp(*ArgIt, "--") == 0) {
  1048. ++ArgIt;
  1049. for (; ArgIt != Argv.end(); ++ArgIt)
  1050. PositionalArgs.push_back(*ArgIt);
  1051. break;
  1052. }
  1053. if (*ArgIt[0] != '-') {
  1054. if (Options.empty())
  1055. Options += *ArgIt;
  1056. else
  1057. PositionalArgs.push_back(*ArgIt);
  1058. continue;
  1059. }
  1060. if (strcmp(*ArgIt, "-M") == 0) {
  1061. MRI = true;
  1062. continue;
  1063. }
  1064. Match = matchFlagWithArg("format", ArgIt, Argv);
  1065. if (Match) {
  1066. FormatType = StringSwitch<Format>(Match)
  1067. .Case("default", Default)
  1068. .Case("gnu", GNU)
  1069. .Case("darwin", DARWIN)
  1070. .Case("bsd", BSD)
  1071. .Default(Unknown);
  1072. if (FormatType == Unknown)
  1073. fail(std::string("Invalid format ") + Match);
  1074. continue;
  1075. }
  1076. if (matchFlagWithArg("plugin", ArgIt, Argv) ||
  1077. matchFlagWithArg("rsp-quoting", ArgIt, Argv))
  1078. continue;
  1079. Options += *ArgIt + 1;
  1080. }
  1081. ArchiveOperation Operation = parseCommandLine();
  1082. return performOperation(Operation, nullptr);
  1083. }
  1084. static int ranlib_main(int argc, char **argv) {
  1085. bool ArchiveSpecified = false;
  1086. for (int i = 1; i < argc; ++i) {
  1087. StringRef arg(argv[i]);
  1088. if (handleGenericOption(arg)) {
  1089. return 0;
  1090. } else if (arg.consume_front("-")) {
  1091. // Handle the -D/-U flag
  1092. while (!arg.empty()) {
  1093. if (arg.front() == 'D') {
  1094. Deterministic = true;
  1095. } else if (arg.front() == 'U') {
  1096. Deterministic = false;
  1097. } else if (arg.front() == 'h') {
  1098. printHelpMessage();
  1099. return 0;
  1100. } else if (arg.front() == 'v') {
  1101. cl::PrintVersionMessage();
  1102. return 0;
  1103. } else {
  1104. // TODO: GNU ranlib also supports a -t flag
  1105. fail("Invalid option: '-" + arg + "'");
  1106. }
  1107. arg = arg.drop_front(1);
  1108. }
  1109. } else {
  1110. if (ArchiveSpecified)
  1111. fail("exactly one archive should be specified");
  1112. ArchiveSpecified = true;
  1113. ArchiveName = arg.str();
  1114. }
  1115. }
  1116. if (!ArchiveSpecified) {
  1117. badUsage("an archive name must be specified");
  1118. }
  1119. return performOperation(CreateSymTab, nullptr);
  1120. }
  1121. int main(int argc, char **argv) {
  1122. InitLLVM X(argc, argv);
  1123. ToolName = argv[0];
  1124. llvm::InitializeAllTargetInfos();
  1125. llvm::InitializeAllTargetMCs();
  1126. llvm::InitializeAllAsmParsers();
  1127. Stem = sys::path::stem(ToolName);
  1128. auto Is = [](StringRef Tool) {
  1129. // We need to recognize the following filenames.
  1130. //
  1131. // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
  1132. // dlltool.exe -> dlltool
  1133. // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
  1134. auto I = Stem.rfind_lower(Tool);
  1135. return I != StringRef::npos &&
  1136. (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
  1137. };
  1138. if (Is("dlltool"))
  1139. return dlltoolDriverMain(makeArrayRef(argv, argc));
  1140. if (Is("ranlib"))
  1141. return ranlib_main(argc, argv);
  1142. if (Is("lib"))
  1143. return libDriverMain(makeArrayRef(argv, argc));
  1144. if (Is("ar"))
  1145. return ar_main(argc, argv);
  1146. fail("not ranlib, ar, lib or dlltool");
  1147. }