cmLocalNinjaGenerator.cxx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 "cmLocalNinjaGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <iterator>
  8. #include <memory>
  9. #include <sstream>
  10. #include <utility>
  11. #include "cmsys/FStream.hxx"
  12. #include "cmCryptoHash.h"
  13. #include "cmCustomCommand.h"
  14. #include "cmCustomCommandGenerator.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorExpression.h"
  17. #include "cmGeneratorTarget.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmGlobalNinjaGenerator.h"
  20. #include "cmLocalGenerator.h"
  21. #include "cmMakefile.h"
  22. #include "cmNinjaTargetGenerator.h"
  23. #include "cmProperty.h"
  24. #include "cmRulePlaceholderExpander.h"
  25. #include "cmSourceFile.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTarget.h"
  31. #include "cmake.h"
  32. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  33. cmMakefile* mf)
  34. : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
  35. , HomeRelativeOutputPath("")
  36. {
  37. }
  38. // Virtual public methods.
  39. cmRulePlaceholderExpander*
  40. cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
  41. {
  42. cmRulePlaceholderExpander* ret =
  43. this->cmLocalGenerator::CreateRulePlaceholderExpander();
  44. ret->SetTargetImpLib("$TARGET_IMPLIB");
  45. return ret;
  46. }
  47. cmLocalNinjaGenerator::~cmLocalNinjaGenerator() = default;
  48. void cmLocalNinjaGenerator::Generate()
  49. {
  50. // Compute the path to use when referencing the current output
  51. // directory from the top output directory.
  52. this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
  53. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
  54. if (this->HomeRelativeOutputPath == ".") {
  55. this->HomeRelativeOutputPath.clear();
  56. }
  57. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  58. for (auto const& config : this->GetConfigNames()) {
  59. this->WriteProcessedMakefile(this->GetImplFileStream(config));
  60. }
  61. }
  62. this->WriteProcessedMakefile(this->GetCommonFileStream());
  63. #ifdef NINJA_GEN_VERBOSE_FILES
  64. this->WriteProcessedMakefile(this->GetRulesFileStream());
  65. #endif
  66. // We do that only once for the top CMakeLists.txt file.
  67. if (this->IsRootMakefile()) {
  68. this->WriteBuildFileTop();
  69. this->WritePools(this->GetRulesFileStream());
  70. const std::string& showIncludesPrefix =
  71. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  72. if (!showIncludesPrefix.empty()) {
  73. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  74. "localized /showIncludes string");
  75. this->GetRulesFileStream()
  76. << "msvc_deps_prefix = " << showIncludesPrefix << "\n\n";
  77. }
  78. }
  79. for (const auto& target : this->GetGeneratorTargets()) {
  80. if (!target->IsInBuildSystem()) {
  81. continue;
  82. }
  83. auto tg = cmNinjaTargetGenerator::New(target.get());
  84. if (tg) {
  85. if (target->Target->IsPerConfig()) {
  86. for (auto const& config : this->GetConfigNames()) {
  87. tg->Generate(config);
  88. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  89. this->GetGlobalGenerator()->IsMultiConfig()) {
  90. cmNinjaBuild phonyAlias("phony");
  91. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  92. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  93. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  94. target.get(), phonyAlias.ExplicitDeps, config,
  95. DependOnTargetArtifact);
  96. this->GetGlobalNinjaGenerator()->WriteBuild(
  97. *this->GetGlobalNinjaGenerator()->GetConfigFileStream(config),
  98. phonyAlias);
  99. }
  100. }
  101. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  102. this->GetGlobalGenerator()->IsMultiConfig()) {
  103. if (!this->GetGlobalNinjaGenerator()->GetDefaultConfigs().empty()) {
  104. cmNinjaBuild phonyAlias("phony");
  105. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  106. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  107. for (auto const& config :
  108. this->GetGlobalNinjaGenerator()->GetDefaultConfigs()) {
  109. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  110. target.get(), phonyAlias.ExplicitDeps, config,
  111. DependOnTargetArtifact);
  112. }
  113. this->GetGlobalNinjaGenerator()->WriteBuild(
  114. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  115. phonyAlias);
  116. }
  117. cmNinjaBuild phonyAlias("phony");
  118. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  119. target.get(), phonyAlias.Outputs, "all", DependOnTargetArtifact);
  120. for (auto const& config : this->GetConfigNames()) {
  121. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  122. target.get(), phonyAlias.ExplicitDeps, config,
  123. DependOnTargetArtifact);
  124. }
  125. this->GetGlobalNinjaGenerator()->WriteBuild(
  126. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  127. phonyAlias);
  128. }
  129. } else {
  130. tg->Generate("");
  131. }
  132. }
  133. }
  134. for (auto const& config : this->GetConfigNames()) {
  135. this->WriteCustomCommandBuildStatements(config);
  136. this->AdditionalCleanFiles(config);
  137. }
  138. }
  139. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  140. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  141. cmGeneratorTarget const* target) const
  142. {
  143. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  144. #if defined(__VMS)
  145. dir += "_dir";
  146. #else
  147. dir += ".dir";
  148. #endif
  149. return dir;
  150. }
  151. // Non-virtual public methods.
  152. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  153. const
  154. {
  155. return static_cast<const cmGlobalNinjaGenerator*>(
  156. this->GetGlobalGenerator());
  157. }
  158. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  159. {
  160. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  161. }
  162. // Virtual protected methods.
  163. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  164. std::string const& path, cmOutputConverter::OutputFormat format,
  165. bool forceFullPaths)
  166. {
  167. if (forceFullPaths) {
  168. return this->ConvertToOutputFormat(
  169. cmSystemTools::CollapseFullPath(path, this->GetCurrentBinaryDirectory()),
  170. format);
  171. }
  172. return this->ConvertToOutputFormat(
  173. this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), path),
  174. format);
  175. }
  176. // Private methods.
  177. cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
  178. const std::string& config) const
  179. {
  180. return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
  181. }
  182. cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
  183. {
  184. return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
  185. }
  186. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  187. {
  188. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  189. }
  190. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  191. {
  192. return this->GetGlobalGenerator()->GetCMakeInstance();
  193. }
  194. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  195. {
  196. return this->GetGlobalGenerator()->GetCMakeInstance();
  197. }
  198. void cmLocalNinjaGenerator::WriteBuildFileTop()
  199. {
  200. this->WriteProjectHeader(this->GetCommonFileStream());
  201. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  202. for (auto const& config : this->GetConfigNames()) {
  203. auto& stream = this->GetImplFileStream(config);
  204. this->WriteProjectHeader(stream);
  205. this->WriteNinjaRequiredVersion(stream);
  206. this->WriteNinjaConfigurationVariable(stream, config);
  207. this->WriteNinjaFilesInclusionConfig(stream);
  208. }
  209. } else {
  210. this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
  211. this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
  212. this->GetConfigNames().front());
  213. }
  214. this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
  215. // For the rule file.
  216. this->WriteProjectHeader(this->GetRulesFileStream());
  217. }
  218. void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
  219. {
  220. cmGlobalNinjaGenerator::WriteDivider(os);
  221. os << "# Project: " << this->GetProjectName() << '\n'
  222. << "# Configurations: " << cmJoin(this->GetConfigNames(), ", ") << '\n';
  223. cmGlobalNinjaGenerator::WriteDivider(os);
  224. }
  225. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  226. {
  227. // Default required version
  228. std::string requiredVersion = cmGlobalNinjaGenerator::RequiredNinjaVersion();
  229. // Ninja generator uses the 'console' pool if available (>= 1.5)
  230. if (this->GetGlobalNinjaGenerator()->SupportsConsolePool()) {
  231. requiredVersion =
  232. cmGlobalNinjaGenerator::RequiredNinjaVersionForConsolePool();
  233. }
  234. // The Ninja generator writes rules which require support for restat
  235. // when rebuilding build.ninja manifest (>= 1.8)
  236. if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() &&
  237. this->GetCMakeInstance()->DoWriteGlobVerifyTarget() &&
  238. !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn(
  239. "CMAKE_SUPPRESS_REGENERATION")) {
  240. requiredVersion =
  241. cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat();
  242. }
  243. cmGlobalNinjaGenerator::WriteComment(
  244. os, "Minimal version of Ninja required by this file");
  245. os << "ninja_required_version = " << requiredVersion << "\n\n";
  246. }
  247. void cmLocalNinjaGenerator::WriteNinjaConfigurationVariable(
  248. std::ostream& os, const std::string& config)
  249. {
  250. cmGlobalNinjaGenerator::WriteVariable(
  251. os, "CONFIGURATION", config,
  252. "Set configuration variable for custom commands.");
  253. }
  254. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  255. {
  256. cmGlobalNinjaGenerator::WriteDivider(os);
  257. cmProp jobpools =
  258. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  259. if (!jobpools) {
  260. jobpools = this->GetMakefile()->GetDef("CMAKE_JOB_POOLS");
  261. }
  262. if (jobpools) {
  263. cmGlobalNinjaGenerator::WriteComment(
  264. os, "Pools defined by global property JOB_POOLS");
  265. std::vector<std::string> pools = cmExpandedList(*jobpools);
  266. for (std::string const& pool : pools) {
  267. const std::string::size_type eq = pool.find('=');
  268. unsigned int jobs;
  269. if (eq != std::string::npos &&
  270. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
  271. os << "pool " << pool.substr(0, eq) << "\n depth = " << jobs
  272. << "\n\n";
  273. } else {
  274. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': " +
  275. pool);
  276. }
  277. }
  278. }
  279. }
  280. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionConfig(std::ostream& os)
  281. {
  282. cmGlobalNinjaGenerator::WriteDivider(os);
  283. os << "# Include auxiliary files.\n\n";
  284. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  285. std::string const ninjaCommonFile =
  286. ng->NinjaOutputPath(cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE);
  287. std::string const commonFilePath = ng->EncodePath(ninjaCommonFile);
  288. cmGlobalNinjaGenerator::WriteInclude(os, commonFilePath,
  289. "Include common file.");
  290. os << "\n";
  291. }
  292. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionCommon(std::ostream& os)
  293. {
  294. cmGlobalNinjaGenerator::WriteDivider(os);
  295. os << "# Include auxiliary files.\n\n";
  296. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  297. std::string const ninjaRulesFile =
  298. ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
  299. std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile);
  300. cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
  301. "Include rules file.");
  302. os << "\n";
  303. }
  304. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  305. {
  306. cmGlobalNinjaGenerator::WriteDivider(os);
  307. os << "# Write statements declared in CMakeLists.txt:\n"
  308. << "# " << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")
  309. << '\n';
  310. if (this->IsRootMakefile()) {
  311. os << "# Which is the root file.\n";
  312. }
  313. cmGlobalNinjaGenerator::WriteDivider(os);
  314. os << '\n';
  315. }
  316. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  317. cmNinjaDeps& outputs,
  318. const std::string& config)
  319. {
  320. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
  321. DependOnTargetArtifact);
  322. }
  323. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  324. cmNinjaDeps& outputs,
  325. const std::string& config,
  326. const std::string& fileConfig,
  327. cmNinjaTargetDepends depends)
  328. {
  329. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
  330. fileConfig, depends);
  331. }
  332. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  333. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
  334. const std::string& config)
  335. {
  336. for (std::string const& i : ccg.GetDepends()) {
  337. std::string dep;
  338. if (this->GetRealDependency(i, config, dep)) {
  339. ninjaDeps.push_back(
  340. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  341. }
  342. }
  343. }
  344. std::string cmLocalNinjaGenerator::WriteCommandScript(
  345. std::vector<std::string> const& cmdLines, std::string const& customStep,
  346. cmGeneratorTarget const* target) const
  347. {
  348. std::string scriptPath;
  349. if (target) {
  350. scriptPath = target->GetSupportDirectory();
  351. } else {
  352. scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
  353. }
  354. cmSystemTools::MakeDirectory(scriptPath);
  355. scriptPath += '/';
  356. scriptPath += customStep;
  357. #ifdef _WIN32
  358. scriptPath += ".bat";
  359. #else
  360. scriptPath += ".sh";
  361. #endif
  362. cmsys::ofstream script(scriptPath.c_str());
  363. #ifdef _WIN32
  364. script << "@echo off\n";
  365. int line = 1;
  366. #else
  367. script << "set -e\n\n";
  368. #endif
  369. for (auto const& i : cmdLines) {
  370. std::string cmd = i;
  371. // The command line was built assuming it would be written to
  372. // the build.ninja file, so it uses '$$' for '$'. Remove this
  373. // for the raw shell script.
  374. cmSystemTools::ReplaceString(cmd, "$$", "$");
  375. #ifdef _WIN32
  376. script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
  377. << '\n';
  378. #else
  379. script << cmd << '\n';
  380. #endif
  381. }
  382. #ifdef _WIN32
  383. script << "goto :EOF\n\n"
  384. ":ABORT\n"
  385. "set ERROR_CODE=%ERRORLEVEL%\n"
  386. "echo Batch file failed at line %FAIL_LINE% "
  387. "with errorcode %ERRORLEVEL%\n"
  388. "exit /b %ERROR_CODE%";
  389. #endif
  390. return scriptPath;
  391. }
  392. std::string cmLocalNinjaGenerator::BuildCommandLine(
  393. std::vector<std::string> const& cmdLines, std::string const& customStep,
  394. cmGeneratorTarget const* target) const
  395. {
  396. // If we have no commands but we need to build a command anyway, use noop.
  397. // This happens when building a POST_BUILD value for link targets that
  398. // don't use POST_BUILD.
  399. if (cmdLines.empty()) {
  400. return cmGlobalNinjaGenerator::SHELL_NOOP;
  401. }
  402. // If this is a custom step then we will have no '$VAR' ninja placeholders.
  403. // This means we can deal with long command sequences by writing to a script.
  404. // Do this if the command lines are on the scale of the OS limit.
  405. if (!customStep.empty()) {
  406. size_t cmdLinesTotal = 0;
  407. for (std::string const& cmd : cmdLines) {
  408. cmdLinesTotal += cmd.length() + 6;
  409. }
  410. if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
  411. std::string const scriptPath =
  412. this->WriteCommandScript(cmdLines, customStep, target);
  413. std::string cmd
  414. #ifndef _WIN32
  415. = "/bin/sh "
  416. #endif
  417. ;
  418. cmd += this->ConvertToOutputFormat(
  419. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
  420. cmOutputConverter::SHELL);
  421. // Add an unused argument based on script content so that Ninja
  422. // knows when the command lines change.
  423. cmd += " ";
  424. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  425. cmd += hash.HashFile(scriptPath).substr(0, 16);
  426. return cmd;
  427. }
  428. }
  429. std::ostringstream cmd;
  430. for (auto li = cmdLines.begin(); li != cmdLines.end(); ++li)
  431. #ifdef _WIN32
  432. {
  433. if (li != cmdLines.begin()) {
  434. cmd << " && ";
  435. } else if (cmdLines.size() > 1) {
  436. cmd << "cmd.exe /C \"";
  437. }
  438. // Put current cmdLine in brackets if it contains "||" because it has
  439. // higher precedence than "&&" in cmd.exe
  440. if (li->find("||") != std::string::npos) {
  441. cmd << "( " << *li << " )";
  442. } else {
  443. cmd << *li;
  444. }
  445. }
  446. if (cmdLines.size() > 1) {
  447. cmd << "\"";
  448. }
  449. #else
  450. {
  451. if (li != cmdLines.begin()) {
  452. cmd << " && ";
  453. }
  454. cmd << *li;
  455. }
  456. #endif
  457. return cmd.str();
  458. }
  459. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  460. cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
  461. {
  462. auto* gg = this->GetGlobalNinjaGenerator();
  463. if (ccg.GetNumberOfCommands() > 0) {
  464. std::string wd = ccg.GetWorkingDirectory();
  465. if (wd.empty()) {
  466. wd = this->GetCurrentBinaryDirectory();
  467. }
  468. std::ostringstream cdCmd;
  469. #ifdef _WIN32
  470. std::string cdStr = "cd /D ";
  471. #else
  472. std::string cdStr = "cd ";
  473. #endif
  474. cdCmd << cdStr
  475. << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  476. cmdLines.push_back(cdCmd.str());
  477. }
  478. std::string launcher = this->MakeCustomLauncher(ccg);
  479. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  480. cmdLines.push_back(launcher +
  481. this->ConvertToOutputFormat(
  482. ccg.GetCommand(i),
  483. gg->IsMultiConfig() ? cmOutputConverter::NINJAMULTI
  484. : cmOutputConverter::SHELL));
  485. std::string& cmd = cmdLines.back();
  486. ccg.AppendArguments(i, cmd);
  487. }
  488. }
  489. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  490. cmCustomCommand const* cc, const cmNinjaDeps& orderOnlyDeps,
  491. const std::string& config)
  492. {
  493. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  494. if (gg->SeenCustomCommand(cc, config)) {
  495. return;
  496. }
  497. cmCustomCommandGenerator ccg(*cc, config, this);
  498. const std::vector<std::string>& outputs = ccg.GetOutputs();
  499. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  500. bool symbolic = false;
  501. for (std::string const& output : outputs) {
  502. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  503. if (sf->GetPropertyAsBool("SYMBOLIC")) {
  504. symbolic = true;
  505. break;
  506. }
  507. }
  508. }
  509. #if 0
  510. # error TODO: Once CC in an ExternalProject target must provide the \
  511. file of each imported target that has an add_dependencies pointing \
  512. at us. How to know which ExternalProject step actually provides it?
  513. #endif
  514. cmNinjaDeps ninjaOutputs(outputs.size() + byproducts.size());
  515. std::transform(outputs.begin(), outputs.end(), ninjaOutputs.begin(),
  516. gg->MapToNinjaPath());
  517. std::transform(byproducts.begin(), byproducts.end(),
  518. ninjaOutputs.begin() + outputs.size(), gg->MapToNinjaPath());
  519. for (std::string const& ninjaOutput : ninjaOutputs) {
  520. gg->SeenCustomCommandOutput(ninjaOutput);
  521. }
  522. cmNinjaDeps ninjaDeps;
  523. this->AppendCustomCommandDeps(ccg, ninjaDeps, config);
  524. std::vector<std::string> cmdLines;
  525. this->AppendCustomCommandLines(ccg, cmdLines);
  526. if (cmdLines.empty()) {
  527. cmNinjaBuild build("phony");
  528. build.Comment = "Phony custom command for " + ninjaOutputs[0];
  529. build.Outputs = std::move(ninjaOutputs);
  530. build.ExplicitDeps = std::move(ninjaDeps);
  531. build.OrderOnlyDeps = orderOnlyDeps;
  532. gg->WriteBuild(this->GetImplFileStream(config), build);
  533. } else {
  534. std::string customStep = cmSystemTools::GetFilenameName(ninjaOutputs[0]);
  535. // Hash full path to make unique.
  536. customStep += '-';
  537. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  538. customStep += hash.HashString(ninjaOutputs[0]).substr(0, 7);
  539. gg->WriteCustomCommandBuild(
  540. this->BuildCommandLine(cmdLines, customStep),
  541. this->ConstructComment(ccg), "Custom command for " + ninjaOutputs[0],
  542. cc->GetDepfile(), cc->GetJobPool(), cc->GetUsesTerminal(),
  543. /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, config,
  544. ninjaDeps, orderOnlyDeps);
  545. }
  546. }
  547. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  548. cmGeneratorTarget* target)
  549. {
  550. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  551. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  552. this->CustomCommandTargets.insert(v);
  553. if (ins.second) {
  554. this->CustomCommands.push_back(cc);
  555. }
  556. ins.first->second.insert(target);
  557. }
  558. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
  559. const std::string& config)
  560. {
  561. for (cmCustomCommand const* customCommand : this->CustomCommands) {
  562. auto i = this->CustomCommandTargets.find(customCommand);
  563. assert(i != this->CustomCommandTargets.end());
  564. // A custom command may appear on multiple targets. However, some build
  565. // systems exist where the target dependencies on some of the targets are
  566. // overspecified, leading to a dependency cycle. If we assume all target
  567. // dependencies are a superset of the true target dependencies for this
  568. // custom command, we can take the set intersection of all target
  569. // dependencies to obtain a correct dependency list.
  570. //
  571. // FIXME: This won't work in certain obscure scenarios involving indirect
  572. // dependencies.
  573. auto j = i->second.begin();
  574. assert(j != i->second.end());
  575. std::vector<std::string> ccTargetDeps;
  576. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
  577. *j, ccTargetDeps, config);
  578. std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
  579. ++j;
  580. for (; j != i->second.end(); ++j) {
  581. std::vector<std::string> jDeps;
  582. std::vector<std::string> depsIntersection;
  583. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps,
  584. config);
  585. std::sort(jDeps.begin(), jDeps.end());
  586. std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
  587. jDeps.begin(), jDeps.end(),
  588. std::back_inserter(depsIntersection));
  589. ccTargetDeps = depsIntersection;
  590. }
  591. this->WriteCustomCommandBuildStatement(i->first, ccTargetDeps, config);
  592. }
  593. }
  594. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  595. cmCustomCommandGenerator const& ccg)
  596. {
  597. cmProp property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  598. if (!cmNonempty(property_value)) {
  599. return std::string();
  600. }
  601. // Expand rule variables referenced in the given launcher command.
  602. cmRulePlaceholderExpander::RuleVariables vars;
  603. std::string output;
  604. const std::vector<std::string>& outputs = ccg.GetOutputs();
  605. if (!outputs.empty()) {
  606. output = outputs[0];
  607. if (ccg.GetWorkingDirectory().empty()) {
  608. output = this->MaybeConvertToRelativePath(
  609. this->GetCurrentBinaryDirectory(), output);
  610. }
  611. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  612. }
  613. vars.Output = output.c_str();
  614. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  615. this->CreateRulePlaceholderExpander());
  616. std::string launcher = *property_value;
  617. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  618. if (!launcher.empty()) {
  619. launcher += " ";
  620. }
  621. return launcher;
  622. }
  623. void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
  624. {
  625. if (cmProp prop_value =
  626. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  627. std::vector<std::string> cleanFiles;
  628. {
  629. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, this, config),
  630. cleanFiles);
  631. }
  632. std::string const& binaryDir = this->GetCurrentBinaryDirectory();
  633. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  634. for (std::string const& cleanFile : cleanFiles) {
  635. // Support relative paths
  636. gg->AddAdditionalCleanFile(
  637. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  638. }
  639. }
  640. }