Imported Upstream version 3.18.2
[platform/upstream/cmake.git] / Source / cmQtAutoGenInitializer.cxx
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 "cmQtAutoGenInitializer.h"
4
5 #include <cstddef>
6 #include <deque>
7 #include <initializer_list>
8 #include <map>
9 #include <ostream>
10 #include <set>
11 #include <string>
12 #include <unordered_set>
13 #include <utility>
14 #include <vector>
15
16 #include <cm/algorithm>
17 #include <cm/iterator>
18 #include <cm/memory>
19 #include <cmext/algorithm>
20
21 #include <cm3p/json/value.h>
22 #include <cm3p/json/writer.h>
23
24 #include "cmsys/SystemInformation.hxx"
25
26 #include "cmCustomCommand.h"
27 #include "cmCustomCommandLines.h"
28 #include "cmGeneratedFileStream.h"
29 #include "cmGeneratorExpression.h"
30 #include "cmGeneratorTarget.h"
31 #include "cmGlobalGenerator.h"
32 #include "cmLinkItem.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmMakefile.h"
36 #include "cmMessageType.h"
37 #include "cmPolicies.h"
38 #include "cmProperty.h"
39 #include "cmQtAutoGen.h"
40 #include "cmQtAutoGenGlobalInitializer.h"
41 #include "cmSourceFile.h"
42 #include "cmSourceFileLocationKind.h"
43 #include "cmSourceGroup.h"
44 #include "cmState.h"
45 #include "cmStateTypes.h"
46 #include "cmStringAlgorithms.h"
47 #include "cmSystemTools.h"
48 #include "cmTarget.h"
49 #include "cmake.h"
50
51 namespace {
52
53 unsigned int GetParallelCPUCount()
54 {
55   static unsigned int count = 0;
56   // Detect only on the first call
57   if (count == 0) {
58     cmsys::SystemInformation info;
59     info.RunCPUCheck();
60     count =
61       cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
62   }
63   return count;
64 }
65
66 std::string FileProjectRelativePath(cmMakefile* makefile,
67                                     std::string const& fileName)
68 {
69   std::string res;
70   {
71     std::string pSource = cmSystemTools::RelativePath(
72       makefile->GetCurrentSourceDirectory(), fileName);
73     std::string pBinary = cmSystemTools::RelativePath(
74       makefile->GetCurrentBinaryDirectory(), fileName);
75     if (pSource.size() < pBinary.size()) {
76       res = std::move(pSource);
77     } else if (pBinary.size() < fileName.size()) {
78       res = std::move(pBinary);
79     } else {
80       res = fileName;
81     }
82   }
83   return res;
84 }
85
86 /**
87  * Tests if targetDepend is a STATIC_LIBRARY and if any of its
88  * recursive STATIC_LIBRARY dependencies depends on targetOrigin
89  * (STATIC_LIBRARY cycle).
90  */
91 bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
92                         cmGeneratorTarget const* targetDepend,
93                         std::string const& config)
94 {
95   bool cycle = false;
96   if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
97       (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
98     std::set<cmGeneratorTarget const*> knownLibs;
99     std::deque<cmGeneratorTarget const*> testLibs;
100
101     // Insert initial static_library dependency
102     knownLibs.insert(targetDepend);
103     testLibs.push_back(targetDepend);
104
105     while (!testLibs.empty()) {
106       cmGeneratorTarget const* testTarget = testLibs.front();
107       testLibs.pop_front();
108       // Check if the test target is the origin target (cycle)
109       if (testTarget == targetOrigin) {
110         cycle = true;
111         break;
112       }
113       // Collect all static_library dependencies from the test target
114       cmLinkImplementationLibraries const* libs =
115         testTarget->GetLinkImplementationLibraries(config);
116       if (libs != nullptr) {
117         for (cmLinkItem const& item : libs->Libraries) {
118           cmGeneratorTarget const* depTarget = item.Target;
119           if ((depTarget != nullptr) &&
120               (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
121               knownLibs.insert(depTarget).second) {
122             testLibs.push_back(depTarget);
123           }
124         }
125       }
126     }
127   }
128   return cycle;
129 }
130
131 /** Sanitizes file search paths.  */
132 class SearchPathSanitizer
133 {
134 public:
135   SearchPathSanitizer(cmMakefile* makefile)
136     : SourcePath_(makefile->GetCurrentSourceDirectory())
137   {
138   }
139   std::vector<std::string> operator()(
140     std::vector<std::string> const& paths) const;
141
142 private:
143   std::string SourcePath_;
144 };
145
146 std::vector<std::string> SearchPathSanitizer::operator()(
147   std::vector<std::string> const& paths) const
148 {
149   std::vector<std::string> res;
150   res.reserve(paths.size());
151   for (std::string const& srcPath : paths) {
152     // Collapse relative paths
153     std::string path = cmSystemTools::CollapseFullPath(srcPath, SourcePath_);
154     // Remove suffix slashes
155     while (cmHasSuffix(path, '/')) {
156       path.pop_back();
157     }
158     // Accept only non empty paths
159     if (!path.empty()) {
160       res.emplace_back(std::move(path));
161     }
162   }
163   return res;
164 }
165
166 /** @brief Writes a CMake info file.  */
167 class InfoWriter
168 {
169 public:
170   // -- Single value
171   void Set(std::string const& key, std::string const& value)
172   {
173     Value_[key] = value;
174   }
175   void SetConfig(std::string const& key,
176                  cmQtAutoGenInitializer::ConfigString const& cfgStr);
177   void SetBool(std::string const& key, bool value) { Value_[key] = value; }
178   void SetUInt(std::string const& key, unsigned int value)
179   {
180     Value_[key] = value;
181   }
182
183   // -- Array utility
184   template <typename CONT>
185   static bool MakeArray(Json::Value& jval, CONT const& container);
186
187   template <typename CONT>
188   static void MakeStringArray(Json::Value& jval, CONT const& container);
189
190   // -- Array value
191   template <typename CONT>
192   void SetArray(std::string const& key, CONT const& container);
193   template <typename CONT>
194   void SetConfigArray(
195     std::string const& key,
196     cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
197
198   // -- Array of arrays
199   template <typename CONT, typename FUNC>
200   void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
201
202   // -- Save to json file
203   bool Save(std::string const& filename);
204
205 private:
206   Json::Value Value_;
207 };
208
209 void InfoWriter::SetConfig(std::string const& key,
210                            cmQtAutoGenInitializer::ConfigString const& cfgStr)
211 {
212   Set(key, cfgStr.Default);
213   for (auto const& item : cfgStr.Config) {
214     Set(cmStrCat(key, '_', item.first), item.second);
215   }
216 }
217
218 template <typename CONT>
219 bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
220 {
221   jval = Json::arrayValue;
222   std::size_t const listSize = cm::size(container);
223   if (listSize == 0) {
224     return false;
225   }
226   jval.resize(static_cast<unsigned int>(listSize));
227   return true;
228 }
229
230 template <typename CONT>
231 void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
232 {
233   if (MakeArray(jval, container)) {
234     Json::ArrayIndex ii = 0;
235     for (std::string const& item : container) {
236       jval[ii++] = item;
237     }
238   }
239 }
240
241 template <typename CONT>
242 void InfoWriter::SetArray(std::string const& key, CONT const& container)
243 {
244   MakeStringArray(Value_[key], container);
245 }
246
247 template <typename CONT, typename FUNC>
248 void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
249                                FUNC func)
250 {
251   Json::Value& jval = Value_[key];
252   if (MakeArray(jval, container)) {
253     Json::ArrayIndex ii = 0;
254     for (auto const& citem : container) {
255       Json::Value& aval = jval[ii++];
256       aval = Json::arrayValue;
257       func(aval, citem);
258     }
259   }
260 }
261
262 template <typename CONT>
263 void InfoWriter::SetConfigArray(
264   std::string const& key,
265   cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
266 {
267   SetArray(key, cfgStr.Default);
268   for (auto const& item : cfgStr.Config) {
269     SetArray(cmStrCat(key, '_', item.first), item.second);
270   }
271 }
272
273 bool InfoWriter::Save(std::string const& filename)
274 {
275   cmGeneratedFileStream fileStream;
276   fileStream.SetCopyIfDifferent(true);
277   fileStream.Open(filename, false, true);
278   if (!fileStream) {
279     return false;
280   }
281
282   Json::StyledStreamWriter jsonWriter;
283   try {
284     jsonWriter.write(fileStream, Value_);
285   } catch (...) {
286     return false;
287   }
288
289   return fileStream.Close();
290 }
291
292 } // End of unnamed namespace
293
294 cmQtAutoGenInitializer::cmQtAutoGenInitializer(
295   cmQtAutoGenGlobalInitializer* globalInitializer,
296   cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
297   bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
298   bool globalAutoRccTarget)
299   : GlobalInitializer(globalInitializer)
300   , GenTarget(genTarget)
301   , GlobalGen(genTarget->GetGlobalGenerator())
302   , LocalGen(genTarget->GetLocalGenerator())
303   , Makefile(genTarget->Makefile)
304   , PathCheckSum(genTarget->Makefile)
305   , QtVersion(qtVersion)
306 {
307   AutogenTarget.GlobalTarget = globalAutogenTarget;
308   Moc.Enabled = mocEnabled;
309   Uic.Enabled = uicEnabled;
310   Rcc.Enabled = rccEnabled;
311   Rcc.GlobalTarget = globalAutoRccTarget;
312 }
313
314 bool cmQtAutoGenInitializer::InitCustomTargets()
315 {
316   // Configurations
317   this->MultiConfig = this->GlobalGen->IsMultiConfig();
318   this->ConfigDefault = this->Makefile->GetConfigurations(this->ConfigsList);
319   if (this->ConfigsList.empty()) {
320     this->ConfigsList.push_back(this->ConfigDefault);
321   }
322
323   // Verbosity
324   {
325     std::string def =
326       this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
327     if (!def.empty()) {
328       unsigned long iVerb = 0;
329       if (cmStrToULong(def, &iVerb)) {
330         // Numeric verbosity
331         this->Verbosity = static_cast<unsigned int>(iVerb);
332       } else {
333         // Non numeric verbosity
334         if (cmIsOn(def)) {
335           this->Verbosity = 1;
336         }
337       }
338     }
339   }
340
341   // Targets FOLDER
342   {
343     cmProp folder =
344       this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
345     if (folder == nullptr) {
346       folder = this->Makefile->GetState()->GetGlobalProperty(
347         "AUTOGEN_TARGETS_FOLDER");
348     }
349     // Inherit FOLDER property from target (#13688)
350     if (folder == nullptr) {
351       folder = this->GenTarget->GetProperty("FOLDER");
352     }
353     if (folder != nullptr) {
354       this->TargetsFolder = *folder;
355     }
356   }
357
358   // Check status of policy CMP0071 regarding handling of GENERATED files
359   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
360     case cmPolicies::WARN:
361       // Ignore GENERATED files but warn
362       this->CMP0071Warn = true;
363       CM_FALLTHROUGH;
364     case cmPolicies::OLD:
365       // Ignore GENERATED files
366       break;
367     case cmPolicies::REQUIRED_IF_USED:
368     case cmPolicies::REQUIRED_ALWAYS:
369     case cmPolicies::NEW:
370       // Process GENERATED files
371       this->CMP0071Accept = true;
372       break;
373   }
374
375   // Check status of policy CMP0100 regarding handling of .hh headers
376   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
377     case cmPolicies::WARN:
378       // Ignore but .hh files but warn
379       this->CMP0100Warn = true;
380       CM_FALLTHROUGH;
381     case cmPolicies::OLD:
382       // Ignore .hh files
383       break;
384     case cmPolicies::REQUIRED_IF_USED:
385     case cmPolicies::REQUIRED_ALWAYS:
386     case cmPolicies::NEW:
387       // Process .hh file
388       this->CMP0100Accept = true;
389       break;
390   }
391
392   // Common directories
393   {
394     // Collapsed current binary directory
395     std::string const cbd = cmSystemTools::CollapseFullPath(
396       std::string(), this->Makefile->GetCurrentBinaryDirectory());
397
398     // Info directory
399     this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
400                               "_autogen.dir");
401     cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
402
403     // Build directory
404     this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
405     if (this->Dir.Build.empty()) {
406       this->Dir.Build =
407         cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
408     }
409     cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
410     // Cleanup build directory
411     this->AddCleanFile(this->Dir.Build);
412
413     // Working directory
414     this->Dir.Work = cbd;
415     cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
416
417     // Include directory
418     ConfigFileNames(this->Dir.Include, cmStrCat(this->Dir.Build, "/include"),
419                     "");
420     this->Dir.IncludeGenExp = this->Dir.Include.Default;
421     if (this->MultiConfig) {
422       this->Dir.IncludeGenExp += "_$<CONFIG>";
423     }
424   }
425
426   // Moc, Uic and _autogen target settings
427   if (this->MocOrUicEnabled()) {
428     // Init moc specific settings
429     if (this->Moc.Enabled && !InitMoc()) {
430       return false;
431     }
432
433     // Init uic specific settings
434     if (this->Uic.Enabled && !InitUic()) {
435       return false;
436     }
437
438     // Autogen target name
439     this->AutogenTarget.Name =
440       cmStrCat(this->GenTarget->GetName(), "_autogen");
441
442     // Autogen target parallel processing
443     {
444       std::string const& prop =
445         this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
446       if (prop.empty() || (prop == "AUTO")) {
447         // Autodetect number of CPUs
448         this->AutogenTarget.Parallel = GetParallelCPUCount();
449       } else {
450         this->AutogenTarget.Parallel = 1;
451       }
452     }
453
454     // Autogen target info and settings files
455     {
456       // Info file
457       this->AutogenTarget.InfoFile =
458         cmStrCat(this->Dir.Info, "/AutogenInfo.json");
459
460       // Used settings file
461       ConfigFileNames(this->AutogenTarget.SettingsFile,
462                       cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
463       ConfigFileClean(this->AutogenTarget.SettingsFile);
464
465       // Parse cache file
466       ConfigFileNames(this->AutogenTarget.ParseCacheFile,
467                       cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
468       ConfigFileClean(this->AutogenTarget.ParseCacheFile);
469     }
470
471     // Autogen target: Compute user defined dependencies
472     {
473       this->AutogenTarget.DependOrigin =
474         this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
475
476       std::string const& deps =
477         this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
478       if (!deps.empty()) {
479         for (std::string const& depName : cmExpandedList(deps)) {
480           // Allow target and file dependencies
481           auto* depTarget = this->Makefile->FindTargetToUse(depName);
482           if (depTarget != nullptr) {
483             this->AutogenTarget.DependTargets.insert(depTarget);
484           } else {
485             this->AutogenTarget.DependFiles.insert(depName);
486           }
487         }
488       }
489     }
490
491     if (this->Moc.Enabled) {
492       // Path prefix
493       if (cmIsOn(this->GenTarget->GetSafeProperty("AUTOMOC_PATH_PREFIX"))) {
494         this->Moc.PathPrefix = true;
495       }
496
497       // CMAKE_AUTOMOC_RELAXED_MODE
498       if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
499         this->Moc.RelaxedMode = true;
500         this->Makefile->IssueMessage(
501           MessageType::AUTHOR_WARNING,
502           cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
503                    "deprecated an will be removed in the future.  Consider "
504                    "disabling it and converting the target ",
505                    this->GenTarget->GetName(), " to regular mode."));
506       }
507
508       // Options
509       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
510                    this->Moc.Options);
511       // Filters
512       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
513                    this->Moc.MacroNames);
514       {
515         auto filterList = cmExpandedList(
516           this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
517         if ((filterList.size() % 2) != 0) {
518           cmSystemTools::Error(
519             cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
520                      filterList.size(), " is not a multiple of 2."));
521           return false;
522         }
523         this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
524         this->Moc.DependFilters.emplace_back(
525           "Q_PLUGIN_METADATA",
526           "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
527           "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
528         for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
529           this->Moc.DependFilters.emplace_back(filterList[ii],
530                                                filterList[ii + 1]);
531         }
532       }
533     }
534   }
535
536   // Init rcc specific settings
537   if (this->Rcc.Enabled && !InitRcc()) {
538     return false;
539   }
540
541   // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
542   if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
543     this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
544   }
545
546   // Scan files
547   if (!this->InitScanFiles()) {
548     return false;
549   }
550
551   // Create autogen target
552   if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
553     return false;
554   }
555
556   // Create rcc targets
557   if (this->Rcc.Enabled && !this->InitRccTargets()) {
558     return false;
559   }
560
561   return true;
562 }
563
564 bool cmQtAutoGenInitializer::InitMoc()
565 {
566   // Mocs compilation file
567   this->Moc.CompilationFile =
568     cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
569
570   // Moc predefs
571   if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
572       (this->QtVersion >= IntegerVersion(5, 8))) {
573     // Command
574     this->Makefile->GetDefExpandList("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND",
575                                      this->Moc.PredefsCmd);
576     // Header
577     if (!this->Moc.PredefsCmd.empty()) {
578       ConfigFileNames(this->Moc.PredefsFile,
579                       cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
580     }
581   }
582
583   // Moc includes
584   {
585     SearchPathSanitizer sanitizer(this->Makefile);
586     auto getDirs =
587       [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
588       // Get the include dirs for this target, without stripping the implicit
589       // include dirs off, see issue #13667.
590       std::vector<std::string> dirs;
591       bool const appendImplicit = (this->QtVersion.Major >= 5);
592       this->LocalGen->GetIncludeDirectoriesImplicit(
593         dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
594       return sanitizer(dirs);
595     };
596
597     // Default configuration include directories
598     this->Moc.Includes.Default = getDirs(this->ConfigDefault);
599     // Other configuration settings
600     if (this->MultiConfig) {
601       for (std::string const& cfg : this->ConfigsList) {
602         std::vector<std::string> dirs = getDirs(cfg);
603         if (dirs == this->Moc.Includes.Default) {
604           continue;
605         }
606         this->Moc.Includes.Config[cfg] = std::move(dirs);
607       }
608     }
609   }
610
611   // Moc compile definitions
612   {
613     auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
614       std::set<std::string> defines;
615       this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
616 #ifdef _WIN32
617       if (this->Moc.PredefsCmd.empty()) {
618         // Add WIN32 definition if we don't have a moc_predefs.h
619         defines.insert("WIN32");
620       }
621 #endif
622       return defines;
623     };
624
625     // Default configuration defines
626     this->Moc.Defines.Default = getDefs(this->ConfigDefault);
627     // Other configuration defines
628     if (this->MultiConfig) {
629       for (std::string const& cfg : this->ConfigsList) {
630         std::set<std::string> defines = getDefs(cfg);
631         if (defines == this->Moc.Defines.Default) {
632           continue;
633         }
634         this->Moc.Defines.Config[cfg] = std::move(defines);
635       }
636     }
637   }
638
639   // Moc executable
640   {
641     if (!this->GetQtExecutable(this->Moc, "moc", false)) {
642       return false;
643     }
644     // Let the _autogen target depend on the moc executable
645     if (this->Moc.ExecutableTarget != nullptr) {
646       this->AutogenTarget.DependTargets.insert(
647         this->Moc.ExecutableTarget->Target);
648     }
649   }
650
651   return true;
652 }
653
654 bool cmQtAutoGenInitializer::InitUic()
655 {
656   // Uic search paths
657   {
658     std::string const& usp =
659       this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
660     if (!usp.empty()) {
661       this->Uic.SearchPaths =
662         SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
663     }
664   }
665   // Uic target options
666   {
667     auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
668       std::vector<std::string> opts;
669       this->GenTarget->GetAutoUicOptions(opts, cfg);
670       return opts;
671     };
672
673     // Default options
674     this->Uic.Options.Default = getOpts(this->ConfigDefault);
675     // Configuration specific options
676     if (this->MultiConfig) {
677       for (std::string const& cfg : this->ConfigsList) {
678         std::vector<std::string> options = getOpts(cfg);
679         if (options == this->Uic.Options.Default) {
680           continue;
681         }
682         this->Uic.Options.Config[cfg] = std::move(options);
683       }
684     }
685   }
686
687   // Uic executable
688   {
689     if (!this->GetQtExecutable(this->Uic, "uic", true)) {
690       return false;
691     }
692     // Let the _autogen target depend on the uic executable
693     if (this->Uic.ExecutableTarget != nullptr) {
694       this->AutogenTarget.DependTargets.insert(
695         this->Uic.ExecutableTarget->Target);
696     }
697   }
698
699   return true;
700 }
701
702 bool cmQtAutoGenInitializer::InitRcc()
703 {
704   // Rcc executable
705   {
706     if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
707       return false;
708     }
709     // Evaluate test output on demand
710     CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
711     if (!features.Evaluated) {
712       // Look for list options
713       if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
714         if (features.HelpOutput.find("--list") != std::string::npos) {
715           features.ListOptions.emplace_back("--list");
716         } else if (features.HelpOutput.find("-list") != std::string::npos) {
717           features.ListOptions.emplace_back("-list");
718         }
719       }
720       // Evaluation finished
721       features.Evaluated = true;
722     }
723   }
724
725   return true;
726 }
727
728 bool cmQtAutoGenInitializer::InitScanFiles()
729 {
730   cmake const* cm = this->Makefile->GetCMakeInstance();
731   auto const& kw = this->GlobalInitializer->kw();
732
733   auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
734                                 bool muIt) -> MUFileHandle {
735     MUFileHandle muf = cm::make_unique<MUFile>();
736     muf->FullPath = fullPath;
737     muf->SF = sf;
738     muf->Generated = sf->GetIsGenerated();
739     bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
740     muf->SkipMoc = this->Moc.Enabled &&
741       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
742     muf->SkipUic = this->Uic.Enabled &&
743       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
744     if (muIt) {
745       muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
746       muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
747     }
748     return muf;
749   };
750
751   auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
752     cmSourceFile* sf = muf->SF;
753     const bool muIt = (muf->MocIt || muf->UicIt);
754     if (this->CMP0100Accept || (extension != "hh")) {
755       // Accept
756       if (muIt && muf->Generated) {
757         this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
758       }
759       this->AutogenTarget.Headers.emplace(sf, std::move(muf));
760     } else if (muIt && this->CMP0100Warn) {
761       // Store file for warning message
762       this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
763     }
764   };
765
766   auto addMUSource = [this](MUFileHandle&& muf) {
767     if ((muf->MocIt || muf->UicIt) && muf->Generated) {
768       this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
769     }
770     this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
771   };
772
773   // Scan through target files
774   {
775     // Scan through target files
776     std::vector<cmSourceFile*> srcFiles;
777     this->GenTarget->GetConfigCommonSourceFiles(srcFiles);
778     for (cmSourceFile* sf : srcFiles) {
779       // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
780       // Since we're iterating over source files that might be not in the
781       // target we need to check for path errors (not existing files).
782       std::string pathError;
783       std::string const& fullPath = sf->ResolveFullPath(&pathError);
784       if (!pathError.empty() || fullPath.empty()) {
785         continue;
786       }
787       std::string const& extLower =
788         cmSystemTools::LowerCase(sf->GetExtension());
789
790       // Register files that will be scanned by moc or uic
791       if (this->MocOrUicEnabled()) {
792         if (cm->IsHeaderExtension(extLower)) {
793           addMUHeader(makeMUFile(sf, fullPath, true), extLower);
794         } else if (cm->IsSourceExtension(extLower)) {
795           addMUSource(makeMUFile(sf, fullPath, true));
796         }
797       }
798
799       // Register rcc enabled files
800       if (this->Rcc.Enabled) {
801         if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
802             !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
803           // Register qrc file
804           Qrc qrc;
805           qrc.QrcFile = fullPath;
806           qrc.QrcName =
807             cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
808           qrc.Generated = sf->GetIsGenerated();
809           // RCC options
810           {
811             std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
812             if (!opts.empty()) {
813               cmExpandList(opts, qrc.Options);
814             }
815           }
816           this->Rcc.Qrcs.push_back(std::move(qrc));
817         }
818       }
819     }
820   }
821   // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
822   // sources meta data cache. Clear it so that OBJECT library targets that
823   // are AUTOGEN initialized after this target get their added
824   // mocs_compilation.cpp source acknowledged by this target.
825   this->GenTarget->ClearSourcesCache();
826
827   // For source files find additional headers and private headers
828   if (this->MocOrUicEnabled()) {
829     // Header search suffixes and extensions
830     static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
831     auto const& exts = cm->GetHeaderExtensions();
832     // Scan through sources
833     for (auto const& pair : this->AutogenTarget.Sources) {
834       MUFile const& muf = *pair.second;
835       if (muf.MocIt || muf.UicIt) {
836         // Search for the default header file and a private header
837         std::string const& srcFullPath = muf.SF->ResolveFullPath();
838         std::string basePath = cmStrCat(
839           cmQtAutoGen::SubDirPrefix(srcFullPath),
840           cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
841         for (auto const& suffix : suffixes) {
842           std::string const suffixedPath = cmStrCat(basePath, suffix);
843           for (auto const& ext : exts) {
844             std::string fullPath = cmStrCat(suffixedPath, '.', ext);
845
846             auto constexpr locationKind = cmSourceFileLocationKind::Known;
847             cmSourceFile* sf =
848               this->Makefile->GetSource(fullPath, locationKind);
849             if (sf != nullptr) {
850               // Check if we know about this header already
851               if (cm::contains(this->AutogenTarget.Headers, sf)) {
852                 continue;
853               }
854               // We only accept not-GENERATED files that do exist.
855               if (!sf->GetIsGenerated() &&
856                   !cmSystemTools::FileExists(fullPath)) {
857                 continue;
858               }
859             } else if (cmSystemTools::FileExists(fullPath)) {
860               // Create a new source file for the existing file
861               sf = this->Makefile->CreateSource(fullPath, false, locationKind);
862             }
863
864             if (sf != nullptr) {
865               auto eMuf = makeMUFile(sf, fullPath, true);
866               // Ony process moc/uic when the parent is processed as well
867               if (!muf.MocIt) {
868                 eMuf->MocIt = false;
869               }
870               if (!muf.UicIt) {
871                 eMuf->UicIt = false;
872               }
873               addMUHeader(std::move(eMuf), ext);
874             }
875           }
876         }
877       }
878     }
879   }
880
881   // Scan through all source files in the makefile to extract moc and uic
882   // parameters.  Historically we support non target source file parameters.
883   // The reason is that their file names might be discovered from source files
884   // at generation time.
885   if (this->MocOrUicEnabled()) {
886     for (const auto& sf : this->Makefile->GetSourceFiles()) {
887       // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
888       // Since we're iterating over source files that might be not in the
889       // target we need to check for path errors (not existing files).
890       std::string pathError;
891       std::string const& fullPath = sf->ResolveFullPath(&pathError);
892       if (!pathError.empty() || fullPath.empty()) {
893         continue;
894       }
895       std::string const& extLower =
896         cmSystemTools::LowerCase(sf->GetExtension());
897
898       if (cm->IsHeaderExtension(extLower)) {
899         if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
900           auto muf = makeMUFile(sf.get(), fullPath, false);
901           if (muf->SkipMoc || muf->SkipUic) {
902             addMUHeader(std::move(muf), extLower);
903           }
904         }
905       } else if (cm->IsSourceExtension(extLower)) {
906         if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
907           auto muf = makeMUFile(sf.get(), fullPath, false);
908           if (muf->SkipMoc || muf->SkipUic) {
909             addMUSource(std::move(muf));
910           }
911         }
912       } else if (this->Uic.Enabled && (extLower == kw.ui)) {
913         // .ui file
914         bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
915         bool const skipUic =
916           (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
917         if (!skipUic) {
918           // Check if the .ui file has uic options
919           std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
920           if (!uicOpts.empty()) {
921             this->Uic.UiFiles.emplace_back(fullPath, cmExpandedList(uicOpts));
922           }
923         } else {
924           // Register skipped .ui file
925           this->Uic.SkipUi.insert(fullPath);
926         }
927       }
928     }
929   }
930
931   // Process GENERATED sources and headers
932   if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
933     if (this->CMP0071Accept) {
934       // Let the autogen target depend on the GENERATED files
935       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
936         this->AutogenTarget.DependFiles.insert(muf->FullPath);
937       }
938     } else if (this->CMP0071Warn) {
939       cm::string_view property;
940       if (this->Moc.Enabled && this->Uic.Enabled) {
941         property = "SKIP_AUTOGEN";
942       } else if (this->Moc.Enabled) {
943         property = "SKIP_AUTOMOC";
944       } else if (this->Uic.Enabled) {
945         property = "SKIP_AUTOUIC";
946       }
947       std::string files;
948       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
949         files += cmStrCat("  ", Quoted(muf->FullPath), '\n');
950       }
951       this->Makefile->IssueMessage(
952         MessageType::AUTHOR_WARNING,
953         cmStrCat(
954           cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
955           "For compatibility, CMake is excluding the GENERATED source "
956           "file(s):\n",
957           files, "from processing by ",
958           cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
959           ".  If any of the files should be processed, set CMP0071 to NEW.  "
960           "If any of the files should not be processed, "
961           "explicitly exclude them by setting the source file property ",
962           property, ":\n  set_property(SOURCE file.h PROPERTY ", property,
963           " ON)\n"));
964     }
965   }
966
967   // Generate CMP0100 warning
968   if (this->MocOrUicEnabled() &&
969       !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
970     cm::string_view property;
971     if (this->Moc.Enabled && this->Uic.Enabled) {
972       property = "SKIP_AUTOGEN";
973     } else if (this->Moc.Enabled) {
974       property = "SKIP_AUTOMOC";
975     } else if (this->Uic.Enabled) {
976       property = "SKIP_AUTOUIC";
977     }
978     std::string files;
979     for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
980       files += cmStrCat("  ", Quoted(sf->GetFullPath()), '\n');
981     }
982     this->Makefile->IssueMessage(
983       MessageType::AUTHOR_WARNING,
984       cmStrCat(
985         cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
986         "For compatibility, CMake is excluding the header file(s):\n", files,
987         "from processing by ",
988         cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
989         ".  If any of the files should be processed, set CMP0100 to NEW.  "
990         "If any of the files should not be processed, "
991         "explicitly exclude them by setting the source file property ",
992         property, ":\n  set_property(SOURCE file.hh PROPERTY ", property,
993         " ON)\n"));
994   }
995
996   // Process qrc files
997   if (!this->Rcc.Qrcs.empty()) {
998     const bool modernQt = (this->QtVersion.Major >= 5);
999     // Target rcc options
1000     std::vector<std::string> optionsTarget =
1001       cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
1002
1003     // Check if file name is unique
1004     for (Qrc& qrc : this->Rcc.Qrcs) {
1005       qrc.Unique = true;
1006       for (Qrc const& qrc2 : this->Rcc.Qrcs) {
1007         if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
1008           qrc.Unique = false;
1009           break;
1010         }
1011       }
1012     }
1013     // Path checksum and file names
1014     for (Qrc& qrc : this->Rcc.Qrcs) {
1015       // Path checksum
1016       qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
1017       // Output file name
1018       qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
1019                                 "/qrc_", qrc.QrcName, ".cpp");
1020       std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
1021                                         qrc.QrcName, '_', qrc.QrcPathChecksum);
1022       qrc.LockFile = cmStrCat(base, "_Lock.lock");
1023       qrc.InfoFile = cmStrCat(base, "_Info.json");
1024       ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
1025     }
1026     // rcc options
1027     for (Qrc& qrc : this->Rcc.Qrcs) {
1028       // Target options
1029       std::vector<std::string> opts = optionsTarget;
1030       // Merge computed "-name XYZ" option
1031       {
1032         std::string name = qrc.QrcName;
1033         // Replace '-' with '_'. The former is not valid for symbol names.
1034         std::replace(name.begin(), name.end(), '-', '_');
1035         if (!qrc.Unique) {
1036           name += cmStrCat('_', qrc.QrcPathChecksum);
1037         }
1038         std::vector<std::string> nameOpts;
1039         nameOpts.emplace_back("-name");
1040         nameOpts.emplace_back(std::move(name));
1041         RccMergeOptions(opts, nameOpts, modernQt);
1042       }
1043       // Merge file option
1044       RccMergeOptions(opts, qrc.Options, modernQt);
1045       qrc.Options = std::move(opts);
1046     }
1047     // rcc resources
1048     for (Qrc& qrc : this->Rcc.Qrcs) {
1049       if (!qrc.Generated) {
1050         std::string error;
1051         RccLister const lister(this->Rcc.Executable,
1052                                this->Rcc.ExecutableFeatures->ListOptions);
1053         if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
1054           cmSystemTools::Error(error);
1055           return false;
1056         }
1057       }
1058     }
1059   }
1060
1061   return true;
1062 }
1063
1064 bool cmQtAutoGenInitializer::InitAutogenTarget()
1065 {
1066   // Register info file as generated by CMake
1067   this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
1068
1069   // Files provided by the autogen target
1070   std::vector<std::string> autogenProvides;
1071   if (this->Moc.Enabled) {
1072     this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
1073     autogenProvides.push_back(this->Moc.CompilationFile);
1074   }
1075
1076   // Compose target comment
1077   std::string autogenComment;
1078   {
1079     std::string tools;
1080     if (this->Moc.Enabled) {
1081       tools += "MOC";
1082     }
1083     if (this->Uic.Enabled) {
1084       if (!tools.empty()) {
1085         tools += " and ";
1086       }
1087       tools += "UIC";
1088     }
1089     autogenComment = cmStrCat("Automatic ", tools, " for target ",
1090                               this->GenTarget->GetName());
1091   }
1092
1093   // Compose command lines
1094   // TODO: Refactor autogen to output a per-config mocs_compilation.cpp instead
1095   // of fiddling with the include directories
1096   std::vector<std::string> configs;
1097   this->GlobalGen->GetQtAutoGenConfigs(configs);
1098   bool stdPipesUTF8 = true;
1099   cmCustomCommandLines commandLines;
1100   for (auto const& config : configs) {
1101     commandLines.push_back(cmMakeCommandLine(
1102       { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
1103         this->AutogenTarget.InfoFile, config }));
1104   }
1105
1106   // Use PRE_BUILD on demand
1107   bool usePRE_BUILD = false;
1108   if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
1109     // Under VS use a PRE_BUILD event instead of a separate target to
1110     // reduce the number of targets loaded into the IDE.
1111     // This also works around a VS 11 bug that may skip updating the target:
1112     //  https://connect.microsoft.com/VisualStudio/feedback/details/769495
1113     usePRE_BUILD = true;
1114   }
1115   // Disable PRE_BUILD in some cases
1116   if (usePRE_BUILD) {
1117     // Cannot use PRE_BUILD with file depends
1118     if (!this->AutogenTarget.DependFiles.empty()) {
1119       usePRE_BUILD = false;
1120     }
1121     // Cannot use PRE_BUILD when a global autogen target is in place
1122     if (AutogenTarget.GlobalTarget) {
1123       usePRE_BUILD = false;
1124     }
1125   }
1126   // Create the autogen target/command
1127   if (usePRE_BUILD) {
1128     // Add additional autogen target dependencies to origin target
1129     for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1130       this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
1131                                           this->Makefile);
1132     }
1133
1134     // Add the pre-build command directly to bypass the OBJECT_LIBRARY
1135     // rejection in cmMakefile::AddCustomCommandToTarget because we know
1136     // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
1137     //
1138     // PRE_BUILD does not support file dependencies!
1139     const std::vector<std::string> no_output;
1140     const std::vector<std::string> no_deps;
1141     cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
1142                        this->Makefile->GetBacktrace(), autogenComment.c_str(),
1143                        this->Dir.Work.c_str(), stdPipesUTF8);
1144     cc.SetEscapeOldStyle(false);
1145     cc.SetEscapeAllowMakeVars(true);
1146     this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
1147   } else {
1148
1149     // Add link library target dependencies to the autogen target
1150     // dependencies
1151     if (this->AutogenTarget.DependOrigin) {
1152       // add_dependencies/addUtility do not support generator expressions.
1153       // We depend only on the libraries found in all configs therefore.
1154       std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
1155       for (std::string const& config : this->ConfigsList) {
1156         cmLinkImplementationLibraries const* libs =
1157           this->GenTarget->GetLinkImplementationLibraries(config);
1158         if (libs != nullptr) {
1159           for (cmLinkItem const& item : libs->Libraries) {
1160             cmGeneratorTarget const* libTarget = item.Target;
1161             if ((libTarget != nullptr) &&
1162                 !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
1163               // Increment target config count
1164               commonTargets[libTarget]++;
1165             }
1166           }
1167         }
1168       }
1169       for (auto const& item : commonTargets) {
1170         if (item.second == this->ConfigsList.size()) {
1171           this->AutogenTarget.DependTargets.insert(item.first->Target);
1172         }
1173       }
1174     }
1175
1176     std::vector<std::string> dependencies(
1177       this->AutogenTarget.DependFiles.begin(),
1178       this->AutogenTarget.DependFiles.end());
1179
1180     const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
1181       this->GlobalGen->GetName().find("Ninja") != std::string::npos;
1182     if (useNinjaDepfile) {
1183       // Create a custom command that generates a timestamp file and
1184       // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
1185       //
1186       // Also create an additional '_autogen_timestamp_deps' that the custom
1187       // command will depend on. It will have no sources or commands to
1188       // execute, but it will have dependencies that would originally be
1189       // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
1190       // serve as a list of order-only dependencies for the custom command,
1191       // without forcing the custom command to re-execute.
1192       //
1193       // The dependency tree would then look like
1194       // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
1195       // '_autogen' target.
1196       const auto timestampTargetName =
1197         cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
1198       std::vector<std::string> timestampTargetProvides;
1199       cmCustomCommandLines timestampTargetCommandLines;
1200
1201       // Add additional autogen target dependencies to
1202       // '_autogen_timestamp_deps'.
1203       for (const cmTarget* t : this->AutogenTarget.DependTargets) {
1204         dependencies.push_back(t->GetName());
1205       }
1206
1207       cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
1208         timestampTargetName, true, this->Dir.Work.c_str(),
1209         /*byproducts=*/timestampTargetProvides,
1210         /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
1211       this->LocalGen->AddGeneratorTarget(
1212         cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
1213
1214       // Set FOLDER property on the timestamp target, so it appears in the
1215       // appropriate folder in an IDE or in the file api.
1216       if (!this->TargetsFolder.empty()) {
1217         timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
1218       }
1219
1220       // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
1221       // moc and uic executables (whichever are enabled).
1222       dependencies.clear();
1223       dependencies.push_back(timestampTargetName);
1224
1225       if (this->Moc.ExecutableTarget != nullptr) {
1226         dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
1227       }
1228       if (this->Uic.ExecutableTarget != nullptr) {
1229         dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
1230       }
1231
1232       // Create the custom command that outputs the timestamp file.
1233       const char timestampFileName[] = "timestamp";
1234       const std::string outputFile =
1235         cmStrCat(this->Dir.Build, "/", timestampFileName);
1236       this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
1237       auto relativeBinaryDir = cmSystemTools::RelativePath(
1238         this->LocalGen->GetBinaryDirectory(),
1239         this->LocalGen->GetCurrentBinaryDirectory());
1240       if (!relativeBinaryDir.empty()) {
1241         relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
1242       }
1243       this->AutogenTarget.DepFileRuleName =
1244         cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
1245                  timestampFileName);
1246       commandLines.push_back(cmMakeCommandLine(
1247         { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
1248
1249       this->AddGeneratedSource(outputFile, this->Moc);
1250       const std::string no_main_dependency;
1251       this->LocalGen->AddCustomCommandToOutput(
1252         outputFile, dependencies, no_main_dependency, commandLines,
1253         autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
1254         /*escapeOldStyle=*/false,
1255         /*uses_terminal=*/false,
1256         /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
1257         stdPipesUTF8);
1258
1259       // Alter variables for the autogen target which now merely wraps the
1260       // custom command
1261       dependencies.clear();
1262       dependencies.push_back(outputFile);
1263       commandLines.clear();
1264       autogenComment.clear();
1265     }
1266
1267     // Create autogen target
1268     cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
1269       this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
1270       /*byproducts=*/autogenProvides,
1271       /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
1272     // Create autogen generator target
1273     this->LocalGen->AddGeneratorTarget(
1274       cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
1275
1276     // Forward origin utilities to autogen target
1277     if (this->AutogenTarget.DependOrigin) {
1278       for (BT<std::pair<std::string, bool>> const& depName :
1279            this->GenTarget->GetUtilities()) {
1280         autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
1281       }
1282     }
1283     if (!useNinjaDepfile) {
1284       // Add additional autogen target dependencies to autogen target
1285       for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1286         autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
1287       }
1288     }
1289
1290     // Set FOLDER property in autogen target
1291     if (!this->TargetsFolder.empty()) {
1292       autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
1293     }
1294
1295     // Add autogen target to the origin target dependencies
1296     this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
1297                                         this->Makefile);
1298
1299     // Add autogen target to the global autogen target dependencies
1300     if (this->AutogenTarget.GlobalTarget) {
1301       this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
1302                                                   this->AutogenTarget.Name);
1303     }
1304   }
1305
1306   return true;
1307 }
1308
1309 bool cmQtAutoGenInitializer::InitRccTargets()
1310 {
1311   for (Qrc const& qrc : this->Rcc.Qrcs) {
1312     // Register info file as generated by CMake
1313     this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
1314     // Register file at target
1315     {
1316       cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
1317       sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
1318     }
1319
1320     std::vector<std::string> ccOutput;
1321     ccOutput.push_back(qrc.OutputFile);
1322
1323     std::vector<std::string> ccDepends;
1324     // Add the .qrc and info file to the custom command dependencies
1325     ccDepends.push_back(qrc.QrcFile);
1326     ccDepends.push_back(qrc.InfoFile);
1327
1328     bool stdPipesUTF8 = true;
1329     cmCustomCommandLines commandLines;
1330     if (this->MultiConfig) {
1331       // Build for all configurations
1332       for (std::string const& config : this->ConfigsList) {
1333         commandLines.push_back(
1334           cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1335                               "cmake_autorcc", qrc.InfoFile, config }));
1336       }
1337     } else {
1338       commandLines.push_back(
1339         cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1340                             "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
1341     }
1342     std::string ccComment =
1343       cmStrCat("Automatic RCC for ",
1344                FileProjectRelativePath(this->Makefile, qrc.QrcFile));
1345
1346     if (qrc.Generated || this->Rcc.GlobalTarget) {
1347       // Create custom rcc target
1348       std::string ccName;
1349       {
1350         ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
1351         if (!qrc.Unique) {
1352           ccName += cmStrCat('_', qrc.QrcPathChecksum);
1353         }
1354
1355         cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
1356           ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
1357           commandLines, false, ccComment.c_str(), false, false, "",
1358           stdPipesUTF8);
1359
1360         // Create autogen generator target
1361         this->LocalGen->AddGeneratorTarget(
1362           cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
1363
1364         // Set FOLDER property in autogen target
1365         if (!this->TargetsFolder.empty()) {
1366           autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
1367         }
1368         if (!this->Rcc.ExecutableTargetName.empty()) {
1369           autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
1370                                     this->Makefile);
1371         }
1372       }
1373       // Add autogen target to the origin target dependencies
1374       this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
1375
1376       // Add autogen target to the global autogen target dependencies
1377       if (this->Rcc.GlobalTarget) {
1378         this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
1379       }
1380     } else {
1381       // Create custom rcc command
1382       {
1383         std::vector<std::string> ccByproducts;
1384
1385         // Add the resource files to the dependencies
1386         for (std::string const& fileName : qrc.Resources) {
1387           // Add resource file to the custom command dependencies
1388           ccDepends.push_back(fileName);
1389         }
1390         if (!this->Rcc.ExecutableTargetName.empty()) {
1391           ccDepends.push_back(this->Rcc.ExecutableTargetName);
1392         }
1393         std::string no_main_dependency;
1394         cmImplicitDependsList no_implicit_depends;
1395         this->LocalGen->AddCustomCommandToOutput(
1396           ccOutput, ccByproducts, ccDepends, no_main_dependency,
1397           no_implicit_depends, commandLines, ccComment.c_str(),
1398           this->Dir.Work.c_str(), false, true, false, false, "", "",
1399           stdPipesUTF8);
1400       }
1401       // Reconfigure when .qrc file changes
1402       this->Makefile->AddCMakeDependFile(qrc.QrcFile);
1403     }
1404   }
1405
1406   return true;
1407 }
1408
1409 bool cmQtAutoGenInitializer::SetupCustomTargets()
1410 {
1411   // Create info directory on demand
1412   if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
1413     cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
1414                                   Quoted(this->Dir.Info)));
1415     return false;
1416   }
1417
1418   // Generate autogen target info file
1419   if (this->MocOrUicEnabled()) {
1420     // Write autogen target info files
1421     if (!this->SetupWriteAutogenInfo()) {
1422       return false;
1423     }
1424   }
1425
1426   // Write AUTORCC info files
1427   return !this->Rcc.Enabled || this->SetupWriteRccInfo();
1428 }
1429
1430 bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
1431 {
1432   // Utility lambdas
1433   auto MfDef = [this](std::string const& key) {
1434     return this->Makefile->GetSafeDefinition(key);
1435   };
1436
1437   // Filtered headers and sources
1438   std::set<std::string> moc_skip;
1439   std::set<std::string> uic_skip;
1440   std::vector<MUFile const*> headers;
1441   std::vector<MUFile const*> sources;
1442
1443   // Filter headers
1444   {
1445     headers.reserve(this->AutogenTarget.Headers.size());
1446     for (auto const& pair : this->AutogenTarget.Headers) {
1447       MUFile const* const muf = pair.second.get();
1448       if (muf->Generated && !this->CMP0071Accept) {
1449         continue;
1450       }
1451       if (muf->SkipMoc) {
1452         moc_skip.insert(muf->FullPath);
1453       }
1454       if (muf->SkipUic) {
1455         uic_skip.insert(muf->FullPath);
1456       }
1457       if (muf->MocIt || muf->UicIt) {
1458         headers.emplace_back(muf);
1459       }
1460     }
1461     std::sort(headers.begin(), headers.end(),
1462               [](MUFile const* a, MUFile const* b) {
1463                 return (a->FullPath < b->FullPath);
1464               });
1465   }
1466
1467   // Filter sources
1468   {
1469     sources.reserve(this->AutogenTarget.Sources.size());
1470     for (auto const& pair : this->AutogenTarget.Sources) {
1471       MUFile const* const muf = pair.second.get();
1472       if (muf->Generated && !this->CMP0071Accept) {
1473         continue;
1474       }
1475       if (muf->SkipMoc) {
1476         moc_skip.insert(muf->FullPath);
1477       }
1478       if (muf->SkipUic) {
1479         uic_skip.insert(muf->FullPath);
1480       }
1481       if (muf->MocIt || muf->UicIt) {
1482         sources.emplace_back(muf);
1483       }
1484     }
1485     std::sort(sources.begin(), sources.end(),
1486               [](MUFile const* a, MUFile const* b) {
1487                 return (a->FullPath < b->FullPath);
1488               });
1489   }
1490
1491   // Info writer
1492   InfoWriter info;
1493
1494   // General
1495   info.SetBool("MULTI_CONFIG", this->MultiConfig);
1496   info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
1497   info.SetUInt("VERBOSITY", this->Verbosity);
1498
1499   // Directories
1500   info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1501   info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1502   info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1503   info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1504   info.Set("BUILD_DIR", this->Dir.Build);
1505   info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1506
1507   info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
1508   info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
1509   info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
1510   info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
1511
1512   info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
1513   info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
1514   info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
1515   info.Set("DEP_FILE", this->AutogenTarget.DepFile);
1516   info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
1517   info.SetArray("HEADER_EXTENSIONS",
1518                 this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
1519   info.SetArrayArray(
1520     "HEADERS", headers, [this](Json::Value& jval, MUFile const* muf) {
1521       jval.resize(3u);
1522       jval[0u] = muf->FullPath;
1523       jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1524       jval[2u] = this->GetMocBuildPath(*muf);
1525     });
1526   info.SetArrayArray(
1527     "SOURCES", sources, [](Json::Value& jval, MUFile const* muf) {
1528       jval.resize(2u);
1529       jval[0u] = muf->FullPath;
1530       jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1531     });
1532
1533   // Write moc settings
1534   if (this->Moc.Enabled) {
1535     info.SetArray("MOC_SKIP", moc_skip);
1536     info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
1537     info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
1538     info.SetArray("MOC_OPTIONS", this->Moc.Options);
1539     info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
1540     info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
1541     info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
1542     info.SetArrayArray(
1543       "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
1544       [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
1545         jval.resize(2u);
1546         jval[0u] = pair.first;
1547         jval[1u] = pair.second;
1548       });
1549     info.Set("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
1550     info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
1551     info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
1552   }
1553
1554   // Write uic settings
1555   if (this->Uic.Enabled) {
1556     // Add skipped .ui files
1557     uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
1558
1559     info.SetArray("UIC_SKIP", uic_skip);
1560     info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFiles,
1561                        [](Json::Value& jval, UicT::UiFileT const& uiFile) {
1562                          jval.resize(2u);
1563                          jval[0u] = uiFile.first;
1564                          InfoWriter::MakeStringArray(jval[1u], uiFile.second);
1565                        });
1566     info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
1567     info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
1568   }
1569
1570   info.Save(this->AutogenTarget.InfoFile);
1571
1572   return true;
1573 }
1574
1575 bool cmQtAutoGenInitializer::SetupWriteRccInfo()
1576 {
1577   for (Qrc const& qrc : this->Rcc.Qrcs) {
1578     // Utility lambdas
1579     auto MfDef = [this](std::string const& key) {
1580       return this->Makefile->GetSafeDefinition(key);
1581     };
1582
1583     InfoWriter info;
1584
1585     // General
1586     info.SetBool("MULTI_CONFIG", this->MultiConfig);
1587     info.SetUInt("VERBOSITY", this->Verbosity);
1588
1589     // Files
1590     info.Set("LOCK_FILE", qrc.LockFile);
1591     info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
1592
1593     // Directories
1594     info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1595     info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1596     info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1597     info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1598     info.Set("BUILD_DIR", this->Dir.Build);
1599     info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1600
1601     // rcc executable
1602     info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
1603     info.SetArray("RCC_LIST_OPTIONS",
1604                   this->Rcc.ExecutableFeatures->ListOptions);
1605
1606     // qrc file
1607     info.Set("SOURCE", qrc.QrcFile);
1608     info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
1609     info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
1610     info.SetArray("OPTIONS", qrc.Options);
1611     info.SetArray("INPUTS", qrc.Resources);
1612
1613     info.Save(qrc.InfoFile);
1614   }
1615
1616   return true;
1617 }
1618
1619 cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
1620   std::string const& filename)
1621 {
1622   cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
1623   gFile->SetProperty("GENERATED", "1");
1624   gFile->SetProperty("SKIP_AUTOGEN", "1");
1625   return gFile;
1626 }
1627
1628 cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
1629   std::string const& filename, GenVarsT const& genVars, bool prepend)
1630 {
1631   // Register source at makefile
1632   cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
1633   // Add source file to target
1634   this->GenTarget->AddSource(filename, prepend);
1635
1636   // Add source file to source group
1637   this->AddToSourceGroup(filename, genVars.GenNameUpper);
1638
1639   return gFile;
1640 }
1641
1642 void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
1643                                               cm::string_view genNameUpper)
1644 {
1645   cmSourceGroup* sourceGroup = nullptr;
1646   // Acquire source group
1647   {
1648     std::string property;
1649     std::string groupName;
1650     {
1651       // Prefer generator specific source group name
1652       std::initializer_list<std::string> const props{
1653         cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
1654       };
1655       for (std::string const& prop : props) {
1656         cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
1657         if (propName && !propName->empty()) {
1658           groupName = *propName;
1659           property = prop;
1660           break;
1661         }
1662       }
1663     }
1664     // Generate a source group on demand
1665     if (!groupName.empty()) {
1666       sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
1667       if (sourceGroup == nullptr) {
1668         cmSystemTools::Error(
1669           cmStrCat(genNameUpper, " error in ", property,
1670                    ": Could not find or create the source group ",
1671                    cmQtAutoGen::Quoted(groupName)));
1672       }
1673     }
1674   }
1675   if (sourceGroup != nullptr) {
1676     sourceGroup->AddGroupFile(fileName);
1677   }
1678 }
1679
1680 void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
1681 {
1682   this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
1683                                           false);
1684 }
1685
1686 void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
1687                                              cm::string_view prefix,
1688                                              cm::string_view suffix)
1689 {
1690   configString.Default = cmStrCat(prefix, suffix);
1691   if (this->MultiConfig) {
1692     for (auto const& cfg : this->ConfigsList) {
1693       configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
1694     }
1695   }
1696 }
1697
1698 void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
1699 {
1700   this->AddCleanFile(configString.Default);
1701   if (this->MultiConfig) {
1702     for (auto const& pair : configString.Config) {
1703       this->AddCleanFile(pair.second);
1704     }
1705   }
1706 }
1707
1708 std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
1709 cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
1710 {
1711   // Converts a char ptr to an unsigned int value
1712   auto toUInt = [](const char* const input) -> unsigned int {
1713     unsigned long tmp = 0;
1714     if (input != nullptr && cmStrToULong(input, &tmp)) {
1715       return static_cast<unsigned int>(tmp);
1716     }
1717     return 0u;
1718   };
1719   auto toUInt2 = [](cmProp input) -> unsigned int {
1720     unsigned long tmp = 0;
1721     if (input != nullptr && cmStrToULong(*input, &tmp)) {
1722       return static_cast<unsigned int>(tmp);
1723     }
1724     return 0u;
1725   };
1726
1727   // Initialize return value to a default
1728   std::pair<IntegerVersion, unsigned int> res(
1729     IntegerVersion(),
1730     toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
1731                                                            "")));
1732
1733   // Acquire known Qt versions
1734   std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
1735   {
1736     // Qt version variable prefixes
1737     static std::initializer_list<
1738       std::pair<cm::string_view, cm::string_view>> const keys{
1739       { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
1740       { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
1741       { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
1742     };
1743
1744     knownQtVersions.reserve(keys.size() * 2);
1745
1746     // Adds a version to the result (nullptr safe)
1747     auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
1748                                                    cmProp minor) {
1749       cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
1750       if (ver.Major != 0) {
1751         knownQtVersions.emplace_back(ver);
1752       }
1753     };
1754
1755     // Read versions from variables
1756     for (auto const& keyPair : keys) {
1757       addVersion(target->Makefile->GetDef(std::string(keyPair.first)),
1758                  target->Makefile->GetDef(std::string(keyPair.second)));
1759     }
1760
1761     // Read versions from directory properties
1762     for (auto const& keyPair : keys) {
1763       addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
1764                  target->Makefile->GetProperty(std::string(keyPair.second)));
1765     }
1766   }
1767
1768   // Evaluate known Qt versions
1769   if (!knownQtVersions.empty()) {
1770     if (res.second == 0) {
1771       // No specific version was requested by the target:
1772       // Use highest known Qt version.
1773       res.first = knownQtVersions.at(0);
1774     } else {
1775       // Pick a version from the known versions:
1776       for (auto it : knownQtVersions) {
1777         if (it.Major == res.second) {
1778           res.first = it;
1779           break;
1780         }
1781       }
1782     }
1783   }
1784   return res;
1785 }
1786
1787 std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
1788 {
1789   std::string res;
1790   if (!muf.MocIt) {
1791     return res;
1792   }
1793
1794   std::string basePath =
1795     cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
1796              FileNameWithoutLastExtension(muf.FullPath));
1797
1798   res = cmStrCat(basePath, ".cpp");
1799   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1800     return res;
1801   }
1802
1803   // File name already emitted.
1804   // Try appending the header suffix to the base path.
1805   basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
1806   res = cmStrCat(basePath, ".cpp");
1807   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1808     return res;
1809   }
1810
1811   // File name with header extension already emitted.
1812   // Try adding a number to the base path.
1813   constexpr std::size_t number_begin = 2;
1814   constexpr std::size_t number_end = 256;
1815   for (std::size_t ii = number_begin; ii != number_end; ++ii) {
1816     res = cmStrCat(basePath, '_', ii, ".cpp");
1817     if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1818       return res;
1819     }
1820   }
1821
1822   // Output file name conflict (unlikely, but still...)
1823   cmSystemTools::Error(
1824     cmStrCat("moc output file name conflict for ", muf.FullPath));
1825
1826   return res;
1827 }
1828
1829 bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
1830                                              const std::string& executable,
1831                                              bool ignoreMissingTarget) const
1832 {
1833   auto print_err = [this, &genVars](std::string const& err) {
1834     cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
1835                                   this->GenTarget->GetName(), ": ", err));
1836   };
1837
1838   // Custom executable
1839   {
1840     std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
1841     std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
1842     if (!val.empty()) {
1843       // Evaluate generator expression
1844       {
1845         cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
1846         cmGeneratorExpression ge(lfbt);
1847         std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
1848         genVars.Executable = cge->Evaluate(this->LocalGen, "");
1849       }
1850       if (genVars.Executable.empty() && !ignoreMissingTarget) {
1851         print_err(prop + " evaluates to an empty value");
1852         return false;
1853       }
1854
1855       // Create empty compiler features.
1856       genVars.ExecutableFeatures =
1857         std::make_shared<cmQtAutoGen::CompilerFeatures>();
1858       return true;
1859     }
1860   }
1861
1862   // Find executable target
1863   {
1864     // Find executable target name
1865     cm::string_view prefix;
1866     if (this->QtVersion.Major == 4) {
1867       prefix = "Qt4::";
1868     } else if (this->QtVersion.Major == 5) {
1869       prefix = "Qt5::";
1870     } else if (this->QtVersion.Major == 6) {
1871       prefix = "Qt6::";
1872     }
1873     std::string const targetName = cmStrCat(prefix, executable);
1874
1875     // Find target
1876     cmGeneratorTarget* genTarget =
1877       this->LocalGen->FindGeneratorTargetToUse(targetName);
1878     if (genTarget != nullptr) {
1879       genVars.ExecutableTargetName = targetName;
1880       genVars.ExecutableTarget = genTarget;
1881       if (genTarget->IsImported()) {
1882         genVars.Executable = genTarget->ImportedGetLocation("");
1883       } else {
1884         genVars.Executable = genTarget->GetLocation("");
1885       }
1886     } else {
1887       if (ignoreMissingTarget) {
1888         // Create empty compiler features.
1889         genVars.ExecutableFeatures =
1890           std::make_shared<cmQtAutoGen::CompilerFeatures>();
1891         return true;
1892       }
1893       print_err(cmStrCat("Could not find ", executable, " executable target ",
1894                          targetName));
1895       return false;
1896     }
1897   }
1898
1899   // Get executable features
1900   {
1901     std::string err;
1902     genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
1903       executable, genVars.Executable, err);
1904     if (!genVars.ExecutableFeatures) {
1905       print_err(err);
1906       return false;
1907     }
1908   }
1909
1910   return true;
1911 }