cmLocalNinjaGenerator.cxx 30 KB

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