cmCustomCommandGenerator.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt 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 (cmHasLiteralPrefix(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(const char* 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(const std::string&, const std::string&)>
  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. if (!this->ComputeInternalDepfile) {
  162. this->ComputeInternalDepfile =
  163. [this](const std::string& cfg, const std::string& file) -> std::string {
  164. return this->GetInternalDepfileName(cfg, file);
  165. };
  166. }
  167. cmGeneratorExpression ge(*lg->GetCMakeInstance(), cc.GetBacktrace());
  168. cmGeneratorTarget const* target{ lg->FindGeneratorTargetToUse(
  169. this->Target) };
  170. bool const distinctConfigs = this->OutputConfig != this->CommandConfig;
  171. const cmCustomCommandLines& cmdlines = this->CC->GetCommandLines();
  172. for (cmCustomCommandLine const& cmdline : cmdlines) {
  173. cmCustomCommandLine argv;
  174. // For the command itself, we default to the COMMAND_CONFIG.
  175. bool useOutputConfig = false;
  176. for (std::string const& clarg : cmdline) {
  177. std::string parsed_arg = EvaluateSplitConfigGenex(
  178. clarg, ge, this->LG, useOutputConfig, this->OutputConfig,
  179. this->CommandConfig, target, &this->Utilities);
  180. if (this->CC->GetCommandExpandLists()) {
  181. cm::append(argv, cmList{ parsed_arg });
  182. } else {
  183. argv.push_back(std::move(parsed_arg));
  184. }
  185. if (distinctConfigs) {
  186. // For remaining arguments, we default to the OUTPUT_CONFIG.
  187. useOutputConfig = true;
  188. }
  189. }
  190. if (!argv.empty()) {
  191. // If the command references an executable target by name,
  192. // collect the target to add a target-level dependency on it.
  193. cmGeneratorTarget* gt = this->LG->FindGeneratorTargetToUse(argv.front());
  194. if (gt && gt->GetType() == cmStateEnums::EXECUTABLE) {
  195. // GetArgv0Location uses the command config, so use a cross-dependency.
  196. bool const cross = true;
  197. this->Utilities.emplace(BT<std::pair<std::string, bool>>(
  198. { gt->GetName(), cross }, cc.GetBacktrace()));
  199. }
  200. } else {
  201. // Later code assumes at least one entry exists, but expanding
  202. // lists on an empty command may have left this empty.
  203. // FIXME: Should we define behavior for removing empty commands?
  204. argv.emplace_back();
  205. }
  206. this->CommandLines.push_back(std::move(argv));
  207. }
  208. if (transformDepfile && !this->CommandLines.empty() &&
  209. !cc.GetDepfile().empty() &&
  210. this->LG->GetGlobalGenerator()->DepfileFormat()) {
  211. cmCustomCommandLine argv;
  212. argv.push_back(cmSystemTools::GetCMakeCommand());
  213. argv.emplace_back("-E");
  214. argv.emplace_back("cmake_transform_depfile");
  215. argv.push_back(this->LG->GetGlobalGenerator()->GetName());
  216. switch (*this->LG->GetGlobalGenerator()->DepfileFormat()) {
  217. case cmDepfileFormat::GccDepfile:
  218. argv.emplace_back("gccdepfile");
  219. break;
  220. case cmDepfileFormat::MakeDepfile:
  221. argv.emplace_back("makedepfile");
  222. break;
  223. case cmDepfileFormat::MSBuildAdditionalInputs:
  224. argv.emplace_back("MSBuildAdditionalInputs");
  225. break;
  226. }
  227. argv.push_back(this->LG->GetSourceDirectory());
  228. argv.push_back(this->LG->GetCurrentSourceDirectory());
  229. argv.push_back(this->LG->GetBinaryDirectory());
  230. argv.push_back(this->LG->GetCurrentBinaryDirectory());
  231. argv.push_back(this->GetFullDepfile());
  232. argv.push_back(this->GetInternalDepfile());
  233. this->CommandLines.push_back(std::move(argv));
  234. }
  235. this->Outputs =
  236. EvaluateOutputs(cc.GetOutputs(), ge, this->LG, this->OutputConfig);
  237. this->Byproducts =
  238. EvaluateOutputs(cc.GetByproducts(), ge, this->LG, this->OutputConfig);
  239. this->Depends = EvaluateDepends(cc.GetDepends(), ge, this->LG,
  240. this->OutputConfig, this->CommandConfig);
  241. const std::string& workingdirectory = this->CC->GetWorkingDirectory();
  242. if (!workingdirectory.empty()) {
  243. this->WorkingDirectory = EvaluateSplitConfigGenex(
  244. workingdirectory, ge, this->LG, true, this->OutputConfig,
  245. this->CommandConfig, target);
  246. // Convert working directory to a full path.
  247. if (!this->WorkingDirectory.empty()) {
  248. std::string const& build_dir = this->LG->GetCurrentBinaryDirectory();
  249. this->WorkingDirectory =
  250. cmSystemTools::CollapseFullPath(this->WorkingDirectory, build_dir);
  251. }
  252. }
  253. this->FillEmulatorsWithArguments();
  254. }
  255. unsigned int cmCustomCommandGenerator::GetNumberOfCommands() const
  256. {
  257. return static_cast<unsigned int>(this->CommandLines.size());
  258. }
  259. void cmCustomCommandGenerator::FillEmulatorsWithArguments()
  260. {
  261. if (!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING")) {
  262. return;
  263. }
  264. for (unsigned int c = 0; c < this->GetNumberOfCommands(); ++c) {
  265. std::string const& argv0 = this->CommandLines[c][0];
  266. cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
  267. if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
  268. !target->IsImported()) {
  269. cmValue emulator_property =
  270. target->GetProperty("CROSSCOMPILING_EMULATOR");
  271. if (!emulator_property) {
  272. continue;
  273. }
  274. cmExpandList(*emulator_property, this->EmulatorsWithArguments[c]);
  275. }
  276. }
  277. }
  278. std::vector<std::string> cmCustomCommandGenerator::GetCrossCompilingEmulator(
  279. unsigned int c) const
  280. {
  281. if (c >= this->EmulatorsWithArguments.size()) {
  282. return std::vector<std::string>();
  283. }
  284. return this->EmulatorsWithArguments[c];
  285. }
  286. const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
  287. {
  288. std::string const& argv0 = this->CommandLines[c][0];
  289. cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
  290. if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
  291. (target->IsImported() ||
  292. target->GetProperty("CROSSCOMPILING_EMULATOR") ||
  293. !this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING"))) {
  294. return target->GetLocation(this->CommandConfig).c_str();
  295. }
  296. return nullptr;
  297. }
  298. bool cmCustomCommandGenerator::HasOnlyEmptyCommandLines() const
  299. {
  300. for (size_t i = 0; i < this->CommandLines.size(); ++i) {
  301. for (size_t j = 0; j < this->CommandLines[i].size(); ++j) {
  302. if (!this->CommandLines[i][j].empty()) {
  303. return false;
  304. }
  305. }
  306. }
  307. return true;
  308. }
  309. std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
  310. {
  311. std::vector<std::string> emulator = this->GetCrossCompilingEmulator(c);
  312. if (!emulator.empty()) {
  313. return emulator[0];
  314. }
  315. if (const char* location = this->GetArgv0Location(c)) {
  316. return std::string(location);
  317. }
  318. return this->CommandLines[c][0];
  319. }
  320. static std::string escapeForShellOldStyle(const std::string& str)
  321. {
  322. std::string result;
  323. #if defined(_WIN32) && !defined(__CYGWIN__)
  324. // if there are spaces
  325. std::string temp = str;
  326. if (temp.find(" ") != std::string::npos &&
  327. temp.find("\"") == std::string::npos) {
  328. result = cmStrCat('"', str, '"');
  329. return result;
  330. }
  331. return str;
  332. #else
  333. for (const char* ch = str.c_str(); *ch != '\0'; ++ch) {
  334. if (*ch == ' ') {
  335. result += '\\';
  336. }
  337. result += *ch;
  338. }
  339. return result;
  340. #endif
  341. }
  342. void cmCustomCommandGenerator::AppendArguments(unsigned int c,
  343. std::string& cmd) const
  344. {
  345. unsigned int offset = 1;
  346. std::vector<std::string> emulator = this->GetCrossCompilingEmulator(c);
  347. if (!emulator.empty()) {
  348. for (unsigned j = 1; j < emulator.size(); ++j) {
  349. cmd += " ";
  350. if (this->OldStyle) {
  351. cmd += escapeForShellOldStyle(emulator[j]);
  352. } else {
  353. cmd +=
  354. this->LG->EscapeForShell(emulator[j], this->MakeVars, false, false,
  355. this->MakeVars && this->LG->IsNinjaMulti());
  356. }
  357. }
  358. offset = 0;
  359. }
  360. cmCustomCommandLine const& commandLine = this->CommandLines[c];
  361. for (unsigned int j = offset; j < commandLine.size(); ++j) {
  362. std::string arg;
  363. if (const char* location = j == 0 ? this->GetArgv0Location(c) : nullptr) {
  364. // GetCommand returned the emulator instead of the argv0 location,
  365. // so transform the latter now.
  366. arg = location;
  367. } else {
  368. arg = commandLine[j];
  369. }
  370. cmd += " ";
  371. if (this->OldStyle) {
  372. cmd += escapeForShellOldStyle(arg);
  373. } else {
  374. cmd +=
  375. this->LG->EscapeForShell(arg, this->MakeVars, false, false,
  376. this->MakeVars && this->LG->IsNinjaMulti());
  377. }
  378. }
  379. }
  380. std::string cmCustomCommandGenerator::GetDepfile() const
  381. {
  382. const auto& depfile = this->CC->GetDepfile();
  383. if (depfile.empty()) {
  384. return "";
  385. }
  386. cmGeneratorExpression ge(*this->LG->GetCMakeInstance(),
  387. this->CC->GetBacktrace());
  388. return EvaluateDepfile(depfile, ge, this->LG, this->OutputConfig);
  389. }
  390. std::string cmCustomCommandGenerator::GetFullDepfile() const
  391. {
  392. std::string depfile = this->GetDepfile();
  393. if (depfile.empty()) {
  394. return "";
  395. }
  396. if (!cmSystemTools::FileIsFullPath(depfile)) {
  397. depfile = cmStrCat(this->LG->GetCurrentBinaryDirectory(), '/', depfile);
  398. }
  399. return cmSystemTools::CollapseFullPath(depfile);
  400. }
  401. std::string cmCustomCommandGenerator::GetInternalDepfileName(
  402. const std::string& /*config*/, const std::string& depfile)
  403. {
  404. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  405. std::string extension;
  406. switch (*this->LG->GetGlobalGenerator()->DepfileFormat()) {
  407. case cmDepfileFormat::GccDepfile:
  408. case cmDepfileFormat::MakeDepfile:
  409. extension = ".d";
  410. break;
  411. case cmDepfileFormat::MSBuildAdditionalInputs:
  412. extension = ".AdditionalInputs";
  413. break;
  414. }
  415. return cmStrCat(this->LG->GetBinaryDirectory(), "/CMakeFiles/d/",
  416. hash.HashString(depfile), extension);
  417. }
  418. std::string cmCustomCommandGenerator::GetInternalDepfile() const
  419. {
  420. std::string depfile = this->GetFullDepfile();
  421. if (depfile.empty()) {
  422. return "";
  423. }
  424. return this->ComputeInternalDepfile(this->OutputConfig, depfile);
  425. }
  426. cm::optional<std::string> cmCustomCommandGenerator::GetComment() const
  427. {
  428. const char* comment = this->CC->GetComment();
  429. if (!comment) {
  430. return cm::nullopt;
  431. }
  432. if (!*comment) {
  433. return std::string();
  434. }
  435. cmGeneratorExpression ge(*this->LG->GetCMakeInstance(),
  436. this->CC->GetBacktrace());
  437. return EvaluateComment(comment, ge, this->LG, this->OutputConfig);
  438. }
  439. std::string cmCustomCommandGenerator::GetWorkingDirectory() const
  440. {
  441. return this->WorkingDirectory;
  442. }
  443. std::vector<std::string> const& cmCustomCommandGenerator::GetOutputs() const
  444. {
  445. return this->Outputs;
  446. }
  447. std::vector<std::string> const& cmCustomCommandGenerator::GetByproducts() const
  448. {
  449. return this->Byproducts;
  450. }
  451. std::vector<std::string> const& cmCustomCommandGenerator::GetDepends() const
  452. {
  453. return this->Depends;
  454. }
  455. std::set<BT<std::pair<std::string, bool>>> const&
  456. cmCustomCommandGenerator::GetUtilities() const
  457. {
  458. return this->Utilities;
  459. }