cmLocalNinjaGenerator.cxx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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 <cmext/string_view>
  12. #include "cmsys/FStream.hxx"
  13. #include "cmCryptoHash.h"
  14. #include "cmCustomCommand.h"
  15. #include "cmCustomCommandGenerator.h"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmGeneratorExpression.h"
  18. #include "cmGeneratorTarget.h"
  19. #include "cmGlobalGenerator.h"
  20. #include "cmGlobalNinjaGenerator.h"
  21. #include "cmLocalGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmMessageType.h"
  24. #include "cmNinjaTargetGenerator.h"
  25. #include "cmPolicies.h"
  26. #include "cmRulePlaceholderExpander.h"
  27. #include "cmSourceFile.h"
  28. #include "cmState.h"
  29. #include "cmStateTypes.h"
  30. #include "cmStringAlgorithms.h"
  31. #include "cmSystemTools.h"
  32. #include "cmTarget.h"
  33. #include "cmValue.h"
  34. #include "cmake.h"
  35. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  36. cmMakefile* mf)
  37. : cmLocalCommonGenerator(gg, mf, WorkDir::TopBin)
  38. {
  39. }
  40. // Virtual public methods.
  41. cmRulePlaceholderExpander*
  42. cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
  43. {
  44. cmRulePlaceholderExpander* ret =
  45. this->cmLocalGenerator::CreateRulePlaceholderExpander();
  46. ret->SetTargetImpLib("$TARGET_IMPLIB");
  47. return ret;
  48. }
  49. cmLocalNinjaGenerator::~cmLocalNinjaGenerator() = default;
  50. void cmLocalNinjaGenerator::Generate()
  51. {
  52. // Compute the path to use when referencing the current output
  53. // directory from the top output directory.
  54. this->HomeRelativeOutputPath =
  55. this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
  56. if (this->HomeRelativeOutputPath == ".") {
  57. this->HomeRelativeOutputPath.clear();
  58. }
  59. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  60. for (auto const& config : this->GetConfigNames()) {
  61. this->WriteProcessedMakefile(this->GetImplFileStream(config));
  62. }
  63. }
  64. this->WriteProcessedMakefile(this->GetCommonFileStream());
  65. #ifdef NINJA_GEN_VERBOSE_FILES
  66. this->WriteProcessedMakefile(this->GetRulesFileStream());
  67. #endif
  68. // We do that only once for the top CMakeLists.txt file.
  69. if (this->IsRootMakefile()) {
  70. this->WriteBuildFileTop();
  71. this->WritePools(this->GetRulesFileStream());
  72. const std::string& showIncludesPrefix =
  73. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  74. if (!showIncludesPrefix.empty()) {
  75. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  76. "localized /showIncludes string");
  77. this->GetRulesFileStream() << "msvc_deps_prefix = ";
  78. // 'cl /showIncludes' encodes output in the console output code page.
  79. // It may differ from the encoding used for file paths in 'build.ninja'.
  80. // Ninja matches the showIncludes prefix using its raw byte sequence.
  81. this->GetRulesFileStream().WriteAltEncoding(
  82. showIncludesPrefix, cmGeneratedFileStream::Encoding::ConsoleOutput);
  83. this->GetRulesFileStream() << "\n\n";
  84. }
  85. }
  86. for (const auto& target : this->GetGeneratorTargets()) {
  87. if (!target->IsInBuildSystem()) {
  88. continue;
  89. }
  90. auto tg = cmNinjaTargetGenerator::New(target.get());
  91. if (tg) {
  92. if (target->Target->IsPerConfig()) {
  93. for (auto const& config : this->GetConfigNames()) {
  94. tg->Generate(config);
  95. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  96. this->GetGlobalGenerator()->IsMultiConfig()) {
  97. cmNinjaBuild phonyAlias("phony");
  98. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  99. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  100. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  101. target.get(), phonyAlias.ExplicitDeps, config,
  102. DependOnTargetArtifact);
  103. this->GetGlobalNinjaGenerator()->WriteBuild(
  104. *this->GetGlobalNinjaGenerator()->GetConfigFileStream(config),
  105. phonyAlias);
  106. }
  107. }
  108. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  109. this->GetGlobalGenerator()->IsMultiConfig()) {
  110. if (!this->GetGlobalNinjaGenerator()->GetDefaultConfigs().empty()) {
  111. cmNinjaBuild phonyAlias("phony");
  112. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  113. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  114. for (auto const& config :
  115. this->GetGlobalNinjaGenerator()->GetDefaultConfigs()) {
  116. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  117. target.get(), phonyAlias.ExplicitDeps, config,
  118. DependOnTargetArtifact);
  119. }
  120. this->GetGlobalNinjaGenerator()->WriteBuild(
  121. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  122. phonyAlias);
  123. }
  124. cmNinjaBuild phonyAlias("phony");
  125. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  126. target.get(), phonyAlias.Outputs, "all", DependOnTargetArtifact);
  127. for (auto const& config : this->GetConfigNames()) {
  128. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  129. target.get(), phonyAlias.ExplicitDeps, config,
  130. DependOnTargetArtifact);
  131. }
  132. this->GetGlobalNinjaGenerator()->WriteBuild(
  133. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  134. phonyAlias);
  135. }
  136. } else {
  137. tg->Generate("");
  138. }
  139. }
  140. }
  141. for (auto const& config : this->GetConfigNames()) {
  142. this->WriteCustomCommandBuildStatements(config);
  143. this->AdditionalCleanFiles(config);
  144. }
  145. }
  146. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  147. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  148. cmGeneratorTarget const* target) const
  149. {
  150. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  151. #if defined(__VMS)
  152. dir += "_dir";
  153. #else
  154. dir += ".dir";
  155. #endif
  156. return dir;
  157. }
  158. // Non-virtual public methods.
  159. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  160. const
  161. {
  162. return static_cast<const cmGlobalNinjaGenerator*>(
  163. this->GetGlobalGenerator());
  164. }
  165. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  166. {
  167. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  168. }
  169. // Virtual protected methods.
  170. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  171. std::string const& path, cmOutputConverter::OutputFormat format)
  172. {
  173. return this->ConvertToOutputFormat(path, format);
  174. }
  175. // Private methods.
  176. cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
  177. const std::string& config) const
  178. {
  179. return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
  180. }
  181. cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
  182. {
  183. return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
  184. }
  185. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  186. {
  187. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  188. }
  189. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  190. {
  191. return this->GetGlobalGenerator()->GetCMakeInstance();
  192. }
  193. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  194. {
  195. return this->GetGlobalGenerator()->GetCMakeInstance();
  196. }
  197. void cmLocalNinjaGenerator::WriteBuildFileTop()
  198. {
  199. this->WriteProjectHeader(this->GetCommonFileStream());
  200. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  201. for (auto const& config : this->GetConfigNames()) {
  202. auto& stream = this->GetImplFileStream(config);
  203. this->WriteProjectHeader(stream);
  204. this->WriteNinjaRequiredVersion(stream);
  205. this->WriteNinjaConfigurationVariable(stream, config);
  206. this->WriteNinjaFilesInclusionConfig(stream);
  207. }
  208. } else {
  209. this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
  210. this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
  211. this->GetConfigNames().front());
  212. }
  213. this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
  214. this->WriteNinjaWorkDir(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()->SupportsDirectConsole()) {
  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. cmValue jobpools =
  258. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  259. if (!jobpools) {
  260. jobpools = this->GetMakefile()->GetDefinition("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::WriteNinjaWorkDir(std::ostream& os)
  305. {
  306. cmGlobalNinjaGenerator::WriteDivider(os);
  307. cmGlobalNinjaGenerator::WriteComment(
  308. os, "Logical path to working directory; prefix for absolute paths.");
  309. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  310. std::string ninja_workdir = this->GetBinaryDirectory();
  311. ng->StripNinjaOutputPathPrefixAsSuffix(ninja_workdir); // Also appends '/'.
  312. os << "cmake_ninja_workdir = " << ng->EncodePath(ninja_workdir) << "\n";
  313. }
  314. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  315. {
  316. cmGlobalNinjaGenerator::WriteDivider(os);
  317. os << "# Write statements declared in CMakeLists.txt:\n"
  318. << "# " << this->Makefile->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE")
  319. << '\n';
  320. if (this->IsRootMakefile()) {
  321. os << "# Which is the root file.\n";
  322. }
  323. cmGlobalNinjaGenerator::WriteDivider(os);
  324. os << '\n';
  325. }
  326. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  327. cmNinjaDeps& outputs,
  328. const std::string& config)
  329. {
  330. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
  331. DependOnTargetArtifact);
  332. }
  333. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  334. cmNinjaDeps& outputs,
  335. const std::string& config,
  336. const std::string& fileConfig,
  337. cmNinjaTargetDepends depends)
  338. {
  339. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
  340. fileConfig, depends);
  341. }
  342. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  343. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
  344. const std::string& config)
  345. {
  346. for (std::string const& i : ccg.GetDepends()) {
  347. std::string dep;
  348. if (this->GetRealDependency(i, config, dep)) {
  349. ninjaDeps.push_back(
  350. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  351. }
  352. }
  353. }
  354. std::string cmLocalNinjaGenerator::WriteCommandScript(
  355. std::vector<std::string> const& cmdLines, std::string const& outputConfig,
  356. std::string const& commandConfig, std::string const& customStep,
  357. cmGeneratorTarget const* target) const
  358. {
  359. std::string scriptPath;
  360. if (target) {
  361. scriptPath = target->GetSupportDirectory();
  362. } else {
  363. scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
  364. }
  365. scriptPath += this->GetGlobalNinjaGenerator()->ConfigDirectory(outputConfig);
  366. cmSystemTools::MakeDirectory(scriptPath);
  367. scriptPath += '/';
  368. scriptPath += customStep;
  369. if (this->GlobalGenerator->IsMultiConfig()) {
  370. scriptPath += cmStrCat('-', commandConfig);
  371. }
  372. #ifdef _WIN32
  373. scriptPath += ".bat";
  374. #else
  375. scriptPath += ".sh";
  376. #endif
  377. cmsys::ofstream script(scriptPath.c_str());
  378. #ifdef _WIN32
  379. script << "@echo off\n";
  380. int line = 1;
  381. #else
  382. script << "set -e\n\n";
  383. #endif
  384. for (auto const& i : cmdLines) {
  385. std::string cmd = i;
  386. // The command line was built assuming it would be written to
  387. // the build.ninja file, so it uses '$$' for '$'. Remove this
  388. // for the raw shell script.
  389. cmSystemTools::ReplaceString(cmd, "$$", "$");
  390. #ifdef _WIN32
  391. script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
  392. << '\n';
  393. #else
  394. script << cmd << '\n';
  395. #endif
  396. }
  397. #ifdef _WIN32
  398. script << "goto :EOF\n\n"
  399. ":ABORT\n"
  400. "set ERROR_CODE=%ERRORLEVEL%\n"
  401. "echo Batch file failed at line %FAIL_LINE% "
  402. "with errorcode %ERRORLEVEL%\n"
  403. "exit /b %ERROR_CODE%";
  404. #endif
  405. return scriptPath;
  406. }
  407. std::string cmLocalNinjaGenerator::BuildCommandLine(
  408. std::vector<std::string> const& cmdLines, std::string const& outputConfig,
  409. std::string const& commandConfig, std::string const& customStep,
  410. cmGeneratorTarget const* target) const
  411. {
  412. // If we have no commands but we need to build a command anyway, use noop.
  413. // This happens when building a POST_BUILD value for link targets that
  414. // don't use POST_BUILD.
  415. if (cmdLines.empty()) {
  416. return cmGlobalNinjaGenerator::SHELL_NOOP;
  417. }
  418. // If this is a custom step then we will have no '$VAR' ninja placeholders.
  419. // This means we can deal with long command sequences by writing to a script.
  420. // Do this if the command lines are on the scale of the OS limit.
  421. if (!customStep.empty()) {
  422. size_t cmdLinesTotal = 0;
  423. for (std::string const& cmd : cmdLines) {
  424. cmdLinesTotal += cmd.length() + 6;
  425. }
  426. if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
  427. std::string const scriptPath = this->WriteCommandScript(
  428. cmdLines, outputConfig, commandConfig, customStep, target);
  429. std::string cmd
  430. #ifndef _WIN32
  431. = "/bin/sh "
  432. #endif
  433. ;
  434. cmd += this->ConvertToOutputFormat(
  435. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
  436. cmOutputConverter::SHELL);
  437. // Add an unused argument based on script content so that Ninja
  438. // knows when the command lines change.
  439. cmd += " ";
  440. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  441. cmd += hash.HashFile(scriptPath).substr(0, 16);
  442. return cmd;
  443. }
  444. }
  445. std::ostringstream cmd;
  446. for (auto li = cmdLines.begin(); li != cmdLines.end(); ++li)
  447. #ifdef _WIN32
  448. {
  449. if (li != cmdLines.begin()) {
  450. cmd << " && ";
  451. } else if (cmdLines.size() > 1) {
  452. cmd << "cmd.exe /C \"";
  453. }
  454. // Put current cmdLine in brackets if it contains "||" because it has
  455. // higher precedence than "&&" in cmd.exe
  456. if (li->find("||") != std::string::npos) {
  457. cmd << "( " << *li << " )";
  458. } else {
  459. cmd << *li;
  460. }
  461. }
  462. if (cmdLines.size() > 1) {
  463. cmd << "\"";
  464. }
  465. #else
  466. {
  467. if (li != cmdLines.begin()) {
  468. cmd << " && ";
  469. }
  470. cmd << *li;
  471. }
  472. #endif
  473. return cmd.str();
  474. }
  475. void cmLocalNinjaGenerator::AppendCustomCommandLines(
  476. cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
  477. {
  478. auto* gg = this->GetGlobalNinjaGenerator();
  479. if (ccg.GetNumberOfCommands() > 0) {
  480. std::string wd = ccg.GetWorkingDirectory();
  481. if (wd.empty()) {
  482. wd = this->GetCurrentBinaryDirectory();
  483. }
  484. std::ostringstream cdCmd;
  485. #ifdef _WIN32
  486. std::string cdStr = "cd /D ";
  487. #else
  488. std::string cdStr = "cd ";
  489. #endif
  490. cdCmd << cdStr
  491. << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
  492. cmdLines.push_back(cdCmd.str());
  493. }
  494. std::string launcher = this->MakeCustomLauncher(ccg);
  495. for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
  496. std::string c = ccg.GetCommand(i);
  497. if (c.empty()) {
  498. continue;
  499. }
  500. cmdLines.push_back(launcher +
  501. this->ConvertToOutputFormat(
  502. c,
  503. gg->IsMultiConfig() ? cmOutputConverter::NINJAMULTI
  504. : cmOutputConverter::SHELL));
  505. std::string& cmd = cmdLines.back();
  506. ccg.AppendArguments(i, cmd);
  507. }
  508. }
  509. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
  510. cmCustomCommand const* cc, const std::set<cmGeneratorTarget*>& targets,
  511. const std::string& fileConfig)
  512. {
  513. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  514. if (gg->SeenCustomCommand(cc, fileConfig)) {
  515. return;
  516. }
  517. auto ccgs = this->MakeCustomCommandGenerators(*cc, fileConfig);
  518. for (cmCustomCommandGenerator const& ccg : ccgs) {
  519. if (ccg.GetOutputs().empty() && ccg.GetByproducts().empty()) {
  520. // Generator expressions evaluate to no output for this config.
  521. continue;
  522. }
  523. cmNinjaDeps orderOnlyDeps;
  524. if (!cc->GetDependsExplicitOnly()) {
  525. // A custom command may appear on multiple targets. However, some build
  526. // systems exist where the target dependencies on some of the targets are
  527. // overspecified, leading to a dependency cycle. If we assume all target
  528. // dependencies are a superset of the true target dependencies for this
  529. // custom command, we can take the set intersection of all target
  530. // dependencies to obtain a correct dependency list.
  531. //
  532. // FIXME: This won't work in certain obscure scenarios involving indirect
  533. // dependencies.
  534. auto j = targets.begin();
  535. assert(j != targets.end());
  536. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
  537. *j, orderOnlyDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
  538. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  539. ++j;
  540. for (; j != targets.end(); ++j) {
  541. std::vector<std::string> jDeps;
  542. std::vector<std::string> depsIntersection;
  543. this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
  544. *j, jDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
  545. std::sort(jDeps.begin(), jDeps.end());
  546. std::set_intersection(orderOnlyDeps.begin(), orderOnlyDeps.end(),
  547. jDeps.begin(), jDeps.end(),
  548. std::back_inserter(depsIntersection));
  549. orderOnlyDeps = depsIntersection;
  550. }
  551. }
  552. const std::vector<std::string>& outputs = ccg.GetOutputs();
  553. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  554. bool symbolic = false;
  555. for (std::string const& output : outputs) {
  556. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  557. if (sf->GetPropertyAsBool("SYMBOLIC")) {
  558. symbolic = true;
  559. break;
  560. }
  561. }
  562. }
  563. cmGlobalNinjaGenerator::CCOutputs ccOutputs(gg);
  564. ccOutputs.Add(outputs);
  565. ccOutputs.Add(byproducts);
  566. std::string mainOutput = ccOutputs.ExplicitOuts[0];
  567. cmNinjaDeps ninjaDeps;
  568. this->AppendCustomCommandDeps(ccg, ninjaDeps, fileConfig);
  569. std::vector<std::string> cmdLines;
  570. this->AppendCustomCommandLines(ccg, cmdLines);
  571. if (cmdLines.empty()) {
  572. cmNinjaBuild build("phony");
  573. build.Comment = cmStrCat("Phony custom command for ", mainOutput);
  574. build.Outputs = std::move(ccOutputs.ExplicitOuts);
  575. build.WorkDirOuts = std::move(ccOutputs.WorkDirOuts);
  576. build.ExplicitDeps = std::move(ninjaDeps);
  577. build.OrderOnlyDeps = orderOnlyDeps;
  578. gg->WriteBuild(this->GetImplFileStream(fileConfig), build);
  579. } else {
  580. std::string customStep = cmSystemTools::GetFilenameName(mainOutput);
  581. if (this->GlobalGenerator->IsMultiConfig()) {
  582. customStep += '-';
  583. customStep += fileConfig;
  584. customStep += '-';
  585. customStep += ccg.GetOutputConfig();
  586. }
  587. // Hash full path to make unique.
  588. customStep += '-';
  589. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  590. customStep += hash.HashString(mainOutput).substr(0, 7);
  591. std::string depfile = ccg.GetDepfile();
  592. if (!depfile.empty()) {
  593. switch (cc->GetCMP0116Status()) {
  594. case cmPolicies::WARN:
  595. if (this->GetCurrentBinaryDirectory() !=
  596. this->GetBinaryDirectory() ||
  597. this->Makefile->PolicyOptionalWarningEnabled(
  598. "CMAKE_POLICY_WARNING_CMP0116")) {
  599. this->GetCMakeInstance()->IssueMessage(
  600. MessageType::AUTHOR_WARNING,
  601. cmPolicies::GetPolicyWarning(cmPolicies::CMP0116),
  602. cc->GetBacktrace());
  603. }
  604. CM_FALLTHROUGH;
  605. case cmPolicies::OLD:
  606. break;
  607. case cmPolicies::REQUIRED_IF_USED:
  608. case cmPolicies::REQUIRED_ALWAYS:
  609. case cmPolicies::NEW:
  610. depfile = ccg.GetInternalDepfile();
  611. break;
  612. }
  613. }
  614. std::string comment = cmStrCat("Custom command for ", mainOutput);
  615. gg->WriteCustomCommandBuild(
  616. this->BuildCommandLine(cmdLines, ccg.GetOutputConfig(), fileConfig,
  617. customStep),
  618. this->ConstructComment(ccg), comment, depfile, cc->GetJobPool(),
  619. cc->GetUsesTerminal(),
  620. /*restat*/ !symbolic || !byproducts.empty(), fileConfig,
  621. std::move(ccOutputs), std::move(ninjaDeps), std::move(orderOnlyDeps));
  622. }
  623. }
  624. }
  625. bool cmLocalNinjaGenerator::HasUniqueByproducts(
  626. std::vector<std::string> const& byproducts, cmListFileBacktrace const& bt)
  627. {
  628. std::vector<std::string> configs =
  629. this->GetMakefile()->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  630. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  631. for (std::string const& p : byproducts) {
  632. if (cmGeneratorExpression::Find(p) == std::string::npos) {
  633. return false;
  634. }
  635. std::set<std::string> seen;
  636. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(p);
  637. for (std::string const& config : configs) {
  638. for (std::string const& b :
  639. this->ExpandCustomCommandOutputPaths(*cge, config)) {
  640. if (!seen.insert(b).second) {
  641. return false;
  642. }
  643. }
  644. }
  645. }
  646. return true;
  647. }
  648. namespace {
  649. bool HasUniqueOutputs(std::vector<cmCustomCommandGenerator> const& ccgs)
  650. {
  651. std::set<std::string> allOutputs;
  652. std::set<std::string> allByproducts;
  653. for (cmCustomCommandGenerator const& ccg : ccgs) {
  654. for (std::string const& output : ccg.GetOutputs()) {
  655. if (!allOutputs.insert(output).second) {
  656. return false;
  657. }
  658. }
  659. for (std::string const& byproduct : ccg.GetByproducts()) {
  660. if (!allByproducts.insert(byproduct).second) {
  661. return false;
  662. }
  663. }
  664. }
  665. return true;
  666. }
  667. }
  668. std::string cmLocalNinjaGenerator::CreateUtilityOutput(
  669. std::string const& targetName, std::vector<std::string> const& byproducts,
  670. cmListFileBacktrace const& bt)
  671. {
  672. // In Ninja Multi-Config, we can only produce cross-config utility
  673. // commands if all byproducts are per-config.
  674. if (!this->GetGlobalGenerator()->IsMultiConfig() ||
  675. !this->HasUniqueByproducts(byproducts, bt)) {
  676. return this->cmLocalGenerator::CreateUtilityOutput(targetName, byproducts,
  677. bt);
  678. }
  679. std::string const base = cmStrCat(this->GetCurrentBinaryDirectory(),
  680. "/CMakeFiles/", targetName, '-');
  681. // The output is not actually created so mark it symbolic.
  682. for (std::string const& config :
  683. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
  684. std::string const force = cmStrCat(base, config);
  685. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  686. sf->SetProperty("SYMBOLIC", "1");
  687. } else {
  688. cmSystemTools::Error("Could not get source file entry for " + force);
  689. }
  690. }
  691. this->GetGlobalNinjaGenerator()->AddPerConfigUtilityTarget(targetName);
  692. return cmStrCat(base, "$<CONFIG>"_s);
  693. }
  694. std::vector<cmCustomCommandGenerator>
  695. cmLocalNinjaGenerator::MakeCustomCommandGenerators(
  696. cmCustomCommand const& cc, std::string const& fileConfig)
  697. {
  698. cmGlobalNinjaGenerator const* gg = this->GetGlobalNinjaGenerator();
  699. bool transformDepfile = false;
  700. switch (cc.GetCMP0116Status()) {
  701. case cmPolicies::WARN:
  702. CM_FALLTHROUGH;
  703. case cmPolicies::OLD:
  704. break;
  705. case cmPolicies::REQUIRED_IF_USED:
  706. case cmPolicies::REQUIRED_ALWAYS:
  707. case cmPolicies::NEW:
  708. transformDepfile = true;
  709. break;
  710. }
  711. // Start with the build graph's configuration.
  712. std::vector<cmCustomCommandGenerator> ccgs;
  713. ccgs.emplace_back(cc, fileConfig, this, transformDepfile);
  714. // Consider adding cross configurations.
  715. if (!gg->EnableCrossConfigBuild()) {
  716. return ccgs;
  717. }
  718. // Outputs and byproducts must be expressed using generator expressions.
  719. for (std::string const& output : cc.GetOutputs()) {
  720. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  721. return ccgs;
  722. }
  723. }
  724. for (std::string const& byproduct : cc.GetByproducts()) {
  725. if (cmGeneratorExpression::Find(byproduct) == std::string::npos) {
  726. return ccgs;
  727. }
  728. }
  729. // Tentatively add the other cross configurations.
  730. for (std::string const& config : gg->GetCrossConfigs(fileConfig)) {
  731. if (fileConfig != config) {
  732. ccgs.emplace_back(cc, fileConfig, this, transformDepfile, config);
  733. }
  734. }
  735. // If outputs and byproducts are not unique to each configuration,
  736. // drop the cross configurations.
  737. if (!HasUniqueOutputs(ccgs)) {
  738. ccgs.erase(ccgs.begin() + 1, ccgs.end());
  739. }
  740. return ccgs;
  741. }
  742. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  743. cmGeneratorTarget* target)
  744. {
  745. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  746. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  747. this->CustomCommandTargets.insert(v);
  748. if (ins.second) {
  749. this->CustomCommands.push_back(cc);
  750. }
  751. ins.first->second.insert(target);
  752. }
  753. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
  754. const std::string& fileConfig)
  755. {
  756. for (cmCustomCommand const* customCommand : this->CustomCommands) {
  757. auto i = this->CustomCommandTargets.find(customCommand);
  758. assert(i != this->CustomCommandTargets.end());
  759. this->WriteCustomCommandBuildStatement(i->first, i->second, fileConfig);
  760. }
  761. }
  762. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  763. cmCustomCommandGenerator const& ccg)
  764. {
  765. cmValue property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  766. if (!cmNonempty(property_value)) {
  767. return std::string();
  768. }
  769. // Expand rule variables referenced in the given launcher command.
  770. cmRulePlaceholderExpander::RuleVariables vars;
  771. std::string output;
  772. const std::vector<std::string>& outputs = ccg.GetOutputs();
  773. if (!outputs.empty()) {
  774. output = outputs[0];
  775. if (ccg.GetWorkingDirectory().empty()) {
  776. output = this->MaybeRelativeToCurBinDir(output);
  777. }
  778. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  779. }
  780. vars.Output = output.c_str();
  781. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  782. this->CreateRulePlaceholderExpander());
  783. std::string launcher = *property_value;
  784. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  785. if (!launcher.empty()) {
  786. launcher += " ";
  787. }
  788. return launcher;
  789. }
  790. void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
  791. {
  792. if (cmValue prop_value =
  793. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  794. std::vector<std::string> cleanFiles;
  795. {
  796. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, this, config),
  797. cleanFiles);
  798. }
  799. std::string const& binaryDir = this->GetCurrentBinaryDirectory();
  800. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  801. for (std::string const& cleanFile : cleanFiles) {
  802. // Support relative paths
  803. gg->AddAdditionalCleanFile(
  804. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  805. }
  806. }
  807. }