cmLocalNinjaGenerator.cxx 31 KB

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