cmLocalNinjaGenerator.cxx 22 KB

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