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 "cmProperty.h"
31 #include "cmRulePlaceholderExpander.h"
32 #include "cmSourceFile.h"
34 #include "cmStateTypes.h"
35 #include "cmStringAlgorithms.h"
36 #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, IncludePathStyle pathStyle,
209 cmOutputConverter::OutputFormat format)
211 // FIXME: Remove IncludePathStyle infrastructure. It is no longer used.
212 static_cast<void>(pathStyle);
213 return this->ConvertToOutputFormat(path, format);
218 cmGeneratedFileStream& cmLocalNinjaGenerator::GetImplFileStream(
219 const std::string& config) const
221 return *this->GetGlobalNinjaGenerator()->GetImplFileStream(config);
224 cmGeneratedFileStream& cmLocalNinjaGenerator::GetCommonFileStream() const
226 return *this->GetGlobalNinjaGenerator()->GetCommonFileStream();
229 cmGeneratedFileStream& cmLocalNinjaGenerator::GetRulesFileStream() const
231 return *this->GetGlobalNinjaGenerator()->GetRulesFileStream();
234 const cmake* cmLocalNinjaGenerator::GetCMakeInstance() const
236 return this->GetGlobalGenerator()->GetCMakeInstance();
239 cmake* cmLocalNinjaGenerator::GetCMakeInstance()
241 return this->GetGlobalGenerator()->GetCMakeInstance();
244 void cmLocalNinjaGenerator::WriteBuildFileTop()
246 this->WriteProjectHeader(this->GetCommonFileStream());
248 if (this->GetGlobalGenerator()->IsMultiConfig()) {
249 for (auto const& config : this->GetConfigNames()) {
250 auto& stream = this->GetImplFileStream(config);
251 this->WriteProjectHeader(stream);
252 this->WriteNinjaRequiredVersion(stream);
253 this->WriteNinjaConfigurationVariable(stream, config);
254 this->WriteNinjaFilesInclusionConfig(stream);
257 this->WriteNinjaRequiredVersion(this->GetCommonFileStream());
258 this->WriteNinjaConfigurationVariable(this->GetCommonFileStream(),
259 this->GetConfigNames().front());
261 this->WriteNinjaFilesInclusionCommon(this->GetCommonFileStream());
262 this->WriteNinjaWorkDir(this->GetCommonFileStream());
264 // For the rule file.
265 this->WriteProjectHeader(this->GetRulesFileStream());
268 void cmLocalNinjaGenerator::WriteProjectHeader(std::ostream& os)
270 cmGlobalNinjaGenerator::WriteDivider(os);
271 os << "# Project: " << this->GetProjectName() << '\n'
272 << "# Configurations: " << cmJoin(this->GetConfigNames(), ", ") << '\n';
273 cmGlobalNinjaGenerator::WriteDivider(os);
276 void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
278 // Default required version
279 std::string requiredVersion = cmGlobalNinjaGenerator::RequiredNinjaVersion();
281 // Ninja generator uses the 'console' pool if available (>= 1.5)
282 if (this->GetGlobalNinjaGenerator()->SupportsConsolePool()) {
284 cmGlobalNinjaGenerator::RequiredNinjaVersionForConsolePool();
287 // The Ninja generator writes rules which require support for restat
288 // when rebuilding build.ninja manifest (>= 1.8)
289 if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() &&
290 this->GetCMakeInstance()->DoWriteGlobVerifyTarget() &&
291 !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn(
292 "CMAKE_SUPPRESS_REGENERATION")) {
294 cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat();
297 cmGlobalNinjaGenerator::WriteComment(
298 os, "Minimal version of Ninja required by this file");
299 os << "ninja_required_version = " << requiredVersion << "\n\n";
302 void cmLocalNinjaGenerator::WriteNinjaConfigurationVariable(
303 std::ostream& os, const std::string& config)
305 cmGlobalNinjaGenerator::WriteVariable(
306 os, "CONFIGURATION", config,
307 "Set configuration variable for custom commands.");
310 void cmLocalNinjaGenerator::WritePools(std::ostream& os)
312 cmGlobalNinjaGenerator::WriteDivider(os);
315 this->GetCMakeInstance()->GetState()->GetGlobalProperty("JOB_POOLS");
317 jobpools = this->GetMakefile()->GetDefinition("CMAKE_JOB_POOLS");
320 cmGlobalNinjaGenerator::WriteComment(
321 os, "Pools defined by global property JOB_POOLS");
322 std::vector<std::string> pools = cmExpandedList(*jobpools);
323 for (std::string const& pool : pools) {
324 const std::string::size_type eq = pool.find('=');
326 if (eq != std::string::npos &&
327 sscanf(pool.c_str() + eq, "=%u", &jobs) == 1) {
328 os << "pool " << pool.substr(0, eq) << "\n depth = " << jobs
331 cmSystemTools::Error("Invalid pool defined by property 'JOB_POOLS': " +
338 void cmLocalNinjaGenerator::WriteNinjaFilesInclusionConfig(std::ostream& os)
340 cmGlobalNinjaGenerator::WriteDivider(os);
341 os << "# Include auxiliary files.\n\n";
342 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
343 std::string const ninjaCommonFile =
344 ng->NinjaOutputPath(cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE);
345 std::string const commonFilePath = ng->EncodePath(ninjaCommonFile);
346 cmGlobalNinjaGenerator::WriteInclude(os, commonFilePath,
347 "Include common file.");
351 void cmLocalNinjaGenerator::WriteNinjaFilesInclusionCommon(std::ostream& os)
353 cmGlobalNinjaGenerator::WriteDivider(os);
354 os << "# Include auxiliary files.\n\n";
355 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
356 std::string const ninjaRulesFile =
357 ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE);
358 std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile);
359 cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath,
360 "Include rules file.");
364 void cmLocalNinjaGenerator::WriteNinjaWorkDir(std::ostream& os)
366 cmGlobalNinjaGenerator::WriteDivider(os);
367 cmGlobalNinjaGenerator::WriteComment(
368 os, "Logical path to working directory; prefix for absolute paths.");
369 cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator();
370 std::string ninja_workdir = this->GetBinaryDirectory();
371 ng->StripNinjaOutputPathPrefixAsSuffix(ninja_workdir); // Also appends '/'.
372 os << "cmake_ninja_workdir = " << ng->EncodePath(ninja_workdir) << "\n";
375 void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
377 cmGlobalNinjaGenerator::WriteDivider(os);
378 os << "# Write statements declared in CMakeLists.txt:\n"
379 << "# " << this->Makefile->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE")
381 if (this->IsRootMakefile()) {
382 os << "# Which is the root file.\n";
384 cmGlobalNinjaGenerator::WriteDivider(os);
388 void cmLocalNinjaGenerator::AppendTargetOutputs(cmGeneratorTarget* target,
389 cmNinjaDeps& outputs,
390 const std::string& config)
392 this->GetGlobalNinjaGenerator()->AppendTargetOutputs(target, outputs, config,
393 DependOnTargetArtifact);
396 void cmLocalNinjaGenerator::AppendTargetDepends(cmGeneratorTarget* target,
397 cmNinjaDeps& outputs,
398 const std::string& config,
399 const std::string& fileConfig,
400 cmNinjaTargetDepends depends)
402 this->GetGlobalNinjaGenerator()->AppendTargetDepends(target, outputs, config,
403 fileConfig, depends);
406 void cmLocalNinjaGenerator::AppendCustomCommandDeps(
407 cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps,
408 const std::string& config)
410 for (std::string const& i : ccg.GetDepends()) {
412 if (this->GetRealDependency(i, config, dep)) {
414 this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
419 std::string cmLocalNinjaGenerator::WriteCommandScript(
420 std::vector<std::string> const& cmdLines, std::string const& outputConfig,
421 std::string const& commandConfig, std::string const& customStep,
422 cmGeneratorTarget const* target) const
424 std::string scriptPath;
426 scriptPath = target->GetSupportDirectory();
428 scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
430 scriptPath += this->GetGlobalNinjaGenerator()->ConfigDirectory(outputConfig);
431 cmSystemTools::MakeDirectory(scriptPath);
433 scriptPath += customStep;
434 if (this->GlobalGenerator->IsMultiConfig()) {
435 scriptPath += cmStrCat('-', commandConfig);
438 scriptPath += ".bat";
443 cmsys::ofstream script(scriptPath.c_str());
446 script << "@echo off\n";
449 script << "set -e\n\n";
452 for (auto const& i : cmdLines) {
454 // The command line was built assuming it would be written to
455 // the build.ninja file, so it uses '$$' for '$'. Remove this
456 // for the raw shell script.
457 cmSystemTools::ReplaceString(cmd, "$$", "$");
459 script << cmd << " || (set FAIL_LINE=" << ++line << "& goto :ABORT)"
462 script << cmd << '\n';
467 script << "goto :EOF\n\n"
469 "set ERROR_CODE=%ERRORLEVEL%\n"
470 "echo Batch file failed at line %FAIL_LINE% "
471 "with errorcode %ERRORLEVEL%\n"
472 "exit /b %ERROR_CODE%";
478 std::string cmLocalNinjaGenerator::BuildCommandLine(
479 std::vector<std::string> const& cmdLines, std::string const& outputConfig,
480 std::string const& commandConfig, std::string const& customStep,
481 cmGeneratorTarget const* target) const
483 // If we have no commands but we need to build a command anyway, use noop.
484 // This happens when building a POST_BUILD value for link targets that
485 // don't use POST_BUILD.
486 if (cmdLines.empty()) {
487 return cmGlobalNinjaGenerator::SHELL_NOOP;
490 // If this is a custom step then we will have no '$VAR' ninja placeholders.
491 // This means we can deal with long command sequences by writing to a script.
492 // Do this if the command lines are on the scale of the OS limit.
493 if (!customStep.empty()) {
494 size_t cmdLinesTotal = 0;
495 for (std::string const& cmd : cmdLines) {
496 cmdLinesTotal += cmd.length() + 6;
498 if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) {
499 std::string const scriptPath = this->WriteCommandScript(
500 cmdLines, outputConfig, commandConfig, customStep, target);
506 cmd += this->ConvertToOutputFormat(
507 this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath),
508 cmOutputConverter::SHELL);
510 // Add an unused argument based on script content so that Ninja
511 // knows when the command lines change.
513 cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
514 cmd += hash.HashFile(scriptPath).substr(0, 16);
519 std::ostringstream cmd;
520 for (auto li = cmdLines.begin(); li != cmdLines.end(); ++li)
523 if (li != cmdLines.begin()) {
525 } else if (cmdLines.size() > 1) {
526 cmd << "cmd.exe /C \"";
528 // Put current cmdLine in brackets if it contains "||" because it has
529 // higher precedence than "&&" in cmd.exe
530 if (li->find("||") != std::string::npos) {
531 cmd << "( " << *li << " )";
536 if (cmdLines.size() > 1) {
541 if (li != cmdLines.begin()) {
550 void cmLocalNinjaGenerator::AppendCustomCommandLines(
551 cmCustomCommandGenerator const& ccg, std::vector<std::string>& cmdLines)
553 auto* gg = this->GetGlobalNinjaGenerator();
555 if (ccg.GetNumberOfCommands() > 0) {
556 std::string wd = ccg.GetWorkingDirectory();
558 wd = this->GetCurrentBinaryDirectory();
561 std::ostringstream cdCmd;
563 std::string cdStr = "cd /D ";
565 std::string cdStr = "cd ";
568 << this->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
569 cmdLines.push_back(cdCmd.str());
572 std::string launcher = this->MakeCustomLauncher(ccg);
574 for (unsigned i = 0; i != ccg.GetNumberOfCommands(); ++i) {
575 std::string c = ccg.GetCommand(i);
579 cmdLines.push_back(launcher +
580 this->ConvertToOutputFormat(
582 gg->IsMultiConfig() ? cmOutputConverter::NINJAMULTI
583 : cmOutputConverter::SHELL));
585 std::string& cmd = cmdLines.back();
586 ccg.AppendArguments(i, cmd);
590 void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
591 cmCustomCommand const* cc, const std::set<cmGeneratorTarget*>& targets,
592 const std::string& fileConfig)
594 cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
595 if (gg->SeenCustomCommand(cc, fileConfig)) {
599 auto ccgs = this->MakeCustomCommandGenerators(*cc, fileConfig);
600 for (cmCustomCommandGenerator const& ccg : ccgs) {
601 if (ccg.GetOutputs().empty() && ccg.GetByproducts().empty()) {
602 // Generator expressions evaluate to no output for this config.
606 cmNinjaDeps orderOnlyDeps;
608 // A custom command may appear on multiple targets. However, some build
609 // systems exist where the target dependencies on some of the targets are
610 // overspecified, leading to a dependency cycle. If we assume all target
611 // dependencies are a superset of the true target dependencies for this
612 // custom command, we can take the set intersection of all target
613 // dependencies to obtain a correct dependency list.
615 // FIXME: This won't work in certain obscure scenarios involving indirect
617 auto j = targets.begin();
618 assert(j != targets.end());
619 this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
620 *j, orderOnlyDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
621 std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
624 for (; j != targets.end(); ++j) {
625 std::vector<std::string> jDeps;
626 std::vector<std::string> depsIntersection;
627 this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(
628 *j, jDeps, ccg.GetOutputConfig(), fileConfig, ccgs.size() > 1);
629 std::sort(jDeps.begin(), jDeps.end());
630 std::set_intersection(orderOnlyDeps.begin(), orderOnlyDeps.end(),
631 jDeps.begin(), jDeps.end(),
632 std::back_inserter(depsIntersection));
633 orderOnlyDeps = depsIntersection;
636 const std::vector<std::string>& outputs = ccg.GetOutputs();
637 const std::vector<std::string>& byproducts = ccg.GetByproducts();
639 bool symbolic = false;
640 for (std::string const& output : outputs) {
641 if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
642 if (sf->GetPropertyAsBool("SYMBOLIC")) {
649 cmGlobalNinjaGenerator::CCOutputs ccOutputs(gg);
650 ccOutputs.Add(outputs);
651 ccOutputs.Add(byproducts);
653 std::string mainOutput = ccOutputs.ExplicitOuts[0];
655 cmNinjaDeps ninjaDeps;
656 this->AppendCustomCommandDeps(ccg, ninjaDeps, fileConfig);
658 std::vector<std::string> cmdLines;
659 this->AppendCustomCommandLines(ccg, cmdLines);
661 if (cmdLines.empty()) {
662 cmNinjaBuild build("phony");
663 build.Comment = cmStrCat("Phony custom command for ", mainOutput);
664 build.Outputs = std::move(ccOutputs.ExplicitOuts);
665 build.WorkDirOuts = std::move(ccOutputs.WorkDirOuts);
666 build.ExplicitDeps = std::move(ninjaDeps);
667 build.OrderOnlyDeps = orderOnlyDeps;
668 gg->WriteBuild(this->GetImplFileStream(fileConfig), build);
670 std::string customStep = cmSystemTools::GetFilenameName(mainOutput);
671 if (this->GlobalGenerator->IsMultiConfig()) {
673 customStep += fileConfig;
675 customStep += ccg.GetOutputConfig();
677 // Hash full path to make unique.
679 cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
680 customStep += hash.HashString(mainOutput).substr(0, 7);
682 std::string depfile = ccg.GetDepfile();
683 if (!depfile.empty()) {
684 switch (cc->GetCMP0116Status()) {
685 case cmPolicies::WARN:
686 if (this->GetCurrentBinaryDirectory() !=
687 this->GetBinaryDirectory() ||
688 this->Makefile->PolicyOptionalWarningEnabled(
689 "CMAKE_POLICY_WARNING_CMP0116")) {
690 this->GetCMakeInstance()->IssueMessage(
691 MessageType::AUTHOR_WARNING,
692 cmPolicies::GetPolicyWarning(cmPolicies::CMP0116),
696 case cmPolicies::OLD:
698 case cmPolicies::REQUIRED_IF_USED:
699 case cmPolicies::REQUIRED_ALWAYS:
700 case cmPolicies::NEW:
701 depfile = ccg.GetInternalDepfile();
706 std::string comment = cmStrCat("Custom command for ", mainOutput);
707 gg->WriteCustomCommandBuild(
708 this->BuildCommandLine(cmdLines, ccg.GetOutputConfig(), fileConfig,
710 this->ConstructComment(ccg), comment, depfile, cc->GetJobPool(),
711 cc->GetUsesTerminal(),
712 /*restat*/ !symbolic || !byproducts.empty(), fileConfig,
713 std::move(ccOutputs), std::move(ninjaDeps), std::move(orderOnlyDeps));
718 bool cmLocalNinjaGenerator::HasUniqueByproducts(
719 std::vector<std::string> const& byproducts, cmListFileBacktrace const& bt)
721 std::vector<std::string> configs =
722 this->GetMakefile()->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
723 cmGeneratorExpression ge(bt);
724 for (std::string const& p : byproducts) {
725 if (cmGeneratorExpression::Find(p) == std::string::npos) {
728 std::set<std::string> seen;
729 std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(p);
730 for (std::string const& config : configs) {
731 for (std::string const& b :
732 this->ExpandCustomCommandOutputPaths(*cge, config)) {
733 if (!seen.insert(b).second) {
743 bool HasUniqueOutputs(std::vector<cmCustomCommandGenerator> const& ccgs)
745 std::set<std::string> allOutputs;
746 std::set<std::string> allByproducts;
747 for (cmCustomCommandGenerator const& ccg : ccgs) {
748 for (std::string const& output : ccg.GetOutputs()) {
749 if (!allOutputs.insert(output).second) {
753 for (std::string const& byproduct : ccg.GetByproducts()) {
754 if (!allByproducts.insert(byproduct).second) {
763 std::string cmLocalNinjaGenerator::CreateUtilityOutput(
764 std::string const& targetName, std::vector<std::string> const& byproducts,
765 cmListFileBacktrace const& bt)
767 // In Ninja Multi-Config, we can only produce cross-config utility
768 // commands if all byproducts are per-config.
769 if (!this->GetGlobalGenerator()->IsMultiConfig() ||
770 !this->HasUniqueByproducts(byproducts, bt)) {
771 return this->cmLocalGenerator::CreateUtilityOutput(targetName, byproducts,
775 std::string const base = cmStrCat(this->GetCurrentBinaryDirectory(),
776 "/CMakeFiles/", targetName, '-');
777 // The output is not actually created so mark it symbolic.
778 for (std::string const& config :
779 this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
780 std::string const force = cmStrCat(base, config);
781 if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
782 sf->SetProperty("SYMBOLIC", "1");
784 cmSystemTools::Error("Could not get source file entry for " + force);
787 this->GetGlobalNinjaGenerator()->AddPerConfigUtilityTarget(targetName);
788 return cmStrCat(base, "$<CONFIG>"_s);
791 std::vector<cmCustomCommandGenerator>
792 cmLocalNinjaGenerator::MakeCustomCommandGenerators(
793 cmCustomCommand const& cc, std::string const& fileConfig)
795 cmGlobalNinjaGenerator const* gg = this->GetGlobalNinjaGenerator();
797 bool transformDepfile = false;
798 switch (cc.GetCMP0116Status()) {
799 case cmPolicies::OLD:
800 case cmPolicies::WARN:
802 case cmPolicies::REQUIRED_IF_USED:
803 case cmPolicies::REQUIRED_ALWAYS:
804 case cmPolicies::NEW:
805 transformDepfile = true;
809 // Start with the build graph's configuration.
810 std::vector<cmCustomCommandGenerator> ccgs;
811 ccgs.emplace_back(cc, fileConfig, this, transformDepfile);
813 // Consider adding cross configurations.
814 if (!gg->EnableCrossConfigBuild()) {
818 // Outputs and byproducts must be expressed using generator expressions.
819 for (std::string const& output : cc.GetOutputs()) {
820 if (cmGeneratorExpression::Find(output) == std::string::npos) {
824 for (std::string const& byproduct : cc.GetByproducts()) {
825 if (cmGeneratorExpression::Find(byproduct) == std::string::npos) {
830 // Tentatively add the other cross configurations.
831 for (std::string const& config : gg->GetCrossConfigs(fileConfig)) {
832 if (fileConfig != config) {
833 ccgs.emplace_back(cc, fileConfig, this, transformDepfile, config);
837 // If outputs and byproducts are not unique to each configuration,
838 // drop the cross configurations.
839 if (!HasUniqueOutputs(ccgs)) {
840 ccgs.erase(ccgs.begin() + 1, ccgs.end());
846 void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
847 cmGeneratorTarget* target)
849 CustomCommandTargetMap::value_type v(cc, std::set<cmGeneratorTarget*>());
850 std::pair<CustomCommandTargetMap::iterator, bool> ins =
851 this->CustomCommandTargets.insert(v);
853 this->CustomCommands.push_back(cc);
855 ins.first->second.insert(target);
858 void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements(
859 const std::string& fileConfig)
861 for (cmCustomCommand const* customCommand : this->CustomCommands) {
862 auto i = this->CustomCommandTargets.find(customCommand);
863 assert(i != this->CustomCommandTargets.end());
865 this->WriteCustomCommandBuildStatement(i->first, i->second, fileConfig);
869 std::string cmLocalNinjaGenerator::MakeCustomLauncher(
870 cmCustomCommandGenerator const& ccg)
872 cmProp property_value = this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
874 if (!cmNonempty(property_value)) {
875 return std::string();
878 // Expand rule variables referenced in the given launcher command.
879 cmRulePlaceholderExpander::RuleVariables vars;
882 const std::vector<std::string>& outputs = ccg.GetOutputs();
883 if (!outputs.empty()) {
885 if (ccg.GetWorkingDirectory().empty()) {
886 output = this->MaybeRelativeToCurBinDir(output);
888 output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
890 vars.Output = output.c_str();
892 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
893 this->CreateRulePlaceholderExpander());
895 std::string launcher = *property_value;
896 rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
897 if (!launcher.empty()) {
904 void cmLocalNinjaGenerator::AdditionalCleanFiles(const std::string& config)
906 if (cmProp prop_value =
907 this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
908 std::vector<std::string> cleanFiles;
910 cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, this, config),
913 std::string const& binaryDir = this->GetCurrentBinaryDirectory();
914 cmGlobalNinjaGenerator* gg = this->GetGlobalNinjaGenerator();
915 for (std::string const& cleanFile : cleanFiles) {
916 // Support relative paths
917 gg->AddAdditionalCleanFile(
918 cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);