Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Source / cmGlobalXCodeGenerator.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 "cmGlobalXCodeGenerator.h"
4
5 #include <algorithm>
6 #include <cassert>
7 #include <cstdio>
8 #include <cstring>
9 #include <functional>
10 #include <iomanip>
11 #include <sstream>
12 #include <unordered_set>
13 #include <utility>
14
15 #include <cm/memory>
16 #include <cmext/algorithm>
17 #include <cmext/string_view>
18
19 #include "cmsys/RegularExpression.hxx"
20
21 #include "cmComputeLinkInformation.h"
22 #include "cmCryptoHash.h"
23 #include "cmCustomCommand.h"
24 #include "cmCustomCommandGenerator.h"
25 #include "cmCustomCommandLines.h"
26 #include "cmCustomCommandTypes.h"
27 #include "cmDocumentationEntry.h"
28 #include "cmGeneratedFileStream.h"
29 #include "cmGeneratorExpression.h"
30 #include "cmGeneratorTarget.h"
31 #include "cmGlobalGeneratorFactory.h"
32 #include "cmLinkItem.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmLocalXCodeGenerator.h"
36 #include "cmMakefile.h"
37 #include "cmMessageType.h"
38 #include "cmOutputConverter.h"
39 #include "cmPolicies.h"
40 #include "cmSourceFile.h"
41 #include "cmSourceFileLocation.h"
42 #include "cmSourceFileLocationKind.h"
43 #include "cmSourceGroup.h"
44 #include "cmState.h"
45 #include "cmStateSnapshot.h"
46 #include "cmStateTypes.h"
47 #include "cmStringAlgorithms.h"
48 #include "cmSystemTools.h"
49 #include "cmTarget.h"
50 #include "cmTargetDepend.h"
51 #include "cmXCode21Object.h"
52 #include "cmXCodeObject.h"
53 #include "cmXCodeScheme.h"
54 #include "cmXMLWriter.h"
55 #include "cmake.h"
56
57 #if !defined(CMAKE_BOOTSTRAP) && defined(__APPLE__)
58 #  include <CoreFoundation/CoreFoundation.h>
59 #  if !TARGET_OS_IPHONE
60 #    define HAVE_APPLICATION_SERVICES
61 #    include <ApplicationServices/ApplicationServices.h>
62 #  endif
63 #endif
64
65 #if !defined(CMAKE_BOOTSTRAP)
66 #  include "cmXMLParser.h"
67
68 // parse the xml file storing the installed version of Xcode on
69 // the machine
70 class cmXcodeVersionParser : public cmXMLParser
71 {
72 public:
73   cmXcodeVersionParser()
74     : Version("1.5")
75   {
76   }
77   void StartElement(const std::string&, const char**) override
78   {
79     this->Data = "";
80   }
81   void EndElement(const std::string& name) override
82   {
83     if (name == "key") {
84       this->Key = this->Data;
85     } else if (name == "string") {
86       if (this->Key == "CFBundleShortVersionString") {
87         this->Version = this->Data;
88       }
89     }
90   }
91   void CharacterDataHandler(const char* data, int length) override
92   {
93     this->Data.append(data, length);
94   }
95   std::string Version;
96   std::string Key;
97   std::string Data;
98 };
99 #endif
100
101 // Builds either an object list or a space-separated string from the
102 // given inputs.
103 class cmGlobalXCodeGenerator::BuildObjectListOrString
104 {
105   cmGlobalXCodeGenerator* Generator;
106   cmXCodeObject* Group;
107   bool Empty;
108   std::string String;
109
110 public:
111   BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
112     : Generator(gen)
113     , Group(nullptr)
114     , Empty(true)
115   {
116     if (buildObjectList) {
117       this->Group = this->Generator->CreateObject(cmXCodeObject::OBJECT_LIST);
118     }
119   }
120
121   bool IsEmpty() const { return this->Empty; }
122
123   void Add(const std::string& newString)
124   {
125     this->Empty = false;
126
127     if (this->Group) {
128       this->Group->AddObject(this->Generator->CreateString(newString));
129     } else {
130       this->String += newString;
131       this->String += ' ';
132     }
133   }
134
135   const std::string& GetString() const { return this->String; }
136
137   cmXCodeObject* CreateList()
138   {
139     if (this->Group) {
140       return this->Group;
141     }
142     return this->Generator->CreateString(this->String);
143   }
144 };
145
146 class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
147 {
148 public:
149   std::unique_ptr<cmGlobalGenerator> CreateGlobalGenerator(
150     const std::string& name, bool allowArch, cmake* cm) const override;
151
152   void GetDocumentation(cmDocumentationEntry& entry) const override
153   {
154     cmGlobalXCodeGenerator::GetDocumentation(entry);
155   }
156
157   std::vector<std::string> GetGeneratorNames() const override
158   {
159     std::vector<std::string> names;
160     names.push_back(cmGlobalXCodeGenerator::GetActualName());
161     return names;
162   }
163
164   std::vector<std::string> GetGeneratorNamesWithPlatform() const override
165   {
166     return std::vector<std::string>();
167   }
168
169   bool SupportsToolset() const override { return true; }
170   bool SupportsPlatform() const override { return false; }
171
172   std::vector<std::string> GetKnownPlatforms() const override
173   {
174     return std::vector<std::string>();
175   }
176
177   std::string GetDefaultPlatformName() const override { return std::string(); }
178 };
179
180 cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
181   cmake* cm, std::string const& version_string, unsigned int version_number)
182   : cmGlobalGenerator(cm)
183 {
184   this->VersionString = version_string;
185   this->XcodeVersion = version_number;
186   if (this->XcodeVersion >= 120) {
187     this->XcodeBuildSystem = BuildSystem::Twelve;
188   } else {
189     this->XcodeBuildSystem = BuildSystem::One;
190   }
191
192   this->RootObject = nullptr;
193   this->MainGroupChildren = nullptr;
194   this->FrameworkGroup = nullptr;
195   this->CurrentMakefile = nullptr;
196   this->CurrentLocalGenerator = nullptr;
197   this->XcodeBuildCommandInitialized = false;
198
199   this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
200   this->ObjectDirArch = this->ObjectDirArchDefault;
201
202   cm->GetState()->SetIsGeneratorMultiConfig(true);
203 }
204
205 std::unique_ptr<cmGlobalGeneratorFactory> cmGlobalXCodeGenerator::NewFactory()
206 {
207   return std::unique_ptr<cmGlobalGeneratorFactory>(new Factory);
208 }
209
210 std::unique_ptr<cmGlobalGenerator>
211 cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(const std::string& name,
212                                                        bool /*allowArch*/,
213                                                        cmake* cm) const
214 {
215   if (name != GetActualName()) {
216     return std::unique_ptr<cmGlobalGenerator>();
217   }
218 #if !defined(CMAKE_BOOTSTRAP)
219   cmXcodeVersionParser parser;
220   std::string versionFile;
221   {
222     std::string out;
223     bool commandResult = cmSystemTools::RunSingleCommand(
224       "xcode-select --print-path", &out, nullptr, nullptr, nullptr,
225       cmSystemTools::OUTPUT_NONE);
226     if (commandResult) {
227       std::string::size_type pos = out.find(".app/");
228       if (pos != std::string::npos) {
229         versionFile = out.substr(0, pos + 5) + "Contents/version.plist";
230       }
231     }
232   }
233   if (!versionFile.empty() && cmSystemTools::FileExists(versionFile)) {
234     parser.ParseFile(versionFile.c_str());
235   } else if (cmSystemTools::FileExists(
236                "/Applications/Xcode.app/Contents/version.plist")) {
237     parser.ParseFile("/Applications/Xcode.app/Contents/version.plist");
238   } else {
239     parser.ParseFile(
240       "/Developer/Applications/Xcode.app/Contents/version.plist");
241   }
242   std::string const& version_string = parser.Version;
243
244   // Compute an integer form of the version number.
245   unsigned int v[2] = { 0, 0 };
246   sscanf(version_string.c_str(), "%u.%u", &v[0], &v[1]);
247   unsigned int version_number = 10 * v[0] + v[1];
248
249   if (version_number < 50) {
250     cm->IssueMessage(MessageType::FATAL_ERROR,
251                      "Xcode " + version_string + " not supported.");
252     return std::unique_ptr<cmGlobalGenerator>();
253   }
254
255   return std::unique_ptr<cmGlobalGenerator>(
256     cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
257                                             version_number));
258 #else
259   std::cerr << "CMake should be built with cmake to use Xcode, "
260                "default to Xcode 1.5\n";
261   return std::unique_ptr<cmGlobalGenerator>(
262     cm::make_unique<cmGlobalXCodeGenerator>(cm));
263 #endif
264 }
265
266 bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
267 {
268   // The Xcode generator knows how to lookup its build tool
269   // directly instead of needing a helper module to do it, so we
270   // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
271   if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
272     mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetXcodeBuildCommand());
273   }
274   return true;
275 }
276
277 std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
278 {
279   if (!this->XcodeBuildCommandInitialized) {
280     this->XcodeBuildCommandInitialized = true;
281     this->XcodeBuildCommand = this->FindXcodeBuildCommand();
282   }
283   return this->XcodeBuildCommand;
284 }
285
286 std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
287 {
288   std::string makeProgram = cmSystemTools::FindProgram("xcodebuild");
289   if (makeProgram.empty()) {
290     makeProgram = "xcodebuild";
291   }
292   return makeProgram;
293 }
294
295 bool cmGlobalXCodeGenerator::SetSystemName(std::string const& s,
296                                            cmMakefile* mf)
297 {
298   this->SystemName = s;
299   return this->cmGlobalGenerator::SetSystemName(s, mf);
300 }
301
302 namespace {
303 cm::string_view cmXcodeBuildSystemString(cmGlobalXCodeGenerator::BuildSystem b)
304 {
305   switch (b) {
306     case cmGlobalXCodeGenerator::BuildSystem::One:
307       return "1"_s;
308     case cmGlobalXCodeGenerator::BuildSystem::Twelve:
309       return "12"_s;
310   }
311   return {};
312 }
313 }
314
315 bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
316                                                  bool build, cmMakefile* mf)
317 {
318   if (!this->ParseGeneratorToolset(ts, mf)) {
319     return false;
320   }
321   if (build) {
322     return true;
323   }
324   if (!this->GeneratorToolset.empty()) {
325     mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET", this->GeneratorToolset);
326   }
327   mf->AddDefinition("CMAKE_XCODE_BUILD_SYSTEM",
328                     cmXcodeBuildSystemString(this->XcodeBuildSystem));
329   return true;
330 }
331
332 bool cmGlobalXCodeGenerator::ParseGeneratorToolset(std::string const& ts,
333                                                    cmMakefile* mf)
334 {
335   std::vector<std::string> const fields = cmTokenize(ts, ",");
336   auto fi = fields.cbegin();
337   if (fi == fields.cend()) {
338     return true;
339   }
340
341   // The first field may be the Xcode GCC_VERSION.
342   if (fi->find('=') == fi->npos) {
343     this->GeneratorToolset = *fi;
344     ++fi;
345   }
346
347   std::unordered_set<std::string> handled;
348
349   // The rest of the fields must be key=value pairs.
350   for (; fi != fields.cend(); ++fi) {
351     std::string::size_type pos = fi->find('=');
352     if (pos == fi->npos) {
353       /* clang-format off */
354       std::string const& e = cmStrCat(
355         "Generator\n"
356         "  ", this->GetName(), "\n"
357         "given toolset specification\n"
358         "  ", ts, "\n"
359         "that contains a field after the first ',' with no '='."
360         );
361       /* clang-format on */
362       mf->IssueMessage(MessageType::FATAL_ERROR, e);
363       return false;
364     }
365     std::string const key = fi->substr(0, pos);
366     std::string const value = fi->substr(pos + 1);
367     if (!handled.insert(key).second) {
368       /* clang-format off */
369       std::string const& e = cmStrCat(
370         "Generator\n"
371         "  ", this->GetName(), "\n"
372         "given toolset specification\n"
373         "  ", ts, "\n"
374         "that contains duplicate field key '", key, "'."
375         );
376       /* clang-format on */
377       mf->IssueMessage(MessageType::FATAL_ERROR, e);
378       return false;
379     }
380     if (!this->ProcessGeneratorToolsetField(key, value, mf)) {
381       return false;
382     }
383   }
384
385   return true;
386 }
387
388 bool cmGlobalXCodeGenerator::ProcessGeneratorToolsetField(
389   std::string const& key, std::string const& value, cmMakefile* mf)
390 {
391   if (key == "buildsystem") {
392     if (value == "1"_s) {
393       this->XcodeBuildSystem = BuildSystem::One;
394     } else if (value == "12"_s) {
395       this->XcodeBuildSystem = BuildSystem::Twelve;
396     } else {
397       /* clang-format off */
398       std::string const& e = cmStrCat(
399         "Generator\n"
400         "  ",  this->GetName(), "\n"
401         "toolset specification field\n"
402         "  buildsystem=", value, "\n"
403         "value is unknown.  It must be '1' or '12'."
404         );
405       /* clang-format on */
406       mf->IssueMessage(MessageType::FATAL_ERROR, e);
407       return false;
408     }
409     if (this->XcodeBuildSystem == BuildSystem::Twelve &&
410         this->XcodeVersion < 120) {
411       /* clang-format off */
412       std::string const& e = cmStrCat(
413         "Generator\n"
414         "  ",  this->GetName(), "\n"
415         "toolset specification field\n"
416         "  buildsystem=", value, "\n"
417         "is not allowed with Xcode ", this->VersionString, '.'
418         );
419       /* clang-format on */
420       mf->IssueMessage(MessageType::FATAL_ERROR, e);
421       return false;
422     }
423     return true;
424   }
425   /* clang-format off */
426   std::string const& e = cmStrCat(
427     "Generator\n"
428     "  ", this->GetName(), "\n"
429     "given toolset specification that contains invalid field '", key, "'."
430     );
431   /* clang-format on */
432   mf->IssueMessage(MessageType::FATAL_ERROR, e);
433   return false;
434 }
435
436 void cmGlobalXCodeGenerator::EnableLanguage(
437   std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
438 {
439   mf->AddDefinition("XCODE", "1");
440   mf->AddDefinition("XCODE_VERSION", this->VersionString);
441   mf->InitCMAKE_CONFIGURATION_TYPES("Debug;Release;MinSizeRel;RelWithDebInfo");
442   mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
443   this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
444   this->ComputeArchitectures(mf);
445 }
446
447 bool cmGlobalXCodeGenerator::Open(const std::string& bindir,
448                                   const std::string& projectName, bool dryRun)
449 {
450   bool ret = false;
451
452 #ifdef HAVE_APPLICATION_SERVICES
453   std::string url = bindir + "/" + projectName + ".xcodeproj";
454
455   if (dryRun) {
456     return cmSystemTools::FileExists(url, false);
457   }
458
459   CFStringRef cfStr = CFStringCreateWithCString(
460     kCFAllocatorDefault, url.c_str(), kCFStringEncodingUTF8);
461   if (cfStr) {
462     CFURLRef cfUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfStr,
463                                                    kCFURLPOSIXPathStyle, true);
464     if (cfUrl) {
465       OSStatus err = LSOpenCFURLRef(cfUrl, nullptr);
466       ret = err == noErr;
467       CFRelease(cfUrl);
468     }
469     CFRelease(cfStr);
470   }
471 #else
472   (void)bindir;
473   (void)projectName;
474   (void)dryRun;
475 #endif
476
477   return ret;
478 }
479
480 std::vector<cmGlobalGenerator::GeneratedMakeCommand>
481 cmGlobalXCodeGenerator::GenerateBuildCommand(
482   const std::string& makeProgram, const std::string& projectName,
483   const std::string& /*projectDir*/,
484   std::vector<std::string> const& targetNames, const std::string& config,
485   int jobs, bool /*verbose*/, const cmBuildOptions& /*buildOptions*/,
486   std::vector<std::string> const& makeOptions)
487 {
488   GeneratedMakeCommand makeCommand;
489   // now build the test
490   makeCommand.Add(
491     this->SelectMakeProgram(makeProgram, this->GetXcodeBuildCommand()));
492
493   if (!projectName.empty()) {
494     makeCommand.Add("-project");
495     std::string projectArg = cmStrCat(projectName, ".xcodeproj");
496     makeCommand.Add(projectArg);
497   }
498   if (cm::contains(targetNames, "clean")) {
499     makeCommand.Add("clean");
500     makeCommand.Add("-target", "ALL_BUILD");
501   } else {
502     makeCommand.Add("build");
503     if (targetNames.empty() ||
504         ((targetNames.size() == 1) && targetNames.front().empty())) {
505       makeCommand.Add("-target", "ALL_BUILD");
506     } else {
507       for (const auto& tname : targetNames) {
508         if (!tname.empty()) {
509           makeCommand.Add("-target", tname);
510         }
511       }
512     }
513   }
514
515   if ((this->XcodeBuildSystem >= BuildSystem::Twelve) ||
516       (jobs != cmake::NO_BUILD_PARALLEL_LEVEL)) {
517     makeCommand.Add("-parallelizeTargets");
518   }
519   makeCommand.Add("-configuration", (config.empty() ? "Debug" : config));
520
521   if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
522       (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
523     makeCommand.Add("-jobs", std::to_string(jobs));
524   }
525
526   if (this->XcodeVersion >= 70) {
527     makeCommand.Add("-hideShellScriptEnvironment");
528   }
529   makeCommand.Add(makeOptions.begin(), makeOptions.end());
530   return { std::move(makeCommand) };
531 }
532
533 //! Create a local generator appropriate to this Global Generator
534 std::unique_ptr<cmLocalGenerator> cmGlobalXCodeGenerator::CreateLocalGenerator(
535   cmMakefile* mf)
536 {
537   std::unique_ptr<cmLocalGenerator> lg(
538     cm::make_unique<cmLocalXCodeGenerator>(this, mf));
539   if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
540     // For this build system variant we generate custom commands as
541     // shell scripts directly rather than inside Makefiles.
542     // FIXME: Rename or refactor this option for clarity.
543     lg->SetLinkScriptShell(true);
544   }
545   return lg;
546 }
547
548 void cmGlobalXCodeGenerator::AddExtraIDETargets()
549 {
550   // make sure extra targets are added before calling
551   // the parent generate which will call trace depends
552   for (auto keyVal : this->ProjectMap) {
553     cmLocalGenerator* root = keyVal.second[0];
554     this->SetGenerationRoot(root);
555     // add ALL_BUILD, INSTALL, etc
556     this->AddExtraTargets(root, keyVal.second);
557   }
558 }
559
560 void cmGlobalXCodeGenerator::Generate()
561 {
562   this->cmGlobalGenerator::Generate();
563   if (cmSystemTools::GetErrorOccurredFlag()) {
564     return;
565   }
566
567   for (auto keyVal : this->ProjectMap) {
568     cmLocalGenerator* root = keyVal.second[0];
569
570     bool generateTopLevelProjectOnly =
571       root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
572
573     if (generateTopLevelProjectOnly) {
574       cmStateSnapshot snp = root->GetStateSnapshot();
575       if (snp.GetBuildsystemDirectoryParent().IsValid()) {
576         continue;
577       }
578     }
579
580     // cache the enabled languages for source file type queries
581     this->GetEnabledLanguages(this->EnabledLangs);
582
583     this->SetGenerationRoot(root);
584     // now create the project
585     this->OutputXCodeProject(root, keyVal.second);
586   }
587 }
588
589 void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root)
590 {
591   this->CurrentProject = root->GetProjectName();
592   this->SetCurrentLocalGenerator(root);
593   this->CurrentRootGenerator = root;
594   this->CurrentXCodeHackMakefile =
595     cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
596   cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile);
597   this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make";
598 }
599
600 std::string cmGlobalXCodeGenerator::PostBuildMakeTarget(
601   std::string const& tName, std::string const& configName)
602 {
603   std::string target = tName;
604   std::replace(target.begin(), target.end(), ' ', '_');
605   std::string out = cmStrCat("PostBuild.", target, '.', configName);
606   return out;
607 }
608
609 #define CMAKE_CHECK_BUILD_SYSTEM_TARGET "ZERO_CHECK"
610
611 void cmGlobalXCodeGenerator::AddExtraTargets(
612   cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens)
613 {
614   // Add ALL_BUILD
615   auto cc = cm::make_unique<cmCustomCommand>();
616   cc->SetCommandLines(
617     cmMakeSingleCommandLine({ "echo", "Build all projects" }));
618   cc->SetCMP0116Status(cmPolicies::NEW);
619   cmTarget* allbuild =
620     root->AddUtilityCommand("ALL_BUILD", true, std::move(cc));
621
622   // Add xcconfig files to ALL_BUILD sources
623   for (auto& config : this->CurrentConfigurationTypes) {
624     auto xcconfig = cmGeneratorExpression::Evaluate(
625       this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
626       this->CurrentLocalGenerator, config);
627     if (!xcconfig.empty()) {
628       allbuild->AddSource(xcconfig);
629     }
630   }
631
632   root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(allbuild, root));
633
634   // Add XCODE depend helper
635   std::string legacyDependHelperDir = root->GetCurrentBinaryDirectory();
636   cmCustomCommandLines legacyDependHelperCommandLines;
637   if (this->XcodeBuildSystem == BuildSystem::One) {
638     legacyDependHelperCommandLines = cmMakeSingleCommandLine(
639       { "make", "-C", legacyDependHelperDir, "-f",
640         this->CurrentXCodeHackMakefile, "OBJDIR=$(OBJDIR)",
641         /* placeholder, see below */ "" });
642   }
643
644   // Add ZERO_CHECK
645   bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
646   bool generateTopLevelProjectOnly =
647     root->GetMakefile()->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY");
648   bool isTopLevel =
649     !root->GetStateSnapshot().GetBuildsystemDirectoryParent().IsValid();
650   bool isGenerateProject = isTopLevel || !generateTopLevelProjectOnly;
651   if (regenerate && isGenerateProject) {
652     this->CreateReRunCMakeFile(root, gens);
653     std::string file =
654       this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile);
655     cmSystemTools::ReplaceString(file, "\\ ", " ");
656     cc = cm::make_unique<cmCustomCommand>();
657     cc->SetCommandLines(cmMakeSingleCommandLine({ "make", "-f", file }));
658     cc->SetCMP0116Status(cmPolicies::NEW);
659     cmTarget* check = root->AddUtilityCommand(CMAKE_CHECK_BUILD_SYSTEM_TARGET,
660                                               true, std::move(cc));
661
662     root->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(check, root));
663   }
664
665   // now make the allbuild depend on all the non-utility targets
666   // in the project
667   for (auto& gen : gens) {
668     for (const auto& target : gen->GetGeneratorTargets()) {
669       if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
670         continue;
671       }
672
673       if (regenerate &&
674           (target->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET)) {
675         target->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET, false);
676       }
677
678       // make all exe, shared libs and modules
679       // run the depend check makefile as a post build rule
680       // this will make sure that when the next target is built
681       // things are up-to-date
682       if (this->XcodeBuildSystem == BuildSystem::One && isGenerateProject &&
683           target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
684         legacyDependHelperCommandLines.front().back() = // fill placeholder
685           this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
686         cc = cm::make_unique<cmCustomCommand>();
687         cc->SetCommandLines(legacyDependHelperCommandLines);
688         cc->SetComment("Depend check for xcode");
689         cc->SetWorkingDirectory(legacyDependHelperDir.c_str());
690         cc->SetCMP0116Status(cmPolicies::NEW);
691         gen->AddCustomCommandToTarget(
692           target->GetName(), cmCustomCommandType::POST_BUILD, std::move(cc),
693           cmObjectLibraryCommands::Accept);
694       }
695
696       if (!this->IsExcluded(gens[0], target.get())) {
697         allbuild->AddUtility(target->GetName(), false);
698       }
699     }
700   }
701 }
702
703 void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
704   cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
705 {
706   std::vector<std::string> lfiles;
707   for (auto gen : gens) {
708     cm::append(lfiles, gen->GetMakefile()->GetListFiles());
709   }
710
711   // sort the array
712   std::sort(lfiles.begin(), lfiles.end());
713   lfiles.erase(std::unique(lfiles.begin(), lfiles.end()), lfiles.end());
714
715   cmake* cm = this->GetCMakeInstance();
716   if (cm->DoWriteGlobVerifyTarget()) {
717     lfiles.emplace_back(cm->GetGlobVerifyStamp());
718   }
719
720   this->CurrentReRunCMakeMakefile =
721     cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts");
722   cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile);
723   this->CurrentReRunCMakeMakefile += "/ReRunCMake.make";
724   cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile);
725   makefileStream.SetCopyIfDifferent(true);
726   makefileStream << "# Generated by CMake, DO NOT EDIT\n\n";
727
728   makefileStream << "TARGETS:= \n";
729   makefileStream << "empty:= \n";
730   makefileStream << "space:= $(empty) $(empty)\n";
731   makefileStream << "spaceplus:= $(empty)\\ $(empty)\n\n";
732
733   for (const auto& lfile : lfiles) {
734     makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard "
735                    << this->ConvertToRelativeForMake(lfile) << "))\n";
736   }
737   makefileStream << "\n";
738
739   std::string checkCache =
740     cmStrCat(root->GetBinaryDirectory(), "/CMakeFiles/cmake.check_cache");
741
742   if (cm->DoWriteGlobVerifyTarget()) {
743     makefileStream << ".NOTPARALLEL:\n\n";
744     makefileStream << ".PHONY: all VERIFY_GLOBS\n\n";
745     makefileStream << "all: VERIFY_GLOBS "
746                    << this->ConvertToRelativeForMake(checkCache) << "\n\n";
747     makefileStream << "VERIFY_GLOBS:\n";
748     makefileStream << "\t"
749                    << this->ConvertToRelativeForMake(
750                         cmSystemTools::GetCMakeCommand())
751                    << " -P "
752                    << this->ConvertToRelativeForMake(cm->GetGlobVerifyScript())
753                    << "\n\n";
754   }
755
756   makefileStream << this->ConvertToRelativeForMake(checkCache)
757                  << ": $(TARGETS)\n";
758   makefileStream << "\t"
759                  << this->ConvertToRelativeForMake(
760                       cmSystemTools::GetCMakeCommand())
761                  << " -H"
762                  << this->ConvertToRelativeForMake(root->GetSourceDirectory())
763                  << " -B"
764                  << this->ConvertToRelativeForMake(root->GetBinaryDirectory())
765                  << "\n";
766 }
767
768 static bool objectIdLessThan(const std::unique_ptr<cmXCodeObject>& l,
769                              const std::unique_ptr<cmXCodeObject>& r)
770 {
771   return l->GetId() < r->GetId();
772 }
773
774 void cmGlobalXCodeGenerator::SortXCodeObjects()
775 {
776   std::sort(this->XCodeObjects.begin(), this->XCodeObjects.end(),
777             objectIdLessThan);
778 }
779
780 void cmGlobalXCodeGenerator::ClearXCodeObjects()
781 {
782   this->TargetDoneSet.clear();
783   this->XCodeObjects.clear();
784   this->XCodeObjectIDs.clear();
785   this->XCodeObjectMap.clear();
786   this->GroupMap.clear();
787   this->GroupNameMap.clear();
788   this->TargetGroup.clear();
789   this->FileRefs.clear();
790   this->ExternalLibRefs.clear();
791   this->EmbeddedLibRefs.clear();
792   this->FileRefToBuildFileMap.clear();
793   this->FileRefToEmbedBuildFileMap.clear();
794   this->CommandsVisited.clear();
795 }
796
797 void cmGlobalXCodeGenerator::addObject(std::unique_ptr<cmXCodeObject> obj)
798 {
799   if (obj->GetType() == cmXCodeObject::OBJECT) {
800     const std::string& id = obj->GetId();
801
802     // If this is a duplicate id, it's an error:
803     //
804     if (this->XCodeObjectIDs.count(id)) {
805       cmSystemTools::Error(
806         "Xcode generator: duplicate object ids not allowed");
807     }
808
809     this->XCodeObjectIDs.insert(id);
810   }
811
812   this->XCodeObjects.push_back(std::move(obj));
813 }
814
815 cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(
816   cmXCodeObject::PBXType ptype, cm::string_view key)
817 {
818   auto obj = cm::make_unique<cmXCode21Object>(ptype, cmXCodeObject::OBJECT,
819                                               this->GetObjectId(ptype, key));
820   auto ptr = obj.get();
821   this->addObject(std::move(obj));
822   return ptr;
823 }
824
825 cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type)
826 {
827   auto obj = cm::make_unique<cmXCodeObject>(
828     cmXCodeObject::None, type,
829     "Temporary cmake object, should not be referred to in Xcode file");
830   auto ptr = obj.get();
831   this->addObject(std::move(obj));
832   return ptr;
833 }
834
835 cmXCodeObject* cmGlobalXCodeGenerator::CreateString(const std::string& s)
836 {
837   cmXCodeObject* obj = this->CreateObject(cmXCodeObject::STRING);
838   obj->SetString(s);
839   return obj;
840 }
841
842 cmXCodeObject* cmGlobalXCodeGenerator::CreateObjectReference(
843   cmXCodeObject* ref)
844 {
845   cmXCodeObject* obj = this->CreateObject(cmXCodeObject::OBJECT_REF);
846   obj->SetObject(ref);
847   return obj;
848 }
849
850 cmXCodeObject* cmGlobalXCodeGenerator::CreateFlatClone(cmXCodeObject* orig)
851 {
852   cmXCodeObject* obj = this->CreateObject(orig->GetType());
853   obj->CopyAttributes(orig);
854   return obj;
855 }
856
857 static std::string GetGroupMapKeyFromPath(cmGeneratorTarget* target,
858                                           const std::string& fullpath)
859 {
860   std::string key(target->GetName());
861   key += "-";
862   key += fullpath;
863   return key;
864 }
865
866 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeBuildFileFromPath(
867   const std::string& fullpath, cmGeneratorTarget* target,
868   const std::string& lang, cmSourceFile* sf)
869 {
870   // Using a map and the full path guarantees that we will always get the same
871   // fileRef object for any given full path. Same goes for the buildFile
872   // object.
873   cmXCodeObject* fileRef =
874     this->CreateXCodeFileReferenceFromPath(fullpath, target, lang, sf);
875   if (fileRef) {
876     auto it = this->FileRefToBuildFileMap.find(fileRef);
877     if (it == this->FileRefToBuildFileMap.end()) {
878       cmXCodeObject* buildFile =
879         this->CreateObject(cmXCodeObject::PBXBuildFile);
880       buildFile->SetComment(fileRef->GetComment());
881       buildFile->AddAttribute("fileRef", this->CreateObjectReference(fileRef));
882       this->FileRefToBuildFileMap[fileRef] = buildFile;
883       return buildFile;
884     }
885     return it->second;
886   }
887   return nullptr;
888 }
889
890 class XCodeGeneratorExpressionInterpreter
891   : public cmGeneratorExpressionInterpreter
892 {
893 public:
894   XCodeGeneratorExpressionInterpreter(cmSourceFile* sourceFile,
895                                       cmLocalGenerator* localGenerator,
896                                       cmGeneratorTarget* headTarget,
897                                       const std::string& lang)
898     : cmGeneratorExpressionInterpreter(
899         localGenerator, "NO-PER-CONFIG-SUPPORT-IN-XCODE", headTarget, lang)
900     , SourceFile(sourceFile)
901   {
902   }
903
904   XCodeGeneratorExpressionInterpreter(
905     XCodeGeneratorExpressionInterpreter const&) = delete;
906   XCodeGeneratorExpressionInterpreter& operator=(
907     XCodeGeneratorExpressionInterpreter const&) = delete;
908
909   const std::string& Evaluate(const char* expression,
910                               const std::string& property)
911   {
912     return this->Evaluate(std::string(expression ? expression : ""), property);
913   }
914
915   const std::string& Evaluate(const std::string& expression,
916                               const std::string& property)
917   {
918     const std::string& processed =
919       this->cmGeneratorExpressionInterpreter::Evaluate(expression, property);
920     if (this->CompiledGeneratorExpression->GetHadContextSensitiveCondition()) {
921       std::ostringstream e;
922       /* clang-format off */
923       e <<
924           "Xcode does not support per-config per-source " << property << ":\n"
925           "  " << expression << "\n"
926           "specified for source:\n"
927           "  " << this->SourceFile->ResolveFullPath() << "\n";
928       /* clang-format on */
929       this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
930     }
931
932     return processed;
933   }
934
935 private:
936   cmSourceFile* SourceFile = nullptr;
937 };
938
939 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
940   cmLocalGenerator* lg, cmSourceFile* sf, cmGeneratorTarget* gtgt)
941 {
942   std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
943
944   XCodeGeneratorExpressionInterpreter genexInterpreter(sf, lg, gtgt, lang);
945
946   // Add flags from target and source file properties.
947   std::string flags;
948   std::string const& srcfmt = sf->GetSafeProperty("Fortran_FORMAT");
949   switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
950     case cmOutputConverter::FortranFormatFixed:
951       flags = "-fixed " + flags;
952       break;
953     case cmOutputConverter::FortranFormatFree:
954       flags = "-free " + flags;
955       break;
956     default:
957       break;
958   }
959
960   // Explicitly add the explicit language flag before any other flag
961   // so user flags can override it.
962   gtgt->AddExplicitLanguageFlags(flags, *sf);
963
964   const std::string COMPILE_FLAGS("COMPILE_FLAGS");
965   if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
966     lg->AppendFlags(flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
967   }
968   const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
969   if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
970     lg->AppendCompileOptions(
971       flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
972   }
973
974   // Add per-source definitions.
975   BuildObjectListOrString flagsBuild(this, false);
976   const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
977   if (cmValue compile_defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
978     this->AppendDefines(
979       flagsBuild,
980       genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS).c_str(),
981       true);
982   }
983
984   if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
985     this->AppendDefines(flagsBuild, "CMAKE_SKIP_PRECOMPILE_HEADERS", true);
986   }
987
988   if (!flagsBuild.IsEmpty()) {
989     if (!flags.empty()) {
990       flags += ' ';
991     }
992     flags += flagsBuild.GetString();
993   }
994
995   // Add per-source include directories.
996   std::vector<std::string> includes;
997   const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
998   if (cmValue cincludes = sf->GetProperty(INCLUDE_DIRECTORIES)) {
999     lg->AppendIncludeDirectories(
1000       includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
1001       *sf);
1002   }
1003   lg->AppendFlags(flags,
1004                   lg->GetIncludeFlags(includes, gtgt, lang, std::string()));
1005
1006   cmXCodeObject* buildFile =
1007     this->CreateXCodeBuildFileFromPath(sf->ResolveFullPath(), gtgt, lang, sf);
1008
1009   cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
1010   settings->AddAttributeIfNotEmpty("COMPILER_FLAGS",
1011                                    this->CreateString(flags));
1012
1013   cmGeneratorTarget::SourceFileFlags tsFlags =
1014     gtgt->GetTargetSourceFileFlags(sf);
1015
1016   cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1017
1018   // Is this a "private" or "public" framework header file?
1019   // Set the ATTRIBUTES attribute appropriately...
1020   //
1021   if (gtgt->IsFrameworkOnApple()) {
1022     if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePrivateHeader) {
1023       attrs->AddObject(this->CreateString("Private"));
1024     } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePublicHeader) {
1025       attrs->AddObject(this->CreateString("Public"));
1026     }
1027   }
1028
1029   // Add user-specified file attributes.
1030   cmValue extraFileAttributes = sf->GetProperty("XCODE_FILE_ATTRIBUTES");
1031   if (extraFileAttributes) {
1032     // Expand the list of attributes.
1033     std::vector<std::string> attributes = cmExpandedList(*extraFileAttributes);
1034
1035     // Store the attributes.
1036     for (const auto& attribute : attributes) {
1037       attrs->AddObject(this->CreateString(attribute));
1038     }
1039   }
1040
1041   settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
1042
1043   if (buildFile) {
1044     buildFile->AddAttributeIfNotEmpty("settings", settings);
1045   }
1046   return buildFile;
1047 }
1048
1049 void cmGlobalXCodeGenerator::AddXCodeProjBuildRule(
1050   cmGeneratorTarget* target, std::vector<cmSourceFile*>& sources) const
1051 {
1052   std::string listfile =
1053     cmStrCat(target->GetLocalGenerator()->GetCurrentSourceDirectory(),
1054              "/CMakeLists.txt");
1055   cmSourceFile* srcCMakeLists = target->Makefile->GetOrCreateSource(
1056     listfile, false, cmSourceFileLocationKind::Known);
1057   if (!cm::contains(sources, srcCMakeLists)) {
1058     sources.push_back(srcCMakeLists);
1059   }
1060 }
1061
1062 namespace {
1063
1064 bool IsLinkPhaseLibraryExtension(const std::string& fileExt)
1065 {
1066   // Empty file extension is a special case for paths to framework's
1067   // internal binary which could be MyFw.framework/Versions/*/MyFw
1068   return (fileExt == ".framework" || fileExt == ".a" || fileExt == ".o" ||
1069           fileExt == ".dylib" || fileExt == ".tbd" || fileExt.empty());
1070 }
1071 bool IsLibraryType(const std::string& fileType)
1072 {
1073   return (fileType == "wrapper.framework" || fileType == "archive.ar" ||
1074           fileType == "compiled.mach-o.objfile" ||
1075           fileType == "compiled.mach-o.dylib" ||
1076           fileType == "compiled.mach-o.executable" ||
1077           fileType == "sourcecode.text-based-dylib-definition");
1078 }
1079
1080 std::string GetDirectoryValueFromFileExtension(const std::string& dirExt)
1081 {
1082   std::string ext = cmSystemTools::LowerCase(dirExt);
1083   if (ext == "framework") {
1084     return "wrapper.framework";
1085   }
1086   if (ext == "xcassets") {
1087     return "folder.assetcatalog";
1088   }
1089   return "folder";
1090 }
1091
1092 std::string GetSourcecodeValueFromFileExtension(
1093   const std::string& _ext, const std::string& lang,
1094   bool& keepLastKnownFileType, const std::vector<std::string>& enabled_langs)
1095 {
1096   std::string ext = cmSystemTools::LowerCase(_ext);
1097   std::string sourcecode = "sourcecode";
1098
1099   if (ext == "o") {
1100     keepLastKnownFileType = true;
1101     sourcecode = "compiled.mach-o.objfile";
1102   } else if (ext == "xctest") {
1103     sourcecode = "wrapper.cfbundle";
1104   } else if (ext == "xib") {
1105     keepLastKnownFileType = true;
1106     sourcecode = "file.xib";
1107   } else if (ext == "storyboard") {
1108     keepLastKnownFileType = true;
1109     sourcecode = "file.storyboard";
1110   } else if (ext == "mm" && !cm::contains(enabled_langs, "OBJCXX")) {
1111     sourcecode += ".cpp.objcpp";
1112   } else if (ext == "m" && !cm::contains(enabled_langs, "OBJC")) {
1113     sourcecode += ".c.objc";
1114   } else if (ext == "swift") {
1115     sourcecode += ".swift";
1116   } else if (ext == "plist") {
1117     sourcecode += ".text.plist";
1118   } else if (ext == "h") {
1119     sourcecode += ".c.h";
1120   } else if (ext == "hxx" || ext == "hpp" || ext == "txx" || ext == "pch" ||
1121              ext == "hh" || ext == "inl") {
1122     sourcecode += ".cpp.h";
1123   } else if (ext == "png" || ext == "gif" || ext == "jpg") {
1124     keepLastKnownFileType = true;
1125     sourcecode = "image";
1126   } else if (ext == "txt") {
1127     sourcecode += ".text";
1128   } else if (lang == "CXX") {
1129     sourcecode += ".cpp.cpp";
1130   } else if (lang == "C") {
1131     sourcecode += ".c.c";
1132   } else if (lang == "OBJCXX") {
1133     sourcecode += ".cpp.objcpp";
1134   } else if (lang == "OBJC") {
1135     sourcecode += ".c.objc";
1136   } else if (lang == "Fortran") {
1137     sourcecode += ".fortran.f90";
1138   } else if (lang == "ASM") {
1139     sourcecode += ".asm";
1140   } else if (ext == "metal") {
1141     sourcecode += ".metal";
1142   } else if (ext == "mig") {
1143     sourcecode += ".mig";
1144   } else if (ext == "tbd") {
1145     sourcecode += ".text-based-dylib-definition";
1146   } else if (ext == "a") {
1147     keepLastKnownFileType = true;
1148     sourcecode = "archive.ar";
1149   } else if (ext == "dylib") {
1150     keepLastKnownFileType = true;
1151     sourcecode = "compiled.mach-o.dylib";
1152   } else if (ext == "framework") {
1153     keepLastKnownFileType = true;
1154     sourcecode = "wrapper.framework";
1155   } else if (ext == "xcassets") {
1156     keepLastKnownFileType = true;
1157     sourcecode = "folder.assetcatalog";
1158   } else if (ext == "xcconfig") {
1159     keepLastKnownFileType = true;
1160     sourcecode = "text.xcconfig";
1161   }
1162   // else
1163   //  {
1164   //  // Already specialized above or we leave sourcecode == "sourcecode"
1165   //  // which is probably the most correct choice. Extensionless headers,
1166   //  // for example... Or file types unknown to Xcode that do not map to a
1167   //  // valid explicitFileType value.
1168   //  }
1169
1170   return sourcecode;
1171 }
1172
1173 template <class T>
1174 std::string GetTargetObjectDirArch(T const& target,
1175                                    const std::string& defaultVal)
1176 {
1177   auto archs = cmExpandedList(target.GetSafeProperty("OSX_ARCHITECTURES"));
1178   if (archs.size() > 1) {
1179     return "$(CURRENT_ARCH)";
1180   } else if (archs.size() == 1) {
1181     return archs.front();
1182   } else {
1183     return defaultVal;
1184   }
1185 }
1186
1187 } // anonymous
1188
1189 // Extracts the framework directory, if path matches the framework syntax
1190 // otherwise returns the path untouched
1191 std::string cmGlobalXCodeGenerator::GetLibraryOrFrameworkPath(
1192   const std::string& path) const
1193 {
1194   auto fwDescriptor = this->SplitFrameworkPath(path);
1195   if (fwDescriptor) {
1196     return fwDescriptor->GetFrameworkPath();
1197   }
1198
1199   return path;
1200 }
1201
1202 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
1203   const std::string& fullpath, cmGeneratorTarget* target,
1204   const std::string& lang, cmSourceFile* sf)
1205 {
1206   bool useLastKnownFileType = false;
1207   std::string fileType;
1208   if (sf) {
1209     if (cmValue e = sf->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
1210       fileType = *e;
1211     } else if (cmValue l = sf->GetProperty("XCODE_LAST_KNOWN_FILE_TYPE")) {
1212       useLastKnownFileType = true;
1213       fileType = *l;
1214     }
1215   }
1216   // Make a copy so that we can override it later
1217   std::string path = cmSystemTools::CollapseFullPath(fullpath);
1218   // Compute the extension without leading '.'.
1219   std::string ext = cmSystemTools::GetFilenameLastExtension(path);
1220   if (!ext.empty()) {
1221     ext = ext.substr(1);
1222   }
1223   if (fileType.empty()) {
1224     path = this->GetLibraryOrFrameworkPath(path);
1225     ext = cmSystemTools::GetFilenameLastExtension(path);
1226     if (!ext.empty()) {
1227       ext = ext.substr(1);
1228     }
1229     // If fullpath references a directory, then we need to specify
1230     // lastKnownFileType as folder in order for Xcode to be able to
1231     // open the contents of the folder.
1232     // (Xcode 4.6 does not like explicitFileType=folder).
1233     if (cmSystemTools::FileIsDirectory(path)) {
1234       fileType = GetDirectoryValueFromFileExtension(ext);
1235       useLastKnownFileType = true;
1236     } else {
1237       if (ext.empty() && !sf) {
1238         // Special case for executable or library without extension
1239         // that is not a source file. We can't tell which without reading
1240         // its Mach-O header, but the file might not exist yet, so we
1241         // have to pick one here.
1242         useLastKnownFileType = true;
1243         fileType = "compiled.mach-o.executable";
1244       } else {
1245         fileType = GetSourcecodeValueFromFileExtension(
1246           ext, lang, useLastKnownFileType, this->EnabledLangs);
1247       }
1248     }
1249   }
1250
1251   std::string key = GetGroupMapKeyFromPath(target, path);
1252   cmXCodeObject* fileRef = this->FileRefs[key];
1253   if (!fileRef) {
1254     fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
1255     fileRef->SetComment(path);
1256     this->FileRefs[key] = fileRef;
1257   }
1258   fileRef->AddAttribute("fileEncoding", this->CreateString("4"));
1259   fileRef->AddAttribute(useLastKnownFileType ? "lastKnownFileType"
1260                                              : "explicitFileType",
1261                         this->CreateString(fileType));
1262   // Store the file path relative to the top of the source tree.
1263   if (!IsLibraryType(fileType)) {
1264     path = this->RelativeToSource(path);
1265   }
1266   std::string name = cmSystemTools::GetFilenameName(path);
1267   const char* sourceTree =
1268     cmSystemTools::FileIsFullPath(path) ? "<absolute>" : "SOURCE_ROOT";
1269   fileRef->AddAttribute("name", this->CreateString(name));
1270   fileRef->AddAttribute("path", this->CreateString(path));
1271   fileRef->AddAttribute("sourceTree", this->CreateString(sourceTree));
1272
1273   cmXCodeObject* group = this->GroupMap[key];
1274   if (!group && IsLibraryType(fileType)) {
1275     group = this->FrameworkGroup;
1276     this->GroupMap[key] = group;
1277   }
1278   if (!group) {
1279     cmSystemTools::Error("Could not find a PBX group for " + key);
1280     return nullptr;
1281   }
1282   cmXCodeObject* children = group->GetAttribute("children");
1283   if (!children->HasObject(fileRef)) {
1284     children->AddObject(fileRef);
1285   }
1286   return fileRef;
1287 }
1288
1289 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReference(
1290   cmSourceFile* sf, cmGeneratorTarget* target)
1291 {
1292   std::string lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf);
1293
1294   return this->CreateXCodeFileReferenceFromPath(sf->ResolveFullPath(), target,
1295                                                 lang, sf);
1296 }
1297
1298 bool cmGlobalXCodeGenerator::SpecialTargetEmitted(std::string const& tname)
1299 {
1300   if (tname == "ALL_BUILD" || tname == "install" || tname == "package" ||
1301       tname == "RUN_TESTS" || tname == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1302     if (this->TargetDoneSet.find(tname) != this->TargetDoneSet.end()) {
1303       return true;
1304     }
1305     this->TargetDoneSet.insert(tname);
1306     return false;
1307   }
1308   return false;
1309 }
1310
1311 void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen)
1312 {
1313   this->CurrentLocalGenerator = gen;
1314   this->CurrentMakefile = gen->GetMakefile();
1315
1316   // Select the current set of configuration types.
1317   this->CurrentConfigurationTypes =
1318     this->CurrentMakefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
1319 }
1320
1321 struct cmSourceFilePathCompare
1322 {
1323   bool operator()(cmSourceFile* l, cmSourceFile* r)
1324   {
1325     return l->ResolveFullPath() < r->ResolveFullPath();
1326   }
1327 };
1328
1329 struct cmCompareTargets
1330 {
1331   bool operator()(cmXCodeObject* l, cmXCodeObject* r) const
1332   {
1333     std::string const& a = l->GetTarget()->GetName();
1334     std::string const& b = r->GetTarget()->GetName();
1335     if (a == "ALL_BUILD") {
1336       return true;
1337     }
1338     if (b == "ALL_BUILD") {
1339       return false;
1340     }
1341     return a < b;
1342   }
1343 };
1344
1345 bool cmGlobalXCodeGenerator::CreateXCodeTargets(
1346   cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
1347 {
1348   this->SetCurrentLocalGenerator(gen);
1349   std::vector<cmGeneratorTarget*> gts =
1350     this->GetLocalGeneratorTargetsInOrder(gen);
1351   for (auto gtgt : gts) {
1352     if (!this->CreateXCodeTarget(gtgt, targets)) {
1353       return false;
1354     }
1355   }
1356   std::sort(targets.begin(), targets.end(), cmCompareTargets());
1357   return true;
1358 }
1359
1360 bool cmGlobalXCodeGenerator::CreateXCodeTarget(
1361   cmGeneratorTarget* gtgt, std::vector<cmXCodeObject*>& targets)
1362 {
1363   std::string targetName = gtgt->GetName();
1364
1365   // make sure ALL_BUILD, INSTALL, etc are only done once
1366   if (this->SpecialTargetEmitted(targetName)) {
1367     return true;
1368   }
1369
1370   if (!gtgt->IsInBuildSystem()) {
1371     return true;
1372   }
1373
1374   for (std::string const& configName : this->CurrentConfigurationTypes) {
1375     gtgt->CheckCxxModuleStatus(configName);
1376   }
1377
1378   if (gtgt->HaveCxx20ModuleSources()) {
1379     gtgt->Makefile->IssueMessage(
1380       MessageType::FATAL_ERROR,
1381       cmStrCat("The \"", gtgt->GetName(),
1382                "\" target contains C++ module sources which are not "
1383                "supported by the generator"));
1384   }
1385
1386   auto& gtgt_visited = this->CommandsVisited[gtgt];
1387   auto& deps = this->GetTargetDirectDepends(gtgt);
1388   for (auto& d : deps) {
1389     // Take the union of visited source files of custom commands so far.
1390     // ComputeTargetOrder ensures our dependencies already visited their
1391     // custom commands and updated CommandsVisited.
1392     auto& dep_visited = this->CommandsVisited[d];
1393     gtgt_visited.insert(dep_visited.begin(), dep_visited.end());
1394   }
1395
1396   if (gtgt->GetType() == cmStateEnums::UTILITY ||
1397       gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
1398       gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1399     cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
1400     if (!t) {
1401       return false;
1402     }
1403     targets.push_back(t);
1404     return true;
1405   }
1406
1407   // organize the sources
1408   std::vector<cmSourceFile*> commonSourceFiles;
1409   if (!gtgt->GetConfigCommonSourceFilesForXcode(commonSourceFiles)) {
1410     return false;
1411   }
1412
1413   // Add CMakeLists.txt file for user convenience.
1414   this->AddXCodeProjBuildRule(gtgt, commonSourceFiles);
1415
1416   // Add the Info.plist we are about to generate for an App Bundle.
1417   if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
1418     std::string plist = this->ComputeInfoPListLocation(gtgt);
1419     cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
1420       plist, true, cmSourceFileLocationKind::Known);
1421     commonSourceFiles.push_back(sf);
1422   }
1423
1424   std::sort(commonSourceFiles.begin(), commonSourceFiles.end(),
1425             cmSourceFilePathCompare());
1426
1427   gtgt->ComputeObjectMapping();
1428
1429   std::vector<cmXCodeObject*> externalObjFiles;
1430   std::vector<cmXCodeObject*> headerFiles;
1431   std::vector<cmXCodeObject*> resourceFiles;
1432   std::vector<cmXCodeObject*> sourceFiles;
1433   for (auto sourceFile : commonSourceFiles) {
1434     cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1435       this->CurrentLocalGenerator, sourceFile, gtgt);
1436     cmXCodeObject* fr = xsf->GetAttribute("fileRef");
1437     cmXCodeObject* filetype =
1438       fr->GetObject()->GetAttribute("explicitFileType");
1439     if (!filetype) {
1440       filetype = fr->GetObject()->GetAttribute("lastKnownFileType");
1441     }
1442
1443     cmGeneratorTarget::SourceFileFlags tsFlags =
1444       gtgt->GetTargetSourceFileFlags(sourceFile);
1445
1446     if (filetype && filetype->GetString() == "compiled.mach-o.objfile") {
1447       if (sourceFile->GetObjectLibrary().empty()) {
1448         externalObjFiles.push_back(xsf);
1449       }
1450     } else if (this->IsHeaderFile(sourceFile) ||
1451                (tsFlags.Type ==
1452                 cmGeneratorTarget::SourceFileTypePrivateHeader) ||
1453                (tsFlags.Type ==
1454                 cmGeneratorTarget::SourceFileTypePublicHeader)) {
1455       headerFiles.push_back(xsf);
1456     } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource) {
1457       resourceFiles.push_back(xsf);
1458     } else if (!sourceFile->GetPropertyAsBool("HEADER_FILE_ONLY") &&
1459                !gtgt->IsSourceFilePartOfUnityBatch(
1460                  sourceFile->ResolveFullPath())) {
1461       // Include this file in the build if it has a known language
1462       // and has not been listed as an ignored extension for this
1463       // generator.
1464       if (!this->CurrentLocalGenerator->GetSourceFileLanguage(*sourceFile)
1465              .empty() &&
1466           !this->IgnoreFile(sourceFile->GetExtension().c_str())) {
1467         sourceFiles.push_back(xsf);
1468       }
1469     }
1470   }
1471
1472   // some build phases only apply to bundles and/or frameworks
1473   bool isFrameworkTarget = gtgt->IsFrameworkOnApple();
1474   bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
1475   bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
1476
1477   cmXCodeObject* buildFiles = nullptr;
1478
1479   // create source build phase
1480   cmXCodeObject* sourceBuildPhase = nullptr;
1481   if (!sourceFiles.empty()) {
1482     sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
1483     sourceBuildPhase->SetComment("Sources");
1484     sourceBuildPhase->AddAttribute("buildActionMask",
1485                                    this->CreateString("2147483647"));
1486     buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1487     for (auto& sourceFile : sourceFiles) {
1488       buildFiles->AddObject(sourceFile);
1489     }
1490     sourceBuildPhase->AddAttribute("files", buildFiles);
1491     sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1492                                    this->CreateString("0"));
1493   }
1494
1495   // create header build phase - only for framework targets
1496   cmXCodeObject* headerBuildPhase = nullptr;
1497   if (!headerFiles.empty() && isFrameworkTarget) {
1498     headerBuildPhase = this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
1499     headerBuildPhase->SetComment("Headers");
1500     headerBuildPhase->AddAttribute("buildActionMask",
1501                                    this->CreateString("2147483647"));
1502     buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1503     for (auto& headerFile : headerFiles) {
1504       buildFiles->AddObject(headerFile);
1505     }
1506     headerBuildPhase->AddAttribute("files", buildFiles);
1507     headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1508                                    this->CreateString("0"));
1509   }
1510
1511   // create resource build phase - only for framework or bundle targets
1512   cmXCodeObject* resourceBuildPhase = nullptr;
1513   if (!resourceFiles.empty() &&
1514       (isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
1515     resourceBuildPhase =
1516       this->CreateObject(cmXCodeObject::PBXResourcesBuildPhase);
1517     resourceBuildPhase->SetComment("Resources");
1518     resourceBuildPhase->AddAttribute("buildActionMask",
1519                                      this->CreateString("2147483647"));
1520     buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1521     for (auto& resourceFile : resourceFiles) {
1522       buildFiles->AddObject(resourceFile);
1523     }
1524     resourceBuildPhase->AddAttribute("files", buildFiles);
1525     resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1526                                      this->CreateString("0"));
1527   }
1528
1529   // create vector of "non-resource content file" build phases - only for
1530   // framework or bundle targets
1531   std::vector<cmXCodeObject*> contentBuildPhases;
1532   if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
1533     using mapOfVectorOfSourceFiles =
1534       std::map<std::string, std::vector<cmSourceFile*>>;
1535     mapOfVectorOfSourceFiles bundleFiles;
1536     for (auto sourceFile : commonSourceFiles) {
1537       cmGeneratorTarget::SourceFileFlags tsFlags =
1538         gtgt->GetTargetSourceFileFlags(sourceFile);
1539       if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeMacContent) {
1540         bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
1541       }
1542     }
1543     for (auto const& keySources : bundleFiles) {
1544       cmXCodeObject* copyFilesBuildPhase =
1545         this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
1546       copyFilesBuildPhase->SetComment("Copy files");
1547       copyFilesBuildPhase->AddAttribute("buildActionMask",
1548                                         this->CreateString("2147483647"));
1549       copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
1550                                         this->CreateString("6"));
1551       std::ostringstream ostr;
1552       if (gtgt->IsFrameworkOnApple()) {
1553         // dstPath in frameworks is relative to Versions/<version>
1554         ostr << keySources.first;
1555       } else if (keySources.first != "MacOS") {
1556         if (gtgt->Target->GetMakefile()->PlatformIsAppleEmbedded()) {
1557           ostr << keySources.first;
1558         } else {
1559           // dstPath in bundles is relative to Contents/MacOS
1560           ostr << "../" << keySources.first;
1561         }
1562       }
1563       copyFilesBuildPhase->AddAttribute("dstPath",
1564                                         this->CreateString(ostr.str()));
1565       copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1566                                         this->CreateString("0"));
1567       buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1568       copyFilesBuildPhase->AddAttribute("files", buildFiles);
1569       for (auto sourceFile : keySources.second) {
1570         cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1571           this->CurrentLocalGenerator, sourceFile, gtgt);
1572         buildFiles->AddObject(xsf);
1573       }
1574       contentBuildPhases.push_back(copyFilesBuildPhase);
1575     }
1576   }
1577
1578   // create vector of "resource content file" build phases - only for
1579   // framework or bundle targets
1580   if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
1581     using mapOfVectorOfSourceFiles =
1582       std::map<std::string, std::vector<cmSourceFile*>>;
1583     mapOfVectorOfSourceFiles bundleFiles;
1584     for (auto sourceFile : commonSourceFiles) {
1585       cmGeneratorTarget::SourceFileFlags tsFlags =
1586         gtgt->GetTargetSourceFileFlags(sourceFile);
1587       if (tsFlags.Type == cmGeneratorTarget::SourceFileTypeDeepResource) {
1588         bundleFiles[tsFlags.MacFolder].push_back(sourceFile);
1589       }
1590     }
1591     for (auto const& keySources : bundleFiles) {
1592       cmXCodeObject* copyFilesBuildPhase =
1593         this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
1594       copyFilesBuildPhase->SetComment("Copy files");
1595       copyFilesBuildPhase->AddAttribute("buildActionMask",
1596                                         this->CreateString("2147483647"));
1597       copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
1598                                         this->CreateString("7"));
1599       copyFilesBuildPhase->AddAttribute("dstPath",
1600                                         this->CreateString(keySources.first));
1601       copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1602                                         this->CreateString("0"));
1603       buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1604       copyFilesBuildPhase->AddAttribute("files", buildFiles);
1605       for (auto sourceFile : keySources.second) {
1606         cmXCodeObject* xsf = this->CreateXCodeSourceFile(
1607           this->CurrentLocalGenerator, sourceFile, gtgt);
1608         buildFiles->AddObject(xsf);
1609       }
1610       contentBuildPhases.push_back(copyFilesBuildPhase);
1611     }
1612   }
1613
1614   // Always create Link Binary With Libraries build phase
1615   cmXCodeObject* frameworkBuildPhase = nullptr;
1616   frameworkBuildPhase =
1617     this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
1618   frameworkBuildPhase->SetComment("Frameworks");
1619   frameworkBuildPhase->AddAttribute("buildActionMask",
1620                                     this->CreateString("2147483647"));
1621   buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1622   frameworkBuildPhase->AddAttribute("files", buildFiles);
1623   // Add all collected .o files to this build phase
1624   for (auto& externalObjFile : externalObjFiles) {
1625     buildFiles->AddObject(externalObjFile);
1626   }
1627   frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1628                                     this->CreateString("0"));
1629
1630   // create list of build phases and create the Xcode target
1631   cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1632
1633   this->CreateCustomCommands(buildPhases, sourceBuildPhase, headerBuildPhase,
1634                              resourceBuildPhase, contentBuildPhases,
1635                              frameworkBuildPhase, gtgt);
1636
1637   targets.push_back(this->CreateXCodeTarget(gtgt, buildPhases));
1638   return true;
1639 }
1640
1641 void cmGlobalXCodeGenerator::ForceLinkerLanguages()
1642 {
1643   for (const auto& localGenerator : this->LocalGenerators) {
1644     // All targets depend on the build-system check target.
1645     for (const auto& tgt : localGenerator->GetGeneratorTargets()) {
1646       // This makes sure all targets link using the proper language.
1647       this->ForceLinkerLanguage(tgt.get());
1648     }
1649   }
1650 }
1651
1652 void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
1653 {
1654   // This matters only for targets that link.
1655   if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
1656       gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
1657       gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
1658     return;
1659   }
1660
1661   std::string llang = gtgt->GetLinkerLanguage("NOCONFIG");
1662   if (llang.empty()) {
1663     return;
1664   }
1665
1666   // If the language is compiled as a source trust Xcode to link with it.
1667   for (auto const& Language :
1668        gtgt
1669          ->GetLinkImplementation("NOCONFIG",
1670                                  cmGeneratorTarget::LinkInterfaceFor::Link)
1671          ->Languages) {
1672     if (Language == llang) {
1673       return;
1674     }
1675   }
1676
1677   // Allow empty source file list for iOS Sticker packs
1678   if (const char* productType = GetTargetProductType(gtgt)) {
1679     if (strcmp(productType,
1680                "com.apple.product-type.app-extension.messages-sticker-pack") ==
1681         0)
1682       return;
1683   }
1684
1685   // Add an empty source file to the target that compiles with the
1686   // linker language.  This should convince Xcode to choose the proper
1687   // language.
1688   cmMakefile* mf = gtgt->Target->GetMakefile();
1689   std::string fname = cmStrCat(
1690     gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/",
1691     gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang));
1692   {
1693     cmGeneratedFileStream fout(fname);
1694     fout << "\n";
1695   }
1696   if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
1697     sf->SetProperty("LANGUAGE", llang);
1698     gtgt->AddSource(fname);
1699   }
1700 }
1701
1702 bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf)
1703 {
1704   return cm::contains(this->CMakeInstance->GetHeaderExtensions(),
1705                       sf->GetExtension());
1706 }
1707
1708 cmXCodeObject* cmGlobalXCodeGenerator::CreateLegacyRunScriptBuildPhase(
1709   const char* name, const char* name2, cmGeneratorTarget* target,
1710   const std::vector<cmCustomCommand>& commands)
1711 {
1712   if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
1713     return nullptr;
1714   }
1715   cmXCodeObject* buildPhase =
1716     this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
1717   buildPhase->AddAttribute("buildActionMask",
1718                            this->CreateString("2147483647"));
1719   cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1720   buildPhase->AddAttribute("files", buildFiles);
1721   buildPhase->AddAttribute("name", this->CreateString(name));
1722   buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1723                            this->CreateString("0"));
1724   buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
1725   this->AddCommandsToBuildPhase(buildPhase, target, commands, name2);
1726   return buildPhase;
1727 }
1728
1729 void cmGlobalXCodeGenerator::CreateCustomCommands(
1730   cmXCodeObject* buildPhases, cmXCodeObject* sourceBuildPhase,
1731   cmXCodeObject* headerBuildPhase, cmXCodeObject* resourceBuildPhase,
1732   std::vector<cmXCodeObject*> const& contentBuildPhases,
1733   cmXCodeObject* frameworkBuildPhase, cmGeneratorTarget* gtgt)
1734 {
1735   std::vector<cmCustomCommand> const& prebuild = gtgt->GetPreBuildCommands();
1736   std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
1737   std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
1738
1739   if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
1740       !gtgt->IsFrameworkOnApple()) {
1741     std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>');
1742     std::string str_so_file =
1743       cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>');
1744     std::string str_link_file =
1745       cmStrCat("$<TARGET_LINKER_FILE:", gtgt->GetName(), '>');
1746     cmCustomCommandLines cmd = cmMakeSingleCommandLine(
1747       { cmSystemTools::GetCMakeCommand(), "-E", "cmake_symlink_library",
1748         str_file, str_so_file, str_link_file });
1749
1750     cmCustomCommand command;
1751     command.SetCommandLines(cmd);
1752     command.SetComment("Creating symlinks");
1753     command.SetWorkingDirectory("");
1754     command.SetBacktrace(this->CurrentMakefile->GetBacktrace());
1755     command.SetStdPipesUTF8(true);
1756
1757     postbuild.push_back(std::move(command));
1758   }
1759
1760   cmXCodeObject* legacyCustomCommandsBuildPhase = nullptr;
1761   cmXCodeObject* preBuildPhase = nullptr;
1762   cmXCodeObject* preLinkPhase = nullptr;
1763   cmXCodeObject* postBuildPhase = nullptr;
1764
1765   if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
1766     // create prebuild phase
1767     preBuildPhase =
1768       this->CreateRunScriptBuildPhase("CMake PreBuild Rules", gtgt, prebuild);
1769     // create prelink phase
1770     preLinkPhase =
1771       this->CreateRunScriptBuildPhase("CMake PreLink Rules", gtgt, prelink);
1772     // create postbuild phase
1773     postBuildPhase = this->CreateRunScriptBuildPhase("CMake PostBuild Rules",
1774                                                      gtgt, postbuild);
1775   } else {
1776     std::vector<cmSourceFile*> classes;
1777     if (!gtgt->GetConfigCommonSourceFilesForXcode(classes)) {
1778       return;
1779     }
1780     // add all the sources
1781     std::vector<cmCustomCommand> commands;
1782     auto& visited = this->CommandsVisited[gtgt];
1783     for (auto sourceFile : classes) {
1784       if (sourceFile->GetCustomCommand() &&
1785           visited.insert(sourceFile).second) {
1786         commands.push_back(*sourceFile->GetCustomCommand());
1787       }
1788     }
1789     // create custom commands phase
1790     legacyCustomCommandsBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1791       "CMake Rules", "cmakeRulesBuildPhase", gtgt, commands);
1792     // create prebuild phase
1793     preBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1794       "CMake PreBuild Rules", "preBuildCommands", gtgt, prebuild);
1795     // create prelink phase
1796     preLinkPhase = this->CreateLegacyRunScriptBuildPhase(
1797       "CMake PreLink Rules", "preLinkCommands", gtgt, prelink);
1798     // create postbuild phase
1799     postBuildPhase = this->CreateLegacyRunScriptBuildPhase(
1800       "CMake PostBuild Rules", "postBuildPhase", gtgt, postbuild);
1801   }
1802
1803   // The order here is the order they will be built in.
1804   // The order "headers, resources, sources" mimics a native project generated
1805   // from an xcode template...
1806   //
1807   if (preBuildPhase) {
1808     buildPhases->AddObject(preBuildPhase);
1809   }
1810   if (legacyCustomCommandsBuildPhase) {
1811     buildPhases->AddObject(legacyCustomCommandsBuildPhase);
1812   }
1813   if (this->XcodeBuildSystem >= BuildSystem::Twelve) {
1814     this->CreateRunScriptBuildPhases(buildPhases, gtgt);
1815   }
1816   if (headerBuildPhase) {
1817     buildPhases->AddObject(headerBuildPhase);
1818   }
1819   if (resourceBuildPhase) {
1820     buildPhases->AddObject(resourceBuildPhase);
1821   }
1822   for (auto obj : contentBuildPhases) {
1823     buildPhases->AddObject(obj);
1824   }
1825   if (sourceBuildPhase) {
1826     buildPhases->AddObject(sourceBuildPhase);
1827   }
1828   if (preLinkPhase) {
1829     buildPhases->AddObject(preLinkPhase);
1830   }
1831   if (frameworkBuildPhase) {
1832     buildPhases->AddObject(frameworkBuildPhase);
1833   }
1834
1835   // When this build phase is present, it must be last. More build phases may
1836   // be added later for embedding things and they will insert themselves just
1837   // before this last build phase.
1838   if (postBuildPhase) {
1839     buildPhases->AddObject(postBuildPhase);
1840   }
1841 }
1842
1843 void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
1844   cmXCodeObject* buildPhases, cmGeneratorTarget const* gt)
1845 {
1846   std::vector<cmSourceFile*> sources;
1847   if (!gt->GetConfigCommonSourceFilesForXcode(sources)) {
1848     return;
1849   }
1850   auto& visited = this->CommandsVisited[gt];
1851   for (auto sf : sources) {
1852     this->CreateRunScriptBuildPhases(buildPhases, sf, gt, visited);
1853   }
1854 }
1855
1856 void cmGlobalXCodeGenerator::CreateRunScriptBuildPhases(
1857   cmXCodeObject* buildPhases, cmSourceFile const* sf,
1858   cmGeneratorTarget const* gt, std::set<cmSourceFile const*>& visited)
1859 {
1860   cmCustomCommand const* cc = sf->GetCustomCommand();
1861   if (cc && visited.insert(sf).second) {
1862     this->CustomCommandRoots[sf].insert(gt);
1863     if (std::vector<cmSourceFile*> const* depends = gt->GetSourceDepends(sf)) {
1864       for (cmSourceFile const* di : *depends) {
1865         this->CreateRunScriptBuildPhases(buildPhases, di, gt, visited);
1866       }
1867     }
1868     cmXCodeObject* buildPhase = this->CreateRunScriptBuildPhase(sf, gt, *cc);
1869     buildPhases->AddObject(buildPhase);
1870   }
1871 }
1872
1873 cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
1874   cmSourceFile const* sf, cmGeneratorTarget const* gt,
1875   cmCustomCommand const& cc)
1876 {
1877   std::set<std::string> allConfigInputs;
1878   std::set<std::string> allConfigOutputs;
1879
1880   cmXCodeObject* buildPhase =
1881     this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
1882                        cmStrCat(gt->GetName(), ':', sf->GetFullPath()));
1883
1884   auto depfilesDirectory = cmStrCat(
1885     gt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/d/");
1886   auto depfilesPrefix = cmStrCat(depfilesDirectory, buildPhase->GetId(), ".");
1887
1888   std::string shellScript = "set -e\n";
1889   for (std::string const& configName : this->CurrentConfigurationTypes) {
1890     cmCustomCommandGenerator ccg(
1891       cc, configName, this->CurrentLocalGenerator, true, {},
1892       [&depfilesPrefix](const std::string& config, const std::string&)
1893         -> std::string { return cmStrCat(depfilesPrefix, config, ".d"); });
1894     std::vector<std::string> realDepends;
1895     realDepends.reserve(ccg.GetDepends().size());
1896     for (auto const& d : ccg.GetDepends()) {
1897       std::string dep;
1898       if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
1899         realDepends.emplace_back(std::move(dep));
1900       }
1901     }
1902
1903     allConfigInputs.insert(realDepends.begin(), realDepends.end());
1904     allConfigOutputs.insert(ccg.GetByproducts().begin(),
1905                             ccg.GetByproducts().end());
1906     allConfigOutputs.insert(ccg.GetOutputs().begin(), ccg.GetOutputs().end());
1907
1908     shellScript =
1909       cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")", configName,
1910                "\"; then :\n", this->ConstructScript(ccg), "fi\n");
1911   }
1912
1913   if (!cc.GetDepfile().empty()) {
1914     buildPhase->AddAttribute(
1915       "dependencyFile",
1916       this->CreateString(cmStrCat(depfilesDirectory, buildPhase->GetId(),
1917                                   ".$(CONFIGURATION).d")));
1918     // to avoid spurious errors during first build,  create empty dependency
1919     // files
1920     cmSystemTools::MakeDirectory(depfilesDirectory);
1921     for (std::string const& configName : this->CurrentConfigurationTypes) {
1922       auto file = cmStrCat(depfilesPrefix, configName, ".d");
1923       if (!cmSystemTools::FileExists(file)) {
1924         cmSystemTools::Touch(file, true);
1925       }
1926     }
1927   }
1928
1929   buildPhase->AddAttribute("buildActionMask",
1930                            this->CreateString("2147483647"));
1931   cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1932   buildPhase->AddAttribute("files", buildFiles);
1933   {
1934     std::string name;
1935     if (!allConfigOutputs.empty()) {
1936       name = cmStrCat("Generate ",
1937                       this->RelativeToBinary(*allConfigOutputs.begin()));
1938     } else {
1939       name = sf->GetLocation().GetName();
1940     }
1941     buildPhase->AddAttribute("name", this->CreateString(name));
1942   }
1943   buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
1944                            this->CreateString("0"));
1945   buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
1946   buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
1947   buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
1948
1949   bool symbolic = false;
1950   {
1951     cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
1952     for (std::string const& i : allConfigInputs) {
1953       inputPaths->AddUniqueObject(this->CreateString(i));
1954       if (!symbolic) {
1955         if (cmSourceFile* isf =
1956               gt->GetLocalGenerator()->GetMakefile()->GetSource(
1957                 i, cmSourceFileLocationKind::Known)) {
1958           symbolic = isf->GetPropertyAsBool("SYMBOLIC");
1959         }
1960       }
1961     }
1962     buildPhase->AddAttribute("inputPaths", inputPaths);
1963   }
1964   {
1965     cmXCodeObject* outputPaths =
1966       this->CreateObject(cmXCodeObject::OBJECT_LIST);
1967     for (std::string const& o : allConfigOutputs) {
1968       outputPaths->AddUniqueObject(this->CreateString(o));
1969       if (!symbolic) {
1970         if (cmSourceFile* osf =
1971               gt->GetLocalGenerator()->GetMakefile()->GetSource(
1972                 o, cmSourceFileLocationKind::Known)) {
1973           symbolic = osf->GetPropertyAsBool("SYMBOLIC");
1974         }
1975       }
1976     }
1977     buildPhase->AddAttribute("outputPaths", outputPaths);
1978   }
1979   if (symbolic) {
1980     buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
1981   }
1982
1983   return buildPhase;
1984 }
1985
1986 cmXCodeObject* cmGlobalXCodeGenerator::CreateRunScriptBuildPhase(
1987   std::string const& name, cmGeneratorTarget const* gt,
1988   std::vector<cmCustomCommand> const& commands)
1989 {
1990   if (commands.empty()) {
1991     return nullptr;
1992   }
1993
1994   std::set<std::string> allConfigOutputs;
1995
1996   std::string shellScript = "set -e\n";
1997   for (std::string const& configName : this->CurrentConfigurationTypes) {
1998     shellScript = cmStrCat(shellScript, R"(if test "$CONFIGURATION" = ")",
1999                            configName, "\"; then :\n");
2000     for (cmCustomCommand const& cc : commands) {
2001       cmCustomCommandGenerator ccg(cc, configName,
2002                                    this->CurrentLocalGenerator);
2003       shellScript = cmStrCat(shellScript, this->ConstructScript(ccg));
2004       allConfigOutputs.insert(ccg.GetByproducts().begin(),
2005                               ccg.GetByproducts().end());
2006     }
2007     shellScript = cmStrCat(shellScript, "fi\n");
2008   }
2009
2010   cmXCodeObject* buildPhase =
2011     this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase,
2012                        cmStrCat(gt->GetName(), ':', name));
2013   buildPhase->AddAttribute("buildActionMask",
2014                            this->CreateString("2147483647"));
2015   cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
2016   buildPhase->AddAttribute("files", buildFiles);
2017   buildPhase->AddAttribute("name", this->CreateString(name));
2018   buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
2019                            this->CreateString("0"));
2020   buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
2021   buildPhase->AddAttribute("shellScript", this->CreateString(shellScript));
2022   buildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
2023   {
2024     cmXCodeObject* outputPaths =
2025       this->CreateObject(cmXCodeObject::OBJECT_LIST);
2026     for (std::string const& o : allConfigOutputs) {
2027       outputPaths->AddUniqueObject(this->CreateString(o));
2028     }
2029     buildPhase->AddAttribute("outputPaths", outputPaths);
2030   }
2031   buildPhase->AddAttribute("alwaysOutOfDate", this->CreateString("1"));
2032
2033   return buildPhase;
2034 }
2035
2036 namespace {
2037 void ReplaceScriptVars(std::string& cmd)
2038 {
2039   cmSystemTools::ReplaceString(cmd, "$(CONFIGURATION)", "$CONFIGURATION");
2040   cmSystemTools::ReplaceString(cmd, "$(EFFECTIVE_PLATFORM_NAME)",
2041                                "$EFFECTIVE_PLATFORM_NAME");
2042 }
2043 }
2044
2045 std::string cmGlobalXCodeGenerator::ConstructScript(
2046   cmCustomCommandGenerator const& ccg)
2047 {
2048   std::string script;
2049   cmLocalGenerator* lg = this->CurrentLocalGenerator;
2050   std::string wd = ccg.GetWorkingDirectory();
2051   if (wd.empty()) {
2052     wd = lg->GetCurrentBinaryDirectory();
2053   }
2054   wd = lg->ConvertToOutputFormat(wd, cmOutputConverter::SHELL);
2055   ReplaceScriptVars(wd);
2056   script = cmStrCat(script, "  cd ", wd, "\n");
2057   for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
2058     std::string cmd = ccg.GetCommand(c);
2059     if (cmd.empty()) {
2060       continue;
2061     }
2062     cmSystemTools::ReplaceString(cmd, "/./", "/");
2063     cmd = lg->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
2064     ccg.AppendArguments(c, cmd);
2065     ReplaceScriptVars(cmd);
2066     script = cmStrCat(script, "  ", cmd, '\n');
2067   }
2068   return script;
2069 }
2070
2071 // This function removes each occurrence of the flag and returns the last one
2072 // (i.e., the dominant flag in GCC)
2073 std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag,
2074                                                 std::string& flags)
2075 {
2076   std::string retFlag;
2077   std::string::size_type lastOccurancePos = flags.rfind(flag);
2078   bool saved = false;
2079   while (lastOccurancePos != std::string::npos) {
2080     // increment pos, we use lastOccurancePos to reduce search space on next
2081     // inc
2082     std::string::size_type pos = lastOccurancePos;
2083     if (pos == 0 || flags[pos - 1] == ' ') {
2084       while (pos < flags.size() && flags[pos] != ' ') {
2085         if (!saved) {
2086           retFlag += flags[pos];
2087         }
2088         flags[pos] = ' ';
2089         pos++;
2090       }
2091       saved = true;
2092     }
2093     // decrement lastOccurancePos while making sure we don't loop around
2094     // and become a very large positive number since size_type is unsigned
2095     lastOccurancePos = lastOccurancePos == 0 ? 0 : lastOccurancePos - 1;
2096     lastOccurancePos = flags.rfind(flag, lastOccurancePos);
2097   }
2098   return retFlag;
2099 }
2100
2101 // This function removes each matching occurrence of the expression and
2102 // returns the last one (i.e., the dominant flag in GCC)
2103 std::string cmGlobalXCodeGenerator::ExtractFlagRegex(const char* exp,
2104                                                      int matchIndex,
2105                                                      std::string& flags)
2106 {
2107   std::string retFlag;
2108
2109   cmsys::RegularExpression regex(exp);
2110   assert(regex.is_valid());
2111   if (!regex.is_valid()) {
2112     return retFlag;
2113   }
2114
2115   std::string::size_type offset = 0;
2116
2117   while (regex.find(&flags[offset])) {
2118     const std::string::size_type startPos = offset + regex.start(matchIndex);
2119     const std::string::size_type endPos = offset + regex.end(matchIndex);
2120     const std::string::size_type size = endPos - startPos;
2121
2122     offset = startPos + 1;
2123
2124     retFlag.assign(flags, startPos, size);
2125     flags.replace(startPos, size, size, ' ');
2126   }
2127
2128   return retFlag;
2129 }
2130
2131 //----------------------------------------------------------------------------
2132 // This function strips off Xcode attributes that do not target the current
2133 // configuration
2134 void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
2135   std::string const& configName, std::string& attribute)
2136 {
2137   // Handle [variant=<config>] condition explicitly here.
2138   std::string::size_type beginVariant = attribute.find("[variant=");
2139   if (beginVariant == std::string::npos) {
2140     // There is no variant in this attribute.
2141     return;
2142   }
2143
2144   std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
2145   if (endVariant == std::string::npos) {
2146     // There is no terminating bracket.
2147     return;
2148   }
2149
2150   // Compare the variant to the configuration.
2151   std::string variant =
2152     attribute.substr(beginVariant + 9, endVariant - beginVariant - 9);
2153   if (variant == configName) {
2154     // The variant matches the configuration so use this
2155     // attribute but drop the [variant=<config>] condition.
2156     attribute.erase(beginVariant, endVariant - beginVariant + 1);
2157   } else {
2158     // The variant does not match the configuration so
2159     // do not use this attribute.
2160     attribute.clear();
2161   }
2162 }
2163
2164 void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
2165   cmXCodeObject* buildphase, cmGeneratorTarget* target,
2166   std::vector<cmCustomCommand> const& commands, const char* name)
2167 {
2168   std::string dir = cmStrCat(
2169     this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts");
2170   cmSystemTools::MakeDirectory(dir);
2171   std::string makefile =
2172     cmStrCat(dir, '/', target->GetName(), '_', name, ".make");
2173
2174   for (const auto& currentConfig : this->CurrentConfigurationTypes) {
2175     this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
2176                                     currentConfig);
2177   }
2178
2179   std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
2180   cdir = this->ConvertToRelativeForMake(cdir);
2181   std::string makecmd =
2182     cmStrCat("make -C ", cdir, " -f ",
2183              this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")),
2184              " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all");
2185   buildphase->AddAttribute("shellScript", this->CreateString(makecmd));
2186   buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
2187 }
2188
2189 void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
2190   const char* makefileBasename, cmGeneratorTarget* target,
2191   std::vector<cmCustomCommand> const& commands, const std::string& configName)
2192 {
2193   std::string makefileName = cmStrCat(makefileBasename, configName);
2194   cmGeneratedFileStream makefileStream(makefileName);
2195   if (!makefileStream) {
2196     return;
2197   }
2198   makefileStream.SetCopyIfDifferent(true);
2199   makefileStream << "# Generated by CMake, DO NOT EDIT\n";
2200   makefileStream << "# Custom rules for " << target->GetName() << "\n";
2201
2202   // disable the implicit rules
2203   makefileStream << ".SUFFIXES: "
2204                  << "\n";
2205
2206   // have all depend on all outputs
2207   makefileStream << "all: ";
2208   std::map<const cmCustomCommand*, std::string> tname;
2209   int count = 0;
2210   for (auto const& command : commands) {
2211     cmCustomCommandGenerator ccg(command, configName,
2212                                  this->CurrentLocalGenerator);
2213     if (ccg.GetNumberOfCommands() > 0) {
2214       const std::vector<std::string>& outputs = ccg.GetOutputs();
2215       if (!outputs.empty()) {
2216         for (auto const& output : outputs) {
2217           makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output);
2218         }
2219       } else {
2220         std::ostringstream str;
2221         str << "_buildpart_" << count++;
2222         tname[&ccg.GetCC()] = target->GetName() + str.str();
2223         makefileStream << "\\\n\t" << tname[&ccg.GetCC()];
2224       }
2225     }
2226   }
2227   makefileStream << "\n\n";
2228
2229   auto depfilesDirectory =
2230     cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
2231              "/CMakeFiles/d/");
2232
2233   for (auto const& command : commands) {
2234     cmCustomCommandGenerator ccg(
2235       command, configName, this->CurrentLocalGenerator, true, {},
2236       [this, &depfilesDirectory](const std::string& config,
2237                                  const std::string& file) -> std::string {
2238         return cmStrCat(
2239           depfilesDirectory,
2240           this->GetObjectId(cmXCodeObject::PBXShellScriptBuildPhase, file),
2241           ".", config, ".d");
2242       });
2243
2244     auto depfile = ccg.GetInternalDepfile();
2245     if (!depfile.empty()) {
2246       makefileStream << "include "
2247                      << cmSystemTools::ConvertToOutputPath(depfile) << "\n\n";
2248
2249       cmSystemTools::MakeDirectory(depfilesDirectory);
2250       if (!cmSystemTools::FileExists(depfile)) {
2251         cmSystemTools::Touch(depfile, true);
2252       }
2253     }
2254
2255     std::vector<std::string> realDepends;
2256     realDepends.reserve(ccg.GetDepends().size());
2257     for (auto const& d : ccg.GetDepends()) {
2258       std::string dep;
2259       if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) {
2260         realDepends.emplace_back(std::move(dep));
2261       }
2262     }
2263
2264     if (ccg.GetNumberOfCommands() > 0) {
2265       makefileStream << "\n";
2266       const std::vector<std::string>& outputs = ccg.GetOutputs();
2267       if (!outputs.empty()) {
2268         // There is at least one output, start the rule for it
2269         const char* sep = "";
2270         for (auto const& output : outputs) {
2271           makefileStream << sep << this->ConvertToRelativeForMake(output);
2272           sep = " ";
2273         }
2274         makefileStream << ": ";
2275       } else {
2276         // There are no outputs.  Use the generated force rule name.
2277         makefileStream << tname[&ccg.GetCC()] << ": ";
2278       }
2279       for (auto const& dep : realDepends) {
2280         makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep);
2281       }
2282       makefileStream << "\n";
2283
2284       if (const char* comment = ccg.GetComment()) {
2285         std::string echo_cmd =
2286           cmStrCat("echo ",
2287                    (this->CurrentLocalGenerator->EscapeForShell(
2288                      comment, ccg.GetCC().GetEscapeAllowMakeVars())));
2289         makefileStream << "\t" << echo_cmd << "\n";
2290       }
2291
2292       // Add each command line to the set of commands.
2293       for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
2294         // Build the command line in a single string.
2295         std::string cmd2 = ccg.GetCommand(c);
2296         cmSystemTools::ReplaceString(cmd2, "/./", "/");
2297         cmd2 = this->ConvertToRelativeForMake(cmd2);
2298         std::string cmd;
2299         std::string wd = ccg.GetWorkingDirectory();
2300         if (!wd.empty()) {
2301           cmd += "cd ";
2302           cmd += this->ConvertToRelativeForMake(wd);
2303           cmd += " && ";
2304         }
2305         cmd += cmd2;
2306         ccg.AppendArguments(c, cmd);
2307         makefileStream << "\t" << cmd << "\n";
2308       }
2309
2310       // Symbolic inputs are not expected to exist, so add dummy rules.
2311       for (auto const& dep : realDepends) {
2312         if (cmSourceFile* dsf =
2313               target->GetLocalGenerator()->GetMakefile()->GetSource(
2314                 dep, cmSourceFileLocationKind::Known)) {
2315           if (dsf->GetPropertyAsBool("SYMBOLIC")) {
2316             makefileStream << this->ConvertToRelativeForMake(dep) << ":\n";
2317           }
2318         }
2319       }
2320     }
2321   }
2322 }
2323
2324 void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute(
2325   cmGeneratorTarget* target, cmXCodeObject* buildSettings,
2326   const std::string& configName)
2327 {
2328   // For now, only EXECUTABLE is concerned
2329   if (target->GetType() != cmStateEnums::EXECUTABLE) {
2330     return;
2331   }
2332
2333   const char* PICValue = target->GetLinkPIEProperty(configName);
2334   if (PICValue == nullptr) {
2335     // POSITION_INDEPENDENT_CODE is not set
2336     return;
2337   }
2338
2339   buildSettings->AddAttribute(
2340     "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES"));
2341 }
2342
2343 void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
2344                                                  cmXCodeObject* buildSettings,
2345                                                  const std::string& configName)
2346 {
2347   if (!gtgt->IsInBuildSystem()) {
2348     return;
2349   }
2350
2351   std::string defFlags;
2352   bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
2353                  (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
2354   bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
2355                  (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
2356                  (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
2357
2358   // Compute the compilation flags for each language.
2359   std::set<std::string> languages;
2360   gtgt->GetLanguages(languages, configName);
2361   std::map<std::string, std::string> cflags;
2362   for (auto const& lang : languages) {
2363     std::string& flags = cflags[lang];
2364
2365     // Add language-specific flags.
2366     this->CurrentLocalGenerator->AddLanguageFlags(
2367       flags, gtgt, cmBuildStep::Compile, lang, configName);
2368
2369     if (gtgt->IsIPOEnabled(lang, configName)) {
2370       this->CurrentLocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
2371     }
2372
2373     // Add shared-library flags if needed.
2374     this->CurrentLocalGenerator->AddCMP0018Flags(flags, gtgt, lang,
2375                                                  configName);
2376
2377     this->CurrentLocalGenerator->AddVisibilityPresetFlags(flags, gtgt, lang);
2378
2379     this->CurrentLocalGenerator->AddCompileOptions(flags, gtgt, lang,
2380                                                    configName);
2381   }
2382
2383   std::string llang = gtgt->GetLinkerLanguage(configName);
2384   if (binary && llang.empty()) {
2385     cmSystemTools::Error(
2386       "CMake can not determine linker language for target: " +
2387       gtgt->GetName());
2388     return;
2389   }
2390
2391   // Choose a language to use for target-wide preprocessor definitions.
2392   static const char* ppLangs[] = { "CXX", "C", "OBJCXX", "OBJC" };
2393   std::string langForPreprocessorDefinitions;
2394   if (cm::contains(ppLangs, llang)) {
2395     langForPreprocessorDefinitions = llang;
2396   } else {
2397     for (const char* l : ppLangs) {
2398       if (languages.count(l)) {
2399         langForPreprocessorDefinitions = l;
2400         break;
2401       }
2402     }
2403   }
2404
2405   if (gtgt->IsIPOEnabled(llang, configName)) {
2406     const char* ltoValue =
2407       this->CurrentMakefile->IsOn("_CMAKE_LTO_THIN") ? "YES_THIN" : "YES";
2408     buildSettings->AddAttribute("LLVM_LTO", this->CreateString(ltoValue));
2409   }
2410
2411   // Handle PIE linker configuration
2412   this->AddPositionIndependentLinkAttribute(gtgt, buildSettings, configName);
2413
2414   // Add define flags
2415   this->CurrentLocalGenerator->AppendFlags(
2416     defFlags, this->CurrentMakefile->GetDefineFlags());
2417
2418   // Add preprocessor definitions for this target and configuration.
2419   BuildObjectListOrString ppDefs(this, true);
2420   this->AppendDefines(
2421     ppDefs, "CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"");
2422   if (const std::string* exportMacro = gtgt->GetExportMacro()) {
2423     // Add the export symbol definition for shared library objects.
2424     this->AppendDefines(ppDefs, exportMacro->c_str());
2425   }
2426   std::vector<std::string> targetDefines;
2427   if (!langForPreprocessorDefinitions.empty()) {
2428     gtgt->GetCompileDefinitions(targetDefines, configName,
2429                                 langForPreprocessorDefinitions);
2430   }
2431   this->AppendDefines(ppDefs, targetDefines);
2432   buildSettings->AddAttribute("GCC_PREPROCESSOR_DEFINITIONS",
2433                               ppDefs.CreateList());
2434   if (languages.count("Swift")) {
2435     // Swift uses a separate attribute for definitions.
2436     std::vector<std::string> targetSwiftDefines;
2437     gtgt->GetCompileDefinitions(targetSwiftDefines, configName, "Swift");
2438     // Remove the '=value' parts, as Swift does not support them.
2439     std::for_each(targetSwiftDefines.begin(), targetSwiftDefines.end(),
2440                   [](std::string& def) {
2441                     std::string::size_type pos = def.find('=');
2442                     if (pos != std::string::npos) {
2443                       def.erase(pos);
2444                     }
2445                   });
2446     if (this->XcodeVersion < 80) {
2447       std::string defineString;
2448       std::set<std::string> defines(targetSwiftDefines.begin(),
2449                                     targetSwiftDefines.end());
2450       this->CurrentLocalGenerator->JoinDefines(defines, defineString, "Swift");
2451       cflags["Swift"] += " " + defineString;
2452     } else {
2453       BuildObjectListOrString swiftDefs(this, true);
2454       this->AppendDefines(swiftDefs, targetSwiftDefines);
2455       buildSettings->AddAttribute("SWIFT_ACTIVE_COMPILATION_CONDITIONS",
2456                                   swiftDefs.CreateList());
2457     }
2458   }
2459
2460   std::string extraLinkOptionsVar;
2461   std::string extraLinkOptions;
2462   if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
2463     extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
2464   } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2465     extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
2466   } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
2467     extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
2468   }
2469   if (!extraLinkOptionsVar.empty()) {
2470     this->CurrentLocalGenerator->AddConfigVariableFlags(
2471       extraLinkOptions, extraLinkOptionsVar, configName);
2472   }
2473
2474   if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
2475       gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
2476     this->CurrentLocalGenerator->GetStaticLibraryFlags(
2477       extraLinkOptions, configName, llang, gtgt);
2478   } else {
2479     cmValue targetLinkFlags = gtgt->GetProperty("LINK_FLAGS");
2480     if (targetLinkFlags) {
2481       this->CurrentLocalGenerator->AppendFlags(extraLinkOptions,
2482                                                *targetLinkFlags);
2483     }
2484     if (!configName.empty()) {
2485       std::string linkFlagsVar =
2486         cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName));
2487       if (cmValue linkFlags = gtgt->GetProperty(linkFlagsVar)) {
2488         this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, *linkFlags);
2489       }
2490     }
2491     std::vector<std::string> opts;
2492     gtgt->GetLinkOptions(opts, configName, llang);
2493     // LINK_OPTIONS are escaped.
2494     this->CurrentLocalGenerator->AppendCompileOptions(extraLinkOptions, opts);
2495   }
2496
2497   // Set target-specific architectures.
2498   std::vector<std::string> archs;
2499   gtgt->GetAppleArchs(configName, archs);
2500
2501   if (!archs.empty()) {
2502     // Enable ARCHS attribute.
2503     buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("NO"));
2504
2505     // Store ARCHS value.
2506     if (archs.size() == 1) {
2507       buildSettings->AddAttribute("ARCHS", this->CreateString(archs[0]));
2508     } else {
2509       cmXCodeObject* archObjects =
2510         this->CreateObject(cmXCodeObject::OBJECT_LIST);
2511       for (auto& arch : archs) {
2512         archObjects->AddObject(this->CreateString(arch));
2513       }
2514       buildSettings->AddAttribute("ARCHS", archObjects);
2515     }
2516   }
2517
2518   // Get the product name components.
2519   std::string pnprefix;
2520   std::string pnbase;
2521   std::string pnsuffix;
2522   gtgt->GetFullNameComponents(pnprefix, pnbase, pnsuffix, configName);
2523
2524   cmValue version = gtgt->GetProperty("VERSION");
2525   cmValue soversion = gtgt->GetProperty("SOVERSION");
2526   if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
2527     version = nullptr;
2528     soversion = nullptr;
2529   }
2530   if (version && !soversion) {
2531     soversion = version;
2532   }
2533   if (!version && soversion) {
2534     version = soversion;
2535   }
2536
2537   std::string realName = pnbase;
2538   std::string soName = pnbase;
2539   if (version && soversion) {
2540     realName += ".";
2541     realName += *version;
2542     soName += ".";
2543     soName += *soversion;
2544   }
2545
2546   if (gtgt->CanCompileSources()) {
2547     std::string const tmpDir =
2548       this->GetTargetTempDir(gtgt, this->GetCMakeCFGIntDir());
2549     buildSettings->AddAttribute("TARGET_TEMP_DIR", this->CreateString(tmpDir));
2550
2551     std::string outDir;
2552     if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
2553       // We cannot suppress the archive, so hide it with intermediate files.
2554       outDir = tmpDir;
2555     } else {
2556       outDir = gtgt->GetDirectory(configName);
2557     }
2558     buildSettings->AddAttribute("CONFIGURATION_BUILD_DIR",
2559                                 this->CreateString(outDir));
2560   }
2561
2562   // Set attributes to specify the proper name for the target.
2563   std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
2564   if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
2565       gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
2566       gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
2567       gtgt->GetType() == cmStateEnums::EXECUTABLE) {
2568
2569     if (gtgt->IsFrameworkOnApple() || gtgt->IsCFBundleOnApple()) {
2570       pnprefix = "";
2571     }
2572
2573     buildSettings->AddAttribute("EXECUTABLE_PREFIX",
2574                                 this->CreateString(pnprefix));
2575     buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
2576                                 this->CreateString(pnsuffix));
2577   }
2578
2579   // Store the product name for all target types.
2580   buildSettings->AddAttribute("PRODUCT_NAME", this->CreateString(realName));
2581
2582   // Handle settings for each target type.
2583   switch (gtgt->GetType()) {
2584     case cmStateEnums::STATIC_LIBRARY:
2585       if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
2586         std::string fw_version = gtgt->GetFrameworkVersion();
2587         buildSettings->AddAttribute("FRAMEWORK_VERSION",
2588                                     this->CreateString(fw_version));
2589         cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2590         if (ext) {
2591           buildSettings->AddAttribute("WRAPPER_EXTENSION",
2592                                       this->CreateString(*ext));
2593         }
2594
2595         std::string plist = this->ComputeInfoPListLocation(gtgt);
2596         // Xcode will create the final version of Info.plist at build time,
2597         // so let it replace the framework name. This avoids creating
2598         // a per-configuration Info.plist file.
2599         this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
2600           gtgt, "$(EXECUTABLE_NAME)", plist);
2601         buildSettings->AddAttribute("INFOPLIST_FILE",
2602                                     this->CreateString(plist));
2603         buildSettings->AddAttribute("MACH_O_TYPE",
2604                                     this->CreateString("staticlib"));
2605       } else {
2606         buildSettings->AddAttribute("LIBRARY_STYLE",
2607                                     this->CreateString("STATIC"));
2608       }
2609       break;
2610
2611     case cmStateEnums::OBJECT_LIBRARY: {
2612       buildSettings->AddAttribute("LIBRARY_STYLE",
2613                                   this->CreateString("STATIC"));
2614       break;
2615     }
2616
2617     case cmStateEnums::MODULE_LIBRARY: {
2618       buildSettings->AddAttribute("LIBRARY_STYLE",
2619                                   this->CreateString("BUNDLE"));
2620       if (gtgt->IsCFBundleOnApple()) {
2621         // It turns out that a BUNDLE is basically the same
2622         // in many ways as an application bundle, as far as
2623         // link flags go
2624         std::string createFlags = this->LookupFlags(
2625           "CMAKE_SHARED_MODULE_CREATE_", llang, "_FLAGS", "-bundle");
2626         if (!createFlags.empty()) {
2627           extraLinkOptions += " ";
2628           extraLinkOptions += createFlags;
2629         }
2630         cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2631         if (ext) {
2632           buildSettings->AddAttribute("WRAPPER_EXTENSION",
2633                                       this->CreateString(*ext));
2634         }
2635         std::string plist = this->ComputeInfoPListLocation(gtgt);
2636         // Xcode will create the final version of Info.plist at build time,
2637         // so let it replace the cfbundle name. This avoids creating
2638         // a per-configuration Info.plist file. The cfbundle plist
2639         // is very similar to the application bundle plist
2640         this->CurrentLocalGenerator->GenerateAppleInfoPList(
2641           gtgt, "$(EXECUTABLE_NAME)", plist);
2642         buildSettings->AddAttribute("INFOPLIST_FILE",
2643                                     this->CreateString(plist));
2644       } else {
2645         buildSettings->AddAttribute("MACH_O_TYPE",
2646                                     this->CreateString("mh_bundle"));
2647         buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC",
2648                                     this->CreateString("NO"));
2649         // Add the flags to create an executable.
2650         std::string createFlags =
2651           this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
2652         if (!createFlags.empty()) {
2653           extraLinkOptions += " ";
2654           extraLinkOptions += createFlags;
2655         }
2656       }
2657       break;
2658     }
2659     case cmStateEnums::SHARED_LIBRARY: {
2660       if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
2661         std::string fw_version = gtgt->GetFrameworkVersion();
2662         buildSettings->AddAttribute("FRAMEWORK_VERSION",
2663                                     this->CreateString(fw_version));
2664         cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2665         if (ext) {
2666           buildSettings->AddAttribute("WRAPPER_EXTENSION",
2667                                       this->CreateString(*ext));
2668         }
2669
2670         std::string plist = this->ComputeInfoPListLocation(gtgt);
2671         // Xcode will create the final version of Info.plist at build time,
2672         // so let it replace the framework name. This avoids creating
2673         // a per-configuration Info.plist file.
2674         this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
2675           gtgt, "$(EXECUTABLE_NAME)", plist);
2676         buildSettings->AddAttribute("INFOPLIST_FILE",
2677                                     this->CreateString(plist));
2678       } else {
2679         // Add the flags to create a shared library.
2680         std::string createFlags = this->LookupFlags(
2681           "CMAKE_SHARED_LIBRARY_CREATE_", llang, "_FLAGS", "-dynamiclib");
2682         if (!createFlags.empty()) {
2683           extraLinkOptions += " ";
2684           extraLinkOptions += createFlags;
2685         }
2686       }
2687
2688       buildSettings->AddAttribute("LIBRARY_STYLE",
2689                                   this->CreateString("DYNAMIC"));
2690       break;
2691     }
2692     case cmStateEnums::EXECUTABLE: {
2693       // Add the flags to create an executable.
2694       std::string createFlags =
2695         this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
2696       if (!createFlags.empty()) {
2697         extraLinkOptions += " ";
2698         extraLinkOptions += createFlags;
2699       }
2700
2701       // Handle bundles and normal executables separately.
2702       if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
2703         cmValue ext = gtgt->GetProperty("BUNDLE_EXTENSION");
2704         if (ext) {
2705           buildSettings->AddAttribute("WRAPPER_EXTENSION",
2706                                       this->CreateString(*ext));
2707         }
2708         std::string plist = this->ComputeInfoPListLocation(gtgt);
2709         // Xcode will create the final version of Info.plist at build time,
2710         // so let it replace the executable name.  This avoids creating
2711         // a per-configuration Info.plist file.
2712         this->CurrentLocalGenerator->GenerateAppleInfoPList(
2713           gtgt, "$(EXECUTABLE_NAME)", plist);
2714         buildSettings->AddAttribute("INFOPLIST_FILE",
2715                                     this->CreateString(plist));
2716       }
2717     } break;
2718     default:
2719       break;
2720   }
2721
2722   BuildObjectListOrString dirs(this, true);
2723   BuildObjectListOrString fdirs(this, true);
2724   BuildObjectListOrString sysdirs(this, true);
2725   BuildObjectListOrString sysfdirs(this, true);
2726   const bool emitSystemIncludes = this->XcodeVersion >= 83;
2727
2728   // Choose a language to use for target-wide include directories.
2729   std::string const& langForIncludes = llang;
2730   std::vector<std::string> includes;
2731   if (!langForIncludes.empty()) {
2732     this->CurrentLocalGenerator->GetIncludeDirectories(
2733       includes, gtgt, langForIncludes, configName);
2734   }
2735   std::set<std::string> emitted;
2736   emitted.insert("/System/Library/Frameworks");
2737
2738   for (auto& include : includes) {
2739     if (this->NameResolvesToFramework(include)) {
2740       std::string frameworkDir = cmStrCat(include, "/../");
2741       frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
2742       if (emitted.insert(frameworkDir).second) {
2743         std::string incpath = this->XCodeEscapePath(frameworkDir);
2744         if (emitSystemIncludes &&
2745             gtgt->IsSystemIncludeDirectory(include, configName,
2746                                            langForIncludes)) {
2747           sysfdirs.Add(incpath);
2748         } else {
2749           fdirs.Add(incpath);
2750         }
2751       }
2752     } else {
2753       std::string incpath = this->XCodeEscapePath(include);
2754       if (emitSystemIncludes &&
2755           gtgt->IsSystemIncludeDirectory(include, configName,
2756                                          langForIncludes)) {
2757         sysdirs.Add(incpath);
2758       } else {
2759         dirs.Add(incpath);
2760       }
2761     }
2762   }
2763   // Add framework search paths needed for linking.
2764   if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
2765     for (auto const& fwDir : cli->GetFrameworkPaths()) {
2766       if (emitted.insert(fwDir).second) {
2767         std::string incpath = this->XCodeEscapePath(fwDir);
2768         if (emitSystemIncludes &&
2769             gtgt->IsSystemIncludeDirectory(fwDir, configName,
2770                                            langForIncludes)) {
2771           sysfdirs.Add(incpath);
2772         } else {
2773           fdirs.Add(incpath);
2774         }
2775       }
2776     }
2777   }
2778   if (!fdirs.IsEmpty()) {
2779     buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList());
2780   }
2781   if (!dirs.IsEmpty()) {
2782     buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
2783     if (languages.count("Swift")) {
2784       buildSettings->AddAttribute("SWIFT_INCLUDE_PATHS", dirs.CreateList());
2785     }
2786   }
2787   if (!sysfdirs.IsEmpty()) {
2788     buildSettings->AddAttribute("SYSTEM_FRAMEWORK_SEARCH_PATHS",
2789                                 sysfdirs.CreateList());
2790   }
2791   if (!sysdirs.IsEmpty()) {
2792     buildSettings->AddAttribute("SYSTEM_HEADER_SEARCH_PATHS",
2793                                 sysdirs.CreateList());
2794   }
2795
2796   if (this->XcodeVersion >= 60 && !emitSystemIncludes) {
2797     // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
2798     // system include directory awareness. We need to also keep on setting
2799     // HEADER_SEARCH_PATHS to work around a missing compile options flag for
2800     // GNU assembly files (#16449)
2801     for (auto const& language : languages) {
2802       std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
2803         includes, gtgt, language, configName);
2804
2805       if (!includeFlags.empty()) {
2806         cflags[language] += " " + includeFlags;
2807       }
2808     }
2809   }
2810
2811   bool same_gflags = true;
2812   std::map<std::string, std::string> gflags;
2813   std::string const* last_gflag = nullptr;
2814   std::string optLevel = "0";
2815
2816   // Minimal map of flags to build settings.
2817   for (auto const& language : languages) {
2818     std::string& flags = cflags[language];
2819     std::string& gflag = gflags[language];
2820     std::string oflag =
2821       this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
2822     if (oflag.size() == 2) {
2823       optLevel = "1";
2824     } else if (oflag.size() > 2) {
2825       optLevel = oflag.substr(2);
2826     }
2827     gflag = this->ExtractFlag("-g", flags);
2828     // put back gdwarf-2 if used since there is no way
2829     // to represent it in the gui, but we still want debug yes
2830     if (gflag == "-gdwarf-2") {
2831       flags += " ";
2832       flags += gflag;
2833     }
2834     if (last_gflag && *last_gflag != gflag) {
2835       same_gflags = false;
2836     }
2837     last_gflag = &gflag;
2838   }
2839
2840   const char* debugStr = "YES";
2841   if (!same_gflags) {
2842     // We can't set the Xcode flag differently depending on the language,
2843     // so put them back in this case.
2844     for (auto const& language : languages) {
2845       cflags[language] += " ";
2846       cflags[language] += gflags[language];
2847     }
2848     debugStr = "NO";
2849   } else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0")) {
2850     debugStr = "NO";
2851   }
2852
2853   // extract C++ stdlib
2854   for (auto const& language : languages) {
2855     if (language != "CXX" && language != "OBJCXX") {
2856       continue;
2857     }
2858     std::string& flags = cflags[language];
2859
2860     auto stdlib =
2861       this->ExtractFlagRegex("(^| )(-stdlib=[^ ]+)( |$)", 2, flags);
2862     if (stdlib.size() > 8) {
2863       const auto cxxLibrary = stdlib.substr(8);
2864       if (language == "CXX" ||
2865           !buildSettings->GetAttribute("CLANG_CXX_LIBRARY")) {
2866         buildSettings->AddAttribute("CLANG_CXX_LIBRARY",
2867                                     this->CreateString(cxxLibrary));
2868       }
2869     }
2870   }
2871
2872   buildSettings->AddAttribute("COMBINE_HIDPI_IMAGES",
2873                               this->CreateString("YES"));
2874   buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS",
2875                               this->CreateString(debugStr));
2876   buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL",
2877                               this->CreateString(optLevel));
2878   buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN",
2879                               this->CreateString("NO"));
2880   buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
2881                               this->CreateString("NO"));
2882
2883   for (auto const& language : languages) {
2884     std::string flags = cflags[language] + " " + defFlags;
2885     if (language == "CXX" || language == "OBJCXX") {
2886       if (language == "CXX" ||
2887           !buildSettings->GetAttribute("OTHER_CPLUSPLUSFLAGS")) {
2888         buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
2889                                     this->CreateString(flags));
2890       }
2891     } else if (language == "Fortran") {
2892       buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
2893                                   this->CreateString(flags));
2894     } else if (language == "C" || language == "OBJC") {
2895       if (language == "C" || !buildSettings->GetAttribute("OTHER_CFLAGS")) {
2896         buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
2897       }
2898     } else if (language == "Swift") {
2899       buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
2900                                   this->CreateString(flags));
2901     }
2902   }
2903
2904   // Add Fortran source format attribute if property is set.
2905   const char* format = nullptr;
2906   std::string const& tgtfmt = gtgt->GetSafeProperty("Fortran_FORMAT");
2907   switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
2908     case cmOutputConverter::FortranFormatFixed:
2909       format = "fixed";
2910       break;
2911     case cmOutputConverter::FortranFormatFree:
2912       format = "free";
2913       break;
2914     default:
2915       break;
2916   }
2917   if (format) {
2918     buildSettings->AddAttribute("IFORT_LANG_SRCFMT",
2919                                 this->CreateString(format));
2920   }
2921
2922   // Create the INSTALL_PATH attribute.
2923   std::string install_name_dir;
2924   if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2925     // Get the install_name directory for the build tree.
2926     install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
2927     // Xcode doesn't create the correct install_name in some cases.
2928     // That is, if the INSTALL_PATH is empty, or if we have versioning
2929     // of dylib libraries, we want to specify the install_name.
2930     // This is done by adding a link flag to create an install_name
2931     // with just the library soname.
2932     std::string install_name;
2933     if (!install_name_dir.empty()) {
2934       // Convert to a path for the native build tool.
2935       cmSystemTools::ConvertToUnixSlashes(install_name_dir);
2936       install_name += install_name_dir;
2937       install_name += "/";
2938     }
2939     install_name += gtgt->GetSOName(configName);
2940
2941     if ((realName != soName) || install_name_dir.empty()) {
2942       install_name_dir = "";
2943       extraLinkOptions += " -install_name ";
2944       extraLinkOptions += XCodeEscapePath(install_name);
2945     }
2946   }
2947   buildSettings->AddAttribute("INSTALL_PATH",
2948                               this->CreateString(install_name_dir));
2949
2950   // Create the LD_RUNPATH_SEARCH_PATHS
2951   cmComputeLinkInformation* pcli = gtgt->GetLinkInformation(configName);
2952   if (pcli) {
2953     std::string search_paths;
2954     std::vector<std::string> runtimeDirs;
2955     pcli->GetRPath(runtimeDirs, false);
2956     // runpath dirs needs to be unique to prevent corruption
2957     std::set<std::string> unique_dirs;
2958
2959     for (auto runpath : runtimeDirs) {
2960       runpath = this->ExpandCFGIntDir(runpath, configName);
2961
2962       if (unique_dirs.find(runpath) == unique_dirs.end()) {
2963         unique_dirs.insert(runpath);
2964         if (!search_paths.empty()) {
2965           search_paths += " ";
2966         }
2967         search_paths += this->XCodeEscapePath(runpath);
2968       }
2969     }
2970     if (!search_paths.empty()) {
2971       buildSettings->AddAttribute("LD_RUNPATH_SEARCH_PATHS",
2972                                   this->CreateString(search_paths));
2973     }
2974   }
2975
2976   buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(gtgt),
2977                               this->CreateString(extraLinkOptions));
2978   buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString(""));
2979   buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString(""));
2980   buildSettings->AddAttribute("USE_HEADERMAP", this->CreateString("NO"));
2981   cmXCodeObject* group = this->CreateObject(cmXCodeObject::OBJECT_LIST);
2982   group->AddObject(this->CreateString("$(inherited)"));
2983   buildSettings->AddAttribute("WARNING_CFLAGS", group);
2984
2985   // Runtime version information.
2986   if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
2987     int major;
2988     int minor;
2989     int patch;
2990
2991     // MACHO_CURRENT_VERSION or VERSION -> current_version
2992     gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major,
2993                                    minor, patch);
2994     std::ostringstream v;
2995
2996     // Xcode always wants at least 1.0.0 or nothing
2997     if (!(major == 0 && minor == 0 && patch == 0)) {
2998       v << major << "." << minor << "." << patch;
2999     }
3000     buildSettings->AddAttribute("DYLIB_CURRENT_VERSION",
3001                                 this->CreateString(v.str()));
3002
3003     // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version
3004     gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION",
3005                                    major, minor, patch);
3006     std::ostringstream vso;
3007
3008     // Xcode always wants at least 1.0.0 or nothing
3009     if (!(major == 0 && minor == 0 && patch == 0)) {
3010       vso << major << "." << minor << "." << patch;
3011     }
3012     buildSettings->AddAttribute("DYLIB_COMPATIBILITY_VERSION",
3013                                 this->CreateString(vso.str()));
3014   }
3015
3016   // Precompile Headers
3017   std::string pchHeader = gtgt->GetPchHeader(configName, llang);
3018   if (!pchHeader.empty()) {
3019     buildSettings->AddAttribute("GCC_PREFIX_HEADER",
3020                                 this->CreateString(pchHeader));
3021     buildSettings->AddAttribute("GCC_PRECOMPILE_PREFIX_HEADER",
3022                                 this->CreateString("YES"));
3023   }
3024
3025   // put this last so it can override existing settings
3026   // Convert "XCODE_ATTRIBUTE_*" properties directly.
3027   {
3028     for (auto const& prop : gtgt->GetPropertyKeys()) {
3029       if (cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
3030         std::string attribute = prop.substr(16);
3031         this->FilterConfigurationAttribute(configName, attribute);
3032         if (!attribute.empty()) {
3033           std::string const& pr = gtgt->GetSafeProperty(prop);
3034           std::string processed = cmGeneratorExpression::Evaluate(
3035             pr, this->CurrentLocalGenerator, configName);
3036           buildSettings->AddAttribute(attribute,
3037                                       this->CreateString(processed));
3038         }
3039       }
3040     }
3041   }
3042 }
3043
3044 cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
3045   cmGeneratorTarget* gtgt)
3046 {
3047   cmXCodeObject* shellBuildPhase = this->CreateObject(
3048     cmXCodeObject::PBXShellScriptBuildPhase, gtgt->GetName());
3049   shellBuildPhase->AddAttribute("buildActionMask",
3050                                 this->CreateString("2147483647"));
3051   cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3052   shellBuildPhase->AddAttribute("files", buildFiles);
3053   cmXCodeObject* inputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3054   shellBuildPhase->AddAttribute("inputPaths", inputPaths);
3055   cmXCodeObject* outputPaths = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3056   shellBuildPhase->AddAttribute("outputPaths", outputPaths);
3057   shellBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
3058                                 this->CreateString("0"));
3059   shellBuildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh"));
3060   shellBuildPhase->AddAttribute(
3061     "shellScript", this->CreateString("# shell script goes here\nexit 0"));
3062   shellBuildPhase->AddAttribute("showEnvVarsInLog", this->CreateString("0"));
3063
3064   cmXCodeObject* target =
3065     this->CreateObject(cmXCodeObject::PBXAggregateTarget);
3066   target->SetComment(gtgt->GetName());
3067   cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3068   std::vector<cmXCodeObject*> emptyContentVector;
3069   this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
3070                              emptyContentVector, nullptr, gtgt);
3071   target->AddAttribute("buildPhases", buildPhases);
3072   this->AddConfigurations(target, gtgt);
3073   cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3074   target->AddAttribute("dependencies", dependencies);
3075   target->AddAttribute("name", this->CreateString(gtgt->GetName()));
3076   target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
3077   target->SetTarget(gtgt);
3078   this->XCodeObjectMap[gtgt] = target;
3079
3080   // Add source files without build rules for editing convenience.
3081   if (gtgt->GetType() != cmStateEnums::GLOBAL_TARGET &&
3082       gtgt->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
3083     std::vector<cmSourceFile*> sources;
3084     if (!gtgt->GetConfigCommonSourceFilesForXcode(sources)) {
3085       return nullptr;
3086     }
3087
3088     // Add CMakeLists.txt file for user convenience.
3089     this->AddXCodeProjBuildRule(gtgt, sources);
3090
3091     for (auto sourceFile : sources) {
3092       if (!sourceFile->GetIsGenerated()) {
3093         this->CreateXCodeFileReference(sourceFile, gtgt);
3094       }
3095     }
3096   }
3097
3098   target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
3099
3100   return target;
3101 }
3102
3103 std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
3104                                                       cmGeneratorTarget* gtgt)
3105 {
3106   std::vector<std::string> const configVector = cmExpandedList(
3107     this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES"));
3108   cmXCodeObject* configlist =
3109     this->CreateObject(cmXCodeObject::XCConfigurationList);
3110   cmXCodeObject* buildConfigurations =
3111     this->CreateObject(cmXCodeObject::OBJECT_LIST);
3112   configlist->AddAttribute("buildConfigurations", buildConfigurations);
3113   std::string comment = cmStrCat("Build configuration list for ",
3114                                  cmXCodeObject::PBXTypeNames[target->GetIsA()],
3115                                  " \"", gtgt->GetName(), '"');
3116   configlist->SetComment(comment);
3117   target->AddAttribute("buildConfigurationList",
3118                        this->CreateObjectReference(configlist));
3119   for (auto const& i : configVector) {
3120     cmXCodeObject* config =
3121       this->CreateObject(cmXCodeObject::XCBuildConfiguration);
3122     buildConfigurations->AddObject(config);
3123     cmXCodeObject* buildSettings =
3124       this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
3125     this->CreateBuildSettings(gtgt, buildSettings, i);
3126     config->AddAttribute("name", this->CreateString(i));
3127     config->SetComment(i);
3128     config->AddAttribute("buildSettings", buildSettings);
3129
3130     this->CreateTargetXCConfigSettings(gtgt, config, i);
3131   }
3132   if (!configVector.empty()) {
3133     configlist->AddAttribute("defaultConfigurationName",
3134                              this->CreateString(configVector[0]));
3135     configlist->AddAttribute("defaultConfigurationIsVisible",
3136                              this->CreateString("0"));
3137     return configVector[0];
3138   }
3139   return "";
3140 }
3141
3142 void cmGlobalXCodeGenerator::CreateGlobalXCConfigSettings(
3143   cmLocalGenerator* root, cmXCodeObject* config, const std::string& configName)
3144 {
3145   auto xcconfig = cmGeneratorExpression::Evaluate(
3146     this->CurrentMakefile->GetSafeDefinition("CMAKE_XCODE_XCCONFIG"),
3147     this->CurrentLocalGenerator, configName);
3148   if (xcconfig.empty()) {
3149     return;
3150   }
3151
3152   auto sf = this->CurrentMakefile->GetSource(xcconfig);
3153   if (!sf) {
3154     cmSystemTools::Error(
3155       cmStrCat("sources for ALL_BUILD do not contain xcconfig file: '",
3156                xcconfig, "' (configuration: ", configName, ")"));
3157     return;
3158   }
3159
3160   cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
3161     sf->ResolveFullPath(), root->FindGeneratorTargetToUse("ALL_BUILD"), "",
3162     sf);
3163
3164   if (!fileRef) {
3165     // error is already reported by CreateXCodeFileReferenceFromPath
3166     return;
3167   }
3168
3169   config->AddAttribute("baseConfigurationReference",
3170                        this->CreateObjectReference(fileRef));
3171 }
3172
3173 void cmGlobalXCodeGenerator::CreateTargetXCConfigSettings(
3174   cmGeneratorTarget* target, cmXCodeObject* config,
3175   const std::string& configName)
3176 {
3177   auto xcconfig =
3178     cmGeneratorExpression::Evaluate(target->GetSafeProperty("XCODE_XCCONFIG"),
3179                                     this->CurrentLocalGenerator, configName);
3180   if (xcconfig.empty()) {
3181     return;
3182   }
3183
3184   auto sf = target->Makefile->GetSource(xcconfig);
3185   if (!sf) {
3186     cmSystemTools::Error(cmStrCat("target sources for target ",
3187                                   target->Target->GetName(),
3188                                   " do not contain xcconfig file: '", xcconfig,
3189                                   "' (configuration: ", configName, ")"));
3190     return;
3191   }
3192
3193   cmXCodeObject* fileRef = this->CreateXCodeFileReferenceFromPath(
3194     sf->ResolveFullPath(), target, "", sf);
3195   if (!fileRef) {
3196     // error is already reported by CreateXCodeFileReferenceFromPath
3197     return;
3198   }
3199   config->AddAttribute("baseConfigurationReference",
3200                        this->CreateObjectReference(fileRef));
3201 }
3202
3203 const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
3204   cmGeneratorTarget const* target) const
3205 {
3206   if (this->XcodeVersion >= 60 &&
3207       (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
3208        target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
3209     return "OTHER_LIBTOOLFLAGS";
3210   }
3211   return "OTHER_LDFLAGS";
3212 }
3213
3214 const char* cmGlobalXCodeGenerator::GetTargetFileType(
3215   cmGeneratorTarget* target)
3216 {
3217   if (cmValue e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
3218     return e->c_str();
3219   }
3220
3221   switch (target->GetType()) {
3222     case cmStateEnums::OBJECT_LIBRARY:
3223       return "archive.ar";
3224     case cmStateEnums::STATIC_LIBRARY:
3225       return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
3226                                                      : "archive.ar");
3227     case cmStateEnums::MODULE_LIBRARY:
3228       if (target->IsXCTestOnApple()) {
3229         return "wrapper.cfbundle";
3230       }
3231       if (target->IsCFBundleOnApple()) {
3232         return "wrapper.plug-in";
3233       }
3234       return "compiled.mach-o.executable";
3235     case cmStateEnums::SHARED_LIBRARY:
3236       return (target->GetPropertyAsBool("FRAMEWORK")
3237                 ? "wrapper.framework"
3238                 : "compiled.mach-o.dylib");
3239     case cmStateEnums::EXECUTABLE:
3240       return "compiled.mach-o.executable";
3241     default:
3242       break;
3243   }
3244   return nullptr;
3245 }
3246
3247 const char* cmGlobalXCodeGenerator::GetTargetProductType(
3248   cmGeneratorTarget* target)
3249 {
3250   if (cmValue e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
3251     return e->c_str();
3252   }
3253
3254   switch (target->GetType()) {
3255     case cmStateEnums::OBJECT_LIBRARY:
3256       return "com.apple.product-type.library.static";
3257     case cmStateEnums::STATIC_LIBRARY:
3258       return (target->GetPropertyAsBool("FRAMEWORK")
3259                 ? "com.apple.product-type.framework"
3260                 : "com.apple.product-type.library.static");
3261     case cmStateEnums::MODULE_LIBRARY:
3262       if (target->IsXCTestOnApple()) {
3263         return "com.apple.product-type.bundle.unit-test";
3264       } else if (target->IsCFBundleOnApple()) {
3265         return "com.apple.product-type.bundle";
3266       } else {
3267         return "com.apple.product-type.tool";
3268       }
3269     case cmStateEnums::SHARED_LIBRARY:
3270       return (target->GetPropertyAsBool("FRAMEWORK")
3271                 ? "com.apple.product-type.framework"
3272                 : "com.apple.product-type.library.dynamic");
3273     case cmStateEnums::EXECUTABLE:
3274       return (target->GetPropertyAsBool("MACOSX_BUNDLE")
3275                 ? "com.apple.product-type.application"
3276                 : "com.apple.product-type.tool");
3277     default:
3278       break;
3279   }
3280   return nullptr;
3281 }
3282
3283 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
3284   cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
3285 {
3286   if (!gtgt->IsInBuildSystem()) {
3287     return nullptr;
3288   }
3289   cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
3290   target->AddAttribute("buildPhases", buildPhases);
3291   cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3292   target->AddAttribute("buildRules", buildRules);
3293   std::string defConfig;
3294   defConfig = this->AddConfigurations(target, gtgt);
3295   cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3296   target->AddAttribute("dependencies", dependencies);
3297   target->AddAttribute("name", this->CreateString(gtgt->GetName()));
3298   target->AddAttribute("productName", this->CreateString(gtgt->GetName()));
3299
3300   cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
3301   if (const char* fileType = this->GetTargetFileType(gtgt)) {
3302     fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
3303   }
3304   std::string fullName;
3305   if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
3306     fullName = cmStrCat("lib", gtgt->GetName(), ".a");
3307   } else {
3308     fullName = gtgt->GetFullName(defConfig);
3309   }
3310   fileRef->AddAttribute("path", this->CreateString(fullName));
3311   fileRef->AddAttribute("sourceTree",
3312                         this->CreateString("BUILT_PRODUCTS_DIR"));
3313   fileRef->SetComment(gtgt->GetName());
3314   target->AddAttribute("productReference",
3315                        this->CreateObjectReference(fileRef));
3316   if (const char* productType = this->GetTargetProductType(gtgt)) {
3317     target->AddAttribute("productType", this->CreateString(productType));
3318   }
3319   target->SetTarget(gtgt);
3320   this->XCodeObjectMap[gtgt] = target;
3321   target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
3322   return target;
3323 }
3324
3325 cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
3326   cmGeneratorTarget const* t)
3327 {
3328   if (!t) {
3329     return nullptr;
3330   }
3331
3332   auto const i = this->XCodeObjectMap.find(t);
3333   if (i == this->XCodeObjectMap.end()) {
3334     return nullptr;
3335   }
3336   return i->second;
3337 }
3338
3339 std::string cmGlobalXCodeGenerator::GetObjectId(cmXCodeObject::PBXType ptype,
3340                                                 cm::string_view key)
3341 {
3342   std::string objectId;
3343   if (!key.empty()) {
3344     cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
3345     hash.Initialize();
3346     hash.Append(&ptype, sizeof(ptype));
3347     hash.Append(key);
3348     objectId = cmSystemTools::UpperCase(hash.FinalizeHex().substr(0, 24));
3349   } else {
3350     char cUuid[40] = { 0 };
3351     CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
3352     CFStringRef s = CFUUIDCreateString(kCFAllocatorDefault, uuid);
3353     CFStringGetCString(s, cUuid, sizeof(cUuid), kCFStringEncodingUTF8);
3354     objectId = cUuid;
3355     CFRelease(s);
3356     CFRelease(uuid);
3357     cmSystemTools::ReplaceString(objectId, "-", "");
3358     if (objectId.size() > 24) {
3359       objectId = objectId.substr(0, 24);
3360     }
3361   }
3362   return objectId;
3363 }
3364
3365 std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
3366                                                   const std::string& id)
3367 {
3368   std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
3369   cmValue storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName);
3370
3371   if (storedGUID) {
3372     return *storedGUID;
3373   }
3374
3375   this->CMakeInstance->AddCacheEntry(
3376     guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
3377
3378   return id;
3379 }
3380
3381 void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target,
3382                                              cmXCodeObject* dependTarget)
3383 {
3384   // This is called once for every edge in the target dependency graph.
3385   cmXCodeObject* container =
3386     this->CreateObject(cmXCodeObject::PBXContainerItemProxy);
3387   container->SetComment("PBXContainerItemProxy");
3388   container->AddAttribute("containerPortal",
3389                           this->CreateObjectReference(this->RootObject));
3390   container->AddAttribute("proxyType", this->CreateString("1"));
3391   container->AddAttribute("remoteGlobalIDString",
3392                           this->CreateObjectReference(dependTarget));
3393   container->AddAttribute(
3394     "remoteInfo", this->CreateString(dependTarget->GetTarget()->GetName()));
3395   cmXCodeObject* targetdep =
3396     this->CreateObject(cmXCodeObject::PBXTargetDependency);
3397   targetdep->SetComment("PBXTargetDependency");
3398   targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget));
3399   targetdep->AddAttribute("targetProxy",
3400                           this->CreateObjectReference(container));
3401
3402   cmXCodeObject* depends = target->GetAttribute("dependencies");
3403   if (!depends) {
3404     cmSystemTools::Error(
3405       "target does not have dependencies attribute error..");
3406
3407   } else {
3408     depends->AddUniqueObject(targetdep);
3409   }
3410 }
3411
3412 void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
3413                                                      const char* attribute,
3414                                                      cmXCodeObject* value)
3415 {
3416   if (settings) {
3417     cmXCodeObject* attr = settings->GetAttribute(attribute);
3418     if (!attr) {
3419       settings->AddAttribute(attribute, value);
3420     } else {
3421       this->AppendBuildSettingAttribute(settings, attribute, attr, value);
3422     }
3423   }
3424 }
3425
3426 void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
3427   cmXCodeObject* settings, const char* attribute, cmXCodeObject* attr,
3428   cmXCodeObject* value)
3429 {
3430   if (value->GetType() != cmXCodeObject::OBJECT_LIST &&
3431       value->GetType() != cmXCodeObject::STRING) {
3432     cmSystemTools::Error("Unsupported value type for appending: " +
3433                          std::string(attribute));
3434     return;
3435   }
3436   if (attr->GetType() == cmXCodeObject::OBJECT_LIST) {
3437     if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
3438       for (auto* obj : value->GetObjectList()) {
3439         attr->AddObject(obj);
3440       }
3441     } else {
3442       attr->AddObject(value);
3443     }
3444   } else if (attr->GetType() == cmXCodeObject::STRING) {
3445     if (value->GetType() == cmXCodeObject::OBJECT_LIST) {
3446       // Add old value as a list item to new object list
3447       // and replace the attribute with the new list
3448       value->PrependObject(attr);
3449       settings->AddAttribute(attribute, value);
3450     } else {
3451       std::string newValue =
3452         cmStrCat(attr->GetString(), ' ', value->GetString());
3453       attr->SetString(newValue);
3454     }
3455   } else {
3456     cmSystemTools::Error("Unsupported attribute type for appending: " +
3457                          std::string(attribute));
3458   }
3459 }
3460
3461 void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
3462   cmXCodeObject* target, const char* attribute, cmXCodeObject* value,
3463   const std::string& configName)
3464 {
3465   // There are multiple configurations.  Add the setting to the
3466   // buildSettings of the configuration name given.
3467   cmXCodeObject* configurationList =
3468     target->GetAttribute("buildConfigurationList")->GetObject();
3469   cmXCodeObject* buildConfigs =
3470     configurationList->GetAttribute("buildConfigurations");
3471   for (auto obj : buildConfigs->GetObjectList()) {
3472     if (configName.empty() ||
3473         obj->GetAttribute("name")->GetString() == configName) {
3474       cmXCodeObject* settings = obj->GetAttribute("buildSettings");
3475       this->AppendOrAddBuildSetting(settings, attribute, value);
3476     }
3477   }
3478 }
3479
3480 void cmGlobalXCodeGenerator::InheritBuildSettingAttribute(
3481   cmXCodeObject* target, const char* attribute)
3482 {
3483   cmXCodeObject* configurationList =
3484     target->GetAttribute("buildConfigurationList")->GetObject();
3485   cmXCodeObject* buildConfigs =
3486     configurationList->GetAttribute("buildConfigurations");
3487   for (auto obj : buildConfigs->GetObjectList()) {
3488     cmXCodeObject* settings = obj->GetAttribute("buildSettings");
3489     if (cmXCodeObject* attr = settings->GetAttribute(attribute)) {
3490       BuildObjectListOrString inherited(this, true);
3491       inherited.Add("$(inherited)");
3492       this->AppendBuildSettingAttribute(settings, attribute, attr,
3493                                         inherited.CreateList());
3494     }
3495   }
3496 }
3497
3498 void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
3499 {
3500   cmGeneratorTarget* gt = target->GetTarget();
3501   if (!gt) {
3502     cmSystemTools::Error("Error no target on xobject\n");
3503     return;
3504   }
3505   if (!gt->IsInBuildSystem()) {
3506     return;
3507   }
3508
3509   // Add dependencies on other CMake targets.
3510   for (const auto& dep : this->GetTargetDirectDepends(gt)) {
3511     if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
3512       this->AddDependTarget(target, dptarget);
3513     }
3514   }
3515
3516   // Separate libraries into ones that can be linked using "Link Binary With
3517   // Libraries" build phase and the ones that can't. Only targets that build
3518   // Apple bundles (.app, .framework, .bundle), executables and dylibs can use
3519   // this feature and only targets that represent actual libraries (object,
3520   // static, dynamic or bundle, excluding executables) will be used. These are
3521   // limitations imposed by CMake use-cases - otherwise a lot of things break.
3522   // The rest will be linked using linker flags (OTHER_LDFLAGS setting in Xcode
3523   // project).
3524   std::map<std::string, std::vector<cmComputeLinkInformation::Item const*>>
3525     configItemMap;
3526   auto addToLinkerArguments =
3527     [&configItemMap](const std::string& configName,
3528                      cmComputeLinkInformation::Item const* libItemPtr) {
3529       auto& linkVector = configItemMap[configName];
3530       if (std::find_if(linkVector.begin(), linkVector.end(),
3531                        [libItemPtr](cmComputeLinkInformation::Item const* p) {
3532                          return p == libItemPtr;
3533                        }) == linkVector.end()) {
3534         linkVector.push_back(libItemPtr);
3535       }
3536     };
3537   std::vector<cmComputeLinkInformation::Item const*> linkPhaseTargetVector;
3538   std::map<std::string, std::vector<std::string>> targetConfigMap;
3539   using ConfigItemPair =
3540     std::pair<std::string, cmComputeLinkInformation::Item const*>;
3541   std::map<std::string, std::vector<ConfigItemPair>> targetItemMap;
3542   std::map<std::string, std::vector<std::string>> targetProductNameMap;
3543   bool useLinkPhase = false;
3544   bool forceLinkPhase = false;
3545   cmValue prop =
3546     target->GetTarget()->GetProperty("XCODE_LINK_BUILD_PHASE_MODE");
3547   if (prop) {
3548     if (*prop == "BUILT_ONLY") {
3549       useLinkPhase = true;
3550     } else if (*prop == "KNOWN_LOCATION") {
3551       useLinkPhase = true;
3552       forceLinkPhase = true;
3553     } else if (*prop != "NONE") {
3554       cmSystemTools::Error("Invalid value for XCODE_LINK_BUILD_PHASE_MODE: " +
3555                            *prop);
3556       return;
3557     }
3558   }
3559   for (auto const& configName : this->CurrentConfigurationTypes) {
3560     cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
3561     if (!cli) {
3562       continue;
3563     }
3564     for (auto const& libItem : cli->GetItems()) {
3565       // We want to put only static libraries, dynamic libraries, frameworks
3566       // and bundles that are built from targets that are not imported in "Link
3567       // Binary With Libraries" build phase. Except if the target property
3568       // XCODE_LINK_BUILD_PHASE_MODE is KNOWN_LOCATION then all imported and
3569       // non-target libraries will be added as well.
3570       if (useLinkPhase &&
3571           (gt->GetType() == cmStateEnums::EXECUTABLE ||
3572            gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
3573            gt->GetType() == cmStateEnums::MODULE_LIBRARY) &&
3574           ((libItem.Target &&
3575             (!libItem.Target->IsImported() || forceLinkPhase) &&
3576             (libItem.Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
3577              libItem.Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
3578              libItem.Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
3579              libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) ||
3580            (!libItem.Target &&
3581             libItem.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
3582             forceLinkPhase))) {
3583         std::string libName;
3584         bool canUseLinkPhase = true;
3585         if (libItem.Target) {
3586           if (libItem.Target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
3587             canUseLinkPhase = canUseLinkPhase && forceLinkPhase;
3588           } else {
3589             // If a library target uses custom build output directory Xcode
3590             // won't pick it up so we have to resort back to linker flags, but
3591             // that's OK as long as the custom output dir is absolute path.
3592             for (auto const& libConfigName : this->CurrentConfigurationTypes) {
3593               canUseLinkPhase = canUseLinkPhase &&
3594                 libItem.Target->UsesDefaultOutputDir(
3595                   libConfigName, cmStateEnums::RuntimeBinaryArtifact);
3596             }
3597           }
3598           libName = libItem.Target->GetName();
3599         } else {
3600           libName = cmSystemTools::GetFilenameName(libItem.Value.Value);
3601           // We don't want all the possible files here, just standard libraries
3602           const auto libExt = cmSystemTools::GetFilenameExtension(libName);
3603           if (!IsLinkPhaseLibraryExtension(libExt)) {
3604             canUseLinkPhase = false;
3605           }
3606         }
3607         if (canUseLinkPhase) {
3608           // Add unique configuration name to target-config map for later
3609           // checks
3610           auto& configVector = targetConfigMap[libName];
3611           if (std::find(configVector.begin(), configVector.end(),
3612                         configName) == configVector.end()) {
3613             configVector.push_back(configName);
3614           }
3615           // Add a pair of config and item to target-item map
3616           auto& itemVector = targetItemMap[libName];
3617           itemVector.emplace_back(ConfigItemPair(configName, &libItem));
3618           // Add product file-name to a lib-product map
3619           auto productName =
3620             cmSystemTools::GetFilenameName(libItem.Value.Value);
3621           auto& productVector = targetProductNameMap[libName];
3622           if (std::find(productVector.begin(), productVector.end(),
3623                         productName) == productVector.end()) {
3624             productVector.push_back(productName);
3625           }
3626           continue;
3627         }
3628       }
3629       // Add this library item to a regular linker flag list
3630       addToLinkerArguments(configName, &libItem);
3631     }
3632   }
3633
3634   // Go through target library map and separate libraries that are linked
3635   // in all configurations and produce only single product, from the rest.
3636   // Only these will be linked through "Link Binary With Libraries" build
3637   // phase.
3638   for (auto const& targetLibConfigs : targetConfigMap) {
3639     // Add this library to "Link Binary With Libraries" build phase if it's
3640     // linked in all configurations and it has only one product name
3641     auto& itemVector = targetItemMap[targetLibConfigs.first];
3642     auto& productVector = targetProductNameMap[targetLibConfigs.first];
3643     if (targetLibConfigs.second == this->CurrentConfigurationTypes &&
3644         productVector.size() == 1) {
3645       // Add this library to "Link Binary With Libraries" list
3646       linkPhaseTargetVector.push_back(itemVector[0].second);
3647     } else {
3648       for (auto const& libItem : targetItemMap[targetLibConfigs.first]) {
3649         // Add this library item to a regular linker flag list
3650         addToLinkerArguments(libItem.first, libItem.second);
3651       }
3652     }
3653   }
3654
3655   // Add libraries to "Link Binary With Libraries" build phase and collect
3656   // their search paths. Xcode does not support per-configuration linking
3657   // in this build phase so we don't have to do this for each configuration
3658   // separately.
3659   std::vector<std::string> linkSearchPaths;
3660   std::vector<std::string> frameworkSearchPaths;
3661   for (auto const& libItem : linkPhaseTargetVector) {
3662     // Add target output directory as a library search path
3663     std::string linkDir;
3664     if (libItem->Target) {
3665       linkDir = libItem->Target->GetLocationForBuild();
3666     } else {
3667       linkDir = libItem->Value.Value;
3668     }
3669     if (cmHasSuffix(libItem->GetFeatureName(), "FRAMEWORK"_s)) {
3670       auto fwDescriptor = this->SplitFrameworkPath(
3671         linkDir, cmGlobalGenerator::FrameworkFormat::Extended);
3672       if (fwDescriptor && !fwDescriptor->Directory.empty()) {
3673         linkDir = fwDescriptor->Directory;
3674         if (std::find(frameworkSearchPaths.begin(), frameworkSearchPaths.end(),
3675                       linkDir) == frameworkSearchPaths.end()) {
3676           frameworkSearchPaths.push_back(linkDir);
3677         }
3678       }
3679     } else {
3680       linkDir = cmSystemTools::GetParentDirectory(linkDir);
3681       if (std::find(linkSearchPaths.begin(), linkSearchPaths.end(), linkDir) ==
3682           linkSearchPaths.end()) {
3683         linkSearchPaths.push_back(linkDir);
3684       }
3685     }
3686
3687     if (libItem->Target && !libItem->Target->IsImported()) {
3688       for (auto const& configName : this->CurrentConfigurationTypes) {
3689         target->AddDependTarget(configName, libItem->Target->GetName());
3690       }
3691     }
3692     // Get the library target
3693     auto* libTarget = FindXCodeTarget(libItem->Target);
3694     cmXCodeObject* buildFile;
3695     if (!libTarget) {
3696       if (libItem->IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
3697         // Get or create a direct file ref in the root project
3698         auto cleanPath = libItem->Value.Value;
3699         if (cmSystemTools::FileIsFullPath(cleanPath)) {
3700           // Some arguments are reported as paths, but they are actually not,
3701           // so we can't collapse them, and neither can we collapse relative
3702           // paths
3703           cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
3704         }
3705         auto it = this->ExternalLibRefs.find(cleanPath);
3706         if (it == this->ExternalLibRefs.end()) {
3707           buildFile = CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
3708           if (!buildFile) {
3709             // Add this library item back to a regular linker flag list
3710             for (const auto& conf : configItemMap) {
3711               addToLinkerArguments(conf.first, libItem);
3712             }
3713             continue;
3714           }
3715           this->ExternalLibRefs.emplace(cleanPath, buildFile);
3716         } else {
3717           buildFile = it->second;
3718         }
3719       } else {
3720         // Add this library item back to a regular linker flag list
3721         for (const auto& conf : configItemMap) {
3722           addToLinkerArguments(conf.first, libItem);
3723         }
3724         continue;
3725       }
3726     } else {
3727       // Add the target output file as a build reference for other targets
3728       // to link against
3729       auto* fileRefObject = libTarget->GetAttribute("productReference");
3730       if (!fileRefObject) {
3731         // Add this library item back to a regular linker flag list
3732         for (const auto& conf : configItemMap) {
3733           addToLinkerArguments(conf.first, libItem);
3734         }
3735         continue;
3736       }
3737       auto it = FileRefToBuildFileMap.find(fileRefObject);
3738       if (it == FileRefToBuildFileMap.end()) {
3739         buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
3740         buildFile->AddAttribute("fileRef", fileRefObject);
3741         FileRefToBuildFileMap[fileRefObject] = buildFile;
3742       } else {
3743         buildFile = it->second;
3744       }
3745     }
3746     // Add this reference to current target
3747     auto* buildPhases = target->GetAttribute("buildPhases");
3748     if (!buildPhases) {
3749       cmSystemTools::Error("Missing buildPhase of target");
3750       continue;
3751     }
3752     auto* frameworkBuildPhase =
3753       buildPhases->GetObject(cmXCodeObject::PBXFrameworksBuildPhase);
3754     if (!frameworkBuildPhase) {
3755       cmSystemTools::Error("Missing PBXFrameworksBuildPhase of buildPhase");
3756       continue;
3757     }
3758     auto* buildFiles = frameworkBuildPhase->GetAttribute("files");
3759     if (!buildFiles) {
3760       cmSystemTools::Error("Missing files of PBXFrameworksBuildPhase");
3761       continue;
3762     }
3763     if (buildFile && !buildFiles->HasObject(buildFile)) {
3764       buildFiles->AddObject(buildFile);
3765     }
3766   }
3767
3768   // Loop over configuration types and set per-configuration info.
3769   for (auto const& configName : this->CurrentConfigurationTypes) {
3770     {
3771       // Add object library contents as link flags.
3772       BuildObjectListOrString libSearchPaths(this, true);
3773       std::vector<cmSourceFile const*> objs;
3774       gt->GetExternalObjects(objs, configName);
3775       for (auto sourceFile : objs) {
3776         if (sourceFile->GetObjectLibrary().empty()) {
3777           continue;
3778         }
3779         libSearchPaths.Add(this->XCodeEscapePath(sourceFile->GetFullPath()));
3780       }
3781       this->AppendBuildSettingAttribute(
3782         target, this->GetTargetLinkFlagsVar(gt), libSearchPaths.CreateList(),
3783         configName);
3784     }
3785
3786     // Skip link information for object libraries.
3787     if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
3788         gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
3789       continue;
3790     }
3791
3792     // Compute the link library and directory information.
3793     cmComputeLinkInformation* cli = gt->GetLinkInformation(configName);
3794     if (!cli) {
3795       continue;
3796     }
3797
3798     // Add dependencies directly on library files.
3799     for (auto const& libDep : cli->GetDepends()) {
3800       target->AddDependLibrary(configName, libDep);
3801     }
3802
3803     // add the library search paths
3804     {
3805       BuildObjectListOrString libSearchPaths(this, true);
3806
3807       std::string linkDirs;
3808       for (auto const& libDir : cli->GetDirectories()) {
3809         if (!libDir.empty() && libDir != "/usr/lib") {
3810           cmPolicies::PolicyStatus cmp0142 =
3811             target->GetTarget()->GetPolicyStatusCMP0142();
3812           if (cmp0142 == cmPolicies::OLD || cmp0142 == cmPolicies::WARN) {
3813             libSearchPaths.Add(this->XCodeEscapePath(
3814               libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)"));
3815           }
3816           libSearchPaths.Add(this->XCodeEscapePath(libDir));
3817         }
3818       }
3819
3820       // Add previously collected paths where to look for libraries
3821       // that were added to "Link Binary With Libraries"
3822       for (auto& libDir : linkSearchPaths) {
3823         libSearchPaths.Add(this->XCodeEscapePath(libDir));
3824       }
3825       if (!libSearchPaths.IsEmpty()) {
3826         this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
3827                                           libSearchPaths.CreateList(),
3828                                           configName);
3829       }
3830     }
3831
3832     // add framework search paths
3833     {
3834       BuildObjectListOrString fwSearchPaths(this, true);
3835       // Add previously collected paths where to look for frameworks
3836       // that were added to "Link Binary With Libraries"
3837       for (auto& fwDir : frameworkSearchPaths) {
3838         fwSearchPaths.Add(this->XCodeEscapePath(fwDir));
3839       }
3840       if (!fwSearchPaths.IsEmpty()) {
3841         this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
3842                                           fwSearchPaths.CreateList(),
3843                                           configName);
3844       }
3845     }
3846
3847     // now add the left-over link libraries
3848     {
3849       // Keep track of framework search paths we've already added or that are
3850       // part of the set of implicit search paths. We don't want to repeat
3851       // them and we also need to avoid hard-coding any SDK-specific paths.
3852       // This is essential for getting device-and-simulator builds to work,
3853       // otherwise we end up hard-coding a path to the wrong SDK for
3854       // SDK-provided frameworks that are added by their full path.
3855       std::set<std::string> emitted(cli->GetFrameworkPathsEmitted());
3856       const auto& fwPaths = cli->GetFrameworkPaths();
3857       emitted.insert(fwPaths.begin(), fwPaths.end());
3858       BuildObjectListOrString libPaths(this, true);
3859       BuildObjectListOrString fwSearchPaths(this, true);
3860       for (auto const& libItem : configItemMap[configName]) {
3861         auto const& libName = *libItem;
3862         if (libName.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
3863           auto cleanPath = libName.Value.Value;
3864           if (cmSystemTools::FileIsFullPath(cleanPath)) {
3865             cleanPath = cmSystemTools::CollapseFullPath(cleanPath);
3866           }
3867           bool isFramework =
3868             cmHasSuffix(libName.GetFeatureName(), "FRAMEWORK"_s);
3869           if (isFramework) {
3870             const auto fwDescriptor = this->SplitFrameworkPath(
3871               cleanPath, cmGlobalGenerator::FrameworkFormat::Extended);
3872             if (!fwDescriptor->Directory.empty() &&
3873                 emitted.insert(fwDescriptor->Directory).second) {
3874               // This is a search path we had not added before and it isn't
3875               // an implicit search path, so we need it
3876               fwSearchPaths.Add(
3877                 this->XCodeEscapePath(fwDescriptor->Directory));
3878             }
3879             if (libName.GetFeatureName() == "__CMAKE_LINK_FRAMEWORK"_s) {
3880               // use the full path
3881               libPaths.Add(
3882                 libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
3883                   .Value);
3884             } else {
3885               libPaths.Add(libName
3886                              .GetFormattedItem(this->XCodeEscapePath(
3887                                fwDescriptor->GetLinkName()))
3888                              .Value);
3889             }
3890           } else {
3891             libPaths.Add(
3892               libName.GetFormattedItem(this->XCodeEscapePath(cleanPath))
3893                 .Value);
3894           }
3895           if ((!libName.Target || libName.Target->IsImported()) &&
3896               (isFramework || IsLinkPhaseLibraryExtension(cleanPath))) {
3897             // Create file reference for embedding
3898             auto it = this->ExternalLibRefs.find(cleanPath);
3899             if (it == this->ExternalLibRefs.end()) {
3900               auto* buildFile =
3901                 this->CreateXCodeBuildFileFromPath(cleanPath, gt, "", nullptr);
3902               if (buildFile) {
3903                 this->ExternalLibRefs.emplace(cleanPath, buildFile);
3904               }
3905             }
3906           }
3907         } else if (!libName.Target ||
3908                    libName.Target->GetType() !=
3909                      cmStateEnums::INTERFACE_LIBRARY) {
3910           libPaths.Add(libName.Value.Value);
3911         }
3912         if (libName.Target && !libName.Target->IsImported()) {
3913           target->AddDependTarget(configName, libName.Target->GetName());
3914         }
3915       }
3916       if (!libPaths.IsEmpty()) {
3917         this->AppendBuildSettingAttribute(target,
3918                                           this->GetTargetLinkFlagsVar(gt),
3919                                           libPaths.CreateList(), configName);
3920       }
3921       if (!fwSearchPaths.IsEmpty()) {
3922         this->AppendBuildSettingAttribute(target, "FRAMEWORK_SEARCH_PATHS",
3923                                           fwSearchPaths.CreateList(),
3924                                           configName);
3925       }
3926     }
3927   }
3928 }
3929
3930 void cmGlobalXCodeGenerator::AddEmbeddedObjects(
3931   cmXCodeObject* target, const std::string& copyFilesBuildPhaseName,
3932   const std::string& embedPropertyName, const std::string& dstSubfolderSpec,
3933   int actionsOnByDefault)
3934 {
3935   cmGeneratorTarget* gt = target->GetTarget();
3936   if (!gt) {
3937     cmSystemTools::Error("Error no target on xobject\n");
3938     return;
3939   }
3940   if (!gt->IsInBuildSystem()) {
3941     return;
3942   }
3943   bool isFrameworkTarget = gt->IsFrameworkOnApple();
3944   bool isBundleTarget = gt->GetPropertyAsBool("MACOSX_BUNDLE");
3945   bool isCFBundleTarget = gt->IsCFBundleOnApple();
3946   if (!(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
3947     return;
3948   }
3949   cmValue files = gt->GetProperty(embedPropertyName);
3950   if (!files) {
3951     return;
3952   }
3953
3954   // Create an "Embedded Frameworks" build phase
3955   auto* copyFilesBuildPhase =
3956     this->CreateObject(cmXCodeObject::PBXCopyFilesBuildPhase);
3957   copyFilesBuildPhase->SetComment(copyFilesBuildPhaseName);
3958   copyFilesBuildPhase->AddAttribute("buildActionMask",
3959                                     this->CreateString("2147483647"));
3960   copyFilesBuildPhase->AddAttribute("dstSubfolderSpec",
3961                                     this->CreateString(dstSubfolderSpec));
3962   copyFilesBuildPhase->AddAttribute(
3963     "name", this->CreateString(copyFilesBuildPhaseName));
3964   if (cmValue fwEmbedPath =
3965         gt->GetProperty(cmStrCat(embedPropertyName, "_PATH"))) {
3966     copyFilesBuildPhase->AddAttribute("dstPath",
3967                                       this->CreateString(*fwEmbedPath));
3968   } else {
3969     copyFilesBuildPhase->AddAttribute("dstPath", this->CreateString(""));
3970   }
3971   copyFilesBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
3972                                     this->CreateString("0"));
3973   cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
3974   // Collect all embedded frameworks and dylibs and add them to build phase
3975   std::vector<std::string> relFiles = cmExpandedList(*files);
3976   for (std::string const& relFile : relFiles) {
3977     cmXCodeObject* buildFile{ nullptr };
3978     std::string filePath = relFile;
3979     auto* genTarget = this->FindGeneratorTarget(relFile);
3980     if (genTarget) {
3981       // This is a target - get it's product path reference
3982       auto* xcTarget = this->FindXCodeTarget(genTarget);
3983       if (!xcTarget) {
3984         cmSystemTools::Error("Can not find a target for " +
3985                              genTarget->GetName());
3986         continue;
3987       }
3988       // Add the target output file as a build reference for other targets
3989       // to link against
3990       auto* fileRefObject = xcTarget->GetAttribute("productReference");
3991       if (!fileRefObject) {
3992         cmSystemTools::Error("Target " + genTarget->GetName() +
3993                              " is missing product reference");
3994         continue;
3995       }
3996       auto it = this->FileRefToEmbedBuildFileMap.find(fileRefObject);
3997       if (it == this->FileRefToEmbedBuildFileMap.end()) {
3998         buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
3999         buildFile->AddAttribute("fileRef", fileRefObject);
4000         this->FileRefToEmbedBuildFileMap[fileRefObject] = buildFile;
4001       } else {
4002         buildFile = it->second;
4003       }
4004     } else if (cmSystemTools::IsPathToFramework(relFile) ||
4005                cmSystemTools::IsPathToMacOSSharedLibrary(relFile)) {
4006       // This is a regular string path - create file reference
4007       auto it = this->EmbeddedLibRefs.find(relFile);
4008       if (it == this->EmbeddedLibRefs.end()) {
4009         cmXCodeObject* fileRef =
4010           this->CreateXCodeFileReferenceFromPath(relFile, gt, "", nullptr);
4011         if (fileRef) {
4012           buildFile = this->CreateObject(cmXCodeObject::PBXBuildFile);
4013           buildFile->SetComment(fileRef->GetComment());
4014           buildFile->AddAttribute("fileRef",
4015                                   this->CreateObjectReference(fileRef));
4016         }
4017         if (!buildFile) {
4018           cmSystemTools::Error("Can't create build file for " + relFile);
4019           continue;
4020         }
4021         this->EmbeddedLibRefs.emplace(filePath, buildFile);
4022       } else {
4023         buildFile = it->second;
4024       }
4025     }
4026     if (!buildFile) {
4027       cmSystemTools::Error("Can't find a build file for " + relFile);
4028       continue;
4029     }
4030     // Set build file configuration
4031     cmXCodeObject* settings =
4032       this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4033     cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4034
4035     bool removeHeaders = actionsOnByDefault & RemoveHeadersOnCopyByDefault;
4036     if (auto prop = gt->GetProperty(
4037           cmStrCat(embedPropertyName, "_REMOVE_HEADERS_ON_COPY"))) {
4038       removeHeaders = cmIsOn(*prop);
4039     }
4040     if (removeHeaders) {
4041       attrs->AddObject(this->CreateString("RemoveHeadersOnCopy"));
4042     }
4043
4044     bool codeSign = actionsOnByDefault & CodeSignOnCopyByDefault;
4045     if (auto prop =
4046           gt->GetProperty(cmStrCat(embedPropertyName, "_CODE_SIGN_ON_COPY"))) {
4047       codeSign = cmIsOn(*prop);
4048     }
4049     if (codeSign) {
4050       attrs->AddObject(this->CreateString("CodeSignOnCopy"));
4051     }
4052
4053     settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
4054     buildFile->AddAttributeIfNotEmpty("settings", settings);
4055     if (!buildFiles->HasObject(buildFile)) {
4056       buildFiles->AddObject(buildFile);
4057     }
4058   }
4059   copyFilesBuildPhase->AddAttribute("files", buildFiles);
4060   auto* buildPhases = target->GetAttribute("buildPhases");
4061   // Embed-something build phases must be inserted before the post-build
4062   // command because that command is expected to be last
4063   buildPhases->InsertObject(buildPhases->GetObjectCount() - 1,
4064                             copyFilesBuildPhase);
4065 }
4066
4067 void cmGlobalXCodeGenerator::AddEmbeddedFrameworks(cmXCodeObject* target)
4068 {
4069   static const auto dstSubfolderSpec = "10";
4070
4071   // Despite the name, by default Xcode uses "Embed Frameworks" build phase
4072   // for both frameworks and dynamic libraries
4073   this->AddEmbeddedObjects(target, "Embed Frameworks",
4074                            "XCODE_EMBED_FRAMEWORKS", dstSubfolderSpec,
4075                            NoActionOnCopyByDefault);
4076 }
4077
4078 void cmGlobalXCodeGenerator::AddEmbeddedPlugIns(cmXCodeObject* target)
4079 {
4080   static const auto dstSubfolderSpec = "13";
4081
4082   this->AddEmbeddedObjects(target, "Embed PlugIns", "XCODE_EMBED_PLUGINS",
4083                            dstSubfolderSpec, NoActionOnCopyByDefault);
4084 }
4085
4086 void cmGlobalXCodeGenerator::AddEmbeddedAppExtensions(cmXCodeObject* target)
4087 {
4088   static const auto dstSubfolderSpec = "13";
4089
4090   this->AddEmbeddedObjects(target, "Embed App Extensions",
4091                            "XCODE_EMBED_APP_EXTENSIONS", dstSubfolderSpec,
4092                            RemoveHeadersOnCopyByDefault);
4093 }
4094
4095 bool cmGlobalXCodeGenerator::CreateGroups(
4096   std::vector<cmLocalGenerator*>& generators)
4097 {
4098   for (auto& generator : generators) {
4099     cmMakefile* mf = generator->GetMakefile();
4100     std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
4101     for (const auto& gtgt : generator->GetGeneratorTargets()) {
4102       // Same skipping logic here as in CreateXCodeTargets so that we do not
4103       // end up with (empty anyhow) ZERO_CHECK, install, or test source
4104       // groups:
4105       //
4106       if (!gtgt->IsInBuildSystem() ||
4107           gtgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
4108           gtgt->GetName() == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
4109         continue;
4110       }
4111
4112       auto addSourceToGroup = [this, mf, &gtgt,
4113                                &sourceGroups](std::string const& source) {
4114         cmSourceGroup* sourceGroup = mf->FindSourceGroup(source, sourceGroups);
4115         cmXCodeObject* pbxgroup =
4116           this->CreateOrGetPBXGroup(gtgt.get(), sourceGroup);
4117         std::string key = GetGroupMapKeyFromPath(gtgt.get(), source);
4118         this->GroupMap[key] = pbxgroup;
4119       };
4120
4121       // Put cmSourceFile instances in proper groups:
4122       for (auto const& si : gtgt->GetAllConfigSources()) {
4123         cmSourceFile const* sf = si.Source;
4124         if (!sf->GetObjectLibrary().empty()) {
4125           // Object library files go on the link line instead.
4126           continue;
4127         }
4128         addSourceToGroup(sf->GetFullPath());
4129       }
4130
4131       // Add CMakeLists.txt file for user convenience.
4132       {
4133         std::string listfile =
4134           cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(),
4135                    "/CMakeLists.txt");
4136         cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
4137           listfile, false, cmSourceFileLocationKind::Known);
4138         addSourceToGroup(sf->ResolveFullPath());
4139       }
4140
4141       // Add the Info.plist we are about to generate for an App Bundle.
4142       if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
4143         std::string plist = this->ComputeInfoPListLocation(gtgt.get());
4144         cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(
4145           plist, true, cmSourceFileLocationKind::Known);
4146         addSourceToGroup(sf->ResolveFullPath());
4147       }
4148     }
4149   }
4150   return true;
4151 }
4152
4153 cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
4154                                                       const std::string& name)
4155 {
4156   cmXCodeObject* parentChildren = nullptr;
4157   if (parent) {
4158     parentChildren = parent->GetAttribute("children");
4159   }
4160   cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
4161   cmXCodeObject* groupChildren =
4162     this->CreateObject(cmXCodeObject::OBJECT_LIST);
4163   group->AddAttribute("name", this->CreateString(name));
4164   group->AddAttribute("children", groupChildren);
4165   group->AddAttribute("sourceTree", this->CreateString("<group>"));
4166   if (parentChildren) {
4167     parentChildren->AddObject(group);
4168   }
4169   return group;
4170 }
4171
4172 cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
4173   cmGeneratorTarget* gtgt, cmSourceGroup* sg)
4174 {
4175   std::string s;
4176   std::string target;
4177   const std::string targetFolder = gtgt->GetEffectiveFolderName();
4178   if (!targetFolder.empty()) {
4179     target = cmStrCat(targetFolder, '/');
4180   }
4181   target += gtgt->GetName();
4182   s = cmStrCat(target, '/', sg->GetFullName());
4183   auto it = this->GroupNameMap.find(s);
4184   if (it != this->GroupNameMap.end()) {
4185     return it->second;
4186   }
4187
4188   it = this->TargetGroup.find(target);
4189   cmXCodeObject* tgroup = nullptr;
4190   if (it != this->TargetGroup.end()) {
4191     tgroup = it->second;
4192   } else {
4193     std::vector<std::string> tgt_folders = cmTokenize(target, "/");
4194     std::string curr_tgt_folder;
4195     for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size();
4196          i++) {
4197       if (i != 0) {
4198         curr_tgt_folder += "/";
4199       }
4200       curr_tgt_folder += tgt_folders[i];
4201       it = this->TargetGroup.find(curr_tgt_folder);
4202       if (it != this->TargetGroup.end()) {
4203         tgroup = it->second;
4204         continue;
4205       }
4206       tgroup = this->CreatePBXGroup(tgroup, tgt_folders[i]);
4207       this->TargetGroup[curr_tgt_folder] = tgroup;
4208       if (i == 0) {
4209         this->MainGroupChildren->AddObject(tgroup);
4210       }
4211     }
4212   }
4213   this->TargetGroup[target] = tgroup;
4214
4215   // If it's the default source group (empty name) then put the source file
4216   // directly in the tgroup...
4217   //
4218   if (sg->GetFullName().empty()) {
4219     this->GroupNameMap[s] = tgroup;
4220     return tgroup;
4221   }
4222
4223   // It's a recursive folder structure, let's find the real parent group
4224   if (sg->GetFullName() != sg->GetName()) {
4225     std::string curr_folder = cmStrCat(target, '/');
4226     for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) {
4227       curr_folder += folder;
4228       auto const i_folder = this->GroupNameMap.find(curr_folder);
4229       // Create new folder
4230       if (i_folder == this->GroupNameMap.end()) {
4231         cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
4232         this->GroupNameMap[curr_folder] = group;
4233         tgroup = group;
4234       } else {
4235         tgroup = i_folder->second;
4236       }
4237       curr_folder += "\\";
4238     }
4239     return tgroup;
4240   }
4241   cmXCodeObject* group = this->CreatePBXGroup(tgroup, sg->GetName());
4242   this->GroupNameMap[s] = group;
4243   return group;
4244 }
4245
4246 bool cmGlobalXCodeGenerator::CreateXCodeObjects(
4247   cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
4248 {
4249   this->ClearXCodeObjects();
4250   this->RootObject = nullptr;
4251   this->MainGroupChildren = nullptr;
4252   this->FrameworkGroup = nullptr;
4253   cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4254   group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
4255   cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4256   for (const std::string& CurrentConfigurationType :
4257        this->CurrentConfigurationTypes) {
4258     cmXCodeObject* buildStyle =
4259       this->CreateObject(cmXCodeObject::PBXBuildStyle);
4260     const std::string& name = CurrentConfigurationType;
4261     buildStyle->AddAttribute("name", this->CreateString(name));
4262     buildStyle->SetComment(name);
4263     cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4264     sgroup->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
4265     buildStyle->AddAttribute("buildSettings", sgroup);
4266     listObjs->AddObject(buildStyle);
4267   }
4268
4269   cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4270   this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4271   mainGroup->AddAttribute("children", this->MainGroupChildren);
4272   mainGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
4273
4274   // now create the cmake groups
4275   if (!this->CreateGroups(generators)) {
4276     return false;
4277   }
4278
4279   cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4280   productGroup->AddAttribute("name", this->CreateString("Products"));
4281   productGroup->AddAttribute("sourceTree", this->CreateString("<group>"));
4282   cmXCodeObject* productGroupChildren =
4283     this->CreateObject(cmXCodeObject::OBJECT_LIST);
4284   productGroup->AddAttribute("children", productGroupChildren);
4285   this->MainGroupChildren->AddObject(productGroup);
4286
4287   this->FrameworkGroup = this->CreateObject(cmXCodeObject::PBXGroup);
4288   this->FrameworkGroup->AddAttribute("name", this->CreateString("Frameworks"));
4289   this->FrameworkGroup->AddAttribute("sourceTree",
4290                                      this->CreateString("<group>"));
4291   cmXCodeObject* frameworkGroupChildren =
4292     this->CreateObject(cmXCodeObject::OBJECT_LIST);
4293   this->FrameworkGroup->AddAttribute("children", frameworkGroupChildren);
4294   this->MainGroupChildren->AddObject(this->FrameworkGroup);
4295
4296   this->RootObject = this->CreateObject(cmXCodeObject::PBXProject);
4297   this->RootObject->SetComment("Project object");
4298
4299   std::string project_id = cmStrCat("PROJECT_", root->GetProjectName());
4300   this->RootObject->SetId(
4301     this->GetOrCreateId(project_id, this->RootObject->GetId()));
4302
4303   group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4304   this->RootObject->AddAttribute("mainGroup",
4305                                  this->CreateObjectReference(mainGroup));
4306   this->RootObject->AddAttribute("buildSettings", group);
4307   this->RootObject->AddAttribute("buildStyles", listObjs);
4308   this->RootObject->AddAttribute("hasScannedForEncodings",
4309                                  this->CreateString("0"));
4310   group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4311   group->AddAttribute("BuildIndependentTargetsInParallel",
4312                       this->CreateString("YES"));
4313   std::ostringstream v;
4314   v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
4315   group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
4316   this->RootObject->AddAttribute("attributes", group);
4317   this->RootObject->AddAttribute("compatibilityVersion",
4318                                  this->CreateString("Xcode 3.2"));
4319   // Point Xcode at the top of the source tree.
4320   {
4321     std::string pdir =
4322       this->RelativeToBinary(root->GetCurrentSourceDirectory());
4323     this->RootObject->AddAttribute("projectDirPath", this->CreateString(pdir));
4324     this->RootObject->AddAttribute("projectRoot", this->CreateString(""));
4325   }
4326   cmXCodeObject* configlist =
4327     this->CreateObject(cmXCodeObject::XCConfigurationList);
4328   cmXCodeObject* buildConfigurations =
4329     this->CreateObject(cmXCodeObject::OBJECT_LIST);
4330   using Configs = std::vector<std::pair<std::string, cmXCodeObject*>>;
4331   Configs configs;
4332   std::string defaultConfigName;
4333   for (const auto& name : this->CurrentConfigurationTypes) {
4334     if (defaultConfigName.empty()) {
4335       defaultConfigName = name;
4336     }
4337     cmXCodeObject* config =
4338       this->CreateObject(cmXCodeObject::XCBuildConfiguration);
4339     config->AddAttribute("name", this->CreateString(name));
4340     configs.push_back(std::make_pair(name, config));
4341   }
4342   if (defaultConfigName.empty()) {
4343     defaultConfigName = "Debug";
4344   }
4345   for (auto& config : configs) {
4346     buildConfigurations->AddObject(config.second);
4347   }
4348   configlist->AddAttribute("buildConfigurations", buildConfigurations);
4349
4350   std::string comment = cmStrCat("Build configuration list for PBXProject \"",
4351                                  this->CurrentProject, '"');
4352   configlist->SetComment(comment);
4353   configlist->AddAttribute("defaultConfigurationIsVisible",
4354                            this->CreateString("0"));
4355   configlist->AddAttribute("defaultConfigurationName",
4356                            this->CreateString(defaultConfigName));
4357   cmXCodeObject* buildSettings =
4358     this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
4359   cmValue sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT");
4360   cmValue deploymentTarget =
4361     this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
4362   if (sysroot) {
4363     buildSettings->AddAttribute("SDKROOT", this->CreateString(*sysroot));
4364   }
4365   // recompute this as it may have been changed since enable language
4366   this->ComputeArchitectures(this->CurrentMakefile);
4367   std::string const archs = cmJoin(this->Architectures, " ");
4368   if (archs.empty()) {
4369     // Tell Xcode to use NATIVE_ARCH instead of ARCHS.
4370     buildSettings->AddAttribute("ONLY_ACTIVE_ARCH", this->CreateString("YES"));
4371     // When targeting macOS, use only the host architecture.
4372     if (this->SystemName == "Darwin"_s &&
4373         (!cmNonempty(sysroot) ||
4374          cmSystemTools::LowerCase(*sysroot).find("macos") !=
4375            std::string::npos)) {
4376       buildSettings->AddAttribute("ARCHS",
4377                                   this->CreateString("$(NATIVE_ARCH_ACTUAL)"));
4378     }
4379   } else {
4380     // Tell Xcode to use ARCHS (ONLY_ACTIVE_ARCH defaults to NO).
4381     buildSettings->AddAttribute("ARCHS", this->CreateString(archs));
4382   }
4383   if (cmNonempty(deploymentTarget)) {
4384     buildSettings->AddAttribute(GetDeploymentPlatform(root->GetMakefile()),
4385                                 this->CreateString(*deploymentTarget));
4386   }
4387   if (!this->GeneratorToolset.empty()) {
4388     buildSettings->AddAttribute("GCC_VERSION",
4389                                 this->CreateString(this->GeneratorToolset));
4390   }
4391   if (this->GetLanguageEnabled("Swift")) {
4392     std::string swiftVersion;
4393     if (cmValue vers = this->CurrentMakefile->GetDefinition(
4394           "CMAKE_Swift_LANGUAGE_VERSION")) {
4395       swiftVersion = *vers;
4396     } else if (this->XcodeVersion >= 102) {
4397       swiftVersion = "4.0";
4398     } else if (this->XcodeVersion >= 83) {
4399       swiftVersion = "3.0";
4400     } else {
4401       swiftVersion = "2.3";
4402     }
4403     buildSettings->AddAttribute("SWIFT_VERSION",
4404                                 this->CreateString(swiftVersion));
4405   }
4406
4407   std::string const symroot = this->GetSymrootDir();
4408   buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
4409
4410   // Inside a try_compile project, do not require signing on any platform.
4411   if (this->CMakeInstance->GetIsInTryCompile()) {
4412     buildSettings->AddAttribute("CODE_SIGNING_ALLOWED",
4413                                 this->CreateString("NO"));
4414   }
4415
4416   for (auto& config : configs) {
4417     CreateGlobalXCConfigSettings(root, config.second, config.first);
4418
4419     cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
4420
4421     // Put this last so it can override existing settings
4422     // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly.
4423     for (const auto& var : this->CurrentMakefile->GetDefinitions()) {
4424       if (cmHasLiteralPrefix(var, "CMAKE_XCODE_ATTRIBUTE_")) {
4425         std::string attribute = var.substr(22);
4426         this->FilterConfigurationAttribute(config.first, attribute);
4427         if (!attribute.empty()) {
4428           std::string processed = cmGeneratorExpression::Evaluate(
4429             this->CurrentMakefile->GetSafeDefinition(var),
4430             this->CurrentLocalGenerator, config.first);
4431           buildSettingsForCfg->AddAttribute(attribute,
4432                                             this->CreateString(processed));
4433         }
4434       }
4435     }
4436     // store per-config buildSettings into configuration object
4437     config.second->AddAttribute("buildSettings", buildSettingsForCfg);
4438   }
4439
4440   this->RootObject->AddAttribute("buildConfigurationList",
4441                                  this->CreateObjectReference(configlist));
4442
4443   std::vector<cmXCodeObject*> targets;
4444   for (auto& generator : generators) {
4445     if (!this->CreateXCodeTargets(generator, targets)) {
4446       return false;
4447     }
4448     for (auto const& ccRoot : this->CustomCommandRoots) {
4449       if (ccRoot.second.size() > 1) {
4450         std::string e = "The custom command ";
4451         std::vector<std::string> const& outputs =
4452           ccRoot.first->GetCustomCommand()->GetOutputs();
4453         if (!outputs.empty()) {
4454           e = cmStrCat(e, "generating\n  ", outputs[0]);
4455         } else {
4456           e = cmStrCat(e, "driven by\n  ", ccRoot.first->GetFullPath());
4457         }
4458         e = cmStrCat(e, "\nis attached to multiple targets:");
4459         for (cmGeneratorTarget const* gt : ccRoot.second) {
4460           e = cmStrCat(e, "\n  ", gt->GetName());
4461         }
4462         e = cmStrCat(
4463           e,
4464           "\nbut none of these is a common dependency of the other(s).  "
4465           "This is not allowed by the Xcode \"new build system\".");
4466         generator->IssueMessage(MessageType::FATAL_ERROR, e);
4467         return false;
4468       }
4469     }
4470     this->CustomCommandRoots.clear();
4471   }
4472   // loop over all targets and add link and depend info
4473   for (auto t : targets) {
4474     this->AddDependAndLinkInformation(t);
4475     this->AddEmbeddedFrameworks(t);
4476     this->AddEmbeddedPlugIns(t);
4477     this->AddEmbeddedAppExtensions(t);
4478     // Inherit project-wide values for any target-specific search paths.
4479     this->InheritBuildSettingAttribute(t, "HEADER_SEARCH_PATHS");
4480     this->InheritBuildSettingAttribute(t, "SYSTEM_HEADER_SEARCH_PATHS");
4481     this->InheritBuildSettingAttribute(t, "FRAMEWORK_SEARCH_PATHS");
4482     this->InheritBuildSettingAttribute(t, "SYSTEM_FRAMEWORK_SEARCH_PATHS");
4483     this->InheritBuildSettingAttribute(t, "LIBRARY_SEARCH_PATHS");
4484     this->InheritBuildSettingAttribute(t, "LD_RUNPATH_SEARCH_PATHS");
4485     this->InheritBuildSettingAttribute(t, "GCC_PREPROCESSOR_DEFINITIONS");
4486     this->InheritBuildSettingAttribute(t, "OTHER_CFLAGS");
4487     this->InheritBuildSettingAttribute(t, "OTHER_LDFLAGS");
4488   }
4489
4490   if (this->XcodeBuildSystem == BuildSystem::One) {
4491     this->CreateXCodeDependHackMakefile(targets);
4492   }
4493   // now add all targets to the root object
4494   cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
4495   for (auto t : targets) {
4496     allTargets->AddObject(t);
4497     cmXCodeObject* productRef = t->GetAttribute("productReference");
4498     if (productRef) {
4499       productGroupChildren->AddObject(productRef->GetObject());
4500     }
4501   }
4502   this->RootObject->AddAttribute("targets", allTargets);
4503   return true;
4504 }
4505
4506 std::string cmGlobalXCodeGenerator::GetSymrootDir() const
4507 {
4508   return cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/build");
4509 }
4510
4511 std::string cmGlobalXCodeGenerator::GetTargetTempDir(
4512   cmGeneratorTarget const* gt, std::string const& configName) const
4513 {
4514   // Use a path inside the SYMROOT.
4515   return cmStrCat(this->GetSymrootDir(), '/', gt->GetName(), ".build/",
4516                   configName);
4517 }
4518
4519 void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf)
4520 {
4521   this->Architectures.clear();
4522   cmValue sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT");
4523   if (sysroot) {
4524     mf->GetDefExpandList("CMAKE_OSX_ARCHITECTURES", this->Architectures);
4525   }
4526
4527   if (this->Architectures.empty()) {
4528     mf->GetDefExpandList("_CMAKE_APPLE_ARCHS_DEFAULT", this->Architectures);
4529   }
4530
4531   if (this->Architectures.empty()) {
4532     // With no ARCHS we use ONLY_ACTIVE_ARCH and possibly a
4533     // platform-specific default ARCHS placeholder value.
4534     // Look up the arch that Xcode chooses in this case.
4535     if (cmValue arch = mf->GetDefinition("CMAKE_XCODE_ARCHS")) {
4536       this->ObjectDirArchDefault = *arch;
4537       // We expect only one arch but choose the first just in case.
4538       std::string::size_type pos = this->ObjectDirArchDefault.find(';');
4539       if (pos != std::string::npos) {
4540         this->ObjectDirArchDefault = this->ObjectDirArchDefault.substr(0, pos);
4541       }
4542     }
4543   }
4544
4545   this->ComputeObjectDirArch(mf);
4546 }
4547
4548 void cmGlobalXCodeGenerator::ComputeObjectDirArch(cmMakefile* mf)
4549 {
4550   if (this->Architectures.size() > 1 || this->UseEffectivePlatformName(mf)) {
4551     this->ObjectDirArch = "$(CURRENT_ARCH)";
4552   } else if (!this->Architectures.empty()) {
4553     this->ObjectDirArch = this->Architectures[0];
4554   } else {
4555     this->ObjectDirArch = this->ObjectDirArchDefault;
4556   }
4557 }
4558
4559 void cmGlobalXCodeGenerator::CreateXCodeDependHackMakefile(
4560   std::vector<cmXCodeObject*>& targets)
4561 {
4562   cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile);
4563   if (!makefileStream) {
4564     cmSystemTools::Error("Could not create " + this->CurrentXCodeHackMakefile);
4565     return;
4566   }
4567   makefileStream.SetCopyIfDifferent(true);
4568   // one more pass for external depend information not handled
4569   // correctly by xcode
4570   /* clang-format off */
4571   makefileStream << "# DO NOT EDIT\n";
4572   makefileStream << "# This makefile makes sure all linkable targets are\n";
4573   makefileStream << "# up-to-date with anything they link to\n"
4574     "default:\n"
4575     "\techo \"Do not invoke directly\"\n"
4576     "\n";
4577   /* clang-format on */
4578
4579   std::set<std::string> dummyRules;
4580
4581   // Write rules to help Xcode relink things at the right time.
4582   /* clang-format off */
4583   makefileStream <<
4584     "# Rules to remove targets that are older than anything to which they\n"
4585     "# link.  This forces Xcode to relink the targets from scratch.  It\n"
4586     "# does not seem to check these dependencies itself.\n";
4587   /* clang-format on */
4588   for (const auto& configName : this->CurrentConfigurationTypes) {
4589     for (auto target : targets) {
4590       cmGeneratorTarget* gt = target->GetTarget();
4591
4592       if (gt->GetType() == cmStateEnums::EXECUTABLE ||
4593           gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
4594           gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
4595           gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
4596           gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
4597         // Declare an entry point for the target post-build phase.
4598         makefileStream << this->PostBuildMakeTarget(gt->GetName(), configName)
4599                        << ":\n";
4600       }
4601
4602       if (gt->GetType() == cmStateEnums::EXECUTABLE ||
4603           gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
4604           gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
4605           gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
4606         std::string tfull = gt->GetFullPath(configName);
4607         std::string trel = this->ConvertToRelativeForMake(tfull);
4608
4609         // Add this target to the post-build phases of its dependencies.
4610         auto const y = target->GetDependTargets().find(configName);
4611         if (y != target->GetDependTargets().end()) {
4612           for (auto const& deptgt : y->second) {
4613             makefileStream << this->PostBuildMakeTarget(deptgt, configName)
4614                            << ": " << trel << "\n";
4615           }
4616         }
4617
4618         std::vector<cmGeneratorTarget*> objlibs;
4619         gt->GetObjectLibrariesCMP0026(objlibs);
4620         for (auto objLib : objlibs) {
4621           makefileStream << this->PostBuildMakeTarget(objLib->GetName(),
4622                                                       configName)
4623                          << ": " << trel << "\n";
4624         }
4625
4626         // Create a rule for this target.
4627         makefileStream << trel << ":";
4628
4629         // List dependencies if any exist.
4630         auto const x = target->GetDependLibraries().find(configName);
4631         if (x != target->GetDependLibraries().end()) {
4632           for (auto const& deplib : x->second) {
4633             std::string file = this->ConvertToRelativeForMake(deplib);
4634             makefileStream << "\\\n\t" << file;
4635             dummyRules.insert(file);
4636           }
4637         }
4638
4639         for (auto objLib : objlibs) {
4640
4641           const std::string objLibName = objLib->GetName();
4642           std::string d = cmStrCat(this->GetTargetTempDir(gt, configName),
4643                                    "/lib", objLibName, ".a");
4644
4645           std::string dependency = this->ConvertToRelativeForMake(d);
4646           makefileStream << "\\\n\t" << dependency;
4647           dummyRules.insert(dependency);
4648         }
4649
4650         // Write the action to remove the target if it is out of date.
4651         makefileStream << "\n";
4652         makefileStream << "\t/bin/rm -f "
4653                        << this->ConvertToRelativeForMake(tfull) << "\n";
4654         // if building for more than one architecture
4655         // then remove those executables as well
4656         if (this->Architectures.size() > 1) {
4657           std::string universal =
4658             cmStrCat(this->GetTargetTempDir(gt, configName), "/$(OBJDIR)/");
4659           for (const auto& architecture : this->Architectures) {
4660             std::string universalFile = cmStrCat(universal, architecture, '/',
4661                                                  gt->GetFullName(configName));
4662             makefileStream << "\t/bin/rm -f "
4663                            << this->ConvertToRelativeForMake(universalFile)
4664                            << "\n";
4665           }
4666         }
4667         makefileStream << "\n\n";
4668       }
4669     }
4670   }
4671
4672   makefileStream << "\n\n"
4673                  << "# For each target create a dummy rule"
4674                  << "so the target does not have to exist\n";
4675   for (auto const& dummyRule : dummyRules) {
4676     makefileStream << dummyRule << ":\n";
4677   }
4678 }
4679
4680 void cmGlobalXCodeGenerator::OutputXCodeProject(
4681   cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
4682 {
4683   if (generators.empty()) {
4684     return;
4685   }
4686   if (!this->CreateXCodeObjects(root, generators)) {
4687     return;
4688   }
4689   std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/',
4690                                   root->GetProjectName(), ".xcodeproj");
4691   cmSystemTools::MakeDirectory(xcodeDir);
4692   std::string xcodeProjFile = xcodeDir + "/project.pbxproj";
4693   cmGeneratedFileStream fout(xcodeProjFile);
4694   fout.SetCopyIfDifferent(true);
4695   if (!fout) {
4696     return;
4697   }
4698   this->WriteXCodePBXProj(fout, root, generators);
4699
4700   bool hasGeneratedSchemes = this->OutputXCodeSharedSchemes(xcodeDir, root);
4701   this->OutputXCodeWorkspaceSettings(xcodeDir, hasGeneratedSchemes);
4702
4703   this->ClearXCodeObjects();
4704
4705   // Since this call may have created new cache entries, save the cache:
4706   //
4707   root->GetMakefile()->GetCMakeInstance()->SaveCache(
4708     root->GetBinaryDirectory());
4709 }
4710
4711 bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
4712   const std::string& xcProjDir, cmLocalGenerator* root)
4713 {
4714   // collect all tests for the targets
4715   std::map<std::string, cmXCodeScheme::TestObjects> testables;
4716
4717   for (const auto& obj : this->XCodeObjects) {
4718     if (obj->GetType() != cmXCodeObject::OBJECT ||
4719         obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
4720       continue;
4721     }
4722
4723     if (!obj->GetTarget()->IsXCTestOnApple()) {
4724       continue;
4725     }
4726
4727     cmValue testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
4728     if (!testee) {
4729       continue;
4730     }
4731
4732     testables[*testee].push_back(obj.get());
4733   }
4734
4735   // generate scheme
4736   bool ret = false;
4737
4738   // Since the lowest available Xcode version for testing was 6.4,
4739   // I'm setting this as a limit then
4740   if (this->XcodeVersion >= 64) {
4741     for (const auto& obj : this->XCodeObjects) {
4742       if (obj->GetType() == cmXCodeObject::OBJECT &&
4743           (obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
4744            obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) &&
4745           (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() ||
4746            obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) {
4747         const std::string& targetName = obj->GetTarget()->GetName();
4748         cmXCodeScheme schm(root, obj.get(), testables[targetName],
4749                            this->CurrentConfigurationTypes,
4750                            this->XcodeVersion);
4751         schm.WriteXCodeSharedScheme(xcProjDir,
4752                                     this->RelativeToSource(xcProjDir));
4753         ret = true;
4754       }
4755     }
4756   }
4757
4758   return ret;
4759 }
4760
4761 void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings(
4762   const std::string& xcProjDir, bool hasGeneratedSchemes)
4763 {
4764   std::string xcodeSharedDataDir =
4765     cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata");
4766   cmSystemTools::MakeDirectory(xcodeSharedDataDir);
4767
4768   std::string workspaceSettingsFile =
4769     cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings");
4770
4771   cmGeneratedFileStream fout(workspaceSettingsFile);
4772   fout.SetCopyIfDifferent(true);
4773   if (!fout) {
4774     return;
4775   }
4776
4777   cmXMLWriter xout(fout);
4778   xout.StartDocument();
4779   xout.Doctype("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\""
4780                "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
4781   xout.StartElement("plist");
4782   xout.Attribute("version", "1.0");
4783   xout.StartElement("dict");
4784   if (this->XcodeVersion >= 100) {
4785     xout.Element("key", "BuildSystemType");
4786     switch (this->XcodeBuildSystem) {
4787       case BuildSystem::One:
4788         xout.Element("string", "Original");
4789         if (this->XcodeVersion >= 130) {
4790           xout.Element("key", "DisableBuildSystemDeprecationDiagnostic");
4791         } else {
4792           xout.Element("key", "DisableBuildSystemDeprecationWarning");
4793         }
4794         xout.Element("true");
4795         break;
4796       case BuildSystem::Twelve:
4797         xout.Element("string", "Latest");
4798         break;
4799     }
4800   }
4801   if (hasGeneratedSchemes) {
4802     xout.Element("key",
4803                  "IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded");
4804     xout.Element("false");
4805   }
4806   xout.EndElement(); // dict
4807   xout.EndElement(); // plist
4808   xout.EndDocument();
4809 }
4810
4811 void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
4812                                                cmLocalGenerator*,
4813                                                std::vector<cmLocalGenerator*>&)
4814 {
4815   SortXCodeObjects();
4816
4817   fout << "// !$*UTF8*$!\n";
4818   fout << "{\n";
4819   cmXCodeObject::Indent(1, fout);
4820   fout << "archiveVersion = 1;\n";
4821   cmXCodeObject::Indent(1, fout);
4822   fout << "classes = {\n";
4823   cmXCodeObject::Indent(1, fout);
4824   fout << "};\n";
4825   cmXCodeObject::Indent(1, fout);
4826   fout << "objectVersion = 46;\n";
4827   cmXCode21Object::PrintList(this->XCodeObjects, fout);
4828   cmXCodeObject::Indent(1, fout);
4829   fout << "rootObject = " << this->RootObject->GetId()
4830        << " /* Project object */;\n";
4831   fout << "}\n";
4832 }
4833
4834 const char* cmGlobalXCodeGenerator::GetCMakeCFGIntDir() const
4835 {
4836   return "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
4837 }
4838
4839 std::string cmGlobalXCodeGenerator::ExpandCFGIntDir(
4840   const std::string& str, const std::string& config) const
4841 {
4842   std::string replace1 = "$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
4843   std::string replace2 = "$(CONFIGURATION)";
4844
4845   std::string tmp = str;
4846   for (std::string::size_type i = tmp.find(replace1); i != std::string::npos;
4847        i = tmp.find(replace1, i)) {
4848     tmp.replace(i, replace1.size(), config);
4849     i += config.size();
4850   }
4851   for (std::string::size_type i = tmp.find(replace2); i != std::string::npos;
4852        i = tmp.find(replace2, i)) {
4853     tmp.replace(i, replace2.size(), config);
4854     i += config.size();
4855   }
4856   return tmp;
4857 }
4858
4859 void cmGlobalXCodeGenerator::GetDocumentation(cmDocumentationEntry& entry)
4860 {
4861   entry.Name = cmGlobalXCodeGenerator::GetActualName();
4862   entry.Brief = "Generate Xcode project files.";
4863 }
4864
4865 std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(
4866   std::string const& p)
4867 {
4868   return cmSystemTools::ConvertToOutputPath(p);
4869 }
4870
4871 std::string cmGlobalXCodeGenerator::RelativeToSource(const std::string& p)
4872 {
4873   std::string const& rootSrc =
4874     this->CurrentRootGenerator->GetCurrentSourceDirectory();
4875   if (cmSystemTools::IsSubDirectory(p, rootSrc)) {
4876     return cmSystemTools::ForceToRelativePath(rootSrc, p);
4877   }
4878   return p;
4879 }
4880
4881 std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p)
4882 {
4883   return this->CurrentRootGenerator->MaybeRelativeToCurBinDir(p);
4884 }
4885
4886 std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
4887 {
4888   if (p.find_first_of(" []") != std::string::npos) {
4889     std::string t = cmStrCat('"', p, '"');
4890     return t;
4891   }
4892   return p;
4893 }
4894
4895 void cmGlobalXCodeGenerator::AppendDirectoryForConfig(
4896   const std::string& prefix, const std::string& config,
4897   const std::string& suffix, std::string& dir)
4898 {
4899   if (!config.empty()) {
4900     dir += prefix;
4901     dir += config;
4902     dir += suffix;
4903   }
4904 }
4905
4906 std::string cmGlobalXCodeGenerator::LookupFlags(
4907   const std::string& varNamePrefix, const std::string& varNameLang,
4908   const std::string& varNameSuffix, const std::string& default_flags)
4909 {
4910   if (!varNameLang.empty()) {
4911     std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix);
4912     if (cmValue varValue = this->CurrentMakefile->GetDefinition(varName)) {
4913       if (!varValue->empty()) {
4914         return *varValue;
4915       }
4916     }
4917   }
4918   return default_flags;
4919 }
4920
4921 void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs,
4922                                            const char* defines_list,
4923                                            bool dflag)
4924 {
4925   // Skip this if there are no definitions.
4926   if (!defines_list) {
4927     return;
4928   }
4929
4930   // Expand the list of definitions.
4931   std::vector<std::string> defines = cmExpandedList(defines_list);
4932
4933   // Store the definitions in the string.
4934   this->AppendDefines(defs, defines, dflag);
4935 }
4936
4937 void cmGlobalXCodeGenerator::AppendDefines(
4938   BuildObjectListOrString& defs, std::vector<std::string> const& defines,
4939   bool dflag)
4940 {
4941   // GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
4942   std::string def;
4943   for (auto const& define : defines) {
4944     // Start with -D if requested.
4945     def = cmStrCat(dflag ? "-D" : "", define);
4946
4947     // Append the flag with needed escapes.
4948     std::string tmp;
4949     this->AppendFlag(tmp, def);
4950     defs.Add(tmp);
4951   }
4952 }
4953
4954 void cmGlobalXCodeGenerator::AppendFlag(std::string& flags,
4955                                         std::string const& flag) const
4956 {
4957   // Short-circuit for an empty flag.
4958   if (flag.empty()) {
4959     return;
4960   }
4961
4962   // Separate from previous flags.
4963   if (!flags.empty()) {
4964     flags += " ";
4965   }
4966
4967   // Check if the flag needs quoting.
4968   bool quoteFlag =
4969     flag.find_first_of("`~!@#$%^&*()+={}[]|:;\"'<>,.? ") != std::string::npos;
4970
4971   // We escape a flag as follows:
4972   //   - Place each flag in single quotes ''
4973   //   - Escape a single quote as \'
4974   //   - Escape a backslash as \\ since it itself is an escape
4975   // Note that in the code below we need one more level of escapes for
4976   // C string syntax in this source file.
4977   //
4978   // The final level of escaping is done when the string is stored
4979   // into the project file by cmXCodeObject::PrintString.
4980
4981   if (quoteFlag) {
4982     // Open single quote.
4983     flags += "'";
4984   }
4985
4986   // Flag value with escaped quotes and backslashes.
4987   for (auto c : flag) {
4988     if (c == '\'') {
4989       flags += "'\\''";
4990     } else if (c == '\\') {
4991       flags += "\\\\";
4992     } else {
4993       flags += c;
4994     }
4995   }
4996
4997   if (quoteFlag) {
4998     // Close single quote.
4999     flags += "'";
5000   }
5001 }
5002
5003 std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
5004   cmGeneratorTarget* target)
5005 {
5006   std::string plist =
5007     cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
5008              "/CMakeFiles/", target->GetName(), ".dir/Info.plist");
5009   return plist;
5010 }
5011
5012 // Return true if the generated build tree may contain multiple builds.
5013 // i.e. "Can I build Debug and Release in the same tree?"
5014 bool cmGlobalXCodeGenerator::IsMultiConfig() const
5015 {
5016   // Newer Xcode versions are multi config:
5017   return true;
5018 }
5019
5020 bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
5021   cmTarget const& target, std::string* reason) const
5022 {
5023   auto objectDirArch = GetTargetObjectDirArch(target, this->ObjectDirArch);
5024
5025   if (objectDirArch.find('$') != std::string::npos) {
5026     if (reason != nullptr) {
5027       *reason = " under Xcode with multiple architectures";
5028     }
5029     return false;
5030   }
5031   return true;
5032 }
5033
5034 bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
5035 {
5036   cmValue epnValue = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
5037     "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
5038
5039   if (!epnValue) {
5040     return mf->PlatformIsAppleEmbedded();
5041   }
5042
5043   return cmIsOn(*epnValue);
5044 }
5045
5046 bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const
5047 {
5048   // Xcode determines Resource location itself
5049   return true;
5050 }
5051
5052 void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
5053   cmGeneratorTarget* gt) const
5054 {
5055   auto objectDirArch = GetTargetObjectDirArch(*gt, this->ObjectDirArch);
5056   gt->ObjectDirectory =
5057     cmStrCat(this->GetTargetTempDir(gt, this->GetCMakeCFGIntDir()),
5058              "/$(OBJECT_FILE_DIR_normal:base)/", objectDirArch, '/');
5059 }
5060
5061 std::string cmGlobalXCodeGenerator::GetDeploymentPlatform(const cmMakefile* mf)
5062 {
5063   switch (mf->GetAppleSDKType()) {
5064     case cmMakefile::AppleSDK::AppleTVOS:
5065     case cmMakefile::AppleSDK::AppleTVSimulator:
5066       return "TVOS_DEPLOYMENT_TARGET";
5067
5068     case cmMakefile::AppleSDK::IPhoneOS:
5069     case cmMakefile::AppleSDK::IPhoneSimulator:
5070       return "IPHONEOS_DEPLOYMENT_TARGET";
5071
5072     case cmMakefile::AppleSDK::WatchOS:
5073     case cmMakefile::AppleSDK::WatchSimulator:
5074       return "WATCHOS_DEPLOYMENT_TARGET";
5075
5076     case cmMakefile::AppleSDK::MacOS:
5077     default:
5078       return "MACOSX_DEPLOYMENT_TARGET";
5079   }
5080 }