cmLocalNinjaGenerator.cxx 24 KB

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