cmLocalNinjaGenerator.cxx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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 "cmCryptoHash.h"
  14. #include "cmCustomCommand.h"
  15. #include "cmCustomCommandGenerator.h"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmGeneratorExpression.h"
  18. #include "cmGeneratorTarget.h"
  19. #include "cmGlobalGenerator.h"
  20. #include "cmGlobalNinjaGenerator.h"
  21. #include "cmList.h"
  22. #include "cmLocalGenerator.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmNinjaTargetGenerator.h"
  26. #include "cmNinjaTypes.h"
  27. #include "cmPolicies.h"
  28. #include "cmRulePlaceholderExpander.h"
  29. #include "cmSourceFile.h"
  30. #include "cmState.h"
  31. #include "cmStateTypes.h"
  32. #include "cmStringAlgorithms.h"
  33. #include "cmSystemTools.h"
  34. #include "cmTarget.h"
  35. #include "cmValue.h"
  36. #include "cmake.h"
  37. cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
  38. cmMakefile* mf)
  39. : cmLocalCommonGenerator(gg, mf)
  40. {
  41. }
  42. // Virtual public methods.
  43. cmRulePlaceholderExpander*
  44. cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
  45. {
  46. cmRulePlaceholderExpander* ret =
  47. this->cmLocalGenerator::CreateRulePlaceholderExpander();
  48. ret->SetTargetImpLib("$TARGET_IMPLIB");
  49. return ret;
  50. }
  51. cmLocalNinjaGenerator::~cmLocalNinjaGenerator() = default;
  52. void cmLocalNinjaGenerator::Generate()
  53. {
  54. // Compute the path to use when referencing the current output
  55. // directory from the top output directory.
  56. this->HomeRelativeOutputPath =
  57. this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
  58. if (this->HomeRelativeOutputPath == ".") {
  59. this->HomeRelativeOutputPath.clear();
  60. }
  61. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  62. for (auto const& config : this->GetConfigNames()) {
  63. this->WriteProcessedMakefile(this->GetImplFileStream(config));
  64. }
  65. }
  66. this->WriteProcessedMakefile(this->GetCommonFileStream());
  67. #ifdef NINJA_GEN_VERBOSE_FILES
  68. this->WriteProcessedMakefile(this->GetRulesFileStream());
  69. #endif
  70. // We do that only once for the top CMakeLists.txt file.
  71. if (this->IsRootMakefile()) {
  72. this->WriteBuildFileTop();
  73. this->WritePools(this->GetRulesFileStream());
  74. const std::string& showIncludesPrefix =
  75. this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  76. if (!showIncludesPrefix.empty()) {
  77. cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
  78. "localized /showIncludes string");
  79. this->GetRulesFileStream() << "msvc_deps_prefix = ";
  80. // 'cl /showIncludes' encodes output in the console output code page.
  81. // It may differ from the encoding used for file paths in 'build.ninja'.
  82. // Ninja matches the showIncludes prefix using its raw byte sequence.
  83. this->GetRulesFileStream().WriteAltEncoding(
  84. showIncludesPrefix, cmGeneratedFileStream::Encoding::ConsoleOutput);
  85. this->GetRulesFileStream() << "\n\n";
  86. }
  87. }
  88. for (const auto& target : this->GetGeneratorTargets()) {
  89. if (!target->IsInBuildSystem()) {
  90. continue;
  91. }
  92. auto tg = cmNinjaTargetGenerator::New(target.get());
  93. if (tg) {
  94. if (target->Target->IsPerConfig()) {
  95. for (auto const& config : this->GetConfigNames()) {
  96. tg->Generate(config);
  97. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  98. this->GetGlobalGenerator()->IsMultiConfig()) {
  99. cmNinjaBuild phonyAlias("phony");
  100. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  101. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  102. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  103. target.get(), phonyAlias.ExplicitDeps, config,
  104. DependOnTargetArtifact);
  105. this->GetGlobalNinjaGenerator()->WriteBuild(
  106. *this->GetGlobalNinjaGenerator()->GetConfigFileStream(config),
  107. phonyAlias);
  108. }
  109. }
  110. if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
  111. this->GetGlobalGenerator()->IsMultiConfig()) {
  112. if (!this->GetGlobalNinjaGenerator()->GetDefaultConfigs().empty()) {
  113. cmNinjaBuild phonyAlias("phony");
  114. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  115. target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
  116. for (auto const& config :
  117. this->GetGlobalNinjaGenerator()->GetDefaultConfigs()) {
  118. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  119. target.get(), phonyAlias.ExplicitDeps, config,
  120. DependOnTargetArtifact);
  121. }
  122. this->GetGlobalNinjaGenerator()->WriteBuild(
  123. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  124. phonyAlias);
  125. }
  126. cmNinjaBuild phonyAlias("phony");
  127. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  128. target.get(), phonyAlias.Outputs, "all", DependOnTargetArtifact);
  129. for (auto const& config : this->GetConfigNames()) {
  130. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
  131. target.get(), phonyAlias.ExplicitDeps, config,
  132. DependOnTargetArtifact);
  133. }
  134. this->GetGlobalNinjaGenerator()->WriteBuild(
  135. *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
  136. phonyAlias);
  137. }
  138. } else {
  139. tg->Generate("");
  140. }
  141. }
  142. }
  143. for (auto const& config : this->GetConfigNames()) {
  144. this->WriteCustomCommandBuildStatements(config);
  145. this->AdditionalCleanFiles(config);
  146. }
  147. }
  148. // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
  149. std::string cmLocalNinjaGenerator::GetTargetDirectory(
  150. cmGeneratorTarget const* target) const
  151. {
  152. std::string dir = cmStrCat("CMakeFiles/", target->GetName());
  153. #if defined(__VMS)
  154. dir += "_dir";
  155. #else
  156. dir += ".dir";
  157. #endif
  158. return dir;
  159. }
  160. // Non-virtual public methods.
  161. const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  162. const
  163. {
  164. return static_cast<const cmGlobalNinjaGenerator*>(
  165. this->GetGlobalGenerator());
  166. }
  167. cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
  168. {
  169. return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
  170. }
  171. std::string const& cmLocalNinjaGenerator::GetWorkingDirectory() const
  172. {
  173. return this->GetState()->GetBinaryDirectory();
  174. }
  175. std::string cmLocalNinjaGenerator::MaybeRelativeToWorkDir(
  176. std::string const& path) const
  177. {
  178. return this->GetGlobalNinjaGenerator()->NinjaOutputPath(
  179. this->MaybeRelativeToTopBinDir(path));
  180. }
  181. std::string cmLocalNinjaGenerator::GetLinkDependencyFile(
  182. cmGeneratorTarget* target, std::string const& config) const
  183. {
  184. return cmStrCat(target->GetSupportDirectory(),
  185. this->GetGlobalNinjaGenerator()->ConfigDirectory(config),
  186. "/link.d");
  187. }
  188. // Virtual protected methods.
  189. std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
  190. std::string const& path, cmOutputConverter::OutputFormat format)
  191. {
  192. return this->ConvertToOutputFormat(path, format);
  193. }
  194. // Private methods.
  195. cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
  196. const std::string& config) const
  197. {
  198. return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
  199. }
  200. cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
  201. {
  202. return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
  203. }
  204. cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
  205. {
  206. return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
  207. }
  208. const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
  209. {
  210. return this->GetGlobalGenerator()->GetCMakeInstance();
  211. }
  212. cmake* cmLocalNinjaGenerator::GetCMakeInstance()
  213. {
  214. return this->GetGlobalGenerator()->GetCMakeInstance();
  215. }
  216. void cmLocalNinjaGenerator::WriteBuildFileTop()
  217. {
  218. this->WriteProjectHeader(this->GetCommonFileStream());
  219. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  220. for (auto const& config : this->GetConfigNames()) {
  221. auto& stream = this->GetImplFileStream(config);
  222. this->WriteProjectHeader(stream);
  223. this->WriteNinjaRequiredVersion(stream);
  224. this->WriteNinjaConfigurationVariable(stream, config);
  225. this->WriteNinjaFilesInclusionConfig(stream);
  226. }
  227. } else {
  228. this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
  229. this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
  230. this->GetConfigNames().front());
  231. }
  232. this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
  233. this->WriteNinjaWorkDir(this->GetCommonFileStream());
  234. // For the rule file.
  235. this->WriteProjectHeader(this->GetRulesFileStream());
  236. }
  237. void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
  238. {
  239. cmGlobalNinjaGenerator::WriteDivider(os);
  240. os << "# Project: " << this->GetProjectName() << '\n'
  241. << "# Configurations: " << cmJoin(this->GetConfigNames(), ", ") << '\n';
  242. cmGlobalNinjaGenerator::WriteDivider(os);
  243. }
  244. void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
  245. {
  246. // Default required version
  247. std::string requiredVersion = cmGlobalNinjaGenerator::RequiredNinjaVersion();
  248. // Ninja generator uses the 'console' pool if available (>= 1.5)
  249. if (this->GetGlobalNinjaGenerator()->SupportsDirectConsole()) {
  250. requiredVersion =
  251. cmGlobalNinjaGenerator::RequiredNinjaVersionForConsolePool();
  252. }
  253. // The Ninja generator writes rules which require support for restat
  254. // when rebuilding build.ninja manifest (>= 1.8)
  255. if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() &&
  256. this->GetCMakeInstance()->DoWriteGlobVerifyTarget() &&
  257. !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn(
  258. "CMAKE_SUPPRESS_REGENERATION")) {
  259. requiredVersion =
  260. cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat();
  261. }
  262. cmGlobalNinjaGenerator::WriteComment(
  263. os, "Minimal version of Ninja required by this file");
  264. os << "ninja_required_version = " << requiredVersion << "\n\n";
  265. }
  266. void cmLocalNinjaGenerator::WriteNinjaConfigurationVariable(
  267. std::ostream& os, const std::string& config)
  268. {
  269. cmGlobalNinjaGenerator::WriteVariable(
  270. os, "CONFIGURATION", config,
  271. "Set configuration variable for custom commands.");
  272. }
  273. void cmLocalNinjaGenerator::WritePools(std::ostream& os)
  274. {
  275. cmGlobalNinjaGenerator::WriteDivider(os);
  276. cmValue jobpools =
  277. this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
  278. if (!jobpools) {
  279. jobpools = this->GetMakefile()->GetDefinition("CMAKE_JOB_POOLS");
  280. }
  281. if (jobpools) {
  282. cmGlobalNinjaGenerator::WriteComment(
  283. os, "Pools defined by global property JOB_POOLS");
  284. cmList pools{ *jobpools };
  285. for (std::string const& pool : pools) {
  286. const std::string::size_type eq = pool.find('=');
  287. unsigned int jobs;
  288. if (eq != std::string::npos &&
  289. sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
  290. os << "pool " << pool.substr(0, eq) << "\n depth = " << jobs
  291. << "\n\n";
  292. } else {
  293. cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': " +
  294. pool);
  295. }
  296. }
  297. }
  298. }
  299. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionConfig(std::ostream& os)
  300. {
  301. cmGlobalNinjaGenerator::WriteDivider(os);
  302. os << "# Include auxiliary files.\n\n";
  303. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  304. std::string const ninjaCommonFile =
  305. ng->NinjaOutputPath(cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE);
  306. std::string const commonFilePath = ng->EncodePath(ninjaCommonFile);
  307. cmGlobalNinjaGenerator::WriteInclude(os, commonFilePath,
  308. "Include common file.");
  309. os << "\n";
  310. }
  311. void cmLocalNinjaGenerator::WriteNinjaFilesInclusionCommon(std::ostream& os)
  312. {
  313. cmGlobalNinjaGenerator::WriteDivider(os);
  314. os << "# Include auxiliary files.\n\n";
  315. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  316. std::string const ninjaRulesFile =
  317. ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
  318. std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile);
  319. cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
  320. "Include rules file.");
  321. os << "\n";
  322. }
  323. void cmLocalNinjaGenerator::WriteNinjaWorkDir(std::ostream& os)
  324. {
  325. cmGlobalNinjaGenerator::WriteDivider(os);
  326. cmGlobalNinjaGenerator::WriteComment(
  327. os, "Logical path to working directory; prefix for absolute paths.");
  328. cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
  329. std::string ninja_workdir = this->GetBinaryDirectory();
  330. ng->StripNinjaOutputPathPrefixAsSuffix(ninja_workdir); // Also appends '/'.
  331. os << "cmake_ninja_workdir = " << ng->EncodePath(ninja_workdir) << "\n";
  332. }
  333. void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
  334. {
  335. cmGlobalNinjaGenerator::WriteDivider(os);
  336. os << "# Write statements declared in CMakeLists.txt:\n"
  337. << "# " << this->Makefile->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE")
  338. << '\n';
  339. if (this->IsRootMakefile()) {
  340. os << "# Which is the root file.\n";
  341. }
  342. cmGlobalNinjaGenerator::WriteDivider(os);
  343. os << '\n';
  344. }
  345. void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
  346. cmNinjaDeps& outputs,
  347. const std::string& config)
  348. {
  349. this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
  350. DependOnTargetArtifact);
  351. }
  352. void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
  353. cmNinjaDeps& outputs,
  354. const std::string& config,
  355. const std::string& fileConfig,
  356. cmNinjaTargetDepends depends)
  357. {
  358. this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
  359. fileConfig, depends);
  360. }
  361. void cmLocalNinjaGenerator::AppendCustomCommandDeps(
  362. cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
  363. const std::string& config)
  364. {
  365. for (std::string const& i : ccg.GetDepends()) {
  366. std::string dep;
  367. if (this->GetRealDependency(i, config, dep)) {
  368. ninjaDeps.push_back(
  369. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
  370. }
  371. }
  372. }
  373. std::string cmLocalNinjaGenerator::WriteCommandScript(
  374. std::vector<std::string> const& cmdLines, std::string const& outputConfig,
  375. std::string const& commandConfig, std::string const& customStep,
  376. cmGeneratorTarget const* target) const
  377. {
  378. std::string scriptPath;
  379. if (target) {
  380. scriptPath = target->GetSupportDirectory();
  381. } else {
  382. scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
  383. }
  384. scriptPath += this->GetGlobalNinjaGenerator()->ConfigDirectory(outputConfig);
  385. cmSystemTools::MakeDirectory(scriptPath);
  386. scriptPath += '/';
  387. scriptPath += customStep;
  388. if (this->GlobalGenerator->IsMultiConfig()) {
  389. scriptPath += cmStrCat('-', commandConfig);
  390. }
  391. #ifdef _WIN32
  392. scriptPath += ".bat";
  393. #else
  394. scriptPath += ".sh";
  395. #endif
  396. cmsys::ofstream script(scriptPath.c_str());
  397. #ifdef _WIN32
  398. script << "@echo off\n";
  399. int line = 1;
  400. #else
  401. script << "set -e\n\n";
  402. #endif
  403. for (auto const& i : cmdLines) {
  404. std::string cmd = i;
  405. // The command line was built assuming it would be written to
  406. // the build.ninja file, so it uses '$$' for '$'. Remove this
  407. // for the raw shell script.
  408. cmSystemTools::ReplaceString(cmd, "$$", "$");
  409. #ifdef _WIN32
  410. script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
  411. << '\n';
  412. #else
  413. script << cmd << '\n';
  414. #endif
  415. }
  416. #ifdef _WIN32
  417. script << "goto :EOF\n\n"
  418. ":ABORT\n"
  419. "set ERROR_CODE=%ERRORLEVEL%\n"
  420. "echo Batch file failed at line %FAIL_LINE% "
  421. "with errorcode %ERRORLEVEL%\n"
  422. "exit /b %ERROR_CODE%";
  423. #endif
  424. return scriptPath;
  425. }
  426. #ifdef _WIN32
  427. namespace {
  428. bool RuleNeedsCMD(std::string const& cmd)
  429. {
  430. std::vector<std::string> args;
  431. cmSystemTools::ParseWindowsCommandLine(cmd.c_str(), args);
  432. auto it = std::find_if(args.cbegin(), args.cend(),
  433. [](std::string const& arg) -> bool {
  434. // FIXME: Detect more windows shell operators.
  435. return cmHasLiteralPrefix(arg, ">");
  436. });
  437. return it != args.cend();
  438. }
  439. }
  440. #endif
  441. std::string cmLocalNinjaGenerator::BuildCommandLine(
  442. std::vector<std::string> const& cmdLines, std::string const& outputConfig,
  443. std::string const& commandConfig, std::string const& customStep,
  444. cmGeneratorTarget const* target) const
  445. {
  446. // If we have no commands but we need to build a command anyway, use noop.
  447. // This happens when building a POST_BUILD value for link targets that
  448. // don't use POST_BUILD.
  449. if (cmdLines.empty()) {
  450. return cmGlobalNinjaGenerator::SHELL_NOOP;
  451. }
  452. // If this is a custom step then we will have no '$VAR' ninja placeholders.
  453. // This means we can deal with long command sequences by writing to a script.
  454. // Do this if the command lines are on the scale of the OS limit.
  455. if (!customStep.empty()) {
  456. size_t cmdLinesTotal = 0;
  457. for (std::string const& cmd : cmdLines) {
  458. cmdLinesTotal += cmd.length() + 6;
  459. }
  460. if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
  461. std::string const scriptPath = this->WriteCommandScript(
  462. cmdLines, outputConfig, commandConfig, customStep, target);
  463. std::string cmd
  464. #ifndef _WIN32
  465. = "/bin/sh "
  466. #endif
  467. ;
  468. cmd += this->ConvertToOutputFormat(
  469. this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
  470. cmOutputConverter::SHELL);
  471. // Add an unused argument based on script content so that Ninja
  472. // knows when the command lines change.
  473. cmd += " ";
  474. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  475. cmd += hash.HashFile(scriptPath).substr(0, 16);
  476. return cmd;
  477. }
  478. }
  479. std::ostringstream cmd;
  480. #ifdef _WIN32
  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 << "cmd.exe /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, const std::set<cmGeneratorTarget*>& targets,
  546. const std::string& 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. const std::vector<std::string>& outputs = ccg.GetOutputs();
  584. const std::vector<std::string>& 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::REQUIRED_IF_USED:
  642. case cmPolicies::REQUIRED_ALWAYS:
  643. case cmPolicies::NEW:
  644. depfile = ccg.GetInternalDepfile();
  645. break;
  646. }
  647. }
  648. std::string comment = cmStrCat("Custom command for ", mainOutput);
  649. gg->WriteCustomCommandBuild(
  650. this->BuildCommandLine(cmdLines, ccg.GetOutputConfig(), fileConfig,
  651. customStep),
  652. this->ConstructComment(ccg), comment, depfile, cc->GetJobPool(),
  653. cc->GetUsesTerminal(),
  654. /*restat*/ !symbolic || !byproducts.empty(), fileConfig,
  655. std::move(ccOutputs), std::move(ninjaDeps),
  656. std::move(sortedOrderOnlyDeps));
  657. }
  658. }
  659. }
  660. bool cmLocalNinjaGenerator::HasUniqueByproducts(
  661. std::vector<std::string> const& byproducts, cmListFileBacktrace const& bt)
  662. {
  663. std::vector<std::string> configs =
  664. this->GetMakefile()->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  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 : configs) {
  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 :
  718. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
  719. std::string const force = cmStrCat(base, config);
  720. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  721. sf->SetProperty("SYMBOLIC", "1");
  722. } else {
  723. cmSystemTools::Error("Could not get source file entry for " + force);
  724. }
  725. }
  726. this->GetGlobalNinjaGenerator()->AddPerConfigUtilityTarget(targetName);
  727. return cmStrCat(base, "$<CONFIG>"_s);
  728. }
  729. std::vector<cmCustomCommandGenerator>
  730. cmLocalNinjaGenerator::MakeCustomCommandGenerators(
  731. cmCustomCommand const& cc, std::string const& fileConfig)
  732. {
  733. cmGlobalNinjaGenerator const* gg = this->GetGlobalNinjaGenerator();
  734. bool transformDepfile = false;
  735. switch (cc.GetCMP0116Status()) {
  736. case cmPolicies::WARN:
  737. CM_FALLTHROUGH;
  738. case cmPolicies::OLD:
  739. break;
  740. case cmPolicies::REQUIRED_IF_USED:
  741. case cmPolicies::REQUIRED_ALWAYS:
  742. case cmPolicies::NEW:
  743. transformDepfile = true;
  744. break;
  745. }
  746. // Start with the build graph's configuration.
  747. std::vector<cmCustomCommandGenerator> ccgs;
  748. ccgs.emplace_back(cc, fileConfig, this, transformDepfile);
  749. // Consider adding cross configurations.
  750. if (!gg->EnableCrossConfigBuild()) {
  751. return ccgs;
  752. }
  753. // Outputs and byproducts must be expressed using generator expressions.
  754. for (std::string const& output : cc.GetOutputs()) {
  755. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  756. return ccgs;
  757. }
  758. }
  759. for (std::string const& byproduct : cc.GetByproducts()) {
  760. if (cmGeneratorExpression::Find(byproduct) == std::string::npos) {
  761. return ccgs;
  762. }
  763. }
  764. // Tentatively add the other cross configurations.
  765. for (std::string const& config : gg->GetCrossConfigs(fileConfig)) {
  766. if (fileConfig != config) {
  767. ccgs.emplace_back(cc, fileConfig, this, transformDepfile, config);
  768. }
  769. }
  770. // If outputs and byproducts are not unique to each configuration,
  771. // drop the cross configurations.
  772. if (!HasUniqueOutputs(ccgs)) {
  773. ccgs.erase(ccgs.begin() + 1, ccgs.end());
  774. }
  775. return ccgs;
  776. }
  777. void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
  778. cmGeneratorTarget* target)
  779. {
  780. CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
  781. std::pair<CustomCommandTargetMap::iterator, bool> ins =
  782. this->CustomCommandTargets.insert(v);
  783. if (ins.second) {
  784. this->CustomCommands.push_back(cc);
  785. }
  786. ins.first->second.insert(target);
  787. }
  788. void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
  789. const std::string& fileConfig)
  790. {
  791. for (cmCustomCommand const* customCommand : this->CustomCommands) {
  792. auto i = this->CustomCommandTargets.find(customCommand);
  793. assert(i != this->CustomCommandTargets.end());
  794. this->WriteCustomCommandBuildStatement(i->first, i->second, fileConfig);
  795. }
  796. }
  797. std::string cmLocalNinjaGenerator::MakeCustomLauncher(
  798. cmCustomCommandGenerator const& ccg)
  799. {
  800. cmValue property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
  801. if (!cmNonempty(property_value)) {
  802. return std::string();
  803. }
  804. // Expand rule variables referenced in the given launcher command.
  805. cmRulePlaceholderExpander::RuleVariables vars;
  806. std::string output;
  807. const std::vector<std::string>& outputs = ccg.GetOutputs();
  808. if (!outputs.empty()) {
  809. output = outputs[0];
  810. if (ccg.GetWorkingDirectory().empty()) {
  811. output = this->MaybeRelativeToCurBinDir(output);
  812. }
  813. output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  814. }
  815. vars.Output = output.c_str();
  816. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  817. this->CreateRulePlaceholderExpander());
  818. std::string launcher = *property_value;
  819. rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
  820. if (!launcher.empty()) {
  821. launcher += " ";
  822. }
  823. return launcher;
  824. }
  825. void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
  826. {
  827. if (cmValue prop_value =
  828. this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  829. cmList cleanFiles{ cmGeneratorExpression::Evaluate(*prop_value, this,
  830. config) };
  831. std::string const& binaryDir = this->GetCurrentBinaryDirectory();
  832. cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
  833. for (auto const& cleanFile : cleanFiles) {
  834. // Support relative paths
  835. gg->AddAdditionalCleanFile(
  836. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  837. }
  838. }
  839. }