cmLocalNinjaGenerator.cxx 31 KB

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