Main.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. //===- Main.cpp -----------------------------------------------------------===//
  2. //
  3. // The MCLinker Project
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include <mcld/Environment.h>
  10. #include <mcld/IRBuilder.h>
  11. #include <mcld/Linker.h>
  12. #include <mcld/LinkerConfig.h>
  13. #include <mcld/LinkerScript.h>
  14. #include <mcld/Module.h>
  15. #include <mcld/ADT/StringEntry.h>
  16. #include <mcld/MC/InputAction.h>
  17. #include <mcld/MC/CommandAction.h>
  18. #include <mcld/MC/FileAction.h>
  19. #include <mcld/MC/ZOption.h>
  20. #include <mcld/Support/raw_ostream.h>
  21. #include <mcld/Support/MsgHandling.h>
  22. #include <mcld/Support/Path.h>
  23. #include <mcld/Support/SystemUtils.h>
  24. #include <mcld/Support/TargetRegistry.h>
  25. #include <llvm/ADT/ArrayRef.h>
  26. #include <llvm/ADT/SmallVector.h>
  27. #include <llvm/ADT/STLExtras.h>
  28. #include <llvm/ADT/StringRef.h>
  29. #include <llvm/ADT/StringSwitch.h>
  30. #include <llvm/Option/Arg.h>
  31. #include <llvm/Option/ArgList.h>
  32. #include <llvm/Option/OptTable.h>
  33. #include <llvm/Option/Option.h>
  34. #include <llvm/Support/ManagedStatic.h>
  35. #include <llvm/Support/Process.h>
  36. #include <llvm/Support/Signals.h>
  37. #include <cassert>
  38. #include <cstdlib>
  39. #include <string>
  40. #if defined(HAVE_UNISTD_H)
  41. #include <unistd.h>
  42. #endif
  43. #if defined(_MSC_VER) || defined(__MINGW32__)
  44. #include <io.h>
  45. #ifndef STDIN_FILENO
  46. #define STDIN_FILENO 0
  47. #endif
  48. #ifndef STDOUT_FILENO
  49. #define STDOUT_FILENO 1
  50. #endif
  51. #ifndef STDERR_FILENO
  52. #define STDERR_FILENO 2
  53. #endif
  54. #endif
  55. namespace {
  56. class Driver {
  57. private:
  58. enum Option {
  59. // This is not an option.
  60. kOpt_INVALID = 0,
  61. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  62. HELPTEXT, METAVAR) \
  63. kOpt_ ## ID,
  64. #include "Options.inc" // NOLINT
  65. #undef OPTION
  66. kOpt_LastOption
  67. };
  68. class OptTable : public llvm::opt::OptTable {
  69. private:
  70. #define PREFIX(NAME, VALUE) \
  71. static const char* const NAME[];
  72. #include "Options.inc" // NOLINT
  73. #undef PREFIX
  74. static const llvm::opt::OptTable::Info InfoTable[];
  75. public:
  76. OptTable();
  77. };
  78. private:
  79. explicit Driver(const char* prog_name)
  80. : prog_name_(prog_name),
  81. module_(script_),
  82. ir_builder_(module_, config_) {
  83. return;
  84. }
  85. public:
  86. static std::unique_ptr<Driver> Create(llvm::ArrayRef<const char*> argv);
  87. bool Run();
  88. private:
  89. bool TranslateArguments(llvm::opt::InputArgList& args);
  90. private:
  91. const char* prog_name_;
  92. mcld::LinkerScript script_;
  93. mcld::LinkerConfig config_;
  94. mcld::Module module_;
  95. mcld::IRBuilder ir_builder_;
  96. mcld::Linker linker_;
  97. private:
  98. DISALLOW_COPY_AND_ASSIGN(Driver);
  99. };
  100. #define PREFIX(NAME, VALUE) \
  101. const char* const Driver::OptTable::NAME[] = VALUE;
  102. #include "Options.inc" // NOLINT
  103. #undef PREFIX
  104. const llvm::opt::OptTable::Info Driver::OptTable::InfoTable[] = {
  105. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  106. HELPTEXT, METAVAR) \
  107. { PREFIX, NAME, HELPTEXT, METAVAR, kOpt_ ## ID, \
  108. llvm::opt::Option::KIND ## Class, PARAM, FLAGS, kOpt_ ## GROUP, \
  109. kOpt_ ## ALIAS, ALIASARGS },
  110. #include "Options.inc" // NOLINT
  111. #undef OPTION
  112. };
  113. Driver::OptTable::OptTable()
  114. : llvm::opt::OptTable(InfoTable) { }
  115. inline bool ShouldColorize() {
  116. const char* term = getenv("TERM");
  117. return term && (0 != strcmp(term, "dumb"));
  118. }
  119. /// ParseProgName - Parse program name
  120. /// This function simplifies cross-compiling by reading triple from the program
  121. /// name. For example, if the program name is `arm-linux-eabi-ld.mcld', we can
  122. /// get the triple is arm-linux-eabi by the program name.
  123. inline std::string ParseProgName(const char* prog_name) {
  124. static const char* suffixes[] = {"ld", "ld.mcld"};
  125. std::string name(mcld::sys::fs::Path(prog_name).stem().native());
  126. for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
  127. if (name == suffixes[i])
  128. return std::string();
  129. }
  130. llvm::StringRef prog_name_ref(prog_name);
  131. llvm::StringRef prefix;
  132. for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
  133. if (!prog_name_ref.endswith(suffixes[i]))
  134. continue;
  135. llvm::StringRef::size_type last_component =
  136. prog_name_ref.rfind('-', prog_name_ref.size() - strlen(suffixes[i]));
  137. if (last_component == llvm::StringRef::npos)
  138. continue;
  139. llvm::StringRef prefix = prog_name_ref.slice(0, last_component);
  140. std::string ignored_error;
  141. if (!mcld::TargetRegistry::lookupTarget(prefix, ignored_error))
  142. continue;
  143. return prefix.str();
  144. }
  145. return std::string();
  146. }
  147. inline void ParseEmulation(llvm::Triple& triple, const char* emulation) {
  148. llvm::Triple emu_triple =
  149. llvm::StringSwitch<llvm::Triple>(emulation)
  150. .Case("aarch64linux", llvm::Triple("aarch64", "", "linux", "gnu"))
  151. .Case("armelf_linux_eabi", llvm::Triple("arm", "", "linux", "gnu"))
  152. .Case("elf_i386", llvm::Triple("i386", "", "", "gnu"))
  153. .Case("elf_x86_64", llvm::Triple("x86_64", "", "", "gnu"))
  154. .Case("elf32_x86_64", llvm::Triple("x86_64", "", "", "gnux32"))
  155. .Case("elf_i386_fbsd", llvm::Triple("i386", "", "freebsd", "gnu"))
  156. .Case("elf_x86_64_fbsd", llvm::Triple("x86_64", "", "freebsd", "gnu"))
  157. .Case("elf32ltsmip", llvm::Triple("mipsel", "", "", "gnu"))
  158. .Case("elf64ltsmip", llvm::Triple("mips64el", "", "", "gnu"))
  159. .Default(llvm::Triple());
  160. if (emu_triple.getArch() == llvm::Triple::UnknownArch &&
  161. emu_triple.getOS() == llvm::Triple::UnknownOS &&
  162. emu_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
  163. mcld::error(mcld::diag::err_invalid_emulation) << emulation << "\n";
  164. if (emu_triple.getArch() != llvm::Triple::UnknownArch)
  165. triple.setArch(emu_triple.getArch());
  166. if (emu_triple.getOS() != llvm::Triple::UnknownOS)
  167. triple.setOS(emu_triple.getOS());
  168. if (emu_triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
  169. triple.setEnvironment(emu_triple.getEnvironment());
  170. }
  171. /// Configure the output filename.
  172. inline bool ConfigureOutputName(llvm::StringRef output_name,
  173. mcld::Module& module,
  174. mcld::LinkerConfig& config) {
  175. std::string output(output_name.str());
  176. if (output.empty()) {
  177. if (config.targets().triple().getOS() == llvm::Triple::Win32) {
  178. output.assign("_out");
  179. switch (config.codeGenType()) {
  180. case mcld::LinkerConfig::Object: {
  181. output += ".obj";
  182. break;
  183. }
  184. case mcld::LinkerConfig::DynObj: {
  185. output += ".dll";
  186. break;
  187. }
  188. case mcld::LinkerConfig::Exec: {
  189. output += ".exe";
  190. break;
  191. }
  192. case mcld::LinkerConfig::External:
  193. break;
  194. default: {
  195. return false;
  196. break;
  197. }
  198. } // switch (config.codeGenType())
  199. } else {
  200. output.assign("a.out");
  201. }
  202. } // if (output.empty())
  203. module.setName(output);
  204. return true;
  205. }
  206. bool InitializeInputs(mcld::IRBuilder& ir_builder,
  207. std::vector<std::unique_ptr<mcld::InputAction>>& input_actions) {
  208. for (auto& action : input_actions) {
  209. assert(action != nullptr);
  210. action->activate(ir_builder.getInputBuilder());
  211. }
  212. if (ir_builder.getInputBuilder().isInGroup()) {
  213. mcld::fatal(mcld::diag::fatal_forbid_nest_group);
  214. return false;
  215. }
  216. return true;
  217. }
  218. bool Driver::TranslateArguments(llvm::opt::InputArgList& args) {
  219. //===--------------------------------------------------------------------===//
  220. // Preference
  221. //===--------------------------------------------------------------------===//
  222. // --color=mode
  223. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Color)) {
  224. bool res = llvm::StringSwitch<bool>(arg->getValue())
  225. .Case("never", false)
  226. .Case("always", true)
  227. .Case("auto", ShouldColorize() &&
  228. llvm::sys::Process::FileDescriptorIsDisplayed(
  229. STDOUT_FILENO))
  230. .Default(false);
  231. config_.options().setColor(res);
  232. mcld::outs().setColor(res);
  233. mcld::errs().setColor(res);
  234. }
  235. // --trace
  236. config_.options().setTrace(args.hasArg(kOpt_Trace));
  237. // --verbose=level
  238. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Verbose)) {
  239. llvm::StringRef value = arg->getValue();
  240. int level;
  241. if (value.getAsInteger(0, level)) {
  242. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  243. << ": " << arg->getValue();
  244. return false;
  245. }
  246. config_.options().setVerbose(level);
  247. }
  248. // --error-limit NUMBER
  249. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_ErrorLimit)) {
  250. llvm::StringRef value = arg->getValue();
  251. int num;
  252. if (value.getAsInteger(0, num) || (num < 0)) {
  253. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  254. << ": " << arg->getValue();
  255. return false;
  256. }
  257. config_.options().setMaxErrorNum(num);
  258. }
  259. // --warning-limit NUMBER
  260. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_WarningLimit)) {
  261. llvm::StringRef value = arg->getValue();
  262. int num;
  263. if (value.getAsInteger(0, num) || (num < 0)) {
  264. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  265. << ": " << arg->getValue();
  266. return false;
  267. }
  268. config_.options().setMaxWarnNum(num);
  269. }
  270. // --warn-shared-textrel
  271. config_.options().setWarnSharedTextrel(args.hasArg(kOpt_WarnSharedTextrel));
  272. //===--------------------------------------------------------------------===//
  273. // Target
  274. //===--------------------------------------------------------------------===//
  275. llvm::Triple triple;
  276. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Triple)) {
  277. // 1. Use the triple from command.
  278. // -mtriple=value
  279. triple.setTriple(arg->getValue());
  280. } else {
  281. std::string prog_triple = ParseProgName(prog_name_);
  282. if (!prog_triple.empty()) {
  283. // 2. Use the triple from the program name prefix.
  284. triple.setTriple(prog_triple);
  285. } else {
  286. // 3. Use the default target triple.
  287. triple.setTriple(mcld::sys::getDefaultTargetTriple());
  288. }
  289. }
  290. // If a specific emulation was requested, apply it now.
  291. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Emulation)) {
  292. // -m emulation
  293. ParseEmulation(triple, arg->getValue());
  294. } else if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Arch)) {
  295. // -march=value
  296. config_.targets().setArch(arg->getValue());
  297. }
  298. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_CPU)) {
  299. config_.targets().setTargetCPU(arg->getValue());
  300. }
  301. config_.targets().setTriple(triple);
  302. // --gpsize=value
  303. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_GPSize)) {
  304. llvm::StringRef value = arg->getValue();
  305. int size;
  306. if (value.getAsInteger(0, size) || (size< 0)) {
  307. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  308. << ": " << arg->getValue() << "\n";
  309. return false;
  310. }
  311. config_.targets().setGPSize(size);
  312. }
  313. // --stub-group-size=value
  314. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_StubGroupSize)) {
  315. llvm::StringRef value = arg->getValue();
  316. int size;
  317. if (value.getAsInteger(0, size) || (size< 0)) {
  318. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  319. << ": " << arg->getValue() << "\n";
  320. return false;
  321. }
  322. config_.targets().setStubGroupSize(size);
  323. }
  324. // --fix-cortex-a53-835769
  325. config_.targets().setFixCA53Erratum835769(
  326. args.hasArg(kOpt_FixCA53Erratum835769));
  327. // --fix-cortex-a53-843419
  328. config_.targets().setFixCA53Erratum843419(
  329. args.hasArg(kOpt_FixCA53Erratum843419));
  330. //===--------------------------------------------------------------------===//
  331. // Dynamic
  332. //===--------------------------------------------------------------------===//
  333. // --entry=entry
  334. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Entry)) {
  335. script_.setEntry(arg->getValue());
  336. }
  337. // -Bsymbolic
  338. config_.options().setBsymbolic(args.hasArg(kOpt_Bsymbolic));
  339. // -Bgroup
  340. config_.options().setBgroup(args.hasArg(kOpt_Bgroup));
  341. // -soname=name
  342. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_SOName)) {
  343. config_.options().setSOName(arg->getValue());
  344. }
  345. // --no-undefined
  346. if (args.hasArg(kOpt_NoUndef)) {
  347. config_.options().setNoUndefined(true);
  348. }
  349. // --allow-multiple-definition
  350. if (args.hasArg(kOpt_AllowMulDefs)) {
  351. config_.options().setMulDefs(true);
  352. }
  353. // -z options
  354. for (llvm::opt::Arg* arg : args.filtered(kOpt_Z)) {
  355. llvm::StringRef value = arg->getValue();
  356. mcld::ZOption z_opt =
  357. llvm::StringSwitch<mcld::ZOption>(value)
  358. .Case("combreloc", mcld::ZOption(mcld::ZOption::CombReloc))
  359. .Case("nocombreloc", mcld::ZOption(mcld::ZOption::NoCombReloc))
  360. .Case("defs", mcld::ZOption(mcld::ZOption::Defs))
  361. .Case("execstack", mcld::ZOption(mcld::ZOption::ExecStack))
  362. .Case("noexecstack", mcld::ZOption(mcld::ZOption::NoExecStack))
  363. .Case("initfirst", mcld::ZOption(mcld::ZOption::InitFirst))
  364. .Case("interpose", mcld::ZOption(mcld::ZOption::InterPose))
  365. .Case("loadfltr", mcld::ZOption(mcld::ZOption::LoadFltr))
  366. .Case("muldefs", mcld::ZOption(mcld::ZOption::MulDefs))
  367. .Case("nocopyreloc", mcld::ZOption(mcld::ZOption::NoCopyReloc))
  368. .Case("nodefaultlib", mcld::ZOption(mcld::ZOption::NoDefaultLib))
  369. .Case("nodelete", mcld::ZOption(mcld::ZOption::NoDelete))
  370. .Case("nodlopen", mcld::ZOption(mcld::ZOption::NoDLOpen))
  371. .Case("nodump", mcld::ZOption(mcld::ZOption::NoDump))
  372. .Case("relro", mcld::ZOption(mcld::ZOption::Relro))
  373. .Case("norelro", mcld::ZOption(mcld::ZOption::NoRelro))
  374. .Case("lazy", mcld::ZOption(mcld::ZOption::Lazy))
  375. .Case("now", mcld::ZOption(mcld::ZOption::Now))
  376. .Case("origin", mcld::ZOption(mcld::ZOption::Origin))
  377. .Default(mcld::ZOption());
  378. if (z_opt.kind() == mcld::ZOption::Unknown) {
  379. if (value.startswith("common-page-size=")) {
  380. // -z common-page-size=value
  381. z_opt.setKind(mcld::ZOption::CommPageSize);
  382. long long unsigned size = 0;
  383. value.drop_front(17).getAsInteger(0, size);
  384. z_opt.setPageSize(static_cast<uint64_t>(size));
  385. } else if (value.startswith("max-page-size=")) {
  386. // -z max-page-size=value
  387. z_opt.setKind(mcld::ZOption::MaxPageSize);
  388. long long unsigned size = 0;
  389. value.drop_front(14).getAsInteger(0, size);
  390. z_opt.setPageSize(static_cast<uint64_t>(size));
  391. }
  392. }
  393. config_.options().addZOption(z_opt);
  394. }
  395. // --dynamic-linker=file
  396. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Dyld)) {
  397. config_.options().setDyld(arg->getValue());
  398. }
  399. // --enable-new-dtags
  400. config_.options().setNewDTags(args.hasArg(kOpt_EnableNewDTags));
  401. // --spare-dyanmic-tags COUNT
  402. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_SpareDTags)) {
  403. llvm::StringRef value = arg->getValue();
  404. int num;
  405. if (value.getAsInteger(0, num) || (num < 0)) {
  406. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  407. << ": " << arg->getValue() << "\n";
  408. return false;
  409. }
  410. config_.options().setNumSpareDTags(num);
  411. }
  412. //===--------------------------------------------------------------------===//
  413. // Output
  414. //===--------------------------------------------------------------------===//
  415. // Setup the codegen type.
  416. if (args.hasArg(kOpt_Shared) || args.hasArg(kOpt_PIE)) {
  417. // -shared, -pie
  418. config_.setCodeGenType(mcld::LinkerConfig::DynObj);
  419. } else if (args.hasArg(kOpt_Relocatable)) {
  420. // -r
  421. config_.setCodeGenType(mcld::LinkerConfig::Object);
  422. } else if (llvm::opt::Arg* arg = args.getLastArg(kOpt_OutputFormat)) {
  423. // --oformat=value
  424. llvm::StringRef value = arg->getValue();
  425. if (value.equals("binary")) {
  426. config_.setCodeGenType(mcld::LinkerConfig::Binary);
  427. }
  428. } else {
  429. config_.setCodeGenType(mcld::LinkerConfig::Exec);
  430. }
  431. // Setup the output filename.
  432. llvm::StringRef output_name;
  433. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Output)) {
  434. output_name = arg->getValue();
  435. }
  436. if (!ConfigureOutputName(output_name, module_, config_)) {
  437. mcld::unreachable(mcld::diag::unrecognized_output_file) << module_.name();
  438. return false;
  439. } else {
  440. if (!args.hasArg(kOpt_SOName)) {
  441. config_.options().setSOName(module_.name());
  442. }
  443. }
  444. // --format=value
  445. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_InputFormat)) {
  446. llvm::StringRef value = arg->getValue();
  447. if (value.equals("binary")) {
  448. config_.options().setBinaryInput();
  449. }
  450. }
  451. // Setup debug info stripping.
  452. config_.options().setStripDebug(args.hasArg(kOpt_StripDebug) ||
  453. args.hasArg(kOpt_StripAll));
  454. // Setup symbol stripping mode.
  455. if (args.hasArg(kOpt_StripAll)) {
  456. config_.options().setStripSymbols(
  457. mcld::GeneralOptions::StripSymbolMode::StripAllSymbols);
  458. } else if (args.hasArg(kOpt_DiscardAll)) {
  459. config_.options().setStripSymbols(
  460. mcld::GeneralOptions::StripSymbolMode::StripLocals);
  461. } else if (args.hasArg(kOpt_DiscardLocals)) {
  462. config_.options().setStripSymbols(
  463. mcld::GeneralOptions::StripSymbolMode::StripTemporaries);
  464. } else {
  465. config_.options().setStripSymbols(
  466. mcld::GeneralOptions::StripSymbolMode::KeepAllSymbols);
  467. }
  468. // --eh-frame-hdr
  469. config_.options().setEhFrameHdr(args.hasArg(kOpt_EHFrameHdr));
  470. // -pie
  471. config_.options().setPIE(args.hasArg(kOpt_PIE));
  472. // --nmagic
  473. config_.options().setNMagic(args.hasArg(kOpt_NMagic));
  474. // --omagic
  475. config_.options().setOMagic(args.hasArg(kOpt_OMagic));
  476. // --hash-style=style
  477. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_HashStyle)) {
  478. mcld::GeneralOptions::HashStyle style =
  479. llvm::StringSwitch<mcld::GeneralOptions::HashStyle>(arg->getValue())
  480. .Case("sysv", mcld::GeneralOptions::HashStyle::SystemV)
  481. .Case("gnu", mcld::GeneralOptions::HashStyle::GNU)
  482. .Case("both", mcld::GeneralOptions::HashStyle::Both)
  483. .Default(mcld::GeneralOptions::HashStyle::Unknown);
  484. if (style != mcld::GeneralOptions::HashStyle::Unknown) {
  485. config_.options().setHashStyle(style);
  486. }
  487. }
  488. // --[no]-export-dynamic
  489. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_ExportDynamic,
  490. kOpt_NoExportDynamic)) {
  491. if (arg->getOption().matches(kOpt_ExportDynamic)) {
  492. config_.options().setExportDynamic(true);
  493. } else {
  494. config_.options().setExportDynamic(false);
  495. }
  496. }
  497. // --no-warn-mismatch
  498. config_.options().setWarnMismatch(!args.hasArg(kOpt_NoWarnMismatch));
  499. // --exclude-libs
  500. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_ExcludeLibs)) {
  501. llvm::StringRef value = arg->getValue();
  502. do {
  503. std::pair<llvm::StringRef, llvm::StringRef> res = value.split(',');
  504. config_.options().excludeLIBS().insert(res.first.str());
  505. value = res.second;
  506. } while (!value.empty());
  507. }
  508. //===--------------------------------------------------------------------===//
  509. // Search Path
  510. //===--------------------------------------------------------------------===//
  511. // --sysroot
  512. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Sysroot)) {
  513. mcld::sys::fs::Path path(arg->getValue());
  514. if (mcld::sys::fs::exists(path) && mcld::sys::fs::is_directory(path)) {
  515. script_.setSysroot(path);
  516. }
  517. }
  518. // -L searchdir
  519. for (llvm::opt::Arg* arg : args.filtered(kOpt_LibraryPath)) {
  520. if (!script_.directories().insert(arg->getValue()))
  521. mcld::warning(mcld::diag::warn_cannot_open_search_dir) << arg->getValue();
  522. }
  523. // -nostdlib
  524. config_.options().setNoStdlib(args.hasArg(kOpt_NoStdlib));
  525. // -rpath=path
  526. for (llvm::opt::Arg* arg : args.filtered(kOpt_RPath)) {
  527. config_.options().getRpathList().push_back(arg->getValue());
  528. }
  529. //===--------------------------------------------------------------------===//
  530. // Symbol
  531. //===--------------------------------------------------------------------===//
  532. // -d/-dc/-dp
  533. config_.options().setDefineCommon(args.hasArg(kOpt_DefineCommon));
  534. // -u symbol
  535. for (llvm::opt::Arg* arg : args.filtered(kOpt_Undefined)) {
  536. config_.options().getUndefSymList().push_back(arg->getValue());
  537. }
  538. //===--------------------------------------------------------------------===//
  539. // Script
  540. //===--------------------------------------------------------------------===//
  541. // --wrap=symbol
  542. for (llvm::opt::Arg* arg : args.filtered(kOpt_Wrap)) {
  543. bool exist = false;
  544. const char* symbol = arg->getValue();
  545. // symbol -> __wrap_symbol
  546. mcld::StringEntry<llvm::StringRef>* to_wrap =
  547. script_.renameMap().insert(symbol, exist);
  548. std::string to_wrap_str;
  549. to_wrap_str.append("__wrap_")
  550. .append(symbol);
  551. to_wrap->setValue(to_wrap_str);
  552. if (exist)
  553. mcld::warning(mcld::diag::rewrap) << symbol << to_wrap_str;
  554. // __real_symbol -> symbol
  555. std::string from_real_str;
  556. to_wrap_str.append("__real_")
  557. .append(symbol);
  558. mcld::StringEntry<llvm::StringRef>* from_real =
  559. script_.renameMap().insert(from_real_str, exist);
  560. from_real->setValue(symbol);
  561. if (exist)
  562. mcld::warning(mcld::diag::rewrap) << symbol << from_real_str;
  563. }
  564. // --portalbe=symbol
  565. for (llvm::opt::Arg* arg : args.filtered(kOpt_Portable)) {
  566. bool exist = false;
  567. const char* symbol = arg->getValue();
  568. // symbol -> symbol_portable
  569. mcld::StringEntry<llvm::StringRef>* to_wrap =
  570. script_.renameMap().insert(symbol, exist);
  571. std::string to_wrap_str;
  572. to_wrap_str.append(symbol)
  573. .append("_portable");
  574. to_wrap->setValue(to_wrap_str);
  575. if (exist)
  576. mcld::warning(mcld::diag::rewrap) << symbol << to_wrap_str;
  577. // __real_symbol -> symbol
  578. std::string from_real_str;
  579. to_wrap_str.append("__real_")
  580. .append(symbol);
  581. mcld::StringEntry<llvm::StringRef>* from_real =
  582. script_.renameMap().insert(from_real_str, exist);
  583. from_real->setValue(symbol);
  584. if (exist)
  585. mcld::warning(mcld::diag::rewrap) << symbol << from_real_str;
  586. }
  587. // --section-start=section=addr
  588. for (llvm::opt::Arg* arg : args.filtered(kOpt_SectionStart)) {
  589. llvm::StringRef value = arg->getValue();
  590. const size_t pos = value.find('=');
  591. uint64_t addr = 0;
  592. value.substr(pos + 1).getAsInteger(0, addr);
  593. bool exist = false;
  594. mcld::StringEntry<uint64_t>* mapping =
  595. script_.addressMap().insert(value.substr(0, pos), exist);
  596. mapping->setValue(addr);
  597. }
  598. // -Tbss=value
  599. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Tbss)) {
  600. llvm::StringRef value = arg->getValue();
  601. uint64_t addr = 0;
  602. if (value.getAsInteger(0, addr)) {
  603. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  604. << ": " << arg->getValue() << "\n";
  605. return false;
  606. }
  607. bool exist = false;
  608. mcld::StringEntry<uint64_t>* mapping =
  609. script_.addressMap().insert(".bss", exist);
  610. mapping->setValue(addr);
  611. }
  612. // -Tdata=value
  613. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Tdata)) {
  614. llvm::StringRef value = arg->getValue();
  615. uint64_t addr = 0;
  616. if (value.getAsInteger(0, addr)) {
  617. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  618. << ": " << arg->getValue() << "\n";
  619. return false;
  620. }
  621. bool exist = false;
  622. mcld::StringEntry<uint64_t>* mapping =
  623. script_.addressMap().insert(".data", exist);
  624. mapping->setValue(addr);
  625. }
  626. // -Ttext=value
  627. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_Ttext)) {
  628. llvm::StringRef value = arg->getValue();
  629. uint64_t addr = 0;
  630. if (value.getAsInteger(0, addr)) {
  631. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  632. << ": " << arg->getValue() << "\n";
  633. return false;
  634. }
  635. bool exist = false;
  636. mcld::StringEntry<uint64_t>* mapping =
  637. script_.addressMap().insert(".text", exist);
  638. mapping->setValue(addr);
  639. }
  640. //===--------------------------------------------------------------------===//
  641. // Optimization
  642. //===--------------------------------------------------------------------===//
  643. // --[no-]gc-sections
  644. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_GCSections,
  645. kOpt_NoGCSections)) {
  646. if (arg->getOption().matches(kOpt_GCSections)) {
  647. config_.options().setGCSections(true);
  648. } else {
  649. config_.options().setGCSections(false);
  650. }
  651. }
  652. // --[no-]print-gc-sections
  653. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_PrintGCSections,
  654. kOpt_NoPrintGCSections)) {
  655. if (arg->getOption().matches(kOpt_PrintGCSections)) {
  656. config_.options().setPrintGCSections(true);
  657. } else {
  658. config_.options().setPrintGCSections(false);
  659. }
  660. }
  661. // --[no-]ld-generated-unwind-info
  662. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_LDGeneratedUnwindInfo,
  663. kOpt_NoLDGeneratedUnwindInfo)) {
  664. if (arg->getOption().matches(kOpt_LDGeneratedUnwindInfo)) {
  665. config_.options().setGenUnwindInfo(true);
  666. } else {
  667. config_.options().setGenUnwindInfo(false);
  668. }
  669. }
  670. // --icf=mode
  671. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_ICF)) {
  672. mcld::GeneralOptions::ICF mode =
  673. llvm::StringSwitch<mcld::GeneralOptions::ICF>(arg->getValue())
  674. .Case("none", mcld::GeneralOptions::ICF::None)
  675. .Case("all", mcld::GeneralOptions::ICF::All)
  676. .Case("safe", mcld::GeneralOptions::ICF::Safe)
  677. .Default(mcld::GeneralOptions::ICF::Unknown);
  678. if (mode == mcld::GeneralOptions::ICF::Unknown) {
  679. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  680. << ": " << arg->getValue() << "\n";
  681. return false;
  682. }
  683. config_.options().setICFMode(mode);
  684. }
  685. // --icf-iterations
  686. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_ICFIters)) {
  687. llvm::StringRef value = arg->getValue();
  688. int num;
  689. if (value.getAsInteger(0, num) || (num < 0)) {
  690. mcld::errs() << "Invalid value for" << arg->getOption().getPrefixedName()
  691. << ": " << arg->getValue() << "\n";
  692. return false;
  693. }
  694. config_.options().setICFIterations(num);
  695. }
  696. // --[no-]print-icf-sections
  697. if (llvm::opt::Arg* arg = args.getLastArg(kOpt_PrintICFSections,
  698. kOpt_NoPrintICFSections)) {
  699. if (arg->getOption().matches(kOpt_PrintICFSections)) {
  700. config_.options().setPrintICFSections(true);
  701. } else {
  702. config_.options().setPrintICFSections(false);
  703. }
  704. }
  705. //===--------------------------------------------------------------------===//
  706. // Positional
  707. //===--------------------------------------------------------------------===//
  708. // # of regular objects, script, and namespec.
  709. size_t input_num = 0;
  710. typedef std::unique_ptr<mcld::InputAction> Action;
  711. std::vector<Action> actions;
  712. Action action;
  713. actions.reserve(32);
  714. for (llvm::opt::Arg* arg : args) {
  715. const unsigned index = arg->getIndex();
  716. switch (arg->getOption().getID()) {
  717. // -T script
  718. case kOpt_Script: {
  719. const char* value = arg->getValue();
  720. config_.options().getScriptList().push_back(value);
  721. // FIXME: Let index of script file be 0.
  722. action.reset(new mcld::ScriptAction(
  723. 0x0, value, mcld::ScriptFile::LDScript, script_.directories()));
  724. actions.push_back(std::move(action));
  725. action.reset(new mcld::ContextAction(0x0));
  726. actions.push_back(std::move(action));
  727. action.reset(new mcld::MemoryAreaAction(0x0,
  728. mcld::FileHandle::ReadOnly));
  729. actions.push_back(std::move(action));
  730. ++input_num;
  731. break;
  732. }
  733. // --defsym=symbol=expr
  734. case kOpt_DefSym: {
  735. std::string expr;
  736. expr.append(arg->getValue())
  737. .append(";");
  738. script_.defsyms().push_back(std::move(expr));
  739. action.reset(new mcld::DefSymAction(index, script_.defsyms().back()));
  740. actions.push_back(std::move(action));
  741. break;
  742. }
  743. // -l namespec
  744. case kOpt_Namespec: {
  745. action.reset(new mcld::NamespecAction(
  746. index, arg->getValue(), script_.directories()));
  747. actions.push_back(std::move(action));
  748. action.reset(new mcld::ContextAction(index));
  749. actions.push_back(std::move(action));
  750. action.reset(new mcld::MemoryAreaAction(index,
  751. mcld::FileHandle::ReadOnly));
  752. actions.push_back(std::move(action));
  753. ++input_num;
  754. break;
  755. }
  756. // --whole-archive
  757. case kOpt_WholeArchive: {
  758. action.reset(new mcld::WholeArchiveAction(index));
  759. actions.push_back(std::move(action));
  760. break;
  761. }
  762. // --no-whole-archive
  763. case kOpt_NoWholeArchive: {
  764. action.reset(new mcld::NoWholeArchiveAction(index));
  765. actions.push_back(std::move(action));
  766. break;
  767. }
  768. // --as-needed
  769. case kOpt_AsNeeded: {
  770. action.reset(new mcld::AsNeededAction(index));
  771. actions.push_back(std::move(action));
  772. break;
  773. }
  774. // --no-as-needed
  775. case kOpt_NoAsNeeded: {
  776. action.reset(new mcld::NoAsNeededAction(index));
  777. actions.push_back(std::move(action));
  778. break;
  779. }
  780. // --add-needed
  781. // FIXME: This is deprecated. Should be --copy-dt-needed-entries.
  782. case kOpt_AddNeeded:
  783. case kOpt_CopyDTNeeded: {
  784. action.reset(new mcld::AddNeededAction(index));
  785. actions.push_back(std::move(action));
  786. break;
  787. }
  788. // --no-add-needed
  789. // FIXME: This is deprecated. Should be --no-copy-dt-needed-entries.
  790. case kOpt_NoAddNeeded:
  791. case kOpt_NoCopyDTNeeded: {
  792. action.reset(new mcld::AddNeededAction(index));
  793. actions.push_back(std::move(action));
  794. break;
  795. }
  796. // -Bdynamic
  797. case kOpt_Bdynamic: {
  798. action.reset(new mcld::BDynamicAction(index));
  799. actions.push_back(std::move(action));
  800. break;
  801. }
  802. // -Bstatic
  803. case kOpt_Bstatic: {
  804. action.reset(new mcld::BStaticAction(index));
  805. actions.push_back(std::move(action));
  806. break;
  807. }
  808. // --start-group
  809. case kOpt_StartGroup: {
  810. action.reset(new mcld::StartGroupAction(index));
  811. actions.push_back(std::move(action));
  812. break;
  813. }
  814. // --end-group
  815. case kOpt_EndGroup: {
  816. action.reset(new mcld::EndGroupAction(index));
  817. actions.push_back(std::move(action));
  818. break;
  819. }
  820. case kOpt_INPUT: {
  821. action.reset(new mcld::InputFileAction(index, arg->getValue()));
  822. actions.push_back(std::move(action));
  823. action.reset(new mcld::ContextAction(index));
  824. actions.push_back(std::move(action));
  825. action.reset(new mcld::MemoryAreaAction(index,
  826. mcld::FileHandle::ReadOnly));
  827. actions.push_back(std::move(action));
  828. ++input_num;
  829. break;
  830. }
  831. default:
  832. break;
  833. }
  834. }
  835. if (input_num == 0) {
  836. mcld::fatal(mcld::diag::err_no_inputs);
  837. return false;
  838. }
  839. // Stable sort
  840. std::stable_sort(actions.begin(),
  841. actions.end(),
  842. [] (const Action& X, const Action& Y) {
  843. return X->position() < Y->position();
  844. });
  845. if (!InitializeInputs(ir_builder_, actions)) {
  846. mcld::errs() << "Failed to initialize input tree!\n";
  847. return false;
  848. }
  849. //===--------------------------------------------------------------------===//
  850. // Unknown
  851. //===--------------------------------------------------------------------===//
  852. std::vector<std::string> unknown_args = args.getAllArgValues(kOpt_UNKNOWN);
  853. for (std::string arg : unknown_args)
  854. mcld::warning(mcld::diag::warn_unsupported_option) << arg;
  855. return true;
  856. }
  857. std::unique_ptr<Driver> Driver::Create(llvm::ArrayRef<const char*> argv) {
  858. // Parse command line options.
  859. OptTable opt_table;
  860. unsigned missing_arg_idx;
  861. unsigned missing_arg_count;
  862. llvm::opt::InputArgList args =
  863. opt_table.ParseArgs(argv.slice(1), missing_arg_idx, missing_arg_count);
  864. if (missing_arg_count > 0) {
  865. mcld::errs() << "Argument to '" << args.getArgString(missing_arg_idx)
  866. << "' is missing (expected " << missing_arg_count
  867. << ((missing_arg_count > 1) ? " values" : " value") << ")\n";
  868. return nullptr;
  869. }
  870. std::unique_ptr<Driver> result(new Driver(argv[0]));
  871. // Return quickly if -help is specified.
  872. if (args.hasArg(kOpt_Help)) {
  873. opt_table.PrintHelp(mcld::outs(), argv[0], "MCLinker",
  874. /* FlagsToInclude */0, /* FlagsToExclude */0);
  875. return nullptr;
  876. }
  877. // Print version information if requested.
  878. if (args.hasArg(kOpt_Version)) {
  879. mcld::outs() << result->config_.options().getVersionString() << "\n";
  880. }
  881. // Setup instance from arguments.
  882. if (!result->TranslateArguments(args)) {
  883. return nullptr;
  884. }
  885. return result;
  886. }
  887. bool Driver::Run() {
  888. mcld::Initialize();
  889. if (!linker_.emulate(script_, config_)) {
  890. mcld::errs() << "Failed to emulate target!\n";
  891. return false;
  892. }
  893. if (!linker_.link(module_, ir_builder_)) {
  894. mcld::errs() << "Failed to link objects!\n";
  895. return false;
  896. }
  897. if (!linker_.emit(module_, module_.name())) {
  898. mcld::errs() << "Failed to emit output!\n";
  899. return false;
  900. }
  901. mcld::Finalize();
  902. return true;
  903. }
  904. } // anonymous namespace
  905. int main(int argc, char** argv) {
  906. std::unique_ptr<Driver> driver =
  907. Driver::Create(llvm::makeArrayRef(argv, argc));
  908. if ((driver == nullptr) || !driver->Run()) {
  909. return EXIT_FAILURE;
  910. } else {
  911. return EXIT_SUCCESS;
  912. }
  913. }