llvm-rc.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. //===-- llvm-rc.cpp - Compile .rc scripts into .res -------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Compile .rc scripts into .res files. This is intended to be a
  10. // platform-independent port of Microsoft's rc.exe tool.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ResourceFileWriter.h"
  14. #include "ResourceScriptCppFilter.h"
  15. #include "ResourceScriptParser.h"
  16. #include "ResourceScriptStmt.h"
  17. #include "ResourceScriptToken.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/Object/WindowsResource.h"
  20. #include "llvm/Option/Arg.h"
  21. #include "llvm/Option/ArgList.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/Error.h"
  24. #include "llvm/Support/FileSystem.h"
  25. #include "llvm/Support/FileUtilities.h"
  26. #include "llvm/Support/Host.h"
  27. #include "llvm/Support/InitLLVM.h"
  28. #include "llvm/Support/ManagedStatic.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/Path.h"
  31. #include "llvm/Support/PrettyStackTrace.h"
  32. #include "llvm/Support/Process.h"
  33. #include "llvm/Support/Program.h"
  34. #include "llvm/Support/Signals.h"
  35. #include "llvm/Support/StringSaver.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm>
  38. #include <system_error>
  39. using namespace llvm;
  40. using namespace llvm::rc;
  41. namespace {
  42. // Input options tables.
  43. enum ID {
  44. OPT_INVALID = 0, // This is not a correct option ID.
  45. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  46. HELPTEXT, METAVAR, VALUES) \
  47. OPT_##ID,
  48. #include "Opts.inc"
  49. #undef OPTION
  50. };
  51. #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
  52. #include "Opts.inc"
  53. #undef PREFIX
  54. const opt::OptTable::Info InfoTable[] = {
  55. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  56. HELPTEXT, METAVAR, VALUES) \
  57. { \
  58. PREFIX, NAME, HELPTEXT, \
  59. METAVAR, OPT_##ID, opt::Option::KIND##Class, \
  60. PARAM, FLAGS, OPT_##GROUP, \
  61. OPT_##ALIAS, ALIASARGS, VALUES},
  62. #include "Opts.inc"
  63. #undef OPTION
  64. };
  65. class RcOptTable : public opt::OptTable {
  66. public:
  67. RcOptTable() : OptTable(InfoTable, /* IgnoreCase = */ true) {}
  68. };
  69. enum Windres_ID {
  70. WINDRES_INVALID = 0, // This is not a correct option ID.
  71. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  72. HELPTEXT, METAVAR, VALUES) \
  73. WINDRES_##ID,
  74. #include "WindresOpts.inc"
  75. #undef OPTION
  76. };
  77. #define PREFIX(NAME, VALUE) const char *const WINDRES_##NAME[] = VALUE;
  78. #include "WindresOpts.inc"
  79. #undef PREFIX
  80. const opt::OptTable::Info WindresInfoTable[] = {
  81. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  82. HELPTEXT, METAVAR, VALUES) \
  83. { \
  84. WINDRES_##PREFIX, NAME, HELPTEXT, \
  85. METAVAR, WINDRES_##ID, opt::Option::KIND##Class, \
  86. PARAM, FLAGS, WINDRES_##GROUP, \
  87. WINDRES_##ALIAS, ALIASARGS, VALUES},
  88. #include "WindresOpts.inc"
  89. #undef OPTION
  90. };
  91. class WindresOptTable : public opt::OptTable {
  92. public:
  93. WindresOptTable() : OptTable(WindresInfoTable, /* IgnoreCase = */ false) {}
  94. };
  95. static ExitOnError ExitOnErr;
  96. static FileRemover TempPreprocFile;
  97. static FileRemover TempResFile;
  98. [[noreturn]] static void fatalError(const Twine &Message) {
  99. errs() << Message << "\n";
  100. exit(1);
  101. }
  102. std::string createTempFile(const Twine &Prefix, StringRef Suffix) {
  103. std::error_code EC;
  104. SmallString<128> FileName;
  105. if ((EC = sys::fs::createTemporaryFile(Prefix, Suffix, FileName)))
  106. fatalError("Unable to create temp file: " + EC.message());
  107. return static_cast<std::string>(FileName);
  108. }
  109. ErrorOr<std::string> findClang(const char *Argv0) {
  110. StringRef Parent = llvm::sys::path::parent_path(Argv0);
  111. ErrorOr<std::string> Path = std::error_code();
  112. if (!Parent.empty()) {
  113. // First look for the tool with all potential names in the specific
  114. // directory of Argv0, if known
  115. for (const auto *Name : {"clang", "clang-cl"}) {
  116. Path = sys::findProgramByName(Name, Parent);
  117. if (Path)
  118. return Path;
  119. }
  120. }
  121. // If no parent directory known, or not found there, look everywhere in PATH
  122. for (const auto *Name : {"clang", "clang-cl"}) {
  123. Path = sys::findProgramByName(Name);
  124. if (Path)
  125. return Path;
  126. }
  127. return Path;
  128. }
  129. bool isUsableArch(Triple::ArchType Arch) {
  130. switch (Arch) {
  131. case Triple::x86:
  132. case Triple::x86_64:
  133. case Triple::arm:
  134. case Triple::thumb:
  135. case Triple::aarch64:
  136. // These work properly with the clang driver, setting the expected
  137. // defines such as _WIN32 etc.
  138. return true;
  139. default:
  140. // Other archs aren't set up for use with windows as target OS, (clang
  141. // doesn't define e.g. _WIN32 etc), so with them we need to set a
  142. // different default arch.
  143. return false;
  144. }
  145. }
  146. Triple::ArchType getDefaultFallbackArch() {
  147. return Triple::x86_64;
  148. }
  149. std::string getClangClTriple() {
  150. Triple T(sys::getDefaultTargetTriple());
  151. if (!isUsableArch(T.getArch()))
  152. T.setArch(getDefaultFallbackArch());
  153. T.setOS(Triple::Win32);
  154. T.setVendor(Triple::PC);
  155. T.setEnvironment(Triple::MSVC);
  156. T.setObjectFormat(Triple::COFF);
  157. return T.str();
  158. }
  159. std::string getMingwTriple() {
  160. Triple T(sys::getDefaultTargetTriple());
  161. if (!isUsableArch(T.getArch()))
  162. T.setArch(getDefaultFallbackArch());
  163. if (T.isWindowsGNUEnvironment())
  164. return T.str();
  165. // Write out the literal form of the vendor/env here, instead of
  166. // constructing them with enum values (which end up with them in
  167. // normalized form). The literal form of the triple can matter for
  168. // finding include files.
  169. return (Twine(T.getArchName()) + "-w64-mingw32").str();
  170. }
  171. enum Format { Rc, Res, Coff, Unknown };
  172. struct RcOptions {
  173. bool Preprocess = true;
  174. bool PrintCmdAndExit = false;
  175. std::string Triple;
  176. std::vector<std::string> PreprocessCmd;
  177. std::vector<std::string> PreprocessArgs;
  178. std::string InputFile;
  179. Format InputFormat = Rc;
  180. std::string OutputFile;
  181. Format OutputFormat = Res;
  182. bool BeVerbose = false;
  183. WriterParams Params;
  184. bool AppendNull = false;
  185. bool IsDryRun = false;
  186. // Set the default language; choose en-US arbitrarily.
  187. unsigned LangId = (/*PrimaryLangId*/ 0x09) | (/*SubLangId*/ 0x01 << 10);
  188. };
  189. bool preprocess(StringRef Src, StringRef Dst, const RcOptions &Opts,
  190. const char *Argv0) {
  191. std::string Clang;
  192. if (Opts.PrintCmdAndExit) {
  193. Clang = "clang";
  194. } else {
  195. ErrorOr<std::string> ClangOrErr = findClang(Argv0);
  196. if (ClangOrErr) {
  197. Clang = *ClangOrErr;
  198. } else {
  199. errs() << "llvm-rc: Unable to find clang, skipping preprocessing."
  200. << "\n";
  201. errs() << "Pass -no-cpp to disable preprocessing. This will be an error "
  202. "in the future."
  203. << "\n";
  204. return false;
  205. }
  206. }
  207. SmallVector<StringRef, 8> Args = {
  208. Clang, "--driver-mode=gcc", "-target", Opts.Triple, "-E",
  209. "-xc", "-DRC_INVOKED"};
  210. if (!Opts.PreprocessCmd.empty()) {
  211. Args.clear();
  212. for (const auto &S : Opts.PreprocessCmd)
  213. Args.push_back(S);
  214. }
  215. Args.push_back(Src);
  216. Args.push_back("-o");
  217. Args.push_back(Dst);
  218. for (const auto &S : Opts.PreprocessArgs)
  219. Args.push_back(S);
  220. if (Opts.PrintCmdAndExit || Opts.BeVerbose) {
  221. for (const auto &A : Args) {
  222. outs() << " ";
  223. sys::printArg(outs(), A, Opts.PrintCmdAndExit);
  224. }
  225. outs() << "\n";
  226. if (Opts.PrintCmdAndExit)
  227. exit(0);
  228. }
  229. // The llvm Support classes don't handle reading from stdout of a child
  230. // process; otherwise we could avoid using a temp file.
  231. int Res = sys::ExecuteAndWait(Clang, Args);
  232. if (Res) {
  233. fatalError("llvm-rc: Preprocessing failed.");
  234. }
  235. return true;
  236. }
  237. static std::pair<bool, std::string> isWindres(llvm::StringRef Argv0) {
  238. StringRef ProgName = llvm::sys::path::stem(Argv0);
  239. // x86_64-w64-mingw32-windres -> x86_64-w64-mingw32, windres
  240. // llvm-rc -> "", llvm-rc
  241. // aarch64-w64-mingw32-llvm-windres-10.exe -> aarch64-w64-mingw32, llvm-windres
  242. ProgName = ProgName.rtrim("0123456789.-");
  243. if (!ProgName.consume_back_insensitive("windres"))
  244. return std::make_pair<bool, std::string>(false, "");
  245. ProgName.consume_back_insensitive("llvm-");
  246. ProgName.consume_back_insensitive("-");
  247. return std::make_pair<bool, std::string>(true, ProgName.str());
  248. }
  249. Format parseFormat(StringRef S) {
  250. Format F = StringSwitch<Format>(S.lower())
  251. .Case("rc", Rc)
  252. .Case("res", Res)
  253. .Case("coff", Coff)
  254. .Default(Unknown);
  255. if (F == Unknown)
  256. fatalError("Unable to parse '" + Twine(S) + "' as a format");
  257. return F;
  258. }
  259. void deduceFormat(Format &Dest, StringRef File) {
  260. Format F = StringSwitch<Format>(sys::path::extension(File.lower()))
  261. .Case(".rc", Rc)
  262. .Case(".res", Res)
  263. .Case(".o", Coff)
  264. .Case(".obj", Coff)
  265. .Default(Unknown);
  266. if (F != Unknown)
  267. Dest = F;
  268. }
  269. std::string unescape(StringRef S) {
  270. std::string Out;
  271. Out.reserve(S.size());
  272. for (int I = 0, E = S.size(); I < E; I++) {
  273. if (S[I] == '\\') {
  274. if (I + 1 < E)
  275. Out.push_back(S[++I]);
  276. else
  277. fatalError("Unterminated escape");
  278. continue;
  279. }
  280. Out.push_back(S[I]);
  281. }
  282. return Out;
  283. }
  284. std::vector<std::string> unescapeSplit(StringRef S) {
  285. std::vector<std::string> OutArgs;
  286. std::string Out;
  287. bool InQuote = false;
  288. for (int I = 0, E = S.size(); I < E; I++) {
  289. if (S[I] == '\\') {
  290. if (I + 1 < E)
  291. Out.push_back(S[++I]);
  292. else
  293. fatalError("Unterminated escape");
  294. continue;
  295. }
  296. if (S[I] == '"') {
  297. InQuote = !InQuote;
  298. continue;
  299. }
  300. if (S[I] == ' ' && !InQuote) {
  301. OutArgs.push_back(Out);
  302. Out.clear();
  303. continue;
  304. }
  305. Out.push_back(S[I]);
  306. }
  307. if (InQuote)
  308. fatalError("Unterminated quote");
  309. if (!Out.empty())
  310. OutArgs.push_back(Out);
  311. return OutArgs;
  312. }
  313. RcOptions parseWindresOptions(ArrayRef<const char *> ArgsArr,
  314. ArrayRef<const char *> InputArgsArray,
  315. std::string Prefix) {
  316. WindresOptTable T;
  317. RcOptions Opts;
  318. unsigned MAI, MAC;
  319. opt::InputArgList InputArgs = T.ParseArgs(ArgsArr, MAI, MAC);
  320. // The tool prints nothing when invoked with no command-line arguments.
  321. if (InputArgs.hasArg(WINDRES_help)) {
  322. T.printHelp(outs(), "windres [options] file...",
  323. "LLVM windres (GNU windres compatible)", false, true);
  324. exit(0);
  325. }
  326. if (InputArgs.hasArg(WINDRES_version)) {
  327. outs() << "llvm-windres, compatible with GNU windres\n";
  328. cl::PrintVersionMessage();
  329. exit(0);
  330. }
  331. std::vector<std::string> FileArgs = InputArgs.getAllArgValues(WINDRES_INPUT);
  332. FileArgs.insert(FileArgs.end(), InputArgsArray.begin(), InputArgsArray.end());
  333. if (InputArgs.hasArg(WINDRES_input)) {
  334. Opts.InputFile = InputArgs.getLastArgValue(WINDRES_input).str();
  335. } else if (!FileArgs.empty()) {
  336. Opts.InputFile = FileArgs.front();
  337. FileArgs.erase(FileArgs.begin());
  338. } else {
  339. // TODO: GNU windres takes input on stdin in this case.
  340. fatalError("Missing input file");
  341. }
  342. if (InputArgs.hasArg(WINDRES_output)) {
  343. Opts.OutputFile = InputArgs.getLastArgValue(WINDRES_output).str();
  344. } else if (!FileArgs.empty()) {
  345. Opts.OutputFile = FileArgs.front();
  346. FileArgs.erase(FileArgs.begin());
  347. } else {
  348. // TODO: GNU windres writes output in rc form to stdout in this case.
  349. fatalError("Missing output file");
  350. }
  351. if (InputArgs.hasArg(WINDRES_input_format)) {
  352. Opts.InputFormat =
  353. parseFormat(InputArgs.getLastArgValue(WINDRES_input_format));
  354. } else {
  355. deduceFormat(Opts.InputFormat, Opts.InputFile);
  356. }
  357. if (Opts.InputFormat == Coff)
  358. fatalError("Unsupported input format");
  359. if (InputArgs.hasArg(WINDRES_output_format)) {
  360. Opts.OutputFormat =
  361. parseFormat(InputArgs.getLastArgValue(WINDRES_output_format));
  362. } else {
  363. // The default in windres differs from the default in RcOptions
  364. Opts.OutputFormat = Coff;
  365. deduceFormat(Opts.OutputFormat, Opts.OutputFile);
  366. }
  367. if (Opts.OutputFormat == Rc)
  368. fatalError("Unsupported output format");
  369. if (Opts.InputFormat == Opts.OutputFormat) {
  370. outs() << "Nothing to do.\n";
  371. exit(0);
  372. }
  373. Opts.PrintCmdAndExit = InputArgs.hasArg(WINDRES__HASH_HASH_HASH);
  374. Opts.Preprocess = !InputArgs.hasArg(WINDRES_no_preprocess);
  375. Triple TT(Prefix);
  376. if (InputArgs.hasArg(WINDRES_target)) {
  377. StringRef Value = InputArgs.getLastArgValue(WINDRES_target);
  378. if (Value == "pe-i386")
  379. Opts.Triple = "i686-w64-mingw32";
  380. else if (Value == "pe-x86-64")
  381. Opts.Triple = "x86_64-w64-mingw32";
  382. else
  383. // Implicit extension; if the --target value isn't one of the known
  384. // BFD targets, allow setting the full triple string via this instead.
  385. Opts.Triple = Value.str();
  386. } else if (TT.getArch() != Triple::UnknownArch)
  387. Opts.Triple = Prefix;
  388. else
  389. Opts.Triple = getMingwTriple();
  390. for (const auto *Arg :
  391. InputArgs.filtered(WINDRES_include_dir, WINDRES_define, WINDRES_undef,
  392. WINDRES_preprocessor_arg)) {
  393. // GNU windres passes the arguments almost as-is on to popen() (it only
  394. // backslash escapes spaces in the arguments), where a shell would
  395. // unescape backslash escapes for quotes and similar. This means that
  396. // when calling GNU windres, callers need to double escape chars like
  397. // quotes, e.g. as -DSTRING=\\\"1.2.3\\\".
  398. //
  399. // Exactly how the arguments are interpreted depends on the platform
  400. // though - but the cases where this matters (where callers would have
  401. // done this double escaping) probably is confined to cases like these
  402. // quoted string defines, and those happen to work the same across unix
  403. // and windows.
  404. std::string Unescaped = unescape(Arg->getValue());
  405. switch (Arg->getOption().getID()) {
  406. case WINDRES_include_dir:
  407. // Technically, these are handled the same way as e.g. defines, but
  408. // the way we consistently unescape the unix way breaks windows paths
  409. // with single backslashes. Alternatively, our unescape function would
  410. // need to mimic the platform specific command line parsing/unescaping
  411. // logic.
  412. Opts.Params.Include.push_back(Arg->getValue());
  413. Opts.PreprocessArgs.push_back("-I");
  414. Opts.PreprocessArgs.push_back(Arg->getValue());
  415. break;
  416. case WINDRES_define:
  417. Opts.PreprocessArgs.push_back("-D");
  418. Opts.PreprocessArgs.push_back(Unescaped);
  419. break;
  420. case WINDRES_undef:
  421. Opts.PreprocessArgs.push_back("-U");
  422. Opts.PreprocessArgs.push_back(Unescaped);
  423. break;
  424. case WINDRES_preprocessor_arg:
  425. Opts.PreprocessArgs.push_back(Unescaped);
  426. break;
  427. }
  428. }
  429. if (InputArgs.hasArg(WINDRES_preprocessor))
  430. Opts.PreprocessCmd =
  431. unescapeSplit(InputArgs.getLastArgValue(WINDRES_preprocessor));
  432. Opts.Params.CodePage = CpWin1252; // Different default
  433. if (InputArgs.hasArg(WINDRES_codepage)) {
  434. if (InputArgs.getLastArgValue(WINDRES_codepage)
  435. .getAsInteger(0, Opts.Params.CodePage))
  436. fatalError("Invalid code page: " +
  437. InputArgs.getLastArgValue(WINDRES_codepage));
  438. }
  439. if (InputArgs.hasArg(WINDRES_language)) {
  440. StringRef Val = InputArgs.getLastArgValue(WINDRES_language);
  441. Val.consume_front_insensitive("0x");
  442. if (Val.getAsInteger(16, Opts.LangId))
  443. fatalError("Invalid language id: " +
  444. InputArgs.getLastArgValue(WINDRES_language));
  445. }
  446. Opts.BeVerbose = InputArgs.hasArg(WINDRES_verbose);
  447. return Opts;
  448. }
  449. RcOptions parseRcOptions(ArrayRef<const char *> ArgsArr,
  450. ArrayRef<const char *> InputArgsArray) {
  451. RcOptTable T;
  452. RcOptions Opts;
  453. unsigned MAI, MAC;
  454. opt::InputArgList InputArgs = T.ParseArgs(ArgsArr, MAI, MAC);
  455. // The tool prints nothing when invoked with no command-line arguments.
  456. if (InputArgs.hasArg(OPT_help)) {
  457. T.printHelp(outs(), "rc [options] file...", "Resource Converter", false);
  458. exit(0);
  459. }
  460. std::vector<std::string> InArgsInfo = InputArgs.getAllArgValues(OPT_INPUT);
  461. InArgsInfo.insert(InArgsInfo.end(), InputArgsArray.begin(),
  462. InputArgsArray.end());
  463. if (InArgsInfo.size() != 1) {
  464. fatalError("Exactly one input file should be provided.");
  465. }
  466. Opts.PrintCmdAndExit = InputArgs.hasArg(OPT__HASH_HASH_HASH);
  467. Opts.Triple = getClangClTriple();
  468. for (const auto *Arg :
  469. InputArgs.filtered(OPT_includepath, OPT_define, OPT_undef)) {
  470. switch (Arg->getOption().getID()) {
  471. case OPT_includepath:
  472. Opts.PreprocessArgs.push_back("-I");
  473. break;
  474. case OPT_define:
  475. Opts.PreprocessArgs.push_back("-D");
  476. break;
  477. case OPT_undef:
  478. Opts.PreprocessArgs.push_back("-U");
  479. break;
  480. }
  481. Opts.PreprocessArgs.push_back(Arg->getValue());
  482. }
  483. Opts.InputFile = InArgsInfo[0];
  484. Opts.BeVerbose = InputArgs.hasArg(OPT_verbose);
  485. Opts.Preprocess = !InputArgs.hasArg(OPT_no_preprocess);
  486. Opts.Params.Include = InputArgs.getAllArgValues(OPT_includepath);
  487. Opts.Params.NoInclude = InputArgs.hasArg(OPT_noinclude);
  488. if (Opts.Params.NoInclude) {
  489. // Clear the INLCUDE variable for the external preprocessor
  490. #ifdef _WIN32
  491. ::_putenv("INCLUDE=");
  492. #else
  493. ::unsetenv("INCLUDE");
  494. #endif
  495. }
  496. if (InputArgs.hasArg(OPT_codepage)) {
  497. if (InputArgs.getLastArgValue(OPT_codepage)
  498. .getAsInteger(10, Opts.Params.CodePage))
  499. fatalError("Invalid code page: " +
  500. InputArgs.getLastArgValue(OPT_codepage));
  501. }
  502. Opts.IsDryRun = InputArgs.hasArg(OPT_dry_run);
  503. auto OutArgsInfo = InputArgs.getAllArgValues(OPT_fileout);
  504. if (OutArgsInfo.empty()) {
  505. SmallString<128> OutputFile(Opts.InputFile);
  506. llvm::sys::fs::make_absolute(OutputFile);
  507. llvm::sys::path::replace_extension(OutputFile, "res");
  508. OutArgsInfo.push_back(std::string(OutputFile.str()));
  509. }
  510. if (!Opts.IsDryRun) {
  511. if (OutArgsInfo.size() != 1)
  512. fatalError(
  513. "No more than one output file should be provided (using /FO flag).");
  514. Opts.OutputFile = OutArgsInfo[0];
  515. }
  516. Opts.AppendNull = InputArgs.hasArg(OPT_add_null);
  517. if (InputArgs.hasArg(OPT_lang_id)) {
  518. StringRef Val = InputArgs.getLastArgValue(OPT_lang_id);
  519. Val.consume_front_insensitive("0x");
  520. if (Val.getAsInteger(16, Opts.LangId))
  521. fatalError("Invalid language id: " +
  522. InputArgs.getLastArgValue(OPT_lang_id));
  523. }
  524. return Opts;
  525. }
  526. RcOptions getOptions(const char *Argv0, ArrayRef<const char *> ArgsArr,
  527. ArrayRef<const char *> InputArgs) {
  528. std::string Prefix;
  529. bool IsWindres;
  530. std::tie(IsWindres, Prefix) = isWindres(Argv0);
  531. if (IsWindres)
  532. return parseWindresOptions(ArgsArr, InputArgs, Prefix);
  533. else
  534. return parseRcOptions(ArgsArr, InputArgs);
  535. }
  536. void doRc(std::string Src, std::string Dest, RcOptions &Opts,
  537. const char *Argv0) {
  538. std::string PreprocessedFile = Src;
  539. if (Opts.Preprocess) {
  540. std::string OutFile = createTempFile("preproc", "rc");
  541. TempPreprocFile.setFile(OutFile);
  542. if (preprocess(Src, OutFile, Opts, Argv0))
  543. PreprocessedFile = OutFile;
  544. }
  545. // Read and tokenize the input file.
  546. ErrorOr<std::unique_ptr<MemoryBuffer>> File =
  547. MemoryBuffer::getFile(PreprocessedFile);
  548. if (!File) {
  549. fatalError("Error opening file '" + Twine(PreprocessedFile) +
  550. "': " + File.getError().message());
  551. }
  552. std::unique_ptr<MemoryBuffer> FileContents = std::move(*File);
  553. StringRef Contents = FileContents->getBuffer();
  554. std::string FilteredContents = filterCppOutput(Contents);
  555. std::vector<RCToken> Tokens = ExitOnErr(tokenizeRC(FilteredContents));
  556. if (Opts.BeVerbose) {
  557. const Twine TokenNames[] = {
  558. #define TOKEN(Name) #Name,
  559. #define SHORT_TOKEN(Name, Ch) #Name,
  560. #include "ResourceScriptTokenList.def"
  561. };
  562. for (const RCToken &Token : Tokens) {
  563. outs() << TokenNames[static_cast<int>(Token.kind())] << ": "
  564. << Token.value();
  565. if (Token.kind() == RCToken::Kind::Int)
  566. outs() << "; int value = " << Token.intValue();
  567. outs() << "\n";
  568. }
  569. }
  570. WriterParams &Params = Opts.Params;
  571. SmallString<128> InputFile(Src);
  572. llvm::sys::fs::make_absolute(InputFile);
  573. Params.InputFilePath = InputFile;
  574. switch (Params.CodePage) {
  575. case CpAcp:
  576. case CpWin1252:
  577. case CpUtf8:
  578. break;
  579. default:
  580. fatalError("Unsupported code page, only 0, 1252 and 65001 are supported!");
  581. }
  582. std::unique_ptr<ResourceFileWriter> Visitor;
  583. if (!Opts.IsDryRun) {
  584. std::error_code EC;
  585. auto FOut = std::make_unique<raw_fd_ostream>(
  586. Dest, EC, sys::fs::FA_Read | sys::fs::FA_Write);
  587. if (EC)
  588. fatalError("Error opening output file '" + Dest + "': " + EC.message());
  589. Visitor = std::make_unique<ResourceFileWriter>(Params, std::move(FOut));
  590. Visitor->AppendNull = Opts.AppendNull;
  591. ExitOnErr(NullResource().visit(Visitor.get()));
  592. unsigned PrimaryLangId = Opts.LangId & 0x3ff;
  593. unsigned SubLangId = Opts.LangId >> 10;
  594. ExitOnErr(LanguageResource(PrimaryLangId, SubLangId).visit(Visitor.get()));
  595. }
  596. rc::RCParser Parser{std::move(Tokens)};
  597. while (!Parser.isEof()) {
  598. auto Resource = ExitOnErr(Parser.parseSingleResource());
  599. if (Opts.BeVerbose)
  600. Resource->log(outs());
  601. if (!Opts.IsDryRun)
  602. ExitOnErr(Resource->visit(Visitor.get()));
  603. }
  604. // STRINGTABLE resources come at the very end.
  605. if (!Opts.IsDryRun)
  606. ExitOnErr(Visitor->dumpAllStringTables());
  607. }
  608. void doCvtres(std::string Src, std::string Dest, std::string TargetTriple) {
  609. object::WindowsResourceParser Parser;
  610. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  611. MemoryBuffer::getFile(Src);
  612. if (!BufferOrErr)
  613. fatalError("Error opening file '" + Twine(Src) +
  614. "': " + BufferOrErr.getError().message());
  615. std::unique_ptr<MemoryBuffer> &Buffer = BufferOrErr.get();
  616. std::unique_ptr<object::WindowsResource> Binary =
  617. ExitOnErr(object::WindowsResource::createWindowsResource(
  618. Buffer->getMemBufferRef()));
  619. std::vector<std::string> Duplicates;
  620. ExitOnErr(Parser.parse(Binary.get(), Duplicates));
  621. for (const auto &DupeDiag : Duplicates)
  622. fatalError("Duplicate resources: " + DupeDiag);
  623. Triple T(TargetTriple);
  624. COFF::MachineTypes MachineType;
  625. switch (T.getArch()) {
  626. case Triple::x86:
  627. MachineType = COFF::IMAGE_FILE_MACHINE_I386;
  628. break;
  629. case Triple::x86_64:
  630. MachineType = COFF::IMAGE_FILE_MACHINE_AMD64;
  631. break;
  632. case Triple::arm:
  633. case Triple::thumb:
  634. MachineType = COFF::IMAGE_FILE_MACHINE_ARMNT;
  635. break;
  636. case Triple::aarch64:
  637. MachineType = COFF::IMAGE_FILE_MACHINE_ARM64;
  638. break;
  639. default:
  640. fatalError("Unsupported architecture in target '" + Twine(TargetTriple) +
  641. "'");
  642. }
  643. std::unique_ptr<MemoryBuffer> OutputBuffer =
  644. ExitOnErr(object::writeWindowsResourceCOFF(MachineType, Parser,
  645. /*DateTimeStamp*/ 0));
  646. std::unique_ptr<FileOutputBuffer> FileBuffer =
  647. ExitOnErr(FileOutputBuffer::create(Dest, OutputBuffer->getBufferSize()));
  648. std::copy(OutputBuffer->getBufferStart(), OutputBuffer->getBufferEnd(),
  649. FileBuffer->getBufferStart());
  650. ExitOnErr(FileBuffer->commit());
  651. }
  652. } // anonymous namespace
  653. int main(int Argc, const char **Argv) {
  654. InitLLVM X(Argc, Argv);
  655. ExitOnErr.setBanner("llvm-rc: ");
  656. const char **DashDash = std::find_if(
  657. Argv + 1, Argv + Argc, [](StringRef Str) { return Str == "--"; });
  658. ArrayRef<const char *> ArgsArr = makeArrayRef(Argv + 1, DashDash);
  659. ArrayRef<const char *> FileArgsArr;
  660. if (DashDash != Argv + Argc)
  661. FileArgsArr = makeArrayRef(DashDash + 1, Argv + Argc);
  662. RcOptions Opts = getOptions(Argv[0], ArgsArr, FileArgsArr);
  663. std::string ResFile = Opts.OutputFile;
  664. if (Opts.InputFormat == Rc) {
  665. if (Opts.OutputFormat == Coff) {
  666. ResFile = createTempFile("rc", "res");
  667. TempResFile.setFile(ResFile);
  668. }
  669. doRc(Opts.InputFile, ResFile, Opts, Argv[0]);
  670. } else {
  671. ResFile = Opts.InputFile;
  672. }
  673. if (Opts.OutputFormat == Coff) {
  674. doCvtres(ResFile, Opts.OutputFile, Opts.Triple);
  675. }
  676. return 0;
  677. }