cmCustomCommandGenerator.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmCustomCommandGenerator.h"
  4. #include <cstddef>
  5. #include <memory>
  6. #include <utility>
  7. #include <cm/optional>
  8. #include <cm/string_view>
  9. #include <cmext/algorithm>
  10. #include <cmext/string_view>
  11. #include "cmCryptoHash.h"
  12. #include "cmCustomCommand.h"
  13. #include "cmCustomCommandLines.h"
  14. #include "cmGeneratorExpression.h"
  15. #include "cmGeneratorTarget.h"
  16. #include "cmGlobalGenerator.h"
  17. #include "cmList.h"
  18. #include "cmLocalGenerator.h"
  19. #include "cmMakefile.h"
  20. #include "cmStateTypes.h"
  21. #include "cmStringAlgorithms.h"
  22. #include "cmSystemTools.h"
  23. #include "cmTransformDepfile.h"
  24. #include "cmValue.h"
  25. namespace {
  26. std::string EvaluateSplitConfigGenex(
  27. cm::string_view input, cmGeneratorExpression const& ge, cmLocalGenerator* lg,
  28. bool useOutputConfig, std::string const& outputConfig,
  29. std::string const& commandConfig, cmGeneratorTarget const* target,
  30. std::set<BT<std::pair<std::string, bool>>>* utils = nullptr)
  31. {
  32. std::string result;
  33. while (!input.empty()) {
  34. // Copy non-genex content directly to the result.
  35. std::string::size_type pos = input.find("$<");
  36. result += input.substr(0, pos);
  37. if (pos == std::string::npos) {
  38. break;
  39. }
  40. input = input.substr(pos);
  41. // Find the balanced end of this regex.
  42. size_t nestingLevel = 1;
  43. for (pos = 2; pos < input.size(); ++pos) {
  44. cm::string_view cur = input.substr(pos);
  45. if (cmHasLiteralPrefix(cur, "$<")) {
  46. ++nestingLevel;
  47. ++pos;
  48. continue;
  49. }
  50. if (cmHasPrefix(cur, '>')) {
  51. --nestingLevel;
  52. if (nestingLevel == 0) {
  53. ++pos;
  54. break;
  55. }
  56. }
  57. }
  58. // Split this genex from following input.
  59. cm::string_view genex = input.substr(0, pos);
  60. input = input.substr(pos);
  61. // Convert an outer COMMAND_CONFIG or OUTPUT_CONFIG to the matching config.
  62. std::string const* config =
  63. useOutputConfig ? &outputConfig : &commandConfig;
  64. if (nestingLevel == 0) {
  65. static cm::string_view const COMMAND_CONFIG = "$<COMMAND_CONFIG:"_s;
  66. static cm::string_view const OUTPUT_CONFIG = "$<OUTPUT_CONFIG:"_s;
  67. if (cmHasPrefix(genex, COMMAND_CONFIG)) {
  68. genex.remove_prefix(COMMAND_CONFIG.size());
  69. genex.remove_suffix(1);
  70. useOutputConfig = false;
  71. config = &commandConfig;
  72. } else if (cmHasPrefix(genex, OUTPUT_CONFIG)) {
  73. genex.remove_prefix(OUTPUT_CONFIG.size());
  74. genex.remove_suffix(1);
  75. useOutputConfig = true;
  76. config = &outputConfig;
  77. }
  78. }
  79. // Evaluate this genex in the selected configuration.
  80. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  81. ge.Parse(std::string(genex));
  82. result += cge->Evaluate(lg, *config, target);
  83. // Record targets referenced by the genex.
  84. if (utils) {
  85. // Use a cross-dependency if we referenced the command config.
  86. bool const cross = !useOutputConfig;
  87. for (cmGeneratorTarget* gt : cge->GetTargets()) {
  88. utils->emplace(BT<std::pair<std::string, bool>>(
  89. { gt->GetName(), cross }, cge->GetBacktrace()));
  90. }
  91. }
  92. }
  93. return result;
  94. }
  95. std::vector<std::string> EvaluateDepends(std::vector<std::string> const& paths,
  96. cmGeneratorExpression const& ge,
  97. cmLocalGenerator* lg,
  98. std::string const& outputConfig,
  99. std::string const& commandConfig)
  100. {
  101. std::vector<std::string> depends;
  102. for (std::string const& p : paths) {
  103. std::string const& ep =
  104. EvaluateSplitConfigGenex(p, ge, lg, /*useOutputConfig=*/true,
  105. /*outputConfig=*/outputConfig,
  106. /*commandConfig=*/commandConfig,
  107. /*target=*/nullptr);
  108. cm::append(depends, cmList{ ep });
  109. }
  110. for (std::string& p : depends) {
  111. if (cmSystemTools::FileIsFullPath(p)) {
  112. p = cmSystemTools::CollapseFullPath(p);
  113. } else {
  114. cmSystemTools::ConvertToUnixSlashes(p);
  115. }
  116. }
  117. return depends;
  118. }
  119. std::vector<std::string> EvaluateOutputs(std::vector<std::string> const& paths,
  120. cmGeneratorExpression const& ge,
  121. cmLocalGenerator* lg,
  122. std::string const& config)
  123. {
  124. std::vector<std::string> outputs;
  125. for (std::string const& p : paths) {
  126. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(p);
  127. cm::append(outputs, lg->ExpandCustomCommandOutputPaths(*cge, config));
  128. }
  129. return outputs;
  130. }
  131. std::string EvaluateDepfile(std::string const& path,
  132. cmGeneratorExpression const& ge,
  133. cmLocalGenerator* lg, std::string const& config)
  134. {
  135. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(path);
  136. return cge->Evaluate(lg, config);
  137. }
  138. std::string EvaluateComment(char const* comment,
  139. cmGeneratorExpression const& ge,
  140. cmLocalGenerator* lg, std::string const& config)
  141. {
  142. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(comment);
  143. return cge->Evaluate(lg, config);
  144. }
  145. }
  146. cmCustomCommandGenerator::cmCustomCommandGenerator(
  147. cmCustomCommand const& cc, std::string config, cmLocalGenerator* lg,
  148. bool transformDepfile, cm::optional<std::string> crossConfig,
  149. std::function<std::string(std::string const&, std::string const&)>
  150. computeInternalDepfile)
  151. : CC(&cc)
  152. , OutputConfig(crossConfig ? *crossConfig : config)
  153. , CommandConfig(std::move(config))
  154. , Target(cc.GetTarget())
  155. , LG(lg)
  156. , OldStyle(cc.GetEscapeOldStyle())
  157. , MakeVars(cc.GetEscapeAllowMakeVars())
  158. , EmulatorsWithArguments(cc.GetCommandLines().size())
  159. , ComputeInternalDepfile(std::move(computeInternalDepfile))
  160. {
  161. cmGeneratorExpression ge(*lg->GetCMakeInstance(), cc.GetBacktrace());
  162. cmGeneratorTarget const* target{ lg->FindGeneratorTargetToUse(
  163. this->Target) };
  164. bool const distinctConfigs = this->OutputConfig != this->CommandConfig;
  165. cmCustomCommandLines const& cmdlines = this->CC->GetCommandLines();
  166. for (cmCustomCommandLine const& cmdline : cmdlines) {
  167. cmCustomCommandLine argv;
  168. // For the command itself, we default to the COMMAND_CONFIG.
  169. bool useOutputConfig = false;
  170. for (std::string const& clarg : cmdline) {
  171. std::string parsed_arg = EvaluateSplitConfigGenex(
  172. clarg, ge, this->LG, useOutputConfig, this->OutputConfig,
  173. this->CommandConfig, target, &this->Utilities);
  174. if (this->CC->GetCommandExpandLists()) {
  175. cm::append(argv, cmList{ parsed_arg });
  176. } else {
  177. argv.push_back(std::move(parsed_arg));
  178. }
  179. if (distinctConfigs) {
  180. // For remaining arguments, we default to the OUTPUT_CONFIG.
  181. useOutputConfig = true;
  182. }
  183. }
  184. if (!argv.empty()) {
  185. // If the command references an executable target by name,
  186. // collect the target to add a target-level dependency on it.
  187. cmGeneratorTarget* gt = this->LG->FindGeneratorTargetToUse(argv.front());
  188. if (gt && gt->GetType() == cmStateEnums::EXECUTABLE) {
  189. // GetArgv0Location uses the command config, so use a cross-dependency.
  190. bool const cross = true;
  191. this->Utilities.emplace(BT<std::pair<std::string, bool>>(
  192. { gt->GetName(), cross }, cc.GetBacktrace()));
  193. }
  194. } else {
  195. // Later code assumes at least one entry exists, but expanding
  196. // lists on an empty command may have left this empty.
  197. // FIXME: Should we define behavior for removing empty commands?
  198. argv.emplace_back();
  199. }
  200. this->CommandLines.push_back(std::move(argv));
  201. }
  202. if (transformDepfile && !this->CommandLines.empty() &&
  203. !cc.GetDepfile().empty() &&
  204. this->LG->GetGlobalGenerator()->DepfileFormat()) {
  205. cmCustomCommandLine argv;
  206. argv.push_back(cmSystemTools::GetCMakeCommand());
  207. argv.emplace_back("-E");
  208. argv.emplace_back("cmake_transform_depfile");
  209. argv.push_back(this->LG->GetGlobalGenerator()->GetName());
  210. switch (*this->LG->GetGlobalGenerator()->DepfileFormat()) {
  211. case cmDepfileFormat::GccDepfile:
  212. argv.emplace_back("gccdepfile");
  213. break;
  214. case cmDepfileFormat::MakeDepfile:
  215. argv.emplace_back("makedepfile");
  216. break;
  217. case cmDepfileFormat::MSBuildAdditionalInputs:
  218. argv.emplace_back("MSBuildAdditionalInputs");
  219. break;
  220. }
  221. argv.push_back(this->LG->GetSourceDirectory());
  222. argv.push_back(this->LG->GetCurrentSourceDirectory());
  223. argv.push_back(this->LG->GetBinaryDirectory());
  224. argv.push_back(this->LG->GetCurrentBinaryDirectory());
  225. argv.push_back(this->GetFullDepfile());
  226. argv.push_back(this->GetInternalDepfile());
  227. this->CommandLines.push_back(std::move(argv));
  228. }
  229. this->Outputs =
  230. EvaluateOutputs(cc.GetOutputs(), ge, this->LG, this->OutputConfig);
  231. this->Byproducts =
  232. EvaluateOutputs(cc.GetByproducts(), ge, this->LG, this->OutputConfig);
  233. this->Depends = EvaluateDepends(cc.GetDepends(), ge, this->LG,
  234. this->OutputConfig, this->CommandConfig);
  235. std::string const& workingdirectory = this->CC->GetWorkingDirectory();
  236. if (!workingdirectory.empty()) {
  237. this->WorkingDirectory = EvaluateSplitConfigGenex(
  238. workingdirectory, ge, this->LG, true, this->OutputConfig,
  239. this->CommandConfig, target);
  240. // Convert working directory to a full path.
  241. if (!this->WorkingDirectory.empty()) {
  242. std::string const& build_dir = this->LG->GetCurrentBinaryDirectory();
  243. this->WorkingDirectory =
  244. cmSystemTools::CollapseFullPath(this->WorkingDirectory, build_dir);
  245. }
  246. }
  247. this->FillEmulatorsWithArguments();
  248. }
  249. unsigned int cmCustomCommandGenerator::GetNumberOfCommands() const
  250. {
  251. return static_cast<unsigned int>(this->CommandLines.size());
  252. }
  253. void cmCustomCommandGenerator::FillEmulatorsWithArguments()
  254. {
  255. if (!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING")) {
  256. return;
  257. }
  258. cmGeneratorExpression ge(*this->LG->GetCMakeInstance(),
  259. this->CC->GetBacktrace());
  260. for (unsigned int c = 0; c < this->GetNumberOfCommands(); ++c) {
  261. // If the command is the plain name of an executable target,
  262. // launch it with its emulator.
  263. std::string const& argv0 = this->CommandLines[c][0];
  264. cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
  265. if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
  266. !target->IsImported()) {
  267. cmValue emulator_property =
  268. target->GetProperty("CROSSCOMPILING_EMULATOR");
  269. if (!emulator_property) {
  270. continue;
  271. }
  272. // Plain target names are replaced by GetArgv0Location with the
  273. // path to the executable artifact in the command config, so
  274. // evaluate the launcher's location in the command config too.
  275. std::string const emulator =
  276. ge.Parse(*emulator_property)->Evaluate(this->LG, this->CommandConfig);
  277. cmExpandList(emulator, this->EmulatorsWithArguments[c]);
  278. }
  279. }
  280. }
  281. std::vector<std::string> cmCustomCommandGenerator::GetCrossCompilingEmulator(
  282. unsigned int c) const
  283. {
  284. if (c >= this->EmulatorsWithArguments.size()) {
  285. return std::vector<std::string>();
  286. }
  287. return this->EmulatorsWithArguments[c];
  288. }
  289. char const* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
  290. {
  291. // If the command is the plain name of an executable target, we replace it
  292. // with the path to the executable artifact in the command config.
  293. std::string const& argv0 = this->CommandLines[c][0];
  294. cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
  295. if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
  296. (target->IsImported() ||
  297. target->GetProperty("CROSSCOMPILING_EMULATOR") ||
  298. !this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING"))) {
  299. return target->GetLocation(this->CommandConfig).c_str();
  300. }
  301. return nullptr;
  302. }
  303. bool cmCustomCommandGenerator::HasOnlyEmptyCommandLines() const
  304. {
  305. for (cmCustomCommandLine const& ccl : this->CommandLines) {
  306. for (std::string const& cl : ccl) {
  307. if (!cl.empty()) {
  308. return false;
  309. }
  310. }
  311. }
  312. return true;
  313. }
  314. std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
  315. {
  316. std::vector<std::string> emulator = this->GetCrossCompilingEmulator(c);
  317. if (!emulator.empty()) {
  318. return emulator[0];
  319. }
  320. if (char const* location = this->GetArgv0Location(c)) {
  321. return std::string(location);
  322. }
  323. return this->CommandLines[c][0];
  324. }
  325. static std::string escapeForShellOldStyle(std::string const& str)
  326. {
  327. std::string result;
  328. #if defined(_WIN32) && !defined(__CYGWIN__)
  329. // if there are spaces
  330. std::string temp = str;
  331. if (temp.find(" ") != std::string::npos &&
  332. temp.find("\"") == std::string::npos) {
  333. result = cmStrCat('"', str, '"');
  334. return result;
  335. }
  336. return str;
  337. #else
  338. for (char const* ch = str.c_str(); *ch != '\0'; ++ch) {
  339. if (*ch == ' ') {
  340. result += '\\';
  341. }
  342. result += *ch;
  343. }
  344. return result;
  345. #endif
  346. }
  347. void cmCustomCommandGenerator::AppendArguments(unsigned int c,
  348. std::string& cmd) const
  349. {
  350. unsigned int offset = 1;
  351. std::vector<std::string> emulator = this->GetCrossCompilingEmulator(c);
  352. if (!emulator.empty()) {
  353. for (unsigned j = 1; j < emulator.size(); ++j) {
  354. cmd += " ";
  355. if (this->OldStyle) {
  356. cmd += escapeForShellOldStyle(emulator[j]);
  357. } else {
  358. cmd +=
  359. this->LG->EscapeForShell(emulator[j], this->MakeVars, false, false,
  360. this->MakeVars && this->LG->IsNinjaMulti());
  361. }
  362. }
  363. offset = 0;
  364. }
  365. cmCustomCommandLine const& commandLine = this->CommandLines[c];
  366. for (unsigned int j = offset; j < commandLine.size(); ++j) {
  367. std::string arg;
  368. if (char const* location = j == 0 ? this->GetArgv0Location(c) : nullptr) {
  369. // GetCommand returned the emulator instead of the argv0 location,
  370. // so transform the latter now.
  371. arg = location;
  372. } else {
  373. arg = commandLine[j];
  374. }
  375. cmd += " ";
  376. if (this->OldStyle) {
  377. cmd += escapeForShellOldStyle(arg);
  378. } else {
  379. cmd +=
  380. this->LG->EscapeForShell(arg, this->MakeVars, false, false,
  381. this->MakeVars && this->LG->IsNinjaMulti());
  382. }
  383. }
  384. }
  385. std::string cmCustomCommandGenerator::GetDepfile() const
  386. {
  387. auto const& depfile = this->CC->GetDepfile();
  388. if (depfile.empty()) {
  389. return "";
  390. }
  391. cmGeneratorExpression ge(*this->LG->GetCMakeInstance(),
  392. this->CC->GetBacktrace());
  393. return EvaluateDepfile(depfile, ge, this->LG, this->OutputConfig);
  394. }
  395. std::string cmCustomCommandGenerator::GetFullDepfile() const
  396. {
  397. std::string depfile = this->GetDepfile();
  398. if (depfile.empty()) {
  399. return "";
  400. }
  401. if (!cmSystemTools::FileIsFullPath(depfile)) {
  402. depfile = cmStrCat(this->LG->GetCurrentBinaryDirectory(), '/', depfile);
  403. }
  404. return cmSystemTools::CollapseFullPath(depfile);
  405. }
  406. std::string cmCustomCommandGenerator::GetInternalDepfileName(
  407. std::string const& /*config*/, std::string const& depfile) const
  408. {
  409. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  410. std::string extension;
  411. switch (*this->LG->GetGlobalGenerator()->DepfileFormat()) {
  412. case cmDepfileFormat::GccDepfile:
  413. case cmDepfileFormat::MakeDepfile:
  414. extension = ".d";
  415. break;
  416. case cmDepfileFormat::MSBuildAdditionalInputs:
  417. extension = ".AdditionalInputs";
  418. break;
  419. }
  420. return cmStrCat(this->LG->GetBinaryDirectory(), "/CMakeFiles/d/",
  421. hash.HashString(depfile), extension);
  422. }
  423. std::string cmCustomCommandGenerator::GetInternalDepfile() const
  424. {
  425. std::string depfile = this->GetFullDepfile();
  426. if (depfile.empty()) {
  427. return "";
  428. }
  429. if (this->ComputeInternalDepfile) {
  430. return this->ComputeInternalDepfile(this->OutputConfig, depfile);
  431. }
  432. return this->GetInternalDepfileName(this->OutputConfig, depfile);
  433. }
  434. cm::optional<std::string> cmCustomCommandGenerator::GetComment() const
  435. {
  436. char const* comment = this->CC->GetComment();
  437. if (!comment) {
  438. return cm::nullopt;
  439. }
  440. if (!*comment) {
  441. return std::string();
  442. }
  443. cmGeneratorExpression ge(*this->LG->GetCMakeInstance(),
  444. this->CC->GetBacktrace());
  445. return EvaluateComment(comment, ge, this->LG, this->OutputConfig);
  446. }
  447. std::string cmCustomCommandGenerator::GetWorkingDirectory() const
  448. {
  449. return this->WorkingDirectory;
  450. }
  451. std::vector<std::string> const& cmCustomCommandGenerator::GetOutputs() const
  452. {
  453. return this->Outputs;
  454. }
  455. std::vector<std::string> const& cmCustomCommandGenerator::GetByproducts() const
  456. {
  457. return this->Byproducts;
  458. }
  459. std::vector<std::string> const& cmCustomCommandGenerator::GetDepends() const
  460. {
  461. return this->Depends;
  462. }
  463. std::set<BT<std::pair<std::string, bool>>> const&
  464. cmCustomCommandGenerator::GetUtilities() const
  465. {
  466. return this->Utilities;
  467. }