ConfigManager.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. //===- ConfigManager.cpp --------------------------------------------------===//
  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. #include "ConfigManager.h"
  9. #include "llvm/ADT/Optional.h"
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/ADT/StringSet.h"
  13. #include "llvm/BinaryFormat/COFF.h"
  14. #include "llvm/Option/Arg.h"
  15. #include "llvm/Option/ArgList.h"
  16. #include "llvm/Support/CRC.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/Support/Compression.h"
  19. #include "llvm/Support/Errc.h"
  20. #include "llvm/Support/Error.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include "llvm/Support/StringSaver.h"
  23. #include <memory>
  24. using namespace llvm;
  25. using namespace llvm::objcopy;
  26. namespace {
  27. enum ObjcopyID {
  28. OBJCOPY_INVALID = 0, // This is not an option ID.
  29. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  30. HELPTEXT, METAVAR, VALUES) \
  31. OBJCOPY_##ID,
  32. #include "ObjcopyOpts.inc"
  33. #undef OPTION
  34. };
  35. #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
  36. #include "ObjcopyOpts.inc"
  37. #undef PREFIX
  38. const opt::OptTable::Info ObjcopyInfoTable[] = {
  39. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  40. HELPTEXT, METAVAR, VALUES) \
  41. {OBJCOPY_##PREFIX, \
  42. NAME, \
  43. HELPTEXT, \
  44. METAVAR, \
  45. OBJCOPY_##ID, \
  46. opt::Option::KIND##Class, \
  47. PARAM, \
  48. FLAGS, \
  49. OBJCOPY_##GROUP, \
  50. OBJCOPY_##ALIAS, \
  51. ALIASARGS, \
  52. VALUES},
  53. #include "ObjcopyOpts.inc"
  54. #undef OPTION
  55. };
  56. class ObjcopyOptTable : public opt::OptTable {
  57. public:
  58. ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {
  59. setGroupedShortOptions(true);
  60. }
  61. };
  62. enum InstallNameToolID {
  63. INSTALL_NAME_TOOL_INVALID = 0, // This is not an option ID.
  64. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  65. HELPTEXT, METAVAR, VALUES) \
  66. INSTALL_NAME_TOOL_##ID,
  67. #include "InstallNameToolOpts.inc"
  68. #undef OPTION
  69. };
  70. #define PREFIX(NAME, VALUE) \
  71. const char *const INSTALL_NAME_TOOL_##NAME[] = VALUE;
  72. #include "InstallNameToolOpts.inc"
  73. #undef PREFIX
  74. const opt::OptTable::Info InstallNameToolInfoTable[] = {
  75. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  76. HELPTEXT, METAVAR, VALUES) \
  77. {INSTALL_NAME_TOOL_##PREFIX, \
  78. NAME, \
  79. HELPTEXT, \
  80. METAVAR, \
  81. INSTALL_NAME_TOOL_##ID, \
  82. opt::Option::KIND##Class, \
  83. PARAM, \
  84. FLAGS, \
  85. INSTALL_NAME_TOOL_##GROUP, \
  86. INSTALL_NAME_TOOL_##ALIAS, \
  87. ALIASARGS, \
  88. VALUES},
  89. #include "InstallNameToolOpts.inc"
  90. #undef OPTION
  91. };
  92. class InstallNameToolOptTable : public opt::OptTable {
  93. public:
  94. InstallNameToolOptTable() : OptTable(InstallNameToolInfoTable) {}
  95. };
  96. enum BitcodeStripID {
  97. BITCODE_STRIP_INVALID = 0, // This is not an option ID.
  98. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  99. HELPTEXT, METAVAR, VALUES) \
  100. BITCODE_STRIP_##ID,
  101. #include "BitcodeStripOpts.inc"
  102. #undef OPTION
  103. };
  104. #define PREFIX(NAME, VALUE) const char *const BITCODE_STRIP_##NAME[] = VALUE;
  105. #include "BitcodeStripOpts.inc"
  106. #undef PREFIX
  107. const opt::OptTable::Info BitcodeStripInfoTable[] = {
  108. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  109. HELPTEXT, METAVAR, VALUES) \
  110. {BITCODE_STRIP_##PREFIX, \
  111. NAME, \
  112. HELPTEXT, \
  113. METAVAR, \
  114. BITCODE_STRIP_##ID, \
  115. opt::Option::KIND##Class, \
  116. PARAM, \
  117. FLAGS, \
  118. BITCODE_STRIP_##GROUP, \
  119. BITCODE_STRIP_##ALIAS, \
  120. ALIASARGS, \
  121. VALUES},
  122. #include "BitcodeStripOpts.inc"
  123. #undef OPTION
  124. };
  125. class BitcodeStripOptTable : public opt::OptTable {
  126. public:
  127. BitcodeStripOptTable() : OptTable(BitcodeStripInfoTable) {}
  128. };
  129. enum StripID {
  130. STRIP_INVALID = 0, // This is not an option ID.
  131. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  132. HELPTEXT, METAVAR, VALUES) \
  133. STRIP_##ID,
  134. #include "StripOpts.inc"
  135. #undef OPTION
  136. };
  137. #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
  138. #include "StripOpts.inc"
  139. #undef PREFIX
  140. const opt::OptTable::Info StripInfoTable[] = {
  141. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  142. HELPTEXT, METAVAR, VALUES) \
  143. {STRIP_##PREFIX, NAME, HELPTEXT, \
  144. METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
  145. PARAM, FLAGS, STRIP_##GROUP, \
  146. STRIP_##ALIAS, ALIASARGS, VALUES},
  147. #include "StripOpts.inc"
  148. #undef OPTION
  149. };
  150. class StripOptTable : public opt::OptTable {
  151. public:
  152. StripOptTable() : OptTable(StripInfoTable) { setGroupedShortOptions(true); }
  153. };
  154. } // namespace
  155. static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
  156. return llvm::StringSwitch<SectionFlag>(SectionName)
  157. .CaseLower("alloc", SectionFlag::SecAlloc)
  158. .CaseLower("load", SectionFlag::SecLoad)
  159. .CaseLower("noload", SectionFlag::SecNoload)
  160. .CaseLower("readonly", SectionFlag::SecReadonly)
  161. .CaseLower("debug", SectionFlag::SecDebug)
  162. .CaseLower("code", SectionFlag::SecCode)
  163. .CaseLower("data", SectionFlag::SecData)
  164. .CaseLower("rom", SectionFlag::SecRom)
  165. .CaseLower("merge", SectionFlag::SecMerge)
  166. .CaseLower("strings", SectionFlag::SecStrings)
  167. .CaseLower("contents", SectionFlag::SecContents)
  168. .CaseLower("share", SectionFlag::SecShare)
  169. .CaseLower("exclude", SectionFlag::SecExclude)
  170. .Default(SectionFlag::SecNone);
  171. }
  172. static Expected<SectionFlag>
  173. parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
  174. SectionFlag ParsedFlags = SectionFlag::SecNone;
  175. for (StringRef Flag : SectionFlags) {
  176. SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
  177. if (ParsedFlag == SectionFlag::SecNone)
  178. return createStringError(
  179. errc::invalid_argument,
  180. "unrecognized section flag '%s'. Flags supported for GNU "
  181. "compatibility: alloc, load, noload, readonly, exclude, debug, "
  182. "code, data, rom, share, contents, merge, strings",
  183. Flag.str().c_str());
  184. ParsedFlags |= ParsedFlag;
  185. }
  186. return ParsedFlags;
  187. }
  188. static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
  189. if (!FlagValue.contains('='))
  190. return createStringError(errc::invalid_argument,
  191. "bad format for --rename-section: missing '='");
  192. // Initial split: ".foo" = ".bar,f1,f2,..."
  193. auto Old2New = FlagValue.split('=');
  194. SectionRename SR;
  195. SR.OriginalName = Old2New.first;
  196. // Flags split: ".bar" "f1" "f2" ...
  197. SmallVector<StringRef, 6> NameAndFlags;
  198. Old2New.second.split(NameAndFlags, ',');
  199. SR.NewName = NameAndFlags[0];
  200. if (NameAndFlags.size() > 1) {
  201. Expected<SectionFlag> ParsedFlagSet =
  202. parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
  203. if (!ParsedFlagSet)
  204. return ParsedFlagSet.takeError();
  205. SR.NewFlags = *ParsedFlagSet;
  206. }
  207. return SR;
  208. }
  209. static Expected<std::pair<StringRef, uint64_t>>
  210. parseSetSectionAlignment(StringRef FlagValue) {
  211. if (!FlagValue.contains('='))
  212. return createStringError(
  213. errc::invalid_argument,
  214. "bad format for --set-section-alignment: missing '='");
  215. auto Split = StringRef(FlagValue).split('=');
  216. if (Split.first.empty())
  217. return createStringError(
  218. errc::invalid_argument,
  219. "bad format for --set-section-alignment: missing section name");
  220. uint64_t NewAlign;
  221. if (Split.second.getAsInteger(0, NewAlign))
  222. return createStringError(
  223. errc::invalid_argument,
  224. "invalid alignment for --set-section-alignment: '%s'",
  225. Split.second.str().c_str());
  226. return std::make_pair(Split.first, NewAlign);
  227. }
  228. static Expected<SectionFlagsUpdate>
  229. parseSetSectionFlagValue(StringRef FlagValue) {
  230. if (!StringRef(FlagValue).contains('='))
  231. return createStringError(errc::invalid_argument,
  232. "bad format for --set-section-flags: missing '='");
  233. // Initial split: ".foo" = "f1,f2,..."
  234. auto Section2Flags = StringRef(FlagValue).split('=');
  235. SectionFlagsUpdate SFU;
  236. SFU.Name = Section2Flags.first;
  237. // Flags split: "f1" "f2" ...
  238. SmallVector<StringRef, 6> SectionFlags;
  239. Section2Flags.second.split(SectionFlags, ',');
  240. Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
  241. if (!ParsedFlagSet)
  242. return ParsedFlagSet.takeError();
  243. SFU.NewFlags = *ParsedFlagSet;
  244. return SFU;
  245. }
  246. namespace {
  247. struct TargetInfo {
  248. FileFormat Format;
  249. MachineInfo Machine;
  250. };
  251. } // namespace
  252. // FIXME: consolidate with the bfd parsing used by lld.
  253. static const StringMap<MachineInfo> TargetMap{
  254. // Name, {EMachine, 64bit, LittleEndian}
  255. // x86
  256. {"elf32-i386", {ELF::EM_386, false, true}},
  257. {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
  258. {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
  259. // Intel MCU
  260. {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
  261. // ARM
  262. {"elf32-littlearm", {ELF::EM_ARM, false, true}},
  263. // ARM AArch64
  264. {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
  265. {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
  266. // RISC-V
  267. {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
  268. {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
  269. // PowerPC
  270. {"elf32-powerpc", {ELF::EM_PPC, false, false}},
  271. {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
  272. {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
  273. {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
  274. // MIPS
  275. {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
  276. {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
  277. {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
  278. {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
  279. {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
  280. {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
  281. {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
  282. // SPARC
  283. {"elf32-sparc", {ELF::EM_SPARC, false, false}},
  284. {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
  285. {"elf32-hexagon", {ELF::EM_HEXAGON, false, true}},
  286. };
  287. static Expected<TargetInfo>
  288. getOutputTargetInfoByTargetName(StringRef TargetName) {
  289. StringRef OriginalTargetName = TargetName;
  290. bool IsFreeBSD = TargetName.consume_back("-freebsd");
  291. auto Iter = TargetMap.find(TargetName);
  292. if (Iter == std::end(TargetMap))
  293. return createStringError(errc::invalid_argument,
  294. "invalid output format: '%s'",
  295. OriginalTargetName.str().c_str());
  296. MachineInfo MI = Iter->getValue();
  297. if (IsFreeBSD)
  298. MI.OSABI = ELF::ELFOSABI_FREEBSD;
  299. FileFormat Format;
  300. if (TargetName.startswith("elf"))
  301. Format = FileFormat::ELF;
  302. else
  303. // This should never happen because `TargetName` is valid (it certainly
  304. // exists in the TargetMap).
  305. llvm_unreachable("unknown target prefix");
  306. return {TargetInfo{Format, MI}};
  307. }
  308. static Error addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
  309. StringRef Filename, MatchStyle MS,
  310. function_ref<Error(Error)> ErrorCallback) {
  311. StringSaver Saver(Alloc);
  312. SmallVector<StringRef, 16> Lines;
  313. auto BufOrErr = MemoryBuffer::getFile(Filename);
  314. if (!BufOrErr)
  315. return createFileError(Filename, BufOrErr.getError());
  316. BufOrErr.get()->getBuffer().split(Lines, '\n');
  317. for (StringRef Line : Lines) {
  318. // Ignore everything after '#', trim whitespace, and only add the symbol if
  319. // it's not empty.
  320. auto TrimmedLine = Line.split('#').first.trim();
  321. if (!TrimmedLine.empty())
  322. if (Error E = Symbols.addMatcher(NameOrPattern::create(
  323. Saver.save(TrimmedLine), MS, ErrorCallback)))
  324. return E;
  325. }
  326. return Error::success();
  327. }
  328. Expected<NameOrPattern>
  329. NameOrPattern::create(StringRef Pattern, MatchStyle MS,
  330. function_ref<Error(Error)> ErrorCallback) {
  331. switch (MS) {
  332. case MatchStyle::Literal:
  333. return NameOrPattern(Pattern);
  334. case MatchStyle::Wildcard: {
  335. SmallVector<char, 32> Data;
  336. bool IsPositiveMatch = true;
  337. if (Pattern[0] == '!') {
  338. IsPositiveMatch = false;
  339. Pattern = Pattern.drop_front();
  340. }
  341. Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
  342. // If we couldn't create it as a glob, report the error, but try again with
  343. // a literal if the error reporting is non-fatal.
  344. if (!GlobOrErr) {
  345. if (Error E = ErrorCallback(GlobOrErr.takeError()))
  346. return std::move(E);
  347. return create(Pattern, MatchStyle::Literal, ErrorCallback);
  348. }
  349. return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
  350. IsPositiveMatch);
  351. }
  352. case MatchStyle::Regex: {
  353. SmallVector<char, 32> Data;
  354. return NameOrPattern(std::make_shared<Regex>(
  355. ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
  356. }
  357. }
  358. llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
  359. }
  360. static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
  361. BumpPtrAllocator &Alloc,
  362. StringRef Filename) {
  363. StringSaver Saver(Alloc);
  364. SmallVector<StringRef, 16> Lines;
  365. auto BufOrErr = MemoryBuffer::getFile(Filename);
  366. if (!BufOrErr)
  367. return createFileError(Filename, BufOrErr.getError());
  368. BufOrErr.get()->getBuffer().split(Lines, '\n');
  369. size_t NumLines = Lines.size();
  370. for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
  371. StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
  372. if (TrimmedLine.empty())
  373. continue;
  374. std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
  375. StringRef NewName = Pair.second.trim();
  376. if (NewName.empty())
  377. return createStringError(errc::invalid_argument,
  378. "%s:%zu: missing new symbol name",
  379. Filename.str().c_str(), LineNo + 1);
  380. SymbolsToRename.insert({Pair.first, NewName});
  381. }
  382. return Error::success();
  383. }
  384. template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
  385. T Result;
  386. if (Val.getAsInteger(0, Result))
  387. return errc::invalid_argument;
  388. return Result;
  389. }
  390. namespace {
  391. enum class ToolType { Objcopy, Strip, InstallNameTool, BitcodeStrip };
  392. } // anonymous namespace
  393. static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
  394. ToolType Tool) {
  395. StringRef HelpText, ToolName;
  396. switch (Tool) {
  397. case ToolType::Objcopy:
  398. ToolName = "llvm-objcopy";
  399. HelpText = " [options] input [output]";
  400. break;
  401. case ToolType::Strip:
  402. ToolName = "llvm-strip";
  403. HelpText = " [options] inputs...";
  404. break;
  405. case ToolType::InstallNameTool:
  406. ToolName = "llvm-install-name-tool";
  407. HelpText = " [options] input";
  408. break;
  409. case ToolType::BitcodeStrip:
  410. ToolName = "llvm-bitcode-strip";
  411. HelpText = " [options] input";
  412. break;
  413. }
  414. OptTable.printHelp(OS, (ToolName + HelpText).str().c_str(),
  415. (ToolName + " tool").str().c_str());
  416. // TODO: Replace this with libOption call once it adds extrahelp support.
  417. // The CommandLine library has a cl::extrahelp class to support this,
  418. // but libOption does not have that yet.
  419. OS << "\nPass @FILE as argument to read options from FILE.\n";
  420. }
  421. static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
  422. // Parse value given with --add-symbol option and create the
  423. // new symbol if possible. The value format for --add-symbol is:
  424. //
  425. // <name>=[<section>:]<value>[,<flags>]
  426. //
  427. // where:
  428. // <name> - symbol name, can be empty string
  429. // <section> - optional section name. If not given ABS symbol is created
  430. // <value> - symbol value, can be decimal or hexadecimal number prefixed
  431. // with 0x.
  432. // <flags> - optional flags affecting symbol type, binding or visibility.
  433. NewSymbolInfo SI;
  434. StringRef Value;
  435. std::tie(SI.SymbolName, Value) = FlagValue.split('=');
  436. if (Value.empty())
  437. return createStringError(
  438. errc::invalid_argument,
  439. "bad format for --add-symbol, missing '=' after '%s'",
  440. SI.SymbolName.str().c_str());
  441. if (Value.contains(':')) {
  442. std::tie(SI.SectionName, Value) = Value.split(':');
  443. if (SI.SectionName.empty() || Value.empty())
  444. return createStringError(
  445. errc::invalid_argument,
  446. "bad format for --add-symbol, missing section name or symbol value");
  447. }
  448. SmallVector<StringRef, 6> Flags;
  449. Value.split(Flags, ',');
  450. if (Flags[0].getAsInteger(0, SI.Value))
  451. return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
  452. Flags[0].str().c_str());
  453. using Functor = std::function<void()>;
  454. SmallVector<StringRef, 6> UnsupportedFlags;
  455. for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
  456. static_cast<Functor>(
  457. StringSwitch<Functor>(Flags[I])
  458. .CaseLower("global",
  459. [&] { SI.Flags.push_back(SymbolFlag::Global); })
  460. .CaseLower("local", [&] { SI.Flags.push_back(SymbolFlag::Local); })
  461. .CaseLower("weak", [&] { SI.Flags.push_back(SymbolFlag::Weak); })
  462. .CaseLower("default",
  463. [&] { SI.Flags.push_back(SymbolFlag::Default); })
  464. .CaseLower("hidden",
  465. [&] { SI.Flags.push_back(SymbolFlag::Hidden); })
  466. .CaseLower("protected",
  467. [&] { SI.Flags.push_back(SymbolFlag::Protected); })
  468. .CaseLower("file", [&] { SI.Flags.push_back(SymbolFlag::File); })
  469. .CaseLower("section",
  470. [&] { SI.Flags.push_back(SymbolFlag::Section); })
  471. .CaseLower("object",
  472. [&] { SI.Flags.push_back(SymbolFlag::Object); })
  473. .CaseLower("function",
  474. [&] { SI.Flags.push_back(SymbolFlag::Function); })
  475. .CaseLower(
  476. "indirect-function",
  477. [&] { SI.Flags.push_back(SymbolFlag::IndirectFunction); })
  478. .CaseLower("debug", [&] { SI.Flags.push_back(SymbolFlag::Debug); })
  479. .CaseLower("constructor",
  480. [&] { SI.Flags.push_back(SymbolFlag::Constructor); })
  481. .CaseLower("warning",
  482. [&] { SI.Flags.push_back(SymbolFlag::Warning); })
  483. .CaseLower("indirect",
  484. [&] { SI.Flags.push_back(SymbolFlag::Indirect); })
  485. .CaseLower("synthetic",
  486. [&] { SI.Flags.push_back(SymbolFlag::Synthetic); })
  487. .CaseLower("unique-object",
  488. [&] { SI.Flags.push_back(SymbolFlag::UniqueObject); })
  489. .StartsWithLower("before=",
  490. [&] {
  491. StringRef SymNamePart =
  492. Flags[I].split('=').second;
  493. if (!SymNamePart.empty())
  494. SI.BeforeSyms.push_back(SymNamePart);
  495. })
  496. .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
  497. if (!UnsupportedFlags.empty())
  498. return createStringError(errc::invalid_argument,
  499. "unsupported flag%s for --add-symbol: '%s'",
  500. UnsupportedFlags.size() > 1 ? "s" : "",
  501. join(UnsupportedFlags, "', '").c_str());
  502. return SI;
  503. }
  504. Expected<const ELFConfig &> ConfigManager::getELFConfig() const {
  505. return ELF;
  506. }
  507. Expected<const COFFConfig &> ConfigManager::getCOFFConfig() const {
  508. if (!Common.SplitDWO.empty() || !Common.SymbolsPrefix.empty() ||
  509. !Common.AllocSectionsPrefix.empty() || !Common.DumpSection.empty() ||
  510. !Common.KeepSection.empty() || !Common.SymbolsToGlobalize.empty() ||
  511. !Common.SymbolsToKeep.empty() || !Common.SymbolsToLocalize.empty() ||
  512. !Common.SymbolsToWeaken.empty() || !Common.SymbolsToKeepGlobal.empty() ||
  513. !Common.SectionsToRename.empty() || !Common.SetSectionAlignment.empty() ||
  514. Common.ExtractDWO || Common.PreserveDates || Common.StripDWO ||
  515. Common.StripNonAlloc || Common.StripSections || Common.Weaken ||
  516. Common.DecompressDebugSections ||
  517. Common.DiscardMode == DiscardType::Locals ||
  518. !Common.SymbolsToAdd.empty()) {
  519. return createStringError(llvm::errc::invalid_argument,
  520. "option not supported by llvm-objcopy for COFF");
  521. }
  522. return COFF;
  523. }
  524. Expected<const MachOConfig &> ConfigManager::getMachOConfig() const {
  525. if (!Common.SplitDWO.empty() || !Common.SymbolsPrefix.empty() ||
  526. !Common.AllocSectionsPrefix.empty() || !Common.KeepSection.empty() ||
  527. !Common.SymbolsToGlobalize.empty() || !Common.SymbolsToKeep.empty() ||
  528. !Common.SymbolsToLocalize.empty() || !Common.SymbolsToWeaken.empty() ||
  529. !Common.SymbolsToKeepGlobal.empty() || !Common.SectionsToRename.empty() ||
  530. !Common.UnneededSymbolsToRemove.empty() ||
  531. !Common.SetSectionAlignment.empty() || !Common.SetSectionFlags.empty() ||
  532. Common.ExtractDWO || Common.PreserveDates || Common.StripAllGNU ||
  533. Common.StripDWO || Common.StripNonAlloc || Common.StripSections ||
  534. Common.Weaken || Common.DecompressDebugSections || Common.StripUnneeded ||
  535. Common.DiscardMode == DiscardType::Locals ||
  536. !Common.SymbolsToAdd.empty()) {
  537. return createStringError(llvm::errc::invalid_argument,
  538. "option not supported by llvm-objcopy for MachO");
  539. }
  540. return MachO;
  541. }
  542. Expected<const WasmConfig &> ConfigManager::getWasmConfig() const {
  543. if (!Common.AddGnuDebugLink.empty() || Common.ExtractPartition ||
  544. !Common.SplitDWO.empty() || !Common.SymbolsPrefix.empty() ||
  545. !Common.AllocSectionsPrefix.empty() ||
  546. Common.DiscardMode != DiscardType::None || !Common.SymbolsToAdd.empty() ||
  547. !Common.SymbolsToGlobalize.empty() || !Common.SymbolsToLocalize.empty() ||
  548. !Common.SymbolsToKeep.empty() || !Common.SymbolsToRemove.empty() ||
  549. !Common.UnneededSymbolsToRemove.empty() ||
  550. !Common.SymbolsToWeaken.empty() || !Common.SymbolsToKeepGlobal.empty() ||
  551. !Common.SectionsToRename.empty() || !Common.SetSectionAlignment.empty() ||
  552. !Common.SetSectionFlags.empty() || !Common.SymbolsToRename.empty()) {
  553. return createStringError(
  554. llvm::errc::invalid_argument,
  555. "only flags for section dumping, removal, and addition are supported");
  556. }
  557. return Wasm;
  558. }
  559. // ParseObjcopyOptions returns the config and sets the input arguments. If a
  560. // help flag is set then ParseObjcopyOptions will print the help messege and
  561. // exit.
  562. Expected<DriverConfig>
  563. objcopy::parseObjcopyOptions(ArrayRef<const char *> RawArgsArr,
  564. function_ref<Error(Error)> ErrorCallback) {
  565. DriverConfig DC;
  566. ObjcopyOptTable T;
  567. const char *const *DashDash =
  568. std::find_if(RawArgsArr.begin(), RawArgsArr.end(),
  569. [](StringRef Str) { return Str == "--"; });
  570. ArrayRef<const char *> ArgsArr = makeArrayRef(RawArgsArr.begin(), DashDash);
  571. if (DashDash != RawArgsArr.end())
  572. DashDash = std::next(DashDash);
  573. unsigned MissingArgumentIndex, MissingArgumentCount;
  574. llvm::opt::InputArgList InputArgs =
  575. T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
  576. if (InputArgs.size() == 0 && DashDash == RawArgsArr.end()) {
  577. printHelp(T, errs(), ToolType::Objcopy);
  578. exit(1);
  579. }
  580. if (InputArgs.hasArg(OBJCOPY_help)) {
  581. printHelp(T, outs(), ToolType::Objcopy);
  582. exit(0);
  583. }
  584. if (InputArgs.hasArg(OBJCOPY_version)) {
  585. outs() << "llvm-objcopy, compatible with GNU objcopy\n";
  586. cl::PrintVersionMessage();
  587. exit(0);
  588. }
  589. SmallVector<const char *, 2> Positional;
  590. for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
  591. return createStringError(errc::invalid_argument, "unknown argument '%s'",
  592. Arg->getAsString(InputArgs).c_str());
  593. for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
  594. Positional.push_back(Arg->getValue());
  595. std::copy(DashDash, RawArgsArr.end(), std::back_inserter(Positional));
  596. if (Positional.empty())
  597. return createStringError(errc::invalid_argument, "no input file specified");
  598. if (Positional.size() > 2)
  599. return createStringError(errc::invalid_argument,
  600. "too many positional arguments");
  601. ConfigManager ConfigMgr;
  602. CommonConfig &Config = ConfigMgr.Common;
  603. COFFConfig &COFFConfig = ConfigMgr.COFF;
  604. ELFConfig &ELFConfig = ConfigMgr.ELF;
  605. MachOConfig &MachOConfig = ConfigMgr.MachO;
  606. Config.InputFilename = Positional[0];
  607. Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
  608. if (InputArgs.hasArg(OBJCOPY_target) &&
  609. (InputArgs.hasArg(OBJCOPY_input_target) ||
  610. InputArgs.hasArg(OBJCOPY_output_target)))
  611. return createStringError(
  612. errc::invalid_argument,
  613. "--target cannot be used with --input-target or --output-target");
  614. if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
  615. return createStringError(errc::invalid_argument,
  616. "--regex and --wildcard are incompatible");
  617. MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
  618. ? MatchStyle::Regex
  619. : MatchStyle::Wildcard;
  620. MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
  621. ? MatchStyle::Regex
  622. : InputArgs.hasArg(OBJCOPY_wildcard)
  623. ? MatchStyle::Wildcard
  624. : MatchStyle::Literal;
  625. StringRef InputFormat, OutputFormat;
  626. if (InputArgs.hasArg(OBJCOPY_target)) {
  627. InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
  628. OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
  629. } else {
  630. InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
  631. OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
  632. }
  633. // FIXME: Currently, we ignore the target for non-binary/ihex formats
  634. // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
  635. // format by llvm::object::createBinary regardless of the option value.
  636. Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
  637. .Case("binary", FileFormat::Binary)
  638. .Case("ihex", FileFormat::IHex)
  639. .Default(FileFormat::Unspecified);
  640. if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility)) {
  641. const uint8_t Invalid = 0xff;
  642. StringRef VisibilityStr =
  643. InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
  644. ELFConfig.NewSymbolVisibility = StringSwitch<uint8_t>(VisibilityStr)
  645. .Case("default", ELF::STV_DEFAULT)
  646. .Case("hidden", ELF::STV_HIDDEN)
  647. .Case("internal", ELF::STV_INTERNAL)
  648. .Case("protected", ELF::STV_PROTECTED)
  649. .Default(Invalid);
  650. if (ELFConfig.NewSymbolVisibility == Invalid)
  651. return createStringError(errc::invalid_argument,
  652. "'%s' is not a valid symbol visibility",
  653. VisibilityStr.str().c_str());
  654. }
  655. for (const auto *Arg : InputArgs.filtered(OBJCOPY_subsystem)) {
  656. StringRef Subsystem, Version;
  657. std::tie(Subsystem, Version) = StringRef(Arg->getValue()).split(':');
  658. COFFConfig.Subsystem =
  659. StringSwitch<unsigned>(Subsystem.lower())
  660. .Case("boot_application",
  661. COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
  662. .Case("console", COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI)
  663. .Case("efi_application", COFF::IMAGE_SUBSYSTEM_EFI_APPLICATION)
  664. .Case("efi_boot_service_driver",
  665. COFF::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
  666. .Case("efi_rom", COFF::IMAGE_SUBSYSTEM_EFI_ROM)
  667. .Case("efi_runtime_driver",
  668. COFF::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
  669. .Case("native", COFF::IMAGE_SUBSYSTEM_NATIVE)
  670. .Case("posix", COFF::IMAGE_SUBSYSTEM_POSIX_CUI)
  671. .Case("windows", COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI)
  672. .Default(COFF::IMAGE_SUBSYSTEM_UNKNOWN);
  673. if (*COFFConfig.Subsystem == COFF::IMAGE_SUBSYSTEM_UNKNOWN)
  674. return createStringError(errc::invalid_argument,
  675. "'%s' is not a valid subsystem",
  676. Subsystem.str().c_str());
  677. if (!Version.empty()) {
  678. StringRef Major, Minor;
  679. std::tie(Major, Minor) = Version.split('.');
  680. unsigned Number;
  681. if (Major.getAsInteger(10, Number))
  682. return createStringError(errc::invalid_argument,
  683. "'%s' is not a valid subsystem major version",
  684. Major.str().c_str());
  685. COFFConfig.MajorSubsystemVersion = Number;
  686. Number = 0;
  687. if (!Minor.empty() && Minor.getAsInteger(10, Number))
  688. return createStringError(errc::invalid_argument,
  689. "'%s' is not a valid subsystem minor version",
  690. Minor.str().c_str());
  691. COFFConfig.MinorSubsystemVersion = Number;
  692. }
  693. }
  694. Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
  695. .Case("binary", FileFormat::Binary)
  696. .Case("ihex", FileFormat::IHex)
  697. .Default(FileFormat::Unspecified);
  698. if (Config.OutputFormat == FileFormat::Unspecified) {
  699. if (OutputFormat.empty()) {
  700. Config.OutputFormat = Config.InputFormat;
  701. } else {
  702. Expected<TargetInfo> Target =
  703. getOutputTargetInfoByTargetName(OutputFormat);
  704. if (!Target)
  705. return Target.takeError();
  706. Config.OutputFormat = Target->Format;
  707. Config.OutputArch = Target->Machine;
  708. }
  709. }
  710. if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
  711. OBJCOPY_compress_debug_sections_eq)) {
  712. Config.CompressionType = DebugCompressionType::Z;
  713. if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
  714. Config.CompressionType =
  715. StringSwitch<DebugCompressionType>(
  716. InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
  717. .Case("zlib-gnu", DebugCompressionType::GNU)
  718. .Case("zlib", DebugCompressionType::Z)
  719. .Default(DebugCompressionType::None);
  720. if (Config.CompressionType == DebugCompressionType::None)
  721. return createStringError(
  722. errc::invalid_argument,
  723. "invalid or unsupported --compress-debug-sections format: %s",
  724. InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
  725. .str()
  726. .c_str());
  727. }
  728. if (!zlib::isAvailable())
  729. return createStringError(
  730. errc::invalid_argument,
  731. "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
  732. }
  733. Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
  734. // The gnu_debuglink's target is expected to not change or else its CRC would
  735. // become invalidated and get rejected. We can avoid recalculating the
  736. // checksum for every target file inside an archive by precomputing the CRC
  737. // here. This prevents a significant amount of I/O.
  738. if (!Config.AddGnuDebugLink.empty()) {
  739. auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
  740. if (!DebugOrErr)
  741. return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
  742. auto Debug = std::move(*DebugOrErr);
  743. Config.GnuDebugLinkCRC32 =
  744. llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
  745. }
  746. Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
  747. Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
  748. Config.AllocSectionsPrefix =
  749. InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
  750. if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
  751. Config.ExtractPartition = Arg->getValue();
  752. for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
  753. if (!StringRef(Arg->getValue()).contains('='))
  754. return createStringError(errc::invalid_argument,
  755. "bad format for --redefine-sym");
  756. auto Old2New = StringRef(Arg->getValue()).split('=');
  757. if (!Config.SymbolsToRename.insert(Old2New).second)
  758. return createStringError(errc::invalid_argument,
  759. "multiple redefinition of symbol '%s'",
  760. Old2New.first.str().c_str());
  761. }
  762. for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
  763. if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
  764. Arg->getValue()))
  765. return std::move(E);
  766. for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
  767. Expected<SectionRename> SR =
  768. parseRenameSectionValue(StringRef(Arg->getValue()));
  769. if (!SR)
  770. return SR.takeError();
  771. if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
  772. return createStringError(errc::invalid_argument,
  773. "multiple renames of section '%s'",
  774. SR->OriginalName.str().c_str());
  775. }
  776. for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
  777. Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
  778. parseSetSectionAlignment(Arg->getValue());
  779. if (!NameAndAlign)
  780. return NameAndAlign.takeError();
  781. Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
  782. }
  783. for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
  784. Expected<SectionFlagsUpdate> SFU =
  785. parseSetSectionFlagValue(Arg->getValue());
  786. if (!SFU)
  787. return SFU.takeError();
  788. if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
  789. return createStringError(
  790. errc::invalid_argument,
  791. "--set-section-flags set multiple times for section '%s'",
  792. SFU->Name.str().c_str());
  793. }
  794. // Prohibit combinations of --set-section-flags when the section name is used
  795. // by --rename-section, either as a source or a destination.
  796. for (const auto &E : Config.SectionsToRename) {
  797. const SectionRename &SR = E.second;
  798. if (Config.SetSectionFlags.count(SR.OriginalName))
  799. return createStringError(
  800. errc::invalid_argument,
  801. "--set-section-flags=%s conflicts with --rename-section=%s=%s",
  802. SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
  803. SR.NewName.str().c_str());
  804. if (Config.SetSectionFlags.count(SR.NewName))
  805. return createStringError(
  806. errc::invalid_argument,
  807. "--set-section-flags=%s conflicts with --rename-section=%s=%s",
  808. SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
  809. SR.NewName.str().c_str());
  810. }
  811. for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
  812. if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
  813. Arg->getValue(), SectionMatchStyle, ErrorCallback)))
  814. return std::move(E);
  815. for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
  816. if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
  817. Arg->getValue(), SectionMatchStyle, ErrorCallback)))
  818. return std::move(E);
  819. for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
  820. if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
  821. Arg->getValue(), SectionMatchStyle, ErrorCallback)))
  822. return std::move(E);
  823. for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
  824. StringRef ArgValue(Arg->getValue());
  825. if (!ArgValue.contains('='))
  826. return createStringError(errc::invalid_argument,
  827. "bad format for --add-section: missing '='");
  828. if (ArgValue.split("=").second.empty())
  829. return createStringError(
  830. errc::invalid_argument,
  831. "bad format for --add-section: missing file name");
  832. Config.AddSection.push_back(ArgValue);
  833. }
  834. for (auto Arg : InputArgs.filtered(OBJCOPY_update_section)) {
  835. StringRef ArgValue(Arg->getValue());
  836. if (!ArgValue.contains('='))
  837. return createStringError(errc::invalid_argument,
  838. "bad format for --update-section: missing '='");
  839. if (ArgValue.split("=").second.empty())
  840. return createStringError(
  841. errc::invalid_argument,
  842. "bad format for --update-section: missing file name");
  843. Config.UpdateSection.push_back(ArgValue);
  844. }
  845. for (auto *Arg : InputArgs.filtered(OBJCOPY_dump_section)) {
  846. StringRef Value(Arg->getValue());
  847. if (Value.split('=').second.empty())
  848. return createStringError(
  849. errc::invalid_argument,
  850. "bad format for --dump-section, expected section=file");
  851. Config.DumpSection.push_back(Value);
  852. }
  853. Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
  854. Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
  855. Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
  856. Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
  857. Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
  858. Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
  859. Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
  860. Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
  861. Config.ExtractMainPartition =
  862. InputArgs.hasArg(OBJCOPY_extract_main_partition);
  863. ELFConfig.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
  864. Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
  865. if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
  866. Config.DiscardMode =
  867. InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
  868. ? DiscardType::All
  869. : DiscardType::Locals;
  870. Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
  871. ELFConfig.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
  872. MachOConfig.KeepUndefined = InputArgs.hasArg(OBJCOPY_keep_undefined);
  873. Config.DecompressDebugSections =
  874. InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
  875. if (Config.DiscardMode == DiscardType::All) {
  876. Config.StripDebug = true;
  877. ELFConfig.KeepFileSymbols = true;
  878. }
  879. for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
  880. if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
  881. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  882. return std::move(E);
  883. for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
  884. if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
  885. Arg->getValue(), SymbolMatchStyle,
  886. ErrorCallback))
  887. return std::move(E);
  888. for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
  889. if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
  890. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  891. return std::move(E);
  892. for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
  893. if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
  894. Arg->getValue(), SymbolMatchStyle,
  895. ErrorCallback))
  896. return std::move(E);
  897. for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
  898. if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
  899. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  900. return std::move(E);
  901. for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
  902. if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
  903. Arg->getValue(), SymbolMatchStyle,
  904. ErrorCallback))
  905. return std::move(E);
  906. for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
  907. if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
  908. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  909. return std::move(E);
  910. for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
  911. if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
  912. Arg->getValue(), SymbolMatchStyle,
  913. ErrorCallback))
  914. return std::move(E);
  915. for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
  916. if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
  917. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  918. return std::move(E);
  919. for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
  920. if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
  921. Arg->getValue(), SymbolMatchStyle,
  922. ErrorCallback))
  923. return std::move(E);
  924. for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
  925. if (Error E =
  926. Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
  927. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  928. return std::move(E);
  929. for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
  930. if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
  931. Arg->getValue(), SymbolMatchStyle,
  932. ErrorCallback))
  933. return std::move(E);
  934. for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
  935. if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
  936. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  937. return std::move(E);
  938. for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
  939. if (Error E =
  940. addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
  941. SymbolMatchStyle, ErrorCallback))
  942. return std::move(E);
  943. for (auto *Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
  944. Expected<NewSymbolInfo> SymInfo = parseNewSymbolInfo(Arg->getValue());
  945. if (!SymInfo)
  946. return SymInfo.takeError();
  947. Config.SymbolsToAdd.push_back(*SymInfo);
  948. }
  949. ELFConfig.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
  950. Config.DeterministicArchives = InputArgs.hasFlag(
  951. OBJCOPY_enable_deterministic_archives,
  952. OBJCOPY_disable_deterministic_archives, /*default=*/true);
  953. Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
  954. if (Config.PreserveDates &&
  955. (Config.OutputFilename == "-" || Config.InputFilename == "-"))
  956. return createStringError(errc::invalid_argument,
  957. "--preserve-dates requires a file");
  958. for (auto Arg : InputArgs)
  959. if (Arg->getOption().matches(OBJCOPY_set_start)) {
  960. auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
  961. if (!EAddr)
  962. return createStringError(
  963. EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
  964. ELFConfig.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
  965. } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
  966. auto EIncr = getAsInteger<int64_t>(Arg->getValue());
  967. if (!EIncr)
  968. return createStringError(EIncr.getError(),
  969. "bad entry point increment: '%s'",
  970. Arg->getValue());
  971. auto Expr = ELFConfig.EntryExpr ? std::move(ELFConfig.EntryExpr)
  972. : [](uint64_t A) { return A; };
  973. ELFConfig.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
  974. return Expr(EAddr) + *EIncr;
  975. };
  976. }
  977. if (Config.DecompressDebugSections &&
  978. Config.CompressionType != DebugCompressionType::None) {
  979. return createStringError(
  980. errc::invalid_argument,
  981. "cannot specify both --compress-debug-sections and "
  982. "--decompress-debug-sections");
  983. }
  984. if (Config.DecompressDebugSections && !zlib::isAvailable())
  985. return createStringError(
  986. errc::invalid_argument,
  987. "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
  988. if (Config.ExtractPartition && Config.ExtractMainPartition)
  989. return createStringError(errc::invalid_argument,
  990. "cannot specify --extract-partition together with "
  991. "--extract-main-partition");
  992. DC.CopyConfigs.push_back(std::move(ConfigMgr));
  993. return std::move(DC);
  994. }
  995. // ParseInstallNameToolOptions returns the config and sets the input arguments.
  996. // If a help flag is set then ParseInstallNameToolOptions will print the help
  997. // messege and exit.
  998. Expected<DriverConfig>
  999. objcopy::parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
  1000. DriverConfig DC;
  1001. ConfigManager ConfigMgr;
  1002. CommonConfig &Config = ConfigMgr.Common;
  1003. MachOConfig &MachOConfig = ConfigMgr.MachO;
  1004. InstallNameToolOptTable T;
  1005. unsigned MissingArgumentIndex, MissingArgumentCount;
  1006. llvm::opt::InputArgList InputArgs =
  1007. T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
  1008. if (MissingArgumentCount)
  1009. return createStringError(
  1010. errc::invalid_argument,
  1011. "missing argument to " +
  1012. StringRef(InputArgs.getArgString(MissingArgumentIndex)) +
  1013. " option");
  1014. if (InputArgs.size() == 0) {
  1015. printHelp(T, errs(), ToolType::InstallNameTool);
  1016. exit(1);
  1017. }
  1018. if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
  1019. printHelp(T, outs(), ToolType::InstallNameTool);
  1020. exit(0);
  1021. }
  1022. if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
  1023. outs() << "llvm-install-name-tool, compatible with cctools "
  1024. "install_name_tool\n";
  1025. cl::PrintVersionMessage();
  1026. exit(0);
  1027. }
  1028. for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
  1029. MachOConfig.RPathToAdd.push_back(Arg->getValue());
  1030. for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_prepend_rpath))
  1031. MachOConfig.RPathToPrepend.push_back(Arg->getValue());
  1032. for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_delete_rpath)) {
  1033. StringRef RPath = Arg->getValue();
  1034. // Cannot add and delete the same rpath at the same time.
  1035. if (is_contained(MachOConfig.RPathToAdd, RPath))
  1036. return createStringError(
  1037. errc::invalid_argument,
  1038. "cannot specify both -add_rpath '%s' and -delete_rpath '%s'",
  1039. RPath.str().c_str(), RPath.str().c_str());
  1040. if (is_contained(MachOConfig.RPathToPrepend, RPath))
  1041. return createStringError(
  1042. errc::invalid_argument,
  1043. "cannot specify both -prepend_rpath '%s' and -delete_rpath '%s'",
  1044. RPath.str().c_str(), RPath.str().c_str());
  1045. MachOConfig.RPathsToRemove.insert(RPath);
  1046. }
  1047. for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_rpath)) {
  1048. StringRef Old = Arg->getValue(0);
  1049. StringRef New = Arg->getValue(1);
  1050. auto Match = [=](StringRef RPath) { return RPath == Old || RPath == New; };
  1051. // Cannot specify duplicate -rpath entries
  1052. auto It1 = find_if(
  1053. MachOConfig.RPathsToUpdate,
  1054. [&Match](const DenseMap<StringRef, StringRef>::value_type &OldNew) {
  1055. return Match(OldNew.getFirst()) || Match(OldNew.getSecond());
  1056. });
  1057. if (It1 != MachOConfig.RPathsToUpdate.end())
  1058. return createStringError(errc::invalid_argument,
  1059. "cannot specify both -rpath '" +
  1060. It1->getFirst() + "' '" + It1->getSecond() +
  1061. "' and -rpath '" + Old + "' '" + New + "'");
  1062. // Cannot specify the same rpath under both -delete_rpath and -rpath
  1063. auto It2 = find_if(MachOConfig.RPathsToRemove, Match);
  1064. if (It2 != MachOConfig.RPathsToRemove.end())
  1065. return createStringError(errc::invalid_argument,
  1066. "cannot specify both -delete_rpath '" + *It2 +
  1067. "' and -rpath '" + Old + "' '" + New + "'");
  1068. // Cannot specify the same rpath under both -add_rpath and -rpath
  1069. auto It3 = find_if(MachOConfig.RPathToAdd, Match);
  1070. if (It3 != MachOConfig.RPathToAdd.end())
  1071. return createStringError(errc::invalid_argument,
  1072. "cannot specify both -add_rpath '" + *It3 +
  1073. "' and -rpath '" + Old + "' '" + New + "'");
  1074. // Cannot specify the same rpath under both -prepend_rpath and -rpath.
  1075. auto It4 = find_if(MachOConfig.RPathToPrepend, Match);
  1076. if (It4 != MachOConfig.RPathToPrepend.end())
  1077. return createStringError(errc::invalid_argument,
  1078. "cannot specify both -prepend_rpath '" + *It4 +
  1079. "' and -rpath '" + Old + "' '" + New + "'");
  1080. MachOConfig.RPathsToUpdate.insert({Old, New});
  1081. }
  1082. if (auto *Arg = InputArgs.getLastArg(INSTALL_NAME_TOOL_id)) {
  1083. MachOConfig.SharedLibId = Arg->getValue();
  1084. if (MachOConfig.SharedLibId->empty())
  1085. return createStringError(errc::invalid_argument,
  1086. "cannot specify an empty id");
  1087. }
  1088. for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_change))
  1089. MachOConfig.InstallNamesToUpdate.insert(
  1090. {Arg->getValue(0), Arg->getValue(1)});
  1091. MachOConfig.RemoveAllRpaths =
  1092. InputArgs.hasArg(INSTALL_NAME_TOOL_delete_all_rpaths);
  1093. SmallVector<StringRef, 2> Positional;
  1094. for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
  1095. return createStringError(errc::invalid_argument, "unknown argument '%s'",
  1096. Arg->getAsString(InputArgs).c_str());
  1097. for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
  1098. Positional.push_back(Arg->getValue());
  1099. if (Positional.empty())
  1100. return createStringError(errc::invalid_argument, "no input file specified");
  1101. if (Positional.size() > 1)
  1102. return createStringError(
  1103. errc::invalid_argument,
  1104. "llvm-install-name-tool expects a single input file");
  1105. Config.InputFilename = Positional[0];
  1106. Config.OutputFilename = Positional[0];
  1107. DC.CopyConfigs.push_back(std::move(ConfigMgr));
  1108. return std::move(DC);
  1109. }
  1110. Expected<DriverConfig>
  1111. objcopy::parseBitcodeStripOptions(ArrayRef<const char *> ArgsArr) {
  1112. DriverConfig DC;
  1113. ConfigManager ConfigMgr;
  1114. CommonConfig &Config = ConfigMgr.Common;
  1115. BitcodeStripOptTable T;
  1116. unsigned MissingArgumentIndex, MissingArgumentCount;
  1117. opt::InputArgList InputArgs =
  1118. T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
  1119. if (InputArgs.size() == 0) {
  1120. printHelp(T, errs(), ToolType::BitcodeStrip);
  1121. exit(1);
  1122. }
  1123. if (InputArgs.hasArg(BITCODE_STRIP_help)) {
  1124. printHelp(T, outs(), ToolType::BitcodeStrip);
  1125. exit(0);
  1126. }
  1127. if (InputArgs.hasArg(BITCODE_STRIP_version)) {
  1128. outs() << "llvm-bitcode-strip, compatible with cctools "
  1129. "bitcode_strip\n";
  1130. cl::PrintVersionMessage();
  1131. exit(0);
  1132. }
  1133. for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_UNKNOWN))
  1134. return createStringError(errc::invalid_argument, "unknown argument '%s'",
  1135. Arg->getAsString(InputArgs).c_str());
  1136. SmallVector<StringRef, 2> Positional;
  1137. for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_INPUT))
  1138. Positional.push_back(Arg->getValue());
  1139. if (Positional.size() > 1)
  1140. return createStringError(errc::invalid_argument,
  1141. "llvm-bitcode-strip expects a single input file");
  1142. assert(!Positional.empty());
  1143. Config.InputFilename = Positional[0];
  1144. Config.OutputFilename = Positional[0];
  1145. DC.CopyConfigs.push_back(std::move(ConfigMgr));
  1146. return std::move(DC);
  1147. }
  1148. // ParseStripOptions returns the config and sets the input arguments. If a
  1149. // help flag is set then ParseStripOptions will print the help messege and
  1150. // exit.
  1151. Expected<DriverConfig>
  1152. objcopy::parseStripOptions(ArrayRef<const char *> RawArgsArr,
  1153. function_ref<Error(Error)> ErrorCallback) {
  1154. const char *const *DashDash =
  1155. std::find_if(RawArgsArr.begin(), RawArgsArr.end(),
  1156. [](StringRef Str) { return Str == "--"; });
  1157. ArrayRef<const char *> ArgsArr = makeArrayRef(RawArgsArr.begin(), DashDash);
  1158. if (DashDash != RawArgsArr.end())
  1159. DashDash = std::next(DashDash);
  1160. StripOptTable T;
  1161. unsigned MissingArgumentIndex, MissingArgumentCount;
  1162. llvm::opt::InputArgList InputArgs =
  1163. T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
  1164. if (InputArgs.size() == 0 && DashDash == RawArgsArr.end()) {
  1165. printHelp(T, errs(), ToolType::Strip);
  1166. exit(1);
  1167. }
  1168. if (InputArgs.hasArg(STRIP_help)) {
  1169. printHelp(T, outs(), ToolType::Strip);
  1170. exit(0);
  1171. }
  1172. if (InputArgs.hasArg(STRIP_version)) {
  1173. outs() << "llvm-strip, compatible with GNU strip\n";
  1174. cl::PrintVersionMessage();
  1175. exit(0);
  1176. }
  1177. SmallVector<StringRef, 2> Positional;
  1178. for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
  1179. return createStringError(errc::invalid_argument, "unknown argument '%s'",
  1180. Arg->getAsString(InputArgs).c_str());
  1181. for (auto Arg : InputArgs.filtered(STRIP_INPUT))
  1182. Positional.push_back(Arg->getValue());
  1183. std::copy(DashDash, RawArgsArr.end(), std::back_inserter(Positional));
  1184. if (Positional.empty())
  1185. return createStringError(errc::invalid_argument, "no input file specified");
  1186. if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
  1187. return createStringError(
  1188. errc::invalid_argument,
  1189. "multiple input files cannot be used in combination with -o");
  1190. ConfigManager ConfigMgr;
  1191. CommonConfig &Config = ConfigMgr.Common;
  1192. ELFConfig &ELFConfig = ConfigMgr.ELF;
  1193. MachOConfig &MachOConfig = ConfigMgr.MachO;
  1194. if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
  1195. return createStringError(errc::invalid_argument,
  1196. "--regex and --wildcard are incompatible");
  1197. MatchStyle SectionMatchStyle =
  1198. InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
  1199. MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
  1200. ? MatchStyle::Regex
  1201. : InputArgs.hasArg(STRIP_wildcard)
  1202. ? MatchStyle::Wildcard
  1203. : MatchStyle::Literal;
  1204. ELFConfig.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
  1205. Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
  1206. if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
  1207. Config.DiscardMode =
  1208. InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
  1209. ? DiscardType::All
  1210. : DiscardType::Locals;
  1211. Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
  1212. Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
  1213. if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
  1214. Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
  1215. Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
  1216. MachOConfig.StripSwiftSymbols = InputArgs.hasArg(STRIP_strip_swift_symbols);
  1217. Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
  1218. ELFConfig.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
  1219. MachOConfig.KeepUndefined = InputArgs.hasArg(STRIP_keep_undefined);
  1220. for (auto Arg : InputArgs.filtered(STRIP_keep_section))
  1221. if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
  1222. Arg->getValue(), SectionMatchStyle, ErrorCallback)))
  1223. return std::move(E);
  1224. for (auto Arg : InputArgs.filtered(STRIP_remove_section))
  1225. if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
  1226. Arg->getValue(), SectionMatchStyle, ErrorCallback)))
  1227. return std::move(E);
  1228. for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
  1229. if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
  1230. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  1231. return std::move(E);
  1232. for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
  1233. if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
  1234. Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
  1235. return std::move(E);
  1236. if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
  1237. !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
  1238. !Config.StripAllGNU && Config.SymbolsToRemove.empty())
  1239. Config.StripAll = true;
  1240. if (Config.DiscardMode == DiscardType::All) {
  1241. Config.StripDebug = true;
  1242. ELFConfig.KeepFileSymbols = true;
  1243. }
  1244. Config.DeterministicArchives =
  1245. InputArgs.hasFlag(STRIP_enable_deterministic_archives,
  1246. STRIP_disable_deterministic_archives, /*default=*/true);
  1247. Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
  1248. Config.InputFormat = FileFormat::Unspecified;
  1249. Config.OutputFormat = FileFormat::Unspecified;
  1250. DriverConfig DC;
  1251. if (Positional.size() == 1) {
  1252. Config.InputFilename = Positional[0];
  1253. Config.OutputFilename =
  1254. InputArgs.getLastArgValue(STRIP_output, Positional[0]);
  1255. DC.CopyConfigs.push_back(std::move(ConfigMgr));
  1256. } else {
  1257. StringMap<unsigned> InputFiles;
  1258. for (StringRef Filename : Positional) {
  1259. if (InputFiles[Filename]++ == 1) {
  1260. if (Filename == "-")
  1261. return createStringError(
  1262. errc::invalid_argument,
  1263. "cannot specify '-' as an input file more than once");
  1264. if (Error E = ErrorCallback(createStringError(
  1265. errc::invalid_argument, "'%s' was already specified",
  1266. Filename.str().c_str())))
  1267. return std::move(E);
  1268. }
  1269. Config.InputFilename = Filename;
  1270. Config.OutputFilename = Filename;
  1271. DC.CopyConfigs.push_back(ConfigMgr);
  1272. }
  1273. }
  1274. if (Config.PreserveDates && (is_contained(Positional, "-") ||
  1275. InputArgs.getLastArgValue(STRIP_output) == "-"))
  1276. return createStringError(errc::invalid_argument,
  1277. "--preserve-dates requires a file");
  1278. return std::move(DC);
  1279. }