cmLocalNinjaGenerator.cxx 32 KB

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