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"
13 #include <cmext/string_view>
15 #include "cmsys/FStream.hxx"
17 #include "cmCryptoHash.h"
18 #include "cmCustomCommand.h"
19 #include "cmCustomCommandGenerator.h"
20 #include "cmGeneratedFileStream.h"
21 #include "cmGeneratorExpression.h"
22 #include "cmGeneratorTarget.h"
23 #include "cmGlobalGenerator.h"
24 #include "cmGlobalNinjaGenerator.h"
25 #include "cmLocalGenerator.h"
26 #include "cmMakefile.h"
27 #include "cmMessageType.h"
28 #include "cmNinjaTargetGenerator.h"
29 #include "cmPolicies.h"
30 #include "cmRulePlaceholderExpander.h"
31 #include "cmSourceFile.h"
33 #include "cmStateTypes.h"
34 #include "cmStringAlgorithms.h"
35 #include "cmSystemTools.h"
40 cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
42 : cmLocalCommonGenerator(gg, mf, WorkDir::TopBin)
46 // Virtual public methods.
48 cmRulePlaceholderExpander*
49 cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
51 cmRulePlaceholderExpander* ret =
52 this->cmLocalGenerator::CreateRulePlaceholderExpander();
53 ret->SetTargetImpLib("$TARGET_IMPLIB");
57 cmLocalNinjaGenerator::~cmLocalNinjaGenerator() = default;
59 void cmLocalNinjaGenerator::Generate()
61 // Compute the path to use when referencing the current output
62 // directory from the top output directory.
63 this->HomeRelativeOutputPath =
64 this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
65 if (this->HomeRelativeOutputPath == ".") {
66 this->HomeRelativeOutputPath.clear();
69 if (this->GetGlobalGenerator()->IsMultiConfig()) {
70 for (auto const& config : this->GetConfigNames()) {
71 this->WriteProcessedMakefile(this->GetImplFileStream(config));
74 this->WriteProcessedMakefile(this->GetCommonFileStream());
75 #ifdef NINJA_GEN_VERBOSE_FILES
76 this->WriteProcessedMakefile(this->GetRulesFileStream());
79 // We do that only once for the top CMakeLists.txt file.
80 if (this->IsRootMakefile()) {
81 this->WriteBuildFileTop();
83 this->WritePools(this->GetRulesFileStream());
85 const std::string& showIncludesPrefix =
86 this->GetMakefile()->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
87 if (!showIncludesPrefix.empty()) {
88 cmGlobalNinjaGenerator::WriteComment(this->GetRulesFileStream(),
89 "localized /showIncludes string");
90 this->GetRulesFileStream() << "msvc_deps_prefix = ";
92 // Ninja uses the ANSI Windows APIs, so strings in the rules file
93 // typically need to be ANSI encoded. However, in this case the compiler
94 // is being invoked using the UTF-8 codepage so the /showIncludes prefix
95 // will be UTF-8 encoded on stdout. Ninja can't successfully compare this
96 // UTF-8 encoded prefix to the ANSI encoded msvc_deps_prefix if it
97 // contains any non-ASCII characters and dependency checking will fail.
98 // As a workaround, leave the msvc_deps_prefix UTF-8 encoded even though
99 // the rest of the file is ANSI encoded.
100 if (GetConsoleOutputCP() == CP_UTF8 && GetACP() != CP_UTF8 &&
101 this->GetGlobalGenerator()->GetMakefileEncoding() != codecvt::None) {
102 this->GetRulesFileStream().WriteRaw(showIncludesPrefix);
104 // Ninja 1.11 and above uses the UTF-8 code page if it's supported, so
105 // in that case we can write it normally without using raw bytes.
106 this->GetRulesFileStream() << showIncludesPrefix;
109 // It's safe to use the standard encoding on other platforms.
110 this->GetRulesFileStream() << showIncludesPrefix;
112 this->GetRulesFileStream() << "\n\n";
116 for (const auto& target : this->GetGeneratorTargets()) {
117 if (!target->IsInBuildSystem()) {
120 auto tg = cmNinjaTargetGenerator::New(target.get());
122 if (target->Target->IsPerConfig()) {
123 for (auto const& config : this->GetConfigNames()) {
124 tg->Generate(config);
125 if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
126 this->GetGlobalGenerator()->IsMultiConfig()) {
127 cmNinjaBuild phonyAlias("phony");
128 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
129 target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
130 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
131 target.get(), phonyAlias.ExplicitDeps, config,
132 DependOnTargetArtifact);
133 this->GetGlobalNinjaGenerator()->WriteBuild(
134 *this->GetGlobalNinjaGenerator()->GetConfigFileStream(config),
138 if (target->GetType() == cmStateEnums::GLOBAL_TARGET &&
139 this->GetGlobalGenerator()->IsMultiConfig()) {
140 if (!this->GetGlobalNinjaGenerator()->GetDefaultConfigs().empty()) {
141 cmNinjaBuild phonyAlias("phony");
142 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
143 target.get(), phonyAlias.Outputs, "", DependOnTargetArtifact);
144 for (auto const& config :
145 this->GetGlobalNinjaGenerator()->GetDefaultConfigs()) {
146 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
147 target.get(), phonyAlias.ExplicitDeps, config,
148 DependOnTargetArtifact);
150 this->GetGlobalNinjaGenerator()->WriteBuild(
151 *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
154 cmNinjaBuild phonyAlias("phony");
155 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
156 target.get(), phonyAlias.Outputs, "all", DependOnTargetArtifact);
157 for (auto const& config : this->GetConfigNames()) {
158 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(
159 target.get(), phonyAlias.ExplicitDeps, config,
160 DependOnTargetArtifact);
162 this->GetGlobalNinjaGenerator()->WriteBuild(
163 *this->GetGlobalNinjaGenerator()->GetDefaultFileStream(),
172 for (auto const& config : this->GetConfigNames()) {
173 this->WriteCustomCommandBuildStatements(config);
174 this->AdditionalCleanFiles(config);
178 // TODO: Picked up from cmLocalUnixMakefileGenerator3. Refactor it.
179 std::string cmLocalNinjaGenerator::GetTargetDirectory(
180 cmGeneratorTarget const* target) const
182 std::string dir = cmStrCat("CMakeFiles/", target->GetName());
191 // Non-virtual public methods.
193 const cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
196 return static_cast<const cmGlobalNinjaGenerator*>(
197 this->GetGlobalGenerator());
200 cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
202 return static_cast<cmGlobalNinjaGenerator*>(this->GetGlobalGenerator());
205 // Virtual protected methods.
207 std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
208 std::string const& path, cmOutputConverter::OutputFormat format)
210 return this->ConvertToOutputFormat(path, format);
215 cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
216 const std::string& config) const
218 return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
221 cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
223 return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
226 cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
228 return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
231 const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
233 return this->GetGlobalGenerator()->GetCMakeInstance();
236 cmake* cmLocalNinjaGenerator::GetCMakeInstance()
238 return this->GetGlobalGenerator()->GetCMakeInstance();
241 void cmLocalNinjaGenerator::WriteBuildFileTop()
243 this->WriteProjectHeader(this->GetCommonFileStream());
245 if (this->GetGlobalGenerator()->IsMultiConfig()) {
246 for (auto const& config : this->GetConfigNames()) {
247 auto& stream = this->GetImplFileStream(config);
248 this->WriteProjectHeader(stream);
249 this->WriteNinjaRequiredVersion(stream);
250 this->WriteNinjaConfigurationVariable(stream, config);
251 this->WriteNinjaFilesInclusionConfig(stream);
254 this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
255 this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
256 this->GetConfigNames().front());
258 this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
259 this->WriteNinjaWorkDir(this->GetCommonFileStream());
261 // For the rule file.
262 this->WriteProjectHeader(this->GetRulesFileStream());
265 void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
267 cmGlobalNinjaGenerator::WriteDivider(os);
268 os << "# Project: " << this->GetProjectName() << '\n'
269 << "# Configurations: " << cmJoin(this->GetConfigNames(), ", ") << '\n';
270 cmGlobalNinjaGenerator::WriteDivider(os);
273 void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
275 // Default required version
276 std::string requiredVersion = cmGlobalNinjaGenerator::RequiredNinjaVersion();
278 // Ninja generator uses the 'console' pool if available (>= 1.5)
279 if (this->GetGlobalNinjaGenerator()->SupportsDirectConsole()) {
281 cmGlobalNinjaGenerator::RequiredNinjaVersionForConsolePool();
284 // The Ninja generator writes rules which require support for restat
285 // when rebuilding build.ninja manifest (>= 1.8)
286 if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() &&
287 this->GetCMakeInstance()->DoWriteGlobVerifyTarget() &&
288 !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn(
289 "CMAKE_SUPPRESS_REGENERATION")) {
291 cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat();
294 cmGlobalNinjaGenerator::WriteComment(
295 os, "Minimal version of Ninja required by this file");
296 os << "ninja_required_version = " << requiredVersion << "\n\n";
299 void cmLocalNinjaGenerator::WriteNinjaConfigurationVariable(
300 std::ostream& os, const std::string& config)
302 cmGlobalNinjaGenerator::WriteVariable(
303 os, "CONFIGURATION", config,
304 "Set configuration variable for custom commands.");
307 void cmLocalNinjaGenerator::WritePools(std::ostream& os)
309 cmGlobalNinjaGenerator::WriteDivider(os);
312 this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
314 jobpools = this->GetMakefile()->GetDefinition("CMAKE_JOB_POOLS");
317 cmGlobalNinjaGenerator::WriteComment(
318 os, "Pools defined by global property JOB_POOLS");
319 std::vector<std::string> pools = cmExpandedList(*jobpools);
320 for (std::string const& pool : pools) {
321 const std::string::size_type eq = pool.find('=');
323 if (eq != std::string::npos &&
324 sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
325 os << "pool " << pool.substr(0, eq) << "\n depth = " << jobs
328 cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': " +
335 void cmLocalNinjaGenerator::WriteNinjaFilesInclusionConfig(std::ostream& os)
337 cmGlobalNinjaGenerator::WriteDivider(os);
338 os << "# Include auxiliary files.\n\n";
339 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
340 std::string const ninjaCommonFile =
341 ng->NinjaOutputPath(cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE);
342 std::string const commonFilePath = ng->EncodePath(ninjaCommonFile);
343 cmGlobalNinjaGenerator::WriteInclude(os, commonFilePath,
344 "Include common file.");
348 void cmLocalNinjaGenerator::WriteNinjaFilesInclusionCommon(std::ostream& os)
350 cmGlobalNinjaGenerator::WriteDivider(os);
351 os << "# Include auxiliary files.\n\n";
352 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
353 std::string const ninjaRulesFile =
354 ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
355 std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile);
356 cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
357 "Include rules file.");
361 void cmLocalNinjaGenerator::WriteNinjaWorkDir(std::ostream& os)
363 cmGlobalNinjaGenerator::WriteDivider(os);
364 cmGlobalNinjaGenerator::WriteComment(
365 os, "Logical path to working directory; prefix for absolute paths.");
366 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
367 std::string ninja_workdir = this->GetBinaryDirectory();
368 ng->StripNinjaOutputPathPrefixAsSuffix(ninja_workdir); // Also appends '/'.
369 os << "cmake_ninja_workdir = " << ng->EncodePath(ninja_workdir) << "\n";
372 void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
374 cmGlobalNinjaGenerator::WriteDivider(os);
375 os << "# Write statements declared in CMakeLists.txt:\n"
376 << "# " << this->Makefile->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE")
378 if (this->IsRootMakefile()) {
379 os << "# Which is the root file.\n";
381 cmGlobalNinjaGenerator::WriteDivider(os);
385 void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
386 cmNinjaDeps& outputs,
387 const std::string& config)
389 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
390 DependOnTargetArtifact);
393 void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
394 cmNinjaDeps& outputs,
395 const std::string& config,
396 const std::string& fileConfig,
397 cmNinjaTargetDepends depends)
399 this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
400 fileConfig, depends);
403 void cmLocalNinjaGenerator::AppendCustomCommandDeps(
404 cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
405 const std::string& config)
407 for (std::string const& i : ccg.GetDepends()) {
409 if (this->GetRealDependency(i, config, dep)) {
411 this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
416 std::string cmLocalNinjaGenerator::WriteCommandScript(
417 std::vector<std::string> const& cmdLines, std::string const& outputConfig,
418 std::string const& commandConfig, std::string const& customStep,
419 cmGeneratorTarget const* target) const
421 std::string scriptPath;
423 scriptPath = target->GetSupportDirectory();
425 scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
427 scriptPath += this->GetGlobalNinjaGenerator()->ConfigDirectory(outputConfig);
428 cmSystemTools::MakeDirectory(scriptPath);
430 scriptPath += customStep;
431 if (this->GlobalGenerator->IsMultiConfig()) {
432 scriptPath += cmStrCat('-', commandConfig);
435 scriptPath += ".bat";
440 cmsys::ofstream script(scriptPath.c_str());
443 script << "@echo off\n";
446 script << "set -e\n\n";
449 for (auto const& i : cmdLines) {
451 // The command line was built assuming it would be written to
452 // the build.ninja file, so it uses '$$' for '$'. Remove this
453 // for the raw shell script.
454 cmSystemTools::ReplaceString(cmd, "$$", "$");
456 script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
459 script << cmd << '\n';
464 script << "goto :EOF\n\n"
466 "set ERROR_CODE=%ERRORLEVEL%\n"
467 "echo Batch file failed at line %FAIL_LINE% "
468 "with errorcode %ERRORLEVEL%\n"
469 "exit /b %ERROR_CODE%";
475 std::string cmLocalNinjaGenerator::BuildCommandLine(
476 std::vector<std::string> const& cmdLines, std::string const& outputConfig,
477 std::string const& commandConfig, std::string const& customStep,
478 cmGeneratorTarget const* target) const
480 // If we have no commands but we need to build a command anyway, use noop.
481 // This happens when building a POST_BUILD value for link targets that
482 // don't use POST_BUILD.
483 if (cmdLines.empty()) {
484 return cmGlobalNinjaGenerator::SHELL_NOOP;
487 // If this is a custom step then we will have no '$VAR' ninja placeholders.
488 // This means we can deal with long command sequences by writing to a script.
489 // Do this if the command lines are on the scale of the OS limit.
490 if (!customStep.empty()) {
491 size_t cmdLinesTotal = 0;
492 for (std::string const& cmd : cmdLines) {
493 cmdLinesTotal += cmd.length() + 6;
495 if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
496 std::string const scriptPath = this->WriteCommandScript(
497 cmdLines, outputConfig, commandConfig, customStep, target);
503 cmd += this->ConvertToOutputFormat(
504 this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
505 cmOutputConverter::SHELL);
507 // Add an unused argument based on script content so that Ninja
508 // knows when the command lines change.
510 cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
511 cmd += hash.HashFile(scriptPath).substr(0, 16);
516 std::ostringstream cmd;
517 for (auto li = cmdLines.begin(); li != cmdLines.end(); ++li)
520 if (li != cmdLines.begin()) {
522 } else if (cmdLines.size() > 1) {
523 cmd << "cmd.exe /C \"";
525 // Put current cmdLine in brackets if it contains "||" because it has
526 // higher precedence than "&&" in cmd.exe
527 if (li->find("||") != std::string::npos) {
528 cmd << "( " << *li << " )";
533 if (cmdLines.size() > 1) {
538 if (li != cmdLines.begin()) {
547 void cmLocalNinjaGenerator::AppendCustomCommandLines(
548 cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
550 auto* gg = this->GetGlobalNinjaGenerator();
552 if (ccg.GetNumberOfCommands() > 0) {
553 std::string wd = ccg.GetWorkingDirectory();
555 wd = this->GetCurrentBinaryDirectory();
558 std::ostringstream cdCmd;
560 std::string cdStr = "cd /D ";
562 std::string cdStr = "cd ";
565 << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
566 cmdLines.push_back(cdCmd.str());
569 std::string launcher = this->MakeCustomLauncher(ccg);
571 for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
572 std::string c = ccg.GetCommand(i);
576 cmdLines.push_back(launcher +
577 this->ConvertToOutputFormat(
579 gg->IsMultiConfig() ? cmOutputConverter::NINJAMULTI
580 : cmOutputConverter::SHELL));
582 std::string& cmd = cmdLines.back();
583 ccg.AppendArguments(i, cmd);
587 void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
588 cmCustomCommand const* cc, const std::set<cmGeneratorTarget*>& targets,
589 const std::string& fileConfig)
591 cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
592 if (gg->SeenCustomCommand(cc, fileConfig)) {
596 auto ccgs = this->MakeCustomCommandGenerators(*cc, fileConfig);
597 for (cmCustomCommandGenerator const& ccg : ccgs) {
598 if (ccg.GetOutputs().empty() && ccg.GetByproducts().empty()) {
599 // Generator expressions evaluate to no output for this config.
603 cmNinjaDeps orderOnlyDeps;
605 // A custom command may appear on multiple targets. However, some build
606 // systems exist where the target dependencies on some of the targets are
607 // overspecified, leading to a dependency cycle. If we assume all target
608 // dependencies are a superset of the true target dependencies for this
609 // custom command, we can take the set intersection of all target
610 // dependencies to obtain a correct dependency list.
612 // FIXME: This won't work in certain obscure scenarios involving indirect
614 auto j = targets.begin();
615 assert(j != targets.end());
616 this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
617 *j, orderOnlyDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
618 std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
621 for (; j != targets.end(); ++j) {
622 std::vector<std::string> jDeps;
623 std::vector<std::string> depsIntersection;
624 this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
625 *j, jDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
626 std::sort(jDeps.begin(), jDeps.end());
627 std::set_intersection(orderOnlyDeps.begin(), orderOnlyDeps.end(),
628 jDeps.begin(), jDeps.end(),
629 std::back_inserter(depsIntersection));
630 orderOnlyDeps = depsIntersection;
633 const std::vector<std::string>& outputs = ccg.GetOutputs();
634 const std::vector<std::string>& byproducts = ccg.GetByproducts();
636 bool symbolic = false;
637 for (std::string const& output : outputs) {
638 if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
639 if (sf->GetPropertyAsBool("SYMBOLIC")) {
646 cmGlobalNinjaGenerator::CCOutputs ccOutputs(gg);
647 ccOutputs.Add(outputs);
648 ccOutputs.Add(byproducts);
650 std::string mainOutput = ccOutputs.ExplicitOuts[0];
652 cmNinjaDeps ninjaDeps;
653 this->AppendCustomCommandDeps(ccg, ninjaDeps, fileConfig);
655 std::vector<std::string> cmdLines;
656 this->AppendCustomCommandLines(ccg, cmdLines);
658 if (cmdLines.empty()) {
659 cmNinjaBuild build("phony");
660 build.Comment = cmStrCat("Phony custom command for ", mainOutput);
661 build.Outputs = std::move(ccOutputs.ExplicitOuts);
662 build.WorkDirOuts = std::move(ccOutputs.WorkDirOuts);
663 build.ExplicitDeps = std::move(ninjaDeps);
664 build.OrderOnlyDeps = orderOnlyDeps;
665 gg->WriteBuild(this->GetImplFileStream(fileConfig), build);
667 std::string customStep = cmSystemTools::GetFilenameName(mainOutput);
668 if (this->GlobalGenerator->IsMultiConfig()) {
670 customStep += fileConfig;
672 customStep += ccg.GetOutputConfig();
674 // Hash full path to make unique.
676 cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
677 customStep += hash.HashString(mainOutput).substr(0, 7);
679 std::string depfile = ccg.GetDepfile();
680 if (!depfile.empty()) {
681 switch (cc->GetCMP0116Status()) {
682 case cmPolicies::WARN:
683 if (this->GetCurrentBinaryDirectory() !=
684 this->GetBinaryDirectory() ||
685 this->Makefile->PolicyOptionalWarningEnabled(
686 "CMAKE_POLICY_WARNING_CMP0116")) {
687 this->GetCMakeInstance()->IssueMessage(
688 MessageType::AUTHOR_WARNING,
689 cmPolicies::GetPolicyWarning(cmPolicies::CMP0116),
693 case cmPolicies::OLD:
695 case cmPolicies::REQUIRED_IF_USED:
696 case cmPolicies::REQUIRED_ALWAYS:
697 case cmPolicies::NEW:
698 depfile = ccg.GetInternalDepfile();
703 std::string comment = cmStrCat("Custom command for ", mainOutput);
704 gg->WriteCustomCommandBuild(
705 this->BuildCommandLine(cmdLines, ccg.GetOutputConfig(), fileConfig,
707 this->ConstructComment(ccg), comment, depfile, cc->GetJobPool(),
708 cc->GetUsesTerminal(),
709 /*restat*/ !symbolic || !byproducts.empty(), fileConfig,
710 std::move(ccOutputs), std::move(ninjaDeps), std::move(orderOnlyDeps));
715 bool cmLocalNinjaGenerator::HasUniqueByproducts(
716 std::vector<std::string> const& byproducts, cmListFileBacktrace const& bt)
718 std::vector<std::string> configs =
719 this->GetMakefile()->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
720 cmGeneratorExpression ge(bt);
721 for (std::string const& p : byproducts) {
722 if (cmGeneratorExpression::Find(p) == std::string::npos) {
725 std::set<std::string> seen;
726 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(p);
727 for (std::string const& config : configs) {
728 for (std::string const& b :
729 this->ExpandCustomCommandOutputPaths(*cge, config)) {
730 if (!seen.insert(b).second) {
740 bool HasUniqueOutputs(std::vector<cmCustomCommandGenerator> const& ccgs)
742 std::set<std::string> allOutputs;
743 std::set<std::string> allByproducts;
744 for (cmCustomCommandGenerator const& ccg : ccgs) {
745 for (std::string const& output : ccg.GetOutputs()) {
746 if (!allOutputs.insert(output).second) {
750 for (std::string const& byproduct : ccg.GetByproducts()) {
751 if (!allByproducts.insert(byproduct).second) {
760 std::string cmLocalNinjaGenerator::CreateUtilityOutput(
761 std::string const& targetName, std::vector<std::string> const& byproducts,
762 cmListFileBacktrace const& bt)
764 // In Ninja Multi-Config, we can only produce cross-config utility
765 // commands if all byproducts are per-config.
766 if (!this->GetGlobalGenerator()->IsMultiConfig() ||
767 !this->HasUniqueByproducts(byproducts, bt)) {
768 return this->cmLocalGenerator::CreateUtilityOutput(targetName, byproducts,
772 std::string const base = cmStrCat(this->GetCurrentBinaryDirectory(),
773 "/CMakeFiles/", targetName, '-');
774 // The output is not actually created so mark it symbolic.
775 for (std::string const& config :
776 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
777 std::string const force = cmStrCat(base, config);
778 if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
779 sf->SetProperty("SYMBOLIC", "1");
781 cmSystemTools::Error("Could not get source file entry for " + force);
784 this->GetGlobalNinjaGenerator()->AddPerConfigUtilityTarget(targetName);
785 return cmStrCat(base, "$<CONFIG>"_s);
788 std::vector<cmCustomCommandGenerator>
789 cmLocalNinjaGenerator::MakeCustomCommandGenerators(
790 cmCustomCommand const& cc, std::string const& fileConfig)
792 cmGlobalNinjaGenerator const* gg = this->GetGlobalNinjaGenerator();
794 bool transformDepfile = false;
795 switch (cc.GetCMP0116Status()) {
796 case cmPolicies::WARN:
798 case cmPolicies::OLD:
800 case cmPolicies::REQUIRED_IF_USED:
801 case cmPolicies::REQUIRED_ALWAYS:
802 case cmPolicies::NEW:
803 transformDepfile = true;
807 // Start with the build graph's configuration.
808 std::vector<cmCustomCommandGenerator> ccgs;
809 ccgs.emplace_back(cc, fileConfig, this, transformDepfile);
811 // Consider adding cross configurations.
812 if (!gg->EnableCrossConfigBuild()) {
816 // Outputs and byproducts must be expressed using generator expressions.
817 for (std::string const& output : cc.GetOutputs()) {
818 if (cmGeneratorExpression::Find(output) == std::string::npos) {
822 for (std::string const& byproduct : cc.GetByproducts()) {
823 if (cmGeneratorExpression::Find(byproduct) == std::string::npos) {
828 // Tentatively add the other cross configurations.
829 for (std::string const& config : gg->GetCrossConfigs(fileConfig)) {
830 if (fileConfig != config) {
831 ccgs.emplace_back(cc, fileConfig, this, transformDepfile, config);
835 // If outputs and byproducts are not unique to each configuration,
836 // drop the cross configurations.
837 if (!HasUniqueOutputs(ccgs)) {
838 ccgs.erase(ccgs.begin() + 1, ccgs.end());
844 void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
845 cmGeneratorTarget* target)
847 CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
848 std::pair<CustomCommandTargetMap::iterator, bool> ins =
849 this->CustomCommandTargets.insert(v);
851 this->CustomCommands.push_back(cc);
853 ins.first->second.insert(target);
856 void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
857 const std::string& fileConfig)
859 for (cmCustomCommand const* customCommand : this->CustomCommands) {
860 auto i = this->CustomCommandTargets.find(customCommand);
861 assert(i != this->CustomCommandTargets.end());
863 this->WriteCustomCommandBuildStatement(i->first, i->second, fileConfig);
867 std::string cmLocalNinjaGenerator::MakeCustomLauncher(
868 cmCustomCommandGenerator const& ccg)
870 cmValue property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
872 if (!cmNonempty(property_value)) {
873 return std::string();
876 // Expand rule variables referenced in the given launcher command.
877 cmRulePlaceholderExpander::RuleVariables vars;
880 const std::vector<std::string>& outputs = ccg.GetOutputs();
881 if (!outputs.empty()) {
883 if (ccg.GetWorkingDirectory().empty()) {
884 output = this->MaybeRelativeToCurBinDir(output);
886 output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
888 vars.Output = output.c_str();
890 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
891 this->CreateRulePlaceholderExpander());
893 std::string launcher = *property_value;
894 rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
895 if (!launcher.empty()) {
902 void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
904 if (cmValue prop_value =
905 this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
906 std::vector<std::string> cleanFiles;
908 cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, this, config),
911 std::string const& binaryDir = this->GetCurrentBinaryDirectory();
912 cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
913 for (std::string const& cleanFile : cleanFiles) {
914 // Support relative paths
915 gg->AddAdditionalCleanFile(
916 cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);