cmCustomCommandGenerator.cxx 16 KB

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