cmCustomCommandGenerator.cxx 15 KB

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