cmLocalNinjaGenerator.cxx 22 KB

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