9f3d62033bb547409ff053977f7357dec843f4d5
[platform/upstream/cmake.git] / Source / cmVisualStudio10TargetGenerator.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 "cmVisualStudio10TargetGenerator.h"
4
5 #include <algorithm>
6 #include <cstdio>
7 #include <cstring>
8 #include <iterator>
9 #include <set>
10 #include <sstream>
11
12 #include <cm/memory>
13 #include <cm/optional>
14 #include <cm/string_view>
15 #include <cm/vector>
16 #include <cmext/algorithm>
17
18 #include "windows.h"
19
20 #include "cmsys/FStream.hxx"
21 #include "cmsys/RegularExpression.hxx"
22
23 #include "cmComputeLinkInformation.h"
24 #include "cmCustomCommand.h"
25 #include "cmCustomCommandGenerator.h"
26 #include "cmGeneratedFileStream.h"
27 #include "cmGeneratorExpression.h"
28 #include "cmGeneratorTarget.h"
29 #include "cmGlobalGenerator.h"
30 #include "cmGlobalVisualStudio10Generator.h"
31 #include "cmGlobalVisualStudio7Generator.h"
32 #include "cmGlobalVisualStudioGenerator.h"
33 #include "cmLinkLineDeviceComputer.h"
34 #include "cmListFileCache.h"
35 #include "cmLocalGenerator.h"
36 #include "cmLocalVisualStudio10Generator.h"
37 #include "cmLocalVisualStudio7Generator.h"
38 #include "cmLocalVisualStudioGenerator.h"
39 #include "cmMakefile.h"
40 #include "cmMessageType.h"
41 #include "cmPropertyMap.h"
42 #include "cmSourceFile.h"
43 #include "cmSourceFileLocation.h"
44 #include "cmSourceFileLocationKind.h"
45 #include "cmSourceGroup.h"
46 #include "cmStateTypes.h"
47 #include "cmStringAlgorithms.h"
48 #include "cmSystemTools.h"
49 #include "cmTarget.h"
50 #include "cmValue.h"
51 #include "cmVisualStudioGeneratorOptions.h"
52
53 struct cmIDEFlagTable;
54
55 static void ConvertToWindowsSlash(std::string& s);
56
57 static std::string cmVS10EscapeXML(std::string arg)
58 {
59   cmSystemTools::ReplaceString(arg, "&", "&amp;");
60   cmSystemTools::ReplaceString(arg, "<", "&lt;");
61   cmSystemTools::ReplaceString(arg, ">", "&gt;");
62   return arg;
63 }
64
65 static std::string cmVS10EscapeAttr(std::string arg)
66 {
67   cmSystemTools::ReplaceString(arg, "&", "&amp;");
68   cmSystemTools::ReplaceString(arg, "<", "&lt;");
69   cmSystemTools::ReplaceString(arg, ">", "&gt;");
70   cmSystemTools::ReplaceString(arg, "\"", "&quot;");
71   cmSystemTools::ReplaceString(arg, "\n", "&#10;");
72   return arg;
73 }
74
75 struct cmVisualStudio10TargetGenerator::Elem
76 {
77   std::ostream& S;
78   const int Indent;
79   bool HasElements = false;
80   bool HasContent = false;
81   std::string Tag;
82
83   Elem(std::ostream& s, const std::string& tag)
84     : S(s)
85     , Indent(0)
86     , Tag(tag)
87   {
88     this->StartElement();
89   }
90   Elem(const Elem&) = delete;
91   Elem(Elem& par, cm::string_view tag)
92     : S(par.S)
93     , Indent(par.Indent + 1)
94     , Tag(std::string(tag))
95   {
96     par.SetHasElements();
97     this->StartElement();
98   }
99   void SetHasElements()
100   {
101     if (!HasElements) {
102       this->S << ">";
103       HasElements = true;
104     }
105   }
106   std::ostream& WriteString(const char* line);
107   void StartElement() { this->WriteString("<") << this->Tag; }
108   void Element(cm::string_view tag, std::string val)
109   {
110     Elem(*this, tag).Content(std::move(val));
111   }
112   Elem& Attribute(const char* an, std::string av)
113   {
114     this->S << " " << an << "=\"" << cmVS10EscapeAttr(std::move(av)) << "\"";
115     return *this;
116   }
117   void Content(std::string val)
118   {
119     if (!this->HasContent) {
120       this->S << ">";
121       this->HasContent = true;
122     }
123     this->S << cmVS10EscapeXML(std::move(val));
124   }
125   ~Elem()
126   {
127     // Do not emit element which has not been started
128     if (Tag.empty()) {
129       return;
130     }
131
132     if (HasElements) {
133       this->WriteString("</") << this->Tag << ">";
134     } else if (HasContent) {
135       this->S << "</" << this->Tag << ">";
136     } else {
137       this->S << " />";
138     }
139   }
140
141   void WritePlatformConfigTag(const std::string& tag, const std::string& cond,
142                               const std::string& content);
143 };
144
145 class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions
146 {
147 public:
148   using Elem = cmVisualStudio10TargetGenerator::Elem;
149   cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
150                          cmVS7FlagTable const* table,
151                          cmVisualStudio10TargetGenerator* g = nullptr)
152     : cmVisualStudioGeneratorOptions(lg, tool, table)
153     , TargetGenerator(g)
154   {
155   }
156
157   void OutputFlag(std::ostream& /*fout*/, int /*indent*/,
158                   const std::string& tag, const std::string& content) override
159   {
160     if (!this->GetConfiguration().empty()) {
161       // if there are configuration specific flags, then
162       // use the configuration specific tag for PreprocessorDefinitions
163       const std::string cond =
164         this->TargetGenerator->CalcCondition(this->GetConfiguration());
165       this->Parent->WritePlatformConfigTag(tag, cond, content);
166     } else {
167       this->Parent->Element(tag, content);
168     }
169   }
170
171 private:
172   cmVisualStudio10TargetGenerator* const TargetGenerator;
173   Elem* Parent = nullptr;
174   friend cmVisualStudio10TargetGenerator::OptionsHelper;
175 };
176
177 struct cmVisualStudio10TargetGenerator::OptionsHelper
178 {
179   cmVS10GeneratorOptions& O;
180   OptionsHelper(cmVS10GeneratorOptions& o, Elem& e)
181     : O(o)
182   {
183     O.Parent = &e;
184   }
185   ~OptionsHelper() { O.Parent = nullptr; }
186
187   void OutputPreprocessorDefinitions(const std::string& lang)
188   {
189     O.OutputPreprocessorDefinitions(O.Parent->S, O.Parent->Indent + 1, lang);
190   }
191   void OutputAdditionalIncludeDirectories(const std::string& lang)
192   {
193     O.OutputAdditionalIncludeDirectories(O.Parent->S, O.Parent->Indent + 1,
194                                          lang);
195   }
196   void OutputFlagMap() { O.OutputFlagMap(O.Parent->S, O.Parent->Indent + 1); }
197   void PrependInheritedString(std::string const& key)
198   {
199     O.PrependInheritedString(key);
200   }
201 };
202
203 static std::string cmVS10EscapeComment(std::string comment)
204 {
205   // MSBuild takes the CDATA of a <Message></Message> element and just
206   // does "echo $CDATA" with no escapes.  We must encode the string.
207   // http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
208   std::string echoable;
209   for (char c : comment) {
210     switch (c) {
211       case '\r':
212         break;
213       case '\n':
214         echoable += '\t';
215         break;
216       case '"': /* no break */
217       case '|': /* no break */
218       case '&': /* no break */
219       case '<': /* no break */
220       case '>': /* no break */
221       case '^':
222         echoable += '^'; /* no break */
223         CM_FALLTHROUGH;
224       default:
225         echoable += c;
226         break;
227     }
228   }
229   return echoable;
230 }
231
232 static bool cmVS10IsTargetsFile(std::string const& path)
233 {
234   std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
235   return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
236 }
237
238 static VsProjectType computeProjectType(cmGeneratorTarget const* t)
239 {
240   if (t->IsCSharpOnly()) {
241     return VsProjectType::csproj;
242   }
243   return VsProjectType::vcxproj;
244 }
245
246 static std::string computeProjectFileExtension(VsProjectType projectType)
247 {
248   switch (projectType) {
249     case VsProjectType::csproj:
250       return ".csproj";
251     case VsProjectType::proj:
252       return ".proj";
253     default:
254       return ".vcxproj";
255   }
256 }
257
258 static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
259 {
260   return computeProjectFileExtension(computeProjectType(t));
261 }
262
263 cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
264   cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
265   : GeneratorTarget(target)
266   , Makefile(target->Target->GetMakefile())
267   , Platform(gg->GetPlatformName())
268   , Name(target->GetName())
269   , GUID(gg->GetGUID(this->Name))
270   , GlobalGenerator(gg)
271   , LocalGenerator(
272       (cmLocalVisualStudio10Generator*)target->GetLocalGenerator())
273 {
274   this->Configurations =
275     this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
276   this->NsightTegra = gg->IsNsightTegra();
277   this->Android = gg->TargetsAndroid();
278   for (int i = 0; i < 4; ++i) {
279     this->NsightTegraVersion[i] = 0;
280   }
281   sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
282          &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
283          &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
284   this->MSTools = !this->NsightTegra && !this->Android;
285   this->Managed = false;
286   this->TargetCompileAsWinRT = false;
287   this->IsMissingFiles = false;
288   this->DefaultArtifactDir =
289     this->LocalGenerator->GetCurrentBinaryDirectory() + "/" +
290     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
291   this->InSourceBuild = (this->Makefile->GetCurrentSourceDirectory() ==
292                          this->Makefile->GetCurrentBinaryDirectory());
293   this->ClassifyAllConfigSources();
294 }
295
296 cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
297 {
298 }
299
300 std::string cmVisualStudio10TargetGenerator::CalcCondition(
301   const std::string& config) const
302 {
303   std::ostringstream oss;
304   oss << "'$(Configuration)|$(Platform)'=='";
305   oss << config << "|" << this->Platform;
306   oss << "'";
307   // handle special case for 32 bit C# targets
308   if (this->ProjectType == VsProjectType::csproj &&
309       this->Platform == "Win32") {
310     oss << " Or ";
311     oss << "'$(Configuration)|$(Platform)'=='";
312     oss << config << "|x86";
313     oss << "'";
314   }
315   return oss.str();
316 }
317
318 void cmVisualStudio10TargetGenerator::Elem::WritePlatformConfigTag(
319   const std::string& tag, const std::string& cond, const std::string& content)
320 {
321   Elem(*this, tag).Attribute("Condition", cond).Content(content);
322 }
323
324 std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString(
325   const char* line)
326 {
327   this->S << '\n';
328   this->S.fill(' ');
329   this->S.width(this->Indent * 2);
330   // write an empty string to get the fill level indent to print
331   this->S << "";
332   this->S << line;
333   return this->S;
334 }
335
336 #define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
337 #define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
338 #define VS10_CXX_USER_PROPS                                                   \
339   "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
340 #define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
341
342 #define VS10_CSharp_DEFAULT_PROPS                                             \
343   "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
344 // This does not seem to exist by default, it's just provided for consistency
345 // in case users want to have default custom props for C# targets
346 #define VS10_CSharp_USER_PROPS                                                \
347   "$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
348 #define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
349
350 #define VS10_CSharp_NETCF_TARGETS                                             \
351   "$(MSBuildExtensionsPath)\\Microsoft\\$(TargetFrameworkIdentifier)\\"       \
352   "$(TargetFrameworkTargetsVersion)\\Microsoft.$(TargetFrameworkIdentifier)"  \
353   ".CSharp.targets"
354
355 void cmVisualStudio10TargetGenerator::Generate()
356 {
357   this->ProjectType = computeProjectType(this->GeneratorTarget);
358   this->Managed = this->ProjectType == VsProjectType::csproj;
359   const std::string ProjectFileExtension =
360     computeProjectFileExtension(this->ProjectType);
361
362   if (this->ProjectType == VsProjectType::csproj &&
363       this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
364     std::string message = "The C# target \"" +
365       this->GeneratorTarget->GetName() +
366       "\" is of type STATIC_LIBRARY. This is discouraged (and may be "
367       "disabled in future). Make it a SHARED library instead.";
368     this->Makefile->IssueMessage(MessageType::DEPRECATION_WARNING, message);
369   }
370
371   if (this->Android &&
372       this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
373       !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
374     this->GlobalGenerator->AddAndroidExecutableWarning(this->Name);
375   }
376
377   // Tell the global generator the name of the project file
378   this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
379                                              this->Name);
380   this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
381                                              ProjectFileExtension);
382   this->DotNetHintReferences.clear();
383   this->AdditionalUsingDirectories.clear();
384   if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
385     if (!this->ComputeClOptions()) {
386       return;
387     }
388     if (!this->ComputeRcOptions()) {
389       return;
390     }
391     if (!this->ComputeCudaOptions()) {
392       return;
393     }
394     if (!this->ComputeCudaLinkOptions()) {
395       return;
396     }
397     if (!this->ComputeMasmOptions()) {
398       return;
399     }
400     if (!this->ComputeNasmOptions()) {
401       return;
402     }
403     if (!this->ComputeLinkOptions()) {
404       return;
405     }
406     if (!this->ComputeLibOptions()) {
407       return;
408     }
409   }
410   std::string path =
411     cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
412              this->Name, ProjectFileExtension);
413   cmGeneratedFileStream BuildFileStream(path);
414   const std::string PathToProjectFile = path;
415   BuildFileStream.SetCopyIfDifferent(true);
416
417   // Write the encoding header into the file
418   char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
419   BuildFileStream.write(magic, 3);
420
421   if (this->ProjectType == VsProjectType::csproj &&
422       this->GeneratorTarget->IsDotNetSdkTarget() &&
423       this->GlobalGenerator->GetVersion() >=
424         cmGlobalVisualStudioGenerator::VSVersion::VS16) {
425     this->WriteSdkStyleProjectFile(BuildFileStream);
426   } else {
427     this->WriteClassicMsBuildProjectFile(BuildFileStream);
428   }
429
430   if (BuildFileStream.Close()) {
431     this->GlobalGenerator->FileReplacedDuringGenerate(PathToProjectFile);
432   }
433
434   // The groups are stored in a separate file for VS 10
435   this->WriteGroups();
436
437   // Update cache with project-specific entries.
438   this->UpdateCache();
439 }
440
441 void cmVisualStudio10TargetGenerator::WriteClassicMsBuildProjectFile(
442   cmGeneratedFileStream& BuildFileStream)
443 {
444   BuildFileStream << "<?xml version=\"1.0\" encoding=\""
445                   << this->GlobalGenerator->Encoding() << "\"?>";
446   {
447     Elem e0(BuildFileStream, "Project");
448     e0.Attribute("DefaultTargets", "Build");
449     const char* toolsVersion = this->GlobalGenerator->GetToolsVersion();
450     if (this->GlobalGenerator->GetVersion() ==
451           cmGlobalVisualStudioGenerator::VSVersion::VS12 &&
452         this->GlobalGenerator->TargetsWindowsCE()) {
453       toolsVersion = "4.0";
454     }
455     e0.Attribute("ToolsVersion", toolsVersion);
456     e0.Attribute("xmlns",
457                  "http://schemas.microsoft.com/developer/msbuild/2003");
458
459     if (this->NsightTegra) {
460       Elem e1(e0, "PropertyGroup");
461       e1.Attribute("Label", "NsightTegraProject");
462       const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0];
463       const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1];
464       if (nsightTegraMajorVersion >= 2) {
465         if (nsightTegraMajorVersion > 3 ||
466             (nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
467           e1.Element("NsightTegraProjectRevisionNumber", "11");
468         } else {
469           // Nsight Tegra 2.0 uses project revision 9.
470           e1.Element("NsightTegraProjectRevisionNumber", "9");
471         }
472         // Tell newer versions to upgrade silently when loading.
473         e1.Element("NsightTegraUpgradeOnceWithoutPrompt", "true");
474       } else {
475         // Require Nsight Tegra 1.6 for JCompile support.
476         e1.Element("NsightTegraProjectRevisionNumber", "7");
477       }
478     }
479
480     if (const char* hostArch =
481           this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
482       Elem e1(e0, "PropertyGroup");
483       e1.Element("PreferredToolArchitecture", hostArch);
484     }
485
486     // ALL_BUILD and ZERO_CHECK projects transitively include
487     // Microsoft.Common.CurrentVersion.targets which triggers Target
488     // ResolveNugetPackageAssets when SDK-style targets are in the project.
489     // However, these projects have no nuget packages to reference and the
490     // build fails.
491     // Setting ResolveNugetPackages to false skips this target and the build
492     // succeeds.
493     cm::string_view targetName{ this->GeneratorTarget->GetName() };
494     if (targetName == "ALL_BUILD" ||
495         targetName == CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
496       Elem e1(e0, "PropertyGroup");
497       e1.Element("ResolveNugetPackages", "false");
498     }
499
500     if (this->ProjectType != VsProjectType::csproj) {
501       this->WriteProjectConfigurations(e0);
502     }
503
504     {
505       Elem e1(e0, "PropertyGroup");
506       this->WriteCommonPropertyGroupGlobals(e1);
507
508       if ((this->MSTools || this->Android) &&
509           this->GeneratorTarget->IsInBuildSystem()) {
510         this->WriteApplicationTypeSettings(e1);
511         this->VerifyNecessaryFiles();
512       }
513
514       cmValue vsProjectName =
515         this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
516       cmValue vsLocalPath =
517         this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
518       cmValue vsProvider =
519         this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
520
521       if (vsProjectName && vsLocalPath && vsProvider) {
522         e1.Element("SccProjectName", *vsProjectName);
523         e1.Element("SccLocalPath", *vsLocalPath);
524         e1.Element("SccProvider", *vsProvider);
525
526         cmValue vsAuxPath =
527           this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
528         if (vsAuxPath) {
529           e1.Element("SccAuxPath", *vsAuxPath);
530         }
531       }
532
533       if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
534         e1.Element("WinMDAssembly", "true");
535       }
536
537       e1.Element("Platform", this->Platform);
538       cmValue projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
539       e1.Element("ProjectName", projLabel ? projLabel : this->Name);
540       {
541         cm::optional<std::string> targetFramework;
542         cm::optional<std::string> targetFrameworkVersion;
543         cm::optional<std::string> targetFrameworkIdentifier;
544         cm::optional<std::string> targetFrameworkTargetsVersion;
545         if (cmValue tf =
546               this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK")) {
547           targetFramework = *tf;
548         } else if (cmValue vstfVer = this->GeneratorTarget->GetProperty(
549                      "VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
550           // FIXME: Someday, add a deprecation warning for VS_* property.
551           targetFrameworkVersion = *vstfVer;
552         } else if (cmValue tfVer = this->GeneratorTarget->GetProperty(
553                      "DOTNET_TARGET_FRAMEWORK_VERSION")) {
554           targetFrameworkVersion = *tfVer;
555         } else if (this->ProjectType == VsProjectType::csproj) {
556           targetFrameworkVersion =
557             this->GlobalGenerator->GetTargetFrameworkVersion();
558         }
559         if (this->ProjectType == VsProjectType::vcxproj &&
560             this->GlobalGenerator->TargetsWindowsCE()) {
561           e1.Element("EnableRedirectPlatform", "true");
562           e1.Element("RedirectPlatformValue", this->Platform);
563         }
564         if (this->ProjectType == VsProjectType::csproj) {
565           if (this->GlobalGenerator->TargetsWindowsCE()) {
566             // FIXME: These target VS_TARGET_FRAMEWORK* target properties
567             // are undocumented settings only ever supported for WinCE.
568             // We need a better way to control these in general.
569             if (cmValue tfId = this->GeneratorTarget->GetProperty(
570                   "VS_TARGET_FRAMEWORK_IDENTIFIER")) {
571               targetFrameworkIdentifier = *tfId;
572             }
573             if (cmValue tfTargetsVer = this->GeneratorTarget->GetProperty(
574                   "VS_TARGET_FRAMEWORKS_TARGET_VERSION")) {
575               targetFrameworkTargetsVersion = *tfTargetsVer;
576             }
577           }
578           if (!targetFrameworkIdentifier) {
579             targetFrameworkIdentifier =
580               this->GlobalGenerator->GetTargetFrameworkIdentifier();
581           }
582           if (!targetFrameworkTargetsVersion) {
583             targetFrameworkTargetsVersion =
584               this->GlobalGenerator->GetTargetFrameworkTargetsVersion();
585           }
586         }
587         if (targetFramework) {
588           if (targetFramework->find(';') != std::string::npos) {
589             e1.Element("TargetFrameworks", *targetFramework);
590           } else {
591             e1.Element("TargetFramework", *targetFramework);
592           }
593         }
594         if (targetFrameworkVersion) {
595           e1.Element("TargetFrameworkVersion", *targetFrameworkVersion);
596         }
597         if (targetFrameworkIdentifier) {
598           e1.Element("TargetFrameworkIdentifier", *targetFrameworkIdentifier);
599         }
600         if (targetFrameworkTargetsVersion) {
601           e1.Element("TargetFrameworkTargetsVersion",
602                      *targetFrameworkTargetsVersion);
603         }
604         if (!this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString()
605                .empty()) {
606           e1.Element(
607             "CudaToolkitCustomDir",
608             this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString() +
609               this->GlobalGenerator->GetPlatformToolsetCudaNvccSubdirString());
610         }
611       }
612
613       // Disable the project upgrade prompt that is displayed the first time a
614       // project using an older toolset version is opened in a newer version of
615       // the IDE (respected by VS 2013 and above).
616       if (this->GlobalGenerator->GetVersion() >=
617           cmGlobalVisualStudioGenerator::VSVersion::VS12) {
618         e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
619       }
620
621       if (const char* vcTargetsPath =
622             this->GlobalGenerator->GetCustomVCTargetsPath()) {
623         e1.Element("VCTargetsPath", vcTargetsPath);
624       }
625
626       if (this->Managed) {
627         if (this->LocalGenerator->GetVersion() >=
628             cmGlobalVisualStudioGenerator::VSVersion::VS17) {
629           e1.Element("ManagedAssembly", "true");
630         }
631         std::string outputType;
632         switch (this->GeneratorTarget->GetType()) {
633           case cmStateEnums::OBJECT_LIBRARY:
634           case cmStateEnums::STATIC_LIBRARY:
635           case cmStateEnums::SHARED_LIBRARY:
636             outputType = "Library";
637             break;
638           case cmStateEnums::MODULE_LIBRARY:
639             outputType = "Module";
640             break;
641           case cmStateEnums::EXECUTABLE: {
642             auto const win32 =
643               this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
644             if (win32.find("$<") != std::string::npos) {
645               this->Makefile->IssueMessage(
646                 MessageType::FATAL_ERROR,
647                 cmStrCat(
648                   "Target \"", this->GeneratorTarget->GetName(),
649                   "\" has a generator expression in its WIN32_EXECUTABLE "
650                   "property. This is not supported on managed executables."));
651               return;
652             }
653             if (cmIsOn(win32)) {
654               outputType = "WinExe";
655             } else {
656               outputType = "Exe";
657             }
658           } break;
659           case cmStateEnums::UTILITY:
660           case cmStateEnums::INTERFACE_LIBRARY:
661           case cmStateEnums::GLOBAL_TARGET:
662             outputType = "Utility";
663             break;
664           case cmStateEnums::UNKNOWN_LIBRARY:
665             break;
666         }
667         e1.Element("OutputType", outputType);
668         e1.Element("AppDesignerFolder", "Properties");
669       }
670     }
671
672     cmValue startupObject =
673       this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
674
675     if (startupObject && this->Managed) {
676       Elem e1(e0, "PropertyGroup");
677       e1.Element("StartupObject", *startupObject);
678     }
679
680     switch (this->ProjectType) {
681       case VsProjectType::vcxproj: {
682         std::string const& props =
683           this->GlobalGenerator->GetPlatformToolsetVersionProps();
684         if (!props.empty()) {
685           Elem(e0, "Import").Attribute("Project", props);
686         }
687         Elem(e0, "Import").Attribute("Project", VS10_CXX_DEFAULT_PROPS);
688       } break;
689       case VsProjectType::csproj:
690         Elem(e0, "Import")
691           .Attribute("Project", VS10_CSharp_DEFAULT_PROPS)
692           .Attribute("Condition", "Exists('" VS10_CSharp_DEFAULT_PROPS "')");
693         break;
694       default:
695         break;
696     }
697
698     this->WriteProjectConfigurationValues(e0);
699
700     if (this->ProjectType == VsProjectType::vcxproj) {
701       Elem(e0, "Import").Attribute("Project", VS10_CXX_PROPS);
702     }
703     {
704       Elem e1(e0, "ImportGroup");
705       e1.Attribute("Label", "ExtensionSettings");
706       e1.SetHasElements();
707
708       if (this->GlobalGenerator->IsCudaEnabled()) {
709         auto customDir =
710           this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
711         std::string cudaPath = customDir.empty()
712           ? "$(VCTargetsPath)\\BuildCustomizations\\"
713           : customDir +
714             this->GlobalGenerator
715               ->GetPlatformToolsetCudaVSIntegrationSubdirString() +
716             "extras\\visual_studio_integration\\MSBuildExtensions\\";
717         Elem(e1, "Import")
718           .Attribute("Project",
719                      std::move(cudaPath) + "CUDA " +
720                        this->GlobalGenerator->GetPlatformToolsetCuda() +
721                        ".props");
722       }
723       if (this->GlobalGenerator->IsMasmEnabled()) {
724         Elem(e1, "Import")
725           .Attribute("Project",
726                      "$(VCTargetsPath)\\BuildCustomizations\\masm.props");
727       }
728       if (this->GlobalGenerator->IsNasmEnabled()) {
729         // Always search in the standard modules location.
730         std::string propsTemplate =
731           GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
732
733         std::string propsLocal =
734           cmStrCat(this->DefaultArtifactDir, "\\nasm.props");
735         ConvertToWindowsSlash(propsLocal);
736         this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true,
737                                       true);
738         Elem(e1, "Import").Attribute("Project", propsLocal);
739       }
740     }
741     {
742       Elem e1(e0, "ImportGroup");
743       e1.Attribute("Label", "PropertySheets");
744       std::string props;
745       switch (this->ProjectType) {
746         case VsProjectType::vcxproj:
747           props = VS10_CXX_USER_PROPS;
748           break;
749         case VsProjectType::csproj:
750           props = VS10_CSharp_USER_PROPS;
751           break;
752         default:
753           break;
754       }
755       if (cmValue p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
756         props = *p;
757       }
758       if (!props.empty()) {
759         ConvertToWindowsSlash(props);
760         Elem(e1, "Import")
761           .Attribute("Project", props)
762           .Attribute("Condition", "exists('" + props + "')")
763           .Attribute("Label", "LocalAppDataPlatform");
764       }
765
766       this->WritePlatformExtensions(e1);
767     }
768
769     this->WriteDotNetDocumentationFile(e0);
770     Elem(e0, "PropertyGroup").Attribute("Label", "UserMacros");
771     this->WriteWinRTPackageCertificateKeyFile(e0);
772     this->WritePathAndIncrementalLinkOptions(e0);
773     this->WriteCEDebugProjectConfigurationValues(e0);
774     this->WriteItemDefinitionGroups(e0);
775     this->WriteCustomCommands(e0);
776     this->WriteAllSources(e0);
777     this->WriteDotNetReferences(e0);
778     this->WritePackageReferences(e0);
779     this->WriteImports(e0);
780     this->WriteEmbeddedResourceGroup(e0);
781     this->WriteXamlFilesGroup(e0);
782     this->WriteWinRTReferences(e0);
783     this->WriteProjectReferences(e0);
784     this->WriteSDKReferences(e0);
785     switch (this->ProjectType) {
786       case VsProjectType::vcxproj:
787         Elem(e0, "Import").Attribute("Project", VS10_CXX_TARGETS);
788         break;
789       case VsProjectType::csproj:
790         if (this->GlobalGenerator->TargetsWindowsCE()) {
791           Elem(e0, "Import").Attribute("Project", VS10_CSharp_NETCF_TARGETS);
792         } else {
793           Elem(e0, "Import").Attribute("Project", VS10_CSharp_TARGETS);
794         }
795         break;
796       default:
797         break;
798     }
799
800     this->WriteTargetSpecificReferences(e0);
801     {
802       Elem e1(e0, "ImportGroup");
803       e1.Attribute("Label", "ExtensionTargets");
804       e1.SetHasElements();
805       this->WriteTargetsFileReferences(e1);
806       if (this->GlobalGenerator->IsCudaEnabled()) {
807         auto customDir =
808           this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
809         std::string cudaPath = customDir.empty()
810           ? "$(VCTargetsPath)\\BuildCustomizations\\"
811           : customDir +
812             this->GlobalGenerator
813               ->GetPlatformToolsetCudaVSIntegrationSubdirString() +
814             "extras\\visual_studio_integration\\MSBuildExtensions\\";
815         Elem(e1, "Import")
816           .Attribute("Project",
817                      std::move(cudaPath) + "CUDA " +
818                        this->GlobalGenerator->GetPlatformToolsetCuda() +
819                        ".targets");
820       }
821       if (this->GlobalGenerator->IsMasmEnabled()) {
822         Elem(e1, "Import")
823           .Attribute("Project",
824                      "$(VCTargetsPath)\\BuildCustomizations\\masm.targets");
825       }
826       if (this->GlobalGenerator->IsNasmEnabled()) {
827         std::string nasmTargets =
828           GetCMakeFilePath("Templates/MSBuild/nasm.targets");
829         Elem(e1, "Import").Attribute("Project", nasmTargets);
830       }
831     }
832     if (this->ProjectType == VsProjectType::vcxproj &&
833         this->HaveCustomCommandDepfile) {
834       std::string depfileTargets =
835         GetCMakeFilePath("Templates/MSBuild/CustomBuildDepFile.targets");
836       Elem(e0, "Import").Attribute("Project", depfileTargets);
837     }
838     if (this->ProjectType == VsProjectType::csproj) {
839       for (std::string const& c : this->Configurations) {
840         Elem e1(e0, "PropertyGroup");
841         e1.Attribute("Condition", "'$(Configuration)' == '" + c + "'");
842         e1.SetHasElements();
843         this->WriteEvents(e1, c);
844       }
845       // make sure custom commands are executed before build (if necessary)
846       {
847         Elem e1(e0, "PropertyGroup");
848         std::ostringstream oss;
849         oss << "\n";
850         for (std::string const& i : this->CSharpCustomCommandNames) {
851           oss << "      " << i << ";\n";
852         }
853         oss << "      "
854             << "$(BuildDependsOn)\n";
855         e1.Element("BuildDependsOn", oss.str());
856       }
857     }
858   }
859 }
860
861 void cmVisualStudio10TargetGenerator::WriteSdkStyleProjectFile(
862   cmGeneratedFileStream& BuildFileStream)
863 {
864   if (this->ProjectType != VsProjectType::csproj ||
865       !this->GeneratorTarget->IsDotNetSdkTarget()) {
866     std::string message = "The target \"" + this->GeneratorTarget->GetName() +
867       "\" is not eligible for .Net SDK style project.";
868     this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
869     return;
870   }
871
872   if (this->HasCustomCommands()) {
873     std::string message = "The target \"" + this->GeneratorTarget->GetName() +
874       "\" does not currently support add_custom_command as the Visual Studio "
875       "generators have not yet learned how to generate custom commands in "
876       ".Net SDK-style projects.";
877     this->Makefile->IssueMessage(MessageType::FATAL_ERROR, message);
878     return;
879   }
880
881   Elem e0(BuildFileStream, "Project");
882   e0.Attribute("Sdk", *this->GeneratorTarget->GetProperty("DOTNET_SDK"));
883
884   {
885     Elem e1(e0, "PropertyGroup");
886     this->WriteCommonPropertyGroupGlobals(e1);
887
888     e1.Element("EnableDefaultItems", "false");
889     // Disable the project upgrade prompt that is displayed the first time a
890     // project using an older toolset version is opened in a newer version
891     // of the IDE.
892     e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
893     e1.Element("ManagedAssembly", "true");
894
895     cmValue targetFramework =
896       this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK");
897     if (targetFramework) {
898       if (targetFramework->find(';') != std::string::npos) {
899         e1.Element("TargetFrameworks", *targetFramework);
900       } else {
901         e1.Element("TargetFramework", *targetFramework);
902       }
903     } else {
904       e1.Element("TargetFramework", "net5.0");
905     }
906
907     std::string outputType;
908     switch (this->GeneratorTarget->GetType()) {
909       case cmStateEnums::OBJECT_LIBRARY:
910       case cmStateEnums::STATIC_LIBRARY:
911       case cmStateEnums::MODULE_LIBRARY:
912         this->Makefile->IssueMessage(
913           MessageType::FATAL_ERROR,
914           cmStrCat("Target \"", this->GeneratorTarget->GetName(),
915                    "\" is of a type not supported for managed binaries."));
916         return;
917       case cmStateEnums::SHARED_LIBRARY:
918         outputType = "Library";
919         break;
920       case cmStateEnums::EXECUTABLE: {
921         auto const win32 =
922           this->GeneratorTarget->GetSafeProperty("WIN32_EXECUTABLE");
923         if (win32.find("$<") != std::string::npos) {
924           this->Makefile->IssueMessage(
925             MessageType::FATAL_ERROR,
926             cmStrCat("Target \"", this->GeneratorTarget->GetName(),
927                      "\" has a generator expression in its WIN32_EXECUTABLE "
928                      "property. This is not supported on managed "
929                      "executables."));
930           return;
931         }
932         outputType = "Exe";
933       } break;
934       case cmStateEnums::UTILITY:
935       case cmStateEnums::INTERFACE_LIBRARY:
936       case cmStateEnums::GLOBAL_TARGET:
937         outputType = "Utility";
938         break;
939       case cmStateEnums::UNKNOWN_LIBRARY:
940         break;
941     }
942     e1.Element("OutputType", outputType);
943
944     cmValue startupObject =
945       this->GeneratorTarget->GetProperty("VS_DOTNET_STARTUP_OBJECT");
946     if (startupObject) {
947       e1.Element("StartupObject", *startupObject);
948     }
949   }
950
951   for (const std::string& config : this->Configurations) {
952     Elem e1(e0, "PropertyGroup");
953     e1.Attribute("Condition", "'$(Configuration)' == '" + config + "'");
954     e1.SetHasElements();
955     this->WriteEvents(e1, config);
956
957     std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
958     ConvertToWindowsSlash(outDir);
959     e1.Element("OutputPath", outDir);
960   }
961
962   this->WriteDotNetDocumentationFile(e0);
963   this->WriteAllSources(e0);
964   this->WriteDotNetReferences(e0);
965   this->WritePackageReferences(e0);
966   this->WriteProjectReferences(e0);
967 }
968
969 void cmVisualStudio10TargetGenerator::WriteCommonPropertyGroupGlobals(Elem& e1)
970 {
971   e1.Attribute("Label", "Globals");
972   e1.Element("ProjectGuid", "{" + this->GUID + "}");
973
974   cmValue vsProjectTypes =
975     this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
976   if (vsProjectTypes) {
977     const char* tagName = "ProjectTypes";
978     if (this->ProjectType == VsProjectType::csproj) {
979       tagName = "ProjectTypeGuids";
980     }
981     e1.Element(tagName, *vsProjectTypes);
982   }
983
984   cmValue vsGlobalKeyword =
985     this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
986   if (!vsGlobalKeyword) {
987     if (this->GlobalGenerator->TargetsAndroid()) {
988       e1.Element("Keyword", "Android");
989     } else {
990       e1.Element("Keyword", "Win32Proj");
991     }
992   } else {
993     e1.Element("Keyword", *vsGlobalKeyword);
994   }
995
996   cmValue vsGlobalRootNamespace =
997     this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
998   if (vsGlobalRootNamespace) {
999     e1.Element("RootNamespace", *vsGlobalRootNamespace);
1000   }
1001
1002   std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
1003   for (std::string const& keyIt : keys) {
1004     static const cm::string_view prefix = "VS_GLOBAL_";
1005     if (!cmHasPrefix(keyIt, prefix))
1006       continue;
1007     cm::string_view globalKey = cm::string_view(keyIt).substr(prefix.length());
1008     // Skip invalid or separately-handled properties.
1009     if (globalKey.empty() || globalKey == "PROJECT_TYPES" ||
1010         globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") {
1011       continue;
1012     }
1013     cmValue value = this->GeneratorTarget->GetProperty(keyIt);
1014     if (!value)
1015       continue;
1016     e1.Element(globalKey, *value);
1017   }
1018 }
1019
1020 bool cmVisualStudio10TargetGenerator::HasCustomCommands() const
1021 {
1022   if (!this->GeneratorTarget->GetPreBuildCommands().empty() ||
1023       !this->GeneratorTarget->GetPreLinkCommands().empty() ||
1024       !this->GeneratorTarget->GetPostBuildCommands().empty()) {
1025     return true;
1026   }
1027
1028   for (cmGeneratorTarget::AllConfigSource const& si :
1029        this->GeneratorTarget->GetAllConfigSources()) {
1030     if (si.Source->GetCustomCommand()) {
1031       return true;
1032     }
1033   }
1034
1035   return false;
1036 }
1037
1038 void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0)
1039 {
1040   std::vector<std::string> packageReferences =
1041     this->GeneratorTarget->GetPackageReferences();
1042
1043   if (!packageReferences.empty()) {
1044     Elem e1(e0, "ItemGroup");
1045     for (std::string const& ri : packageReferences) {
1046       size_t versionIndex = ri.find_last_of('_');
1047       if (versionIndex != std::string::npos) {
1048         Elem e2(e1, "PackageReference");
1049         e2.Attribute("Include", ri.substr(0, versionIndex));
1050         e2.Attribute("Version", ri.substr(versionIndex + 1));
1051       }
1052     }
1053   }
1054 }
1055
1056 void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0)
1057 {
1058   std::vector<std::string> references;
1059   if (cmValue vsDotNetReferences =
1060         this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
1061     cmExpandList(*vsDotNetReferences, references);
1062   }
1063   cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1064   for (auto const& i : props.GetList()) {
1065     static const cm::string_view vsDnRef = "VS_DOTNET_REFERENCE_";
1066     if (cmHasPrefix(i.first, vsDnRef)) {
1067       std::string path = i.second;
1068       if (!cmsys::SystemTools::FileIsFullPath(path)) {
1069         path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
1070       }
1071       ConvertToWindowsSlash(path);
1072       this->DotNetHintReferences[""].emplace_back(
1073         DotNetHintReference(i.first.substr(vsDnRef.length()), path));
1074     }
1075   }
1076   if (!references.empty() || !this->DotNetHintReferences.empty()) {
1077     Elem e1(e0, "ItemGroup");
1078     for (std::string const& ri : references) {
1079       // if the entry from VS_DOTNET_REFERENCES is an existing file, generate
1080       // a new hint-reference and name it from the filename
1081       if (cmsys::SystemTools::FileExists(ri, true)) {
1082         std::string name =
1083           cmsys::SystemTools::GetFilenameWithoutLastExtension(ri);
1084         std::string path = ri;
1085         ConvertToWindowsSlash(path);
1086         this->DotNetHintReferences[""].emplace_back(
1087           DotNetHintReference(name, path));
1088       } else {
1089         this->WriteDotNetReference(e1, ri, "", "");
1090       }
1091     }
1092     for (const auto& h : this->DotNetHintReferences) {
1093       // DotNetHintReferences is also populated from AddLibraries().
1094       // The configuration specific hint references are added there.
1095       for (const auto& i : h.second) {
1096         this->WriteDotNetReference(e1, i.first, i.second, h.first);
1097       }
1098     }
1099   }
1100 }
1101
1102 void cmVisualStudio10TargetGenerator::WriteDotNetReference(
1103   Elem& e1, std::string const& ref, std::string const& hint,
1104   std::string const& config)
1105 {
1106   Elem e2(e1, "Reference");
1107   // If 'config' is not empty, the reference is only added for the given
1108   // configuration. This is used when referencing imported managed assemblies.
1109   // See also cmVisualStudio10TargetGenerator::AddLibraries().
1110   if (!config.empty()) {
1111     e2.Attribute("Condition", this->CalcCondition(config));
1112   }
1113   e2.Attribute("Include", ref);
1114   e2.Element("CopyLocalSatelliteAssemblies", "true");
1115   e2.Element("ReferenceOutputAssembly", "true");
1116   if (!hint.empty()) {
1117     const char* privateReference = "True";
1118     if (cmValue value = this->GeneratorTarget->GetProperty(
1119           "VS_DOTNET_REFERENCES_COPY_LOCAL")) {
1120       if (cmIsOff(*value)) {
1121         privateReference = "False";
1122       }
1123     }
1124     e2.Element("Private", privateReference);
1125     e2.Element("HintPath", hint);
1126   }
1127   this->WriteDotNetReferenceCustomTags(e2, ref);
1128 }
1129
1130 void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0)
1131 {
1132   cmValue imports =
1133     this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT");
1134   if (imports) {
1135     std::vector<std::string> argsSplit = cmExpandedList(*imports, false);
1136     for (auto& path : argsSplit) {
1137       if (!cmsys::SystemTools::FileIsFullPath(path)) {
1138         path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
1139       }
1140       ConvertToWindowsSlash(path);
1141       Elem e1(e0, "Import");
1142       e1.Attribute("Project", path);
1143     }
1144   }
1145 }
1146
1147 void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
1148   Elem& e2, std::string const& ref)
1149 {
1150
1151   static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
1152   static const std::string refpropInfix = "_TAG_";
1153   const std::string refPropFullPrefix = refpropPrefix + ref + refpropInfix;
1154   using CustomTags = std::map<std::string, std::string>;
1155   CustomTags tags;
1156   cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
1157   for (const auto& i : props.GetList()) {
1158     if (cmHasPrefix(i.first, refPropFullPrefix) && !i.second.empty()) {
1159       tags[i.first.substr(refPropFullPrefix.length())] = i.second;
1160     }
1161   }
1162   for (auto const& tag : tags) {
1163     e2.Element(tag.first, tag.second);
1164   }
1165 }
1166
1167 void cmVisualStudio10TargetGenerator::WriteDotNetDocumentationFile(Elem& e0)
1168 {
1169   std::string const& documentationFile =
1170     this->GeneratorTarget->GetSafeProperty("VS_DOTNET_DOCUMENTATION_FILE");
1171
1172   if (this->ProjectType == VsProjectType::csproj &&
1173       !documentationFile.empty()) {
1174     Elem e1(e0, "PropertyGroup");
1175     Elem e2(e1, "DocumentationFile");
1176     e2.Content(documentationFile);
1177   }
1178 }
1179
1180 void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0)
1181 {
1182   if (!this->ResxObjs.empty()) {
1183     Elem e1(e0, "ItemGroup");
1184     std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
1185     ConvertToWindowsSlash(srcDir);
1186     for (cmSourceFile const* oi : this->ResxObjs) {
1187       std::string obj = oi->GetFullPath();
1188       ConvertToWindowsSlash(obj);
1189       bool useRelativePath = false;
1190       if (this->ProjectType == VsProjectType::csproj && this->InSourceBuild) {
1191         // If we do an in-source build and the resource file is in a
1192         // subdirectory
1193         // of the .csproj file, we have to use relative pathnames, otherwise
1194         // visual studio does not show the file in the IDE. Sorry.
1195         if (cmHasPrefix(obj, srcDir)) {
1196           obj = this->ConvertPath(obj, true);
1197           ConvertToWindowsSlash(obj);
1198           useRelativePath = true;
1199         }
1200       }
1201       Elem e2(e1, "EmbeddedResource");
1202       e2.Attribute("Include", obj);
1203
1204       if (this->ProjectType != VsProjectType::csproj) {
1205         std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
1206         e2.Element("DependentUpon", hFileName);
1207
1208         for (std::string const& c : this->Configurations) {
1209           std::string s;
1210           if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
1211               // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
1212               this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
1213             s = "$(RootNamespace).";
1214           }
1215           s += "%(Filename).resources";
1216           e2.WritePlatformConfigTag("LogicalName", this->CalcCondition(c), s);
1217         }
1218       } else {
1219         std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
1220         ConvertToWindowsSlash(binDir);
1221         // If the resource was NOT added using a relative path (which should
1222         // be the default), we have to provide a link here
1223         if (!useRelativePath) {
1224           std::string link = this->GetCSharpSourceLink(oi);
1225           if (link.empty()) {
1226             link = cmsys::SystemTools::GetFilenameName(obj);
1227           }
1228           e2.Element("Link", link);
1229         }
1230         // Determine if this is a generated resource from a .Designer.cs file
1231         std::string designerResource =
1232           cmSystemTools::GetFilenamePath(oi->GetFullPath()) + "/" +
1233           cmSystemTools::GetFilenameWithoutLastExtension(oi->GetFullPath()) +
1234           ".Designer.cs";
1235         if (cmsys::SystemTools::FileExists(designerResource)) {
1236           std::string generator = "PublicResXFileCodeGenerator";
1237           if (cmValue g = oi->GetProperty("VS_RESOURCE_GENERATOR")) {
1238             generator = *g;
1239           }
1240           if (!generator.empty()) {
1241             e2.Element("Generator", generator);
1242             if (cmHasPrefix(designerResource, srcDir)) {
1243               designerResource.erase(0, srcDir.length());
1244             } else if (cmHasPrefix(designerResource, binDir)) {
1245               designerResource.erase(0, binDir.length());
1246             } else {
1247               designerResource =
1248                 cmsys::SystemTools::GetFilenameName(designerResource);
1249             }
1250             ConvertToWindowsSlash(designerResource);
1251             e2.Element("LastGenOutput", designerResource);
1252           }
1253         }
1254         const cmPropertyMap& props = oi->GetProperties();
1255         for (const std::string& p : props.GetKeys()) {
1256           static const cm::string_view propNamePrefix = "VS_CSHARP_";
1257           if (cmHasPrefix(p, propNamePrefix)) {
1258             cm::string_view tagName =
1259               cm::string_view(p).substr(propNamePrefix.length());
1260             if (!tagName.empty()) {
1261               cmValue value = props.GetPropertyValue(p);
1262               if (cmNonempty(value)) {
1263                 e2.Element(tagName, *value);
1264               }
1265             }
1266           }
1267         }
1268       }
1269     }
1270   }
1271 }
1272
1273 void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0)
1274 {
1275   if (!this->XamlObjs.empty()) {
1276     Elem e1(e0, "ItemGroup");
1277     for (cmSourceFile const* oi : this->XamlObjs) {
1278       std::string obj = oi->GetFullPath();
1279       std::string xamlType;
1280       cmValue xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE");
1281       if (xamlTypeProperty) {
1282         xamlType = *xamlTypeProperty;
1283       } else {
1284         xamlType = "Page";
1285       }
1286
1287       Elem e2(e1, xamlType);
1288       this->WriteSource(e2, oi);
1289       e2.SetHasElements();
1290       e2.Element("SubType", "Designer");
1291     }
1292   }
1293 }
1294
1295 void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences(Elem& e0)
1296 {
1297   if (this->MSTools) {
1298     if (this->GlobalGenerator->TargetsWindowsPhone() &&
1299         this->GlobalGenerator->GetSystemVersion() == "8.0") {
1300       Elem(e0, "Import")
1301         .Attribute("Project",
1302                    "$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
1303                    "$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
1304                    "$(TargetPlatformVersion).targets");
1305     }
1306   }
1307 }
1308
1309 void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences(Elem& e1)
1310 {
1311   for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) {
1312     std::ostringstream oss;
1313     oss << "Exists('" << tac.File << "')";
1314     if (!tac.Configs.empty()) {
1315       oss << " And (";
1316       for (size_t j = 0; j < tac.Configs.size(); ++j) {
1317         if (j > 0) {
1318           oss << " Or ";
1319         }
1320         oss << "'$(Configuration)'=='" << tac.Configs[j] << "'";
1321       }
1322       oss << ")";
1323     }
1324
1325     Elem(e1, "Import")
1326       .Attribute("Project", tac.File)
1327       .Attribute("Condition", oss.str());
1328   }
1329 }
1330
1331 void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0)
1332 {
1333   std::vector<std::string> references;
1334   if (cmValue vsWinRTReferences =
1335         this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
1336     cmExpandList(*vsWinRTReferences, references);
1337   }
1338
1339   if (this->GlobalGenerator->TargetsWindowsPhone() &&
1340       this->GlobalGenerator->GetSystemVersion() == "8.0" &&
1341       references.empty()) {
1342     references.push_back("platform.winmd");
1343   }
1344   if (!references.empty()) {
1345     Elem e1(e0, "ItemGroup");
1346     for (std::string const& ri : references) {
1347       Elem e2(e1, "Reference");
1348       e2.Attribute("Include", ri);
1349       e2.Element("IsWinMDFile", "true");
1350     }
1351   }
1352 }
1353
1354 // ConfigurationType Application, Utility StaticLibrary DynamicLibrary
1355
1356 void cmVisualStudio10TargetGenerator::WriteProjectConfigurations(Elem& e0)
1357 {
1358   Elem e1(e0, "ItemGroup");
1359   e1.Attribute("Label", "ProjectConfigurations");
1360   for (std::string const& c : this->Configurations) {
1361     Elem e2(e1, "ProjectConfiguration");
1362     e2.Attribute("Include", c + "|" + this->Platform);
1363     e2.Element("Configuration", c);
1364     e2.Element("Platform", this->Platform);
1365   }
1366 }
1367
1368 void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues(Elem& e0)
1369 {
1370   for (std::string const& c : this->Configurations) {
1371     Elem e1(e0, "PropertyGroup");
1372     e1.Attribute("Condition", this->CalcCondition(c));
1373     e1.Attribute("Label", "Configuration");
1374
1375     if (this->ProjectType != VsProjectType::csproj) {
1376       std::string configType;
1377       if (cmValue vsConfigurationType =
1378             this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
1379         configType = cmGeneratorExpression::Evaluate(*vsConfigurationType,
1380                                                      this->LocalGenerator, c);
1381       } else {
1382         switch (this->GeneratorTarget->GetType()) {
1383           case cmStateEnums::SHARED_LIBRARY:
1384           case cmStateEnums::MODULE_LIBRARY:
1385             configType = "DynamicLibrary";
1386             break;
1387           case cmStateEnums::OBJECT_LIBRARY:
1388           case cmStateEnums::STATIC_LIBRARY:
1389             configType = "StaticLibrary";
1390             break;
1391           case cmStateEnums::EXECUTABLE:
1392             if (this->NsightTegra &&
1393                 !this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
1394               // Android executables are .so too.
1395               configType = "DynamicLibrary";
1396             } else if (this->Android) {
1397               configType = "DynamicLibrary";
1398             } else {
1399               configType = "Application";
1400             }
1401             break;
1402           case cmStateEnums::UTILITY:
1403           case cmStateEnums::INTERFACE_LIBRARY:
1404           case cmStateEnums::GLOBAL_TARGET:
1405             if (this->NsightTegra) {
1406               // Tegra-Android platform does not understand "Utility".
1407               configType = "StaticLibrary";
1408             } else {
1409               configType = "Utility";
1410             }
1411             break;
1412           case cmStateEnums::UNKNOWN_LIBRARY:
1413             break;
1414         }
1415       }
1416       e1.Element("ConfigurationType", configType);
1417     }
1418
1419     if (this->MSTools) {
1420       if (!this->Managed) {
1421         this->WriteMSToolConfigurationValues(e1, c);
1422       } else {
1423         this->WriteMSToolConfigurationValuesManaged(e1, c);
1424       }
1425     } else if (this->NsightTegra) {
1426       this->WriteNsightTegraConfigurationValues(e1, c);
1427     } else if (this->Android) {
1428       this->WriteAndroidConfigurationValues(e1, c);
1429     }
1430   }
1431 }
1432
1433 void cmVisualStudio10TargetGenerator::WriteCEDebugProjectConfigurationValues(
1434   Elem& e0)
1435 {
1436   if (!this->GlobalGenerator->TargetsWindowsCE()) {
1437     return;
1438   }
1439   cmValue additionalFiles =
1440     this->GeneratorTarget->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
1441   cmValue remoteDirectory =
1442     this->GeneratorTarget->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
1443   if (!(additionalFiles || remoteDirectory)) {
1444     return;
1445   }
1446   for (std::string const& c : this->Configurations) {
1447     Elem e1(e0, "PropertyGroup");
1448     e1.Attribute("Condition", this->CalcCondition(c));
1449
1450     if (remoteDirectory) {
1451       e1.Element("RemoteDirectory", *remoteDirectory);
1452     }
1453     if (additionalFiles) {
1454       e1.Element("CEAdditionalFiles", *additionalFiles);
1455     }
1456   }
1457 }
1458
1459 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
1460   Elem& e1, std::string const& config)
1461 {
1462   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1463   cmValue mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG");
1464   if (mfcFlag) {
1465     std::string const mfcFlagValue =
1466       cmGeneratorExpression::Evaluate(*mfcFlag, this->LocalGenerator, config);
1467
1468     std::string useOfMfcValue = "false";
1469     if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
1470       if (mfcFlagValue == "1") {
1471         useOfMfcValue = "Static";
1472       } else if (mfcFlagValue == "2") {
1473         useOfMfcValue = "Dynamic";
1474       }
1475     }
1476     e1.Element("UseOfMfc", useOfMfcValue);
1477   }
1478
1479   if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
1480        this->ClOptions[config]->UsingUnicode()) ||
1481       this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1482       this->GlobalGenerator->TargetsWindowsPhone() ||
1483       this->GlobalGenerator->TargetsWindowsStore() ||
1484       this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1485     e1.Element("CharacterSet", "Unicode");
1486   } else if (this->GeneratorTarget->GetType() <=
1487                cmStateEnums::OBJECT_LIBRARY &&
1488              this->ClOptions[config]->UsingSBCS()) {
1489     e1.Element("CharacterSet", "NotSet");
1490   } else {
1491     e1.Element("CharacterSet", "MultiByte");
1492   }
1493   if (cmValue projectToolsetOverride =
1494         this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1495     e1.Element("PlatformToolset", *projectToolsetOverride);
1496   } else if (const char* toolset = gg->GetPlatformToolset()) {
1497     e1.Element("PlatformToolset", toolset);
1498   }
1499   if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
1500       this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
1501     e1.Element("WindowsAppContainer", "true");
1502   }
1503   if (this->IPOEnabledConfigurations.count(config) > 0) {
1504     e1.Element("WholeProgramOptimization", "true");
1505   }
1506   if (this->ASanEnabledConfigurations.find(config) !=
1507       this->ASanEnabledConfigurations.end()) {
1508     e1.Element("EnableAsan", "true");
1509   }
1510   {
1511     auto s = this->SpectreMitigation.find(config);
1512     if (s != this->SpectreMitigation.end()) {
1513       e1.Element("SpectreMitigation", s->second);
1514     }
1515   }
1516 }
1517
1518 void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
1519   Elem& e1, std::string const& config)
1520 {
1521   if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
1522     return;
1523   }
1524
1525   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1526
1527   Options& o = *(this->ClOptions[config]);
1528
1529   if (o.IsDebug()) {
1530     e1.Element("DebugSymbols", "true");
1531     e1.Element("DefineDebug", "true");
1532   }
1533
1534   std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
1535   ConvertToWindowsSlash(outDir);
1536   e1.Element("OutputPath", outDir);
1537
1538   if (o.HasFlag("Platform")) {
1539     e1.Element("PlatformTarget", o.GetFlag("Platform"));
1540     o.RemoveFlag("Platform");
1541   }
1542
1543   if (cmValue projectToolsetOverride =
1544         this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1545     e1.Element("PlatformToolset", *projectToolsetOverride);
1546   } else if (const char* toolset = gg->GetPlatformToolset()) {
1547     e1.Element("PlatformToolset", toolset);
1548   }
1549
1550   std::string postfixName =
1551     cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
1552   std::string assemblyName = this->GeneratorTarget->GetOutputName(
1553     config, cmStateEnums::RuntimeBinaryArtifact);
1554   if (cmValue postfix = this->GeneratorTarget->GetProperty(postfixName)) {
1555     assemblyName += *postfix;
1556   }
1557   e1.Element("AssemblyName", assemblyName);
1558
1559   if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
1560     e1.Element("StartAction", "Program");
1561     e1.Element("StartProgram", outDir + assemblyName + ".exe");
1562   }
1563
1564   OptionsHelper oh(o, e1);
1565   oh.OutputFlagMap();
1566 }
1567
1568 //----------------------------------------------------------------------------
1569 void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
1570   Elem& e1, std::string const&)
1571 {
1572   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1573   const char* toolset = gg->GetPlatformToolset();
1574   e1.Element("NdkToolchainVersion", toolset ? toolset : "Default");
1575   if (cmValue minApi = this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
1576     e1.Element("AndroidMinAPI", "android-" + *minApi);
1577   }
1578   if (cmValue api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
1579     e1.Element("AndroidTargetAPI", "android-" + *api);
1580   }
1581
1582   if (cmValue cpuArch = this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
1583     e1.Element("AndroidArch", *cpuArch);
1584   }
1585
1586   if (cmValue stlType =
1587         this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1588     e1.Element("AndroidStlType", *stlType);
1589   }
1590 }
1591
1592 void cmVisualStudio10TargetGenerator::WriteAndroidConfigurationValues(
1593   Elem& e1, std::string const&)
1594 {
1595   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
1596   if (cmValue projectToolsetOverride =
1597         this->GeneratorTarget->GetProperty("VS_PLATFORM_TOOLSET")) {
1598     e1.Element("PlatformToolset", *projectToolsetOverride);
1599   } else if (const char* toolset = gg->GetPlatformToolset()) {
1600     e1.Element("PlatformToolset", toolset);
1601   }
1602   if (cmValue stlType =
1603         this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
1604     if (*stlType != "none") {
1605       e1.Element("UseOfStl", *stlType);
1606     }
1607   }
1608   std::string const& apiLevel = gg->GetSystemVersion();
1609   if (!apiLevel.empty()) {
1610     e1.Element("AndroidAPILevel", cmStrCat("android-", apiLevel));
1611   }
1612 }
1613
1614 void cmVisualStudio10TargetGenerator::WriteCustomCommands(Elem& e0)
1615 {
1616   this->CSharpCustomCommandNames.clear();
1617
1618   cmSourceFile const* srcCMakeLists =
1619     this->LocalGenerator->CreateVCProjBuildRule();
1620
1621   for (cmGeneratorTarget::AllConfigSource const& si :
1622        this->GeneratorTarget->GetAllConfigSources()) {
1623     if (si.Source == srcCMakeLists) {
1624       // Skip explicit reference to CMakeLists.txt source.
1625       continue;
1626     }
1627     this->WriteCustomCommand(e0, si.Source);
1628   }
1629
1630   // Add CMakeLists.txt file with rule to re-run CMake for user convenience.
1631   if (this->GeneratorTarget->GetType() != cmStateEnums::GLOBAL_TARGET &&
1632       this->GeneratorTarget->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1633     if (srcCMakeLists) {
1634       // Write directly rather than through WriteCustomCommand because
1635       // we do not want the de-duplication and it has no dependencies.
1636       if (cmCustomCommand const* command = srcCMakeLists->GetCustomCommand()) {
1637         this->WriteCustomRule(e0, srcCMakeLists, *command);
1638       }
1639     }
1640   }
1641 }
1642
1643 void cmVisualStudio10TargetGenerator::WriteCustomCommand(
1644   Elem& e0, cmSourceFile const* sf)
1645 {
1646   if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget)
1647         .insert(sf)
1648         .second) {
1649     if (std::vector<cmSourceFile*> const* depends =
1650           this->GeneratorTarget->GetSourceDepends(sf)) {
1651       for (cmSourceFile const* di : *depends) {
1652         this->WriteCustomCommand(e0, di);
1653       }
1654     }
1655     if (cmCustomCommand const* command = sf->GetCustomCommand()) {
1656       // C# projects write their <Target> within WriteCustomRule()
1657       this->WriteCustomRule(e0, sf, *command);
1658     }
1659   }
1660 }
1661
1662 void cmVisualStudio10TargetGenerator::WriteCustomRule(
1663   Elem& e0, cmSourceFile const* source, cmCustomCommand const& command)
1664 {
1665   std::string sourcePath = source->GetFullPath();
1666   // VS 10 will always rebuild a custom command attached to a .rule
1667   // file that doesn't exist so create the file explicitly.
1668   if (source->GetPropertyAsBool("__CMAKE_RULE")) {
1669     if (!cmSystemTools::FileExists(sourcePath)) {
1670       // Make sure the path exists for the file
1671       std::string path = cmSystemTools::GetFilenamePath(sourcePath);
1672       cmSystemTools::MakeDirectory(path);
1673       cmsys::ofstream fout(sourcePath.c_str());
1674       if (fout) {
1675         fout << "# generated from CMake\n";
1676         fout.flush();
1677         fout.close();
1678         // Force given file to have a very old timestamp, thus
1679         // preventing dependent rebuilds.
1680         this->ForceOld(sourcePath);
1681       } else {
1682         std::string error =
1683           cmStrCat("Could not create file: [", sourcePath, "]  ");
1684         cmSystemTools::Error(error + cmSystemTools::GetLastSystemError());
1685       }
1686     }
1687   }
1688   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
1689
1690   std::unique_ptr<Elem> spe1;
1691   std::unique_ptr<Elem> spe2;
1692   if (this->ProjectType != VsProjectType::csproj) {
1693     spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
1694     spe2 = cm::make_unique<Elem>(*spe1, "CustomBuild");
1695     this->WriteSource(*spe2, source);
1696     spe2->SetHasElements();
1697     if (command.GetStdPipesUTF8()) {
1698       this->WriteStdOutEncodingUtf8(*spe2);
1699     }
1700   } else {
1701     Elem e1(e0, "ItemGroup");
1702     Elem e2(e1, "None");
1703     this->WriteSource(e2, source);
1704     e2.SetHasElements();
1705   }
1706   for (std::string const& c : this->Configurations) {
1707     cmCustomCommandGenerator ccg(command, c, lg, true);
1708     std::string comment = lg->ConstructComment(ccg);
1709     comment = cmVS10EscapeComment(comment);
1710     std::string script = lg->ConstructScript(ccg);
1711     bool symbolic = false;
1712     // input files for custom command
1713     std::stringstream additional_inputs;
1714     {
1715       const char* sep = "";
1716       if (this->ProjectType == VsProjectType::csproj) {
1717         // csproj files do not attach the command to a specific file
1718         // so the primary input must be listed explicitly.
1719         additional_inputs << source->GetFullPath();
1720         sep = ";";
1721       }
1722
1723       // Avoid listing an input more than once.
1724       std::set<std::string> unique_inputs;
1725       // The source is either implicit an input or has been added above.
1726       unique_inputs.insert(source->GetFullPath());
1727
1728       for (std::string const& d : ccg.GetDepends()) {
1729         std::string dep;
1730         if (lg->GetRealDependency(d, c, dep)) {
1731           if (!unique_inputs.insert(dep).second) {
1732             // already listed
1733             continue;
1734           }
1735           ConvertToWindowsSlash(dep);
1736           additional_inputs << sep << dep;
1737           sep = ";";
1738           if (!symbolic) {
1739             if (cmSourceFile* sf = this->Makefile->GetSource(
1740                   dep, cmSourceFileLocationKind::Known)) {
1741               symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1742             }
1743           }
1744         }
1745       }
1746       if (this->ProjectType != VsProjectType::csproj) {
1747         additional_inputs << sep << "%(AdditionalInputs)";
1748       }
1749     }
1750     // output files for custom command
1751     std::stringstream outputs;
1752     {
1753       const char* sep = "";
1754       for (std::string const& o : ccg.GetOutputs()) {
1755         std::string out = o;
1756         ConvertToWindowsSlash(out);
1757         outputs << sep << out;
1758         sep = ";";
1759         if (!symbolic) {
1760           if (cmSourceFile* sf = this->Makefile->GetSource(
1761                 o, cmSourceFileLocationKind::Known)) {
1762             symbolic = sf->GetPropertyAsBool("SYMBOLIC");
1763           }
1764         }
1765       }
1766     }
1767     script += lg->FinishConstructScript(this->ProjectType);
1768     if (this->ProjectType == VsProjectType::csproj) {
1769       std::string name = "CustomCommand_" + c + "_" +
1770         cmSystemTools::ComputeStringMD5(sourcePath);
1771       this->WriteCustomRuleCSharp(e0, c, name, script, additional_inputs.str(),
1772                                   outputs.str(), comment, ccg);
1773     } else {
1774       this->WriteCustomRuleCpp(*spe2, c, script, additional_inputs.str(),
1775                                outputs.str(), comment, ccg, symbolic);
1776     }
1777   }
1778 }
1779
1780 void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
1781   Elem& e2, std::string const& config, std::string const& script,
1782   std::string const& additional_inputs, std::string const& outputs,
1783   std::string const& comment, cmCustomCommandGenerator const& ccg,
1784   bool symbolic)
1785 {
1786   const std::string cond = this->CalcCondition(config);
1787   e2.WritePlatformConfigTag("Message", cond, comment);
1788   e2.WritePlatformConfigTag("Command", cond, script);
1789   e2.WritePlatformConfigTag("AdditionalInputs", cond, additional_inputs);
1790   e2.WritePlatformConfigTag("Outputs", cond, outputs);
1791   if (this->LocalGenerator->GetVersion() >
1792       cmGlobalVisualStudioGenerator::VSVersion::VS10) {
1793     // VS >= 11 let us turn off linking of custom command outputs.
1794     e2.WritePlatformConfigTag("LinkObjects", cond, "false");
1795   }
1796   if (symbolic &&
1797       this->LocalGenerator->GetVersion() >=
1798         cmGlobalVisualStudioGenerator::VSVersion::VS16) {
1799     // VS >= 16.4 warn if outputs are not created, but one of our
1800     // outputs is marked SYMBOLIC and not expected to be created.
1801     e2.WritePlatformConfigTag("VerifyInputsAndOutputsExist", cond, "false");
1802   }
1803
1804   std::string depfile = ccg.GetFullDepfile();
1805   if (!depfile.empty()) {
1806     this->HaveCustomCommandDepfile = true;
1807     std::string internal_depfile = ccg.GetInternalDepfile();
1808     ConvertToWindowsSlash(internal_depfile);
1809     e2.WritePlatformConfigTag("DepFileAdditionalInputsFile", cond,
1810                               internal_depfile);
1811   }
1812 }
1813
1814 void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
1815   Elem& e0, std::string const& config, std::string const& name,
1816   std::string const& script, std::string const& inputs,
1817   std::string const& outputs, std::string const& comment,
1818   cmCustomCommandGenerator const& ccg)
1819 {
1820   if (!ccg.GetFullDepfile().empty()) {
1821     this->Makefile->IssueMessage(
1822       MessageType::FATAL_ERROR,
1823       cmStrCat("CSharp target \"", this->GeneratorTarget->GetName(),
1824                "\" does not support add_custom_command DEPFILE."));
1825   }
1826   this->CSharpCustomCommandNames.insert(name);
1827   Elem e1(e0, "Target");
1828   e1.Attribute("Condition", this->CalcCondition(config));
1829   e1.S << "\n    Name=\"" << name << "\"";
1830   e1.S << "\n    Inputs=\"" << cmVS10EscapeAttr(inputs) << "\"";
1831   e1.S << "\n    Outputs=\"" << cmVS10EscapeAttr(outputs) << "\"";
1832   if (!comment.empty()) {
1833     Elem(e1, "Exec").Attribute("Command", "echo " + comment);
1834   }
1835   Elem(e1, "Exec").Attribute("Command", script);
1836 }
1837
1838 std::string cmVisualStudio10TargetGenerator::ConvertPath(
1839   std::string const& path, bool forceRelative)
1840 {
1841   return forceRelative
1842     ? cmSystemTools::RelativePath(
1843         this->LocalGenerator->GetCurrentBinaryDirectory(), path)
1844     : path;
1845 }
1846
1847 static void ConvertToWindowsSlash(std::string& s)
1848 {
1849   // first convert all of the slashes
1850   for (auto& ch : s) {
1851     if (ch == '/') {
1852       ch = '\\';
1853     }
1854   }
1855 }
1856
1857 void cmVisualStudio10TargetGenerator::WriteGroups()
1858 {
1859   if (this->ProjectType == VsProjectType::csproj) {
1860     return;
1861   }
1862
1863   // collect up group information
1864   std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
1865
1866   std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
1867     this->GeneratorTarget->GetAllConfigSources();
1868
1869   std::set<cmSourceGroup const*> groupsUsed;
1870   for (cmGeneratorTarget::AllConfigSource const& si : sources) {
1871     std::string const& source = si.Source->GetFullPath();
1872     cmSourceGroup* sourceGroup =
1873       this->Makefile->FindSourceGroup(source, sourceGroups);
1874     groupsUsed.insert(sourceGroup);
1875   }
1876
1877   if (cmSourceFile const* srcCMakeLists =
1878         this->LocalGenerator->CreateVCProjBuildRule()) {
1879     std::string const& source = srcCMakeLists->GetFullPath();
1880     cmSourceGroup* sourceGroup =
1881       this->Makefile->FindSourceGroup(source, sourceGroups);
1882     groupsUsed.insert(sourceGroup);
1883   }
1884
1885   this->AddMissingSourceGroups(groupsUsed, sourceGroups);
1886
1887   // Write out group file
1888   std::string path = cmStrCat(
1889     this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name,
1890     computeProjectFileExtension(this->GeneratorTarget), ".filters");
1891   cmGeneratedFileStream fout(path);
1892   fout.SetCopyIfDifferent(true);
1893   char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
1894   fout.write(magic, 3);
1895
1896   fout << "<?xml version=\"1.0\" encoding=\""
1897        << this->GlobalGenerator->Encoding() << "\"?>";
1898   {
1899     Elem e0(fout, "Project");
1900     e0.Attribute("ToolsVersion", this->GlobalGenerator->GetToolsVersion());
1901     e0.Attribute("xmlns",
1902                  "http://schemas.microsoft.com/developer/msbuild/2003");
1903
1904     for (auto const& ti : this->Tools) {
1905       this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups);
1906     }
1907
1908     // Added files are images and the manifest.
1909     if (!this->AddedFiles.empty()) {
1910       Elem e1(e0, "ItemGroup");
1911       e1.SetHasElements();
1912       for (std::string const& oi : this->AddedFiles) {
1913         std::string fileName =
1914           cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi));
1915         if (fileName == "wmappmanifest.xml") {
1916           Elem e2(e1, "XML");
1917           e2.Attribute("Include", oi);
1918           e2.Element("Filter", "Resource Files");
1919         } else if (cmSystemTools::GetFilenameExtension(fileName) ==
1920                    ".appxmanifest") {
1921           Elem e2(e1, "AppxManifest");
1922           e2.Attribute("Include", oi);
1923           e2.Element("Filter", "Resource Files");
1924         } else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx") {
1925           Elem e2(e1, "None");
1926           e2.Attribute("Include", oi);
1927           e2.Element("Filter", "Resource Files");
1928         } else {
1929           Elem e2(e1, "Image");
1930           e2.Attribute("Include", oi);
1931           e2.Element("Filter", "Resource Files");
1932         }
1933       }
1934     }
1935
1936     if (!this->ResxObjs.empty()) {
1937       Elem e1(e0, "ItemGroup");
1938       for (cmSourceFile const* oi : this->ResxObjs) {
1939         std::string obj = oi->GetFullPath();
1940         ConvertToWindowsSlash(obj);
1941         Elem e2(e1, "EmbeddedResource");
1942         e2.Attribute("Include", obj);
1943         e2.Element("Filter", "Resource Files");
1944       }
1945     }
1946     {
1947       Elem e1(e0, "ItemGroup");
1948       e1.SetHasElements();
1949       std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(),
1950                                                   groupsUsed.end());
1951       std::sort(groupsVec.begin(), groupsVec.end(),
1952                 [](cmSourceGroup const* l, cmSourceGroup const* r) {
1953                   return l->GetFullName() < r->GetFullName();
1954                 });
1955       for (cmSourceGroup const* sg : groupsVec) {
1956         std::string const& name = sg->GetFullName();
1957         if (!name.empty()) {
1958           std::string guidName = "SG_Filter_" + name;
1959           std::string guid = this->GlobalGenerator->GetGUID(guidName);
1960           Elem e2(e1, "Filter");
1961           e2.Attribute("Include", name);
1962           e2.Element("UniqueIdentifier", "{" + guid + "}");
1963         }
1964       }
1965
1966       if (!this->ResxObjs.empty() || !this->AddedFiles.empty()) {
1967         std::string guidName = "SG_Filter_Resource Files";
1968         std::string guid = this->GlobalGenerator->GetGUID(guidName);
1969         Elem e2(e1, "Filter");
1970         e2.Attribute("Include", "Resource Files");
1971         e2.Element("UniqueIdentifier", "{" + guid + "}");
1972         e2.Element("Extensions",
1973                    "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;"
1974                    "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms");
1975       }
1976     }
1977   }
1978   fout << '\n';
1979
1980   if (fout.Close()) {
1981     this->GlobalGenerator->FileReplacedDuringGenerate(path);
1982   }
1983 }
1984
1985 // Add to groupsUsed empty source groups that have non-empty children.
1986 void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
1987   std::set<cmSourceGroup const*>& groupsUsed,
1988   const std::vector<cmSourceGroup>& allGroups)
1989 {
1990   for (cmSourceGroup const& current : allGroups) {
1991     std::vector<cmSourceGroup> const& children = current.GetGroupChildren();
1992     if (children.empty()) {
1993       continue; // the group is really empty
1994     }
1995
1996     this->AddMissingSourceGroups(groupsUsed, children);
1997
1998     if (groupsUsed.count(&current) > 0) {
1999       continue; // group has already been added to set
2000     }
2001
2002     // check if it least one of the group's descendants is not empty
2003     // (at least one child must already have been added)
2004     auto child_it = children.begin();
2005     while (child_it != children.end()) {
2006       if (groupsUsed.count(&(*child_it)) > 0) {
2007         break; // found a child that was already added => add current group too
2008       }
2009       child_it++;
2010     }
2011
2012     if (child_it == children.end()) {
2013       continue; // no descendants have source files => ignore this group
2014     }
2015
2016     groupsUsed.insert(&current);
2017   }
2018 }
2019
2020 void cmVisualStudio10TargetGenerator::WriteGroupSources(
2021   Elem& e0, std::string const& name, ToolSources const& sources,
2022   std::vector<cmSourceGroup>& sourceGroups)
2023 {
2024   Elem e1(e0, "ItemGroup");
2025   e1.SetHasElements();
2026   for (ToolSource const& s : sources) {
2027     cmSourceFile const* sf = s.SourceFile;
2028     std::string const& source = sf->GetFullPath();
2029     cmSourceGroup* sourceGroup =
2030       this->Makefile->FindSourceGroup(source, sourceGroups);
2031     std::string const& filter = sourceGroup->GetFullName();
2032     std::string path = this->ConvertPath(source, s.RelativePath);
2033     ConvertToWindowsSlash(path);
2034     Elem e2(e1, name);
2035     e2.Attribute("Include", path);
2036     if (!filter.empty()) {
2037       e2.Element("Filter", filter);
2038     }
2039   }
2040 }
2041
2042 void cmVisualStudio10TargetGenerator::WriteHeaderSource(
2043   Elem& e1, cmSourceFile const* sf, ConfigToSettings const& toolSettings)
2044 {
2045   std::string const& fileName = sf->GetFullPath();
2046   Elem e2(e1, "ClInclude");
2047   this->WriteSource(e2, sf);
2048   if (this->IsResxHeader(fileName)) {
2049     e2.Element("FileType", "CppForm");
2050   } else if (this->IsXamlHeader(fileName)) {
2051     e2.Element("DependentUpon",
2052                fileName.substr(0, fileName.find_last_of(".")));
2053   }
2054   this->FinishWritingSource(e2, toolSettings);
2055 }
2056
2057 void cmVisualStudio10TargetGenerator::ParseSettingsProperty(
2058   const std::string& settingsPropertyValue, ConfigToSettings& toolSettings)
2059 {
2060   if (!settingsPropertyValue.empty()) {
2061     cmGeneratorExpression ge;
2062
2063     std::unique_ptr<cmCompiledGeneratorExpression> cge =
2064       ge.Parse(settingsPropertyValue);
2065
2066     for (const std::string& config : this->Configurations) {
2067       std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2068
2069       std::vector<std::string> settings = cmExpandedList(evaluated);
2070       for (const std::string& setting : settings) {
2071         const std::string::size_type assignment = setting.find('=');
2072         if (assignment != std::string::npos) {
2073           const std::string propName = setting.substr(0, assignment);
2074           const std::string propValue = setting.substr(assignment + 1);
2075
2076           if (!propValue.empty()) {
2077             toolSettings[config][propName] = propValue;
2078           }
2079         }
2080       }
2081     }
2082   }
2083 }
2084
2085 bool cmVisualStudio10TargetGenerator::PropertyIsSameInAllConfigs(
2086   const ConfigToSettings& toolSettings, const std::string& propName)
2087 {
2088   std::string firstPropValue = "";
2089   for (const auto& configToSettings : toolSettings) {
2090     const std::unordered_map<std::string, std::string>& settings =
2091       configToSettings.second;
2092
2093     if (firstPropValue.empty()) {
2094       if (settings.find(propName) != settings.end()) {
2095         firstPropValue = settings.find(propName)->second;
2096       }
2097     }
2098
2099     if (settings.find(propName) == settings.end()) {
2100       return false;
2101     }
2102
2103     if (settings.find(propName)->second != firstPropValue) {
2104       return false;
2105     }
2106   }
2107
2108   return true;
2109 }
2110
2111 void cmVisualStudio10TargetGenerator::WriteExtraSource(
2112   Elem& e1, cmSourceFile const* sf, ConfigToSettings& toolSettings)
2113 {
2114   bool toolHasSettings = false;
2115   const char* tool = "None";
2116   std::string settingsGenerator;
2117   std::string settingsLastGenOutput;
2118   std::string sourceLink;
2119   std::string subType;
2120   std::string copyToOutDir;
2121   std::string includeInVsix;
2122   std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
2123
2124   if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2125     toolHasSettings = true;
2126   }
2127   if (ext == "hlsl") {
2128     tool = "FXCompile";
2129     // Figure out the type of shader compiler to use.
2130     if (cmValue st = sf->GetProperty("VS_SHADER_TYPE")) {
2131       for (const std::string& config : this->Configurations) {
2132         toolSettings[config]["ShaderType"] = *st;
2133       }
2134     }
2135     // Figure out which entry point to use if any
2136     if (cmValue se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
2137       for (const std::string& config : this->Configurations) {
2138         toolSettings[config]["EntryPointName"] = *se;
2139       }
2140     }
2141     // Figure out which shader model to use if any
2142     if (cmValue sm = sf->GetProperty("VS_SHADER_MODEL")) {
2143       for (const std::string& config : this->Configurations) {
2144         toolSettings[config]["ShaderModel"] = *sm;
2145       }
2146     }
2147     // Figure out which output header file to use if any
2148     if (cmValue ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
2149       for (const std::string& config : this->Configurations) {
2150         toolSettings[config]["HeaderFileOutput"] = *ohf;
2151       }
2152     }
2153     // Figure out which variable name to use if any
2154     if (cmValue vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
2155       for (const std::string& config : this->Configurations) {
2156         toolSettings[config]["VariableName"] = *vn;
2157       }
2158     }
2159     // Figure out if there's any additional flags to use
2160     if (cmValue saf = sf->GetProperty("VS_SHADER_FLAGS")) {
2161       cmGeneratorExpression ge;
2162       std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*saf);
2163
2164       for (const std::string& config : this->Configurations) {
2165         std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2166
2167         if (!evaluated.empty()) {
2168           toolSettings[config]["AdditionalOptions"] = evaluated;
2169         }
2170       }
2171     }
2172     // Figure out if debug information should be generated
2173     if (cmValue sed = sf->GetProperty("VS_SHADER_ENABLE_DEBUG")) {
2174       cmGeneratorExpression ge;
2175       std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sed);
2176
2177       for (const std::string& config : this->Configurations) {
2178         std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2179
2180         if (!evaluated.empty()) {
2181           toolSettings[config]["EnableDebuggingInformation"] =
2182             cmIsOn(evaluated) ? "true" : "false";
2183         }
2184       }
2185     }
2186     // Figure out if optimizations should be disabled
2187     if (cmValue sdo = sf->GetProperty("VS_SHADER_DISABLE_OPTIMIZATIONS")) {
2188       cmGeneratorExpression ge;
2189       std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*sdo);
2190
2191       for (const std::string& config : this->Configurations) {
2192         std::string evaluated = cge->Evaluate(this->LocalGenerator, config);
2193
2194         if (!evaluated.empty()) {
2195           toolSettings[config]["DisableOptimizations"] =
2196             cmIsOn(evaluated) ? "true" : "false";
2197         }
2198       }
2199     }
2200     if (cmValue sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) {
2201       for (const std::string& config : this->Configurations) {
2202         toolSettings[config]["ObjectFileOutput"] = *sofn;
2203       }
2204     }
2205   } else if (ext == "jpg" || ext == "png") {
2206     tool = "Image";
2207   } else if (ext == "resw") {
2208     tool = "PRIResource";
2209   } else if (ext == "xml") {
2210     tool = "XML";
2211   } else if (ext == "natvis") {
2212     tool = "Natvis";
2213   } else if (ext == "settings") {
2214     settingsLastGenOutput =
2215       cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2216     std::size_t pos = settingsLastGenOutput.find(".settings");
2217     settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
2218     settingsGenerator = "SettingsSingleFileGenerator";
2219     toolHasSettings = true;
2220   } else if (ext == "vsixmanifest") {
2221     subType = "Designer";
2222   }
2223   if (cmValue c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
2224     tool = "Content";
2225     copyToOutDir = *c;
2226     toolHasSettings = true;
2227   }
2228   if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
2229     includeInVsix = "True";
2230     tool = "Content";
2231     toolHasSettings = true;
2232   }
2233
2234   // Collect VS_CSHARP_* property values (if some are set)
2235   std::map<std::string, std::string> sourceFileTags;
2236   this->GetCSharpSourceProperties(sf, sourceFileTags);
2237
2238   if (this->NsightTegra) {
2239     // Nsight Tegra needs specific file types to check up-to-dateness.
2240     std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
2241     if (name == "androidmanifest.xml" || name == "build.xml" ||
2242         name == "proguard.cfg" || name == "proguard-project.txt" ||
2243         ext == "properties") {
2244       tool = "AndroidBuild";
2245     } else if (ext == "java") {
2246       tool = "JCompile";
2247     } else if (ext == "asm" || ext == "s") {
2248       tool = "ClCompile";
2249     }
2250   }
2251
2252   cmValue toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
2253   if (cmNonempty(toolOverride)) {
2254     tool = toolOverride->c_str();
2255   }
2256
2257   std::string deployContent;
2258   std::string deployLocation;
2259   if (this->GlobalGenerator->TargetsWindowsPhone() ||
2260       this->GlobalGenerator->TargetsWindowsStore()) {
2261     cmValue content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
2262     if (cmNonempty(content)) {
2263       toolHasSettings = true;
2264       deployContent = *content;
2265
2266       cmValue location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
2267       if (cmNonempty(location)) {
2268         deployLocation = *location;
2269       }
2270     }
2271   }
2272
2273   if (ParsedToolTargetSettings.find(tool) == ParsedToolTargetSettings.end()) {
2274     cmValue toolTargetProperty = this->GeneratorTarget->Target->GetProperty(
2275       "VS_SOURCE_SETTINGS_" + std::string(tool));
2276     ConfigToSettings toolTargetSettings;
2277     if (toolTargetProperty) {
2278       ParseSettingsProperty(*toolTargetProperty, toolTargetSettings);
2279     }
2280
2281     ParsedToolTargetSettings[tool] = toolTargetSettings;
2282   }
2283
2284   for (const auto& configToSetting : ParsedToolTargetSettings[tool]) {
2285     for (const auto& setting : configToSetting.second) {
2286       toolSettings[configToSetting.first][setting.first] = setting.second;
2287     }
2288   }
2289
2290   if (!toolSettings.empty()) {
2291     toolHasSettings = true;
2292   }
2293
2294   Elem e2(e1, tool);
2295   this->WriteSource(e2, sf);
2296   if (toolHasSettings) {
2297     e2.SetHasElements();
2298
2299     this->FinishWritingSource(e2, toolSettings);
2300
2301     if (!deployContent.empty()) {
2302       cmGeneratorExpression ge;
2303       std::unique_ptr<cmCompiledGeneratorExpression> cge =
2304         ge.Parse(deployContent);
2305       // Deployment location cannot be set on a configuration basis
2306       if (!deployLocation.empty()) {
2307         e2.Element("Link", deployLocation + "\\%(FileName)%(Extension)");
2308       }
2309       for (size_t i = 0; i != this->Configurations.size(); ++i) {
2310         if (cge->Evaluate(this->LocalGenerator, this->Configurations[i]) ==
2311             "1") {
2312           e2.WritePlatformConfigTag("DeploymentContent",
2313                                     "'$(Configuration)|$(Platform)'=='" +
2314                                       this->Configurations[i] + "|" +
2315                                       this->Platform + "'",
2316                                     "true");
2317         } else {
2318           e2.WritePlatformConfigTag("ExcludedFromBuild",
2319                                     "'$(Configuration)|$(Platform)'=='" +
2320                                       this->Configurations[i] + "|" +
2321                                       this->Platform + "'",
2322                                     "true");
2323         }
2324       }
2325     }
2326
2327     if (!settingsGenerator.empty()) {
2328       e2.Element("Generator", settingsGenerator);
2329     }
2330     if (!settingsLastGenOutput.empty()) {
2331       e2.Element("LastGenOutput", settingsLastGenOutput);
2332     }
2333     if (!subType.empty()) {
2334       e2.Element("SubType", subType);
2335     }
2336     if (!copyToOutDir.empty()) {
2337       e2.Element("CopyToOutputDirectory", copyToOutDir);
2338     }
2339     if (!includeInVsix.empty()) {
2340       e2.Element("IncludeInVSIX", includeInVsix);
2341     }
2342     // write source file specific tags
2343     this->WriteCSharpSourceProperties(e2, sourceFileTags);
2344   }
2345 }
2346
2347 void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2,
2348                                                   cmSourceFile const* sf)
2349 {
2350   // Visual Studio tools append relative paths to the current dir, as in:
2351   //
2352   //  c:\path\to\current\dir\..\..\..\relative\path\to\source.c
2353   //
2354   // and fail if this exceeds the maximum allowed path length.  Our path
2355   // conversion uses full paths when possible to allow deeper trees.
2356   // However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
2357   // we must use relative paths.
2358   bool forceRelative = sf->GetLanguage() == "CUDA";
2359   std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
2360   if (this->LocalGenerator->GetVersion() ==
2361         cmGlobalVisualStudioGenerator::VSVersion::VS10 &&
2362       cmSystemTools::FileIsFullPath(sourceFile)) {
2363     // Normal path conversion resulted in a full path.  VS 10 (but not 11)
2364     // refuses to show the property page in the IDE for a source file with a
2365     // full path (not starting in a '.' or '/' AFAICT).  CMake <= 2.8.4 used a
2366     // relative path but to allow deeper build trees CMake 2.8.[5678] used a
2367     // full path except for custom commands.  Custom commands do not work
2368     // without a relative path, but they do not seem to be involved in tools
2369     // with the above behavior.  For other sources we now use a relative path
2370     // when the combined path will not be too long so property pages appear.
2371     std::string sourceRel = this->ConvertPath(sf->GetFullPath(), true);
2372     size_t const maxLen = 250;
2373     if (sf->GetCustomCommand() ||
2374         ((this->LocalGenerator->GetCurrentBinaryDirectory().length() + 1 +
2375           sourceRel.length()) <= maxLen)) {
2376       forceRelative = true;
2377       sourceFile = sourceRel;
2378     } else {
2379       this->GlobalGenerator->PathTooLong(this->GeneratorTarget, sf, sourceRel);
2380     }
2381   }
2382   ConvertToWindowsSlash(sourceFile);
2383   e2.Attribute("Include", sourceFile);
2384
2385   if (this->ProjectType == VsProjectType::csproj && !this->InSourceBuild) {
2386     // For out of source projects we have to provide a link (if not specified
2387     // via property) for every source file (besides .cs files) otherwise they
2388     // will not be visible in VS at all.
2389     // First we check if the file is in a source group, then we check if the
2390     // file path is relative to current source- or binary-dir, otherwise it is
2391     // added with the plain filename without any path. This means the file will
2392     // show up at root-level of the csproj (where CMakeLists.txt etc. are).
2393     std::string link = this->GetCSharpSourceLink(sf);
2394     if (link.empty())
2395       link = cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
2396     e2.Element("Link", link);
2397   }
2398
2399   ToolSource toolSource = { sf, forceRelative };
2400   this->Tools[e2.Tag].push_back(toolSource);
2401 }
2402
2403 void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
2404 {
2405   if (this->GeneratorTarget->GetType() == cmStateEnums::GLOBAL_TARGET) {
2406     return;
2407   }
2408
2409   const bool haveUnityBuild =
2410     this->GeneratorTarget->GetPropertyAsBool("UNITY_BUILD");
2411
2412   if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2413     Elem e1(e0, "PropertyGroup");
2414     e1.Element("EnableUnitySupport", "true");
2415   }
2416
2417   Elem e1(e0, "ItemGroup");
2418   e1.SetHasElements();
2419
2420   std::vector<size_t> all_configs;
2421   for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
2422     all_configs.push_back(ci);
2423   }
2424
2425   std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
2426     this->GeneratorTarget->GetAllConfigSources();
2427
2428   cmSourceFile const* srcCMakeLists =
2429     this->LocalGenerator->CreateVCProjBuildRule();
2430
2431   for (cmGeneratorTarget::AllConfigSource const& si : sources) {
2432     if (si.Source == srcCMakeLists) {
2433       // Skip explicit reference to CMakeLists.txt source.
2434       continue;
2435     }
2436
2437     ConfigToSettings toolSettings;
2438     for (const auto& config : this->Configurations) {
2439       toolSettings[config];
2440     }
2441     if (cmValue p = si.Source->GetProperty("VS_SETTINGS")) {
2442       ParseSettingsProperty(*p, toolSettings);
2443     }
2444
2445     const char* tool = nullptr;
2446     switch (si.Kind) {
2447       case cmGeneratorTarget::SourceKindAppManifest:
2448         tool = "AppxManifest";
2449         break;
2450       case cmGeneratorTarget::SourceKindCertificate:
2451         tool = "None";
2452         break;
2453       case cmGeneratorTarget::SourceKindCustomCommand:
2454         // Handled elsewhere.
2455         break;
2456       case cmGeneratorTarget::SourceKindExternalObject:
2457         tool = "Object";
2458         if (this->LocalGenerator->GetVersion() <
2459             cmGlobalVisualStudioGenerator::VSVersion::VS11) {
2460           // For VS == 10 we cannot use LinkObjects to avoid linking custom
2461           // command outputs.  If an object file is generated in this target,
2462           // then vs10 will use it in the build, and we have to list it as
2463           // None instead of Object.
2464           std::vector<cmSourceFile*> const* d =
2465             this->GeneratorTarget->GetSourceDepends(si.Source);
2466           if (d && !d->empty()) {
2467             tool = "None";
2468           }
2469         }
2470         break;
2471       case cmGeneratorTarget::SourceKindExtra:
2472         this->WriteExtraSource(e1, si.Source, toolSettings);
2473         break;
2474       case cmGeneratorTarget::SourceKindHeader:
2475         this->WriteHeaderSource(e1, si.Source, toolSettings);
2476         break;
2477       case cmGeneratorTarget::SourceKindIDL:
2478         tool = "Midl";
2479         break;
2480       case cmGeneratorTarget::SourceKindManifest:
2481         // Handled elsewhere.
2482         break;
2483       case cmGeneratorTarget::SourceKindModuleDefinition:
2484         tool = "None";
2485         break;
2486       case cmGeneratorTarget::SourceKindUnityBatched:
2487       case cmGeneratorTarget::SourceKindObjectSource: {
2488         const std::string& lang = si.Source->GetLanguage();
2489         if (lang == "C" || lang == "CXX") {
2490           tool = "ClCompile";
2491         } else if (lang == "ASM_MASM" &&
2492                    this->GlobalGenerator->IsMasmEnabled()) {
2493           tool = "MASM";
2494         } else if (lang == "ASM_NASM" &&
2495                    this->GlobalGenerator->IsNasmEnabled()) {
2496           tool = "NASM";
2497         } else if (lang == "RC") {
2498           tool = "ResourceCompile";
2499         } else if (lang == "CSharp") {
2500           tool = "Compile";
2501         } else if (lang == "CUDA" && this->GlobalGenerator->IsCudaEnabled()) {
2502           tool = "CudaCompile";
2503         } else {
2504           tool = "None";
2505         }
2506       } break;
2507       case cmGeneratorTarget::SourceKindResx:
2508         this->ResxObjs.push_back(si.Source);
2509         break;
2510       case cmGeneratorTarget::SourceKindXaml:
2511         this->XamlObjs.push_back(si.Source);
2512         break;
2513     }
2514
2515     if (tool) {
2516       // Compute set of configurations to exclude, if any.
2517       std::vector<size_t> const& include_configs = si.Configs;
2518       std::vector<size_t> exclude_configs;
2519       std::set_difference(all_configs.begin(), all_configs.end(),
2520                           include_configs.begin(), include_configs.end(),
2521                           std::back_inserter(exclude_configs));
2522
2523       Elem e2(e1, tool);
2524       bool isCSharp = (si.Source->GetLanguage() == "CSharp");
2525       if (isCSharp && exclude_configs.size() > 0) {
2526         std::stringstream conditions;
2527         bool firstConditionSet{ false };
2528         for (const auto& ci : include_configs) {
2529           if (firstConditionSet) {
2530             conditions << " Or ";
2531           }
2532           conditions << "('$(Configuration)|$(Platform)'=='" +
2533               this->Configurations[ci] + "|" + this->Platform + "')";
2534           firstConditionSet = true;
2535         }
2536         e2.Attribute("Condition", conditions.str());
2537       }
2538       this->WriteSource(e2, si.Source);
2539
2540       bool useNativeUnityBuild = false;
2541       if (haveUnityBuild && this->GlobalGenerator->GetSupportsUnityBuilds()) {
2542         // Magic value taken from cmGlobalVisualStudioVersionedGenerator.cxx
2543         static const std::string vs15 = "141";
2544         std::string toolset =
2545           this->GlobalGenerator->GetPlatformToolsetString();
2546         cmSystemTools::ReplaceString(toolset, "v", "");
2547
2548         if (toolset.empty() ||
2549             cmSystemTools::VersionCompareGreaterEq(toolset, vs15)) {
2550           useNativeUnityBuild = true;
2551         }
2552       }
2553
2554       if (haveUnityBuild && strcmp(tool, "ClCompile") == 0 &&
2555           si.Source->GetProperty("UNITY_SOURCE_FILE")) {
2556         if (useNativeUnityBuild) {
2557           e2.Attribute(
2558             "IncludeInUnityFile",
2559             si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")
2560               ? "false"
2561               : "true");
2562           e2.Attribute("CustomUnityFile", "true");
2563
2564           std::string unityDir = cmSystemTools::GetFilenamePath(
2565             *si.Source->GetProperty("UNITY_SOURCE_FILE"));
2566           e2.Attribute("UnityFilesDirectory", unityDir);
2567         } else {
2568           // Visual Studio versions prior to 2017 15.8 do not know about unity
2569           // builds, thus we exclude the files already part of unity sources.
2570           if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
2571             exclude_configs = all_configs;
2572           }
2573         }
2574       }
2575
2576       if (si.Kind == cmGeneratorTarget::SourceKindObjectSource ||
2577           si.Kind == cmGeneratorTarget::SourceKindUnityBatched) {
2578         this->OutputSourceSpecificFlags(e2, si.Source);
2579       }
2580       if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
2581         e2.Element("PrecompiledHeader", "NotUsing");
2582       }
2583       if (!isCSharp && !exclude_configs.empty()) {
2584         this->WriteExcludeFromBuild(e2, exclude_configs);
2585       }
2586
2587       this->FinishWritingSource(e2, toolSettings);
2588     }
2589   }
2590
2591   if (this->IsMissingFiles) {
2592     this->WriteMissingFiles(e1);
2593   }
2594 }
2595
2596 void cmVisualStudio10TargetGenerator::FinishWritingSource(
2597   Elem& e2, ConfigToSettings const& toolSettings)
2598 {
2599   std::vector<std::string> writtenSettings;
2600   for (const auto& configSettings : toolSettings) {
2601     for (const auto& setting : configSettings.second) {
2602
2603       if (std::find(writtenSettings.begin(), writtenSettings.end(),
2604                     setting.first) != writtenSettings.end()) {
2605         continue;
2606       }
2607
2608       if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
2609         e2.Element(setting.first, setting.second);
2610         writtenSettings.push_back(setting.first);
2611       } else {
2612         e2.WritePlatformConfigTag(setting.first,
2613                                   "'$(Configuration)|$(Platform)'=='" +
2614                                     configSettings.first + "|" +
2615                                     this->Platform + "'",
2616                                   setting.second);
2617       }
2618     }
2619   }
2620 }
2621
2622 void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
2623   Elem& e2, cmSourceFile const* source)
2624 {
2625   cmSourceFile const& sf = *source;
2626
2627   std::string objectName;
2628   if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
2629     objectName = this->GeneratorTarget->GetObjectName(&sf);
2630   }
2631   std::string flags;
2632   bool configDependentFlags = false;
2633   std::string options;
2634   bool configDependentOptions = false;
2635   std::string defines;
2636   bool configDependentDefines = false;
2637   std::string includes;
2638   bool configDependentIncludes = false;
2639   if (cmValue cflags = sf.GetProperty("COMPILE_FLAGS")) {
2640     configDependentFlags =
2641       cmGeneratorExpression::Find(*cflags) != std::string::npos;
2642     flags += *cflags;
2643   }
2644   if (cmValue coptions = sf.GetProperty("COMPILE_OPTIONS")) {
2645     configDependentOptions =
2646       cmGeneratorExpression::Find(*coptions) != std::string::npos;
2647     options += *coptions;
2648   }
2649   if (cmValue cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
2650     configDependentDefines =
2651       cmGeneratorExpression::Find(*cdefs) != std::string::npos;
2652     defines += *cdefs;
2653   }
2654   if (cmValue cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
2655     configDependentIncludes =
2656       cmGeneratorExpression::Find(*cincludes) != std::string::npos;
2657     includes += *cincludes;
2658   }
2659
2660   // Force language if the file extension does not match.
2661   // Note that MSVC treats the upper-case '.C' extension as C and not C++.
2662   std::string const ext = sf.GetExtension();
2663   std::string const extLang = ext == "C"
2664     ? "C"
2665     : this->GlobalGenerator->GetLanguageFromExtension(ext.c_str());
2666   std::string lang = this->LocalGenerator->GetSourceFileLanguage(sf);
2667   const char* compileAs = 0;
2668   if (lang != extLang) {
2669     if (lang == "CXX") {
2670       // force a C++ file type
2671       compileAs = "CompileAsCpp";
2672     } else if (lang == "C") {
2673       // force to c
2674       compileAs = "CompileAsC";
2675     }
2676   }
2677
2678   bool noWinRT = this->TargetCompileAsWinRT && lang == "C";
2679   // for the first time we need a new line if there is something
2680   // produced here.
2681   if (!objectName.empty()) {
2682     if (lang == "CUDA") {
2683       e2.Element("CompileOut", "$(IntDir)/" + objectName);
2684     } else {
2685       e2.Element("ObjectFileName", "$(IntDir)/" + objectName);
2686     }
2687   }
2688
2689   if (lang == "ASM_NASM") {
2690     if (cmValue objectDeps = sf.GetProperty("OBJECT_DEPENDS")) {
2691       std::string dependencies;
2692       std::vector<std::string> depends = cmExpandedList(*objectDeps);
2693       const char* sep = "";
2694       for (std::string& d : depends) {
2695         ConvertToWindowsSlash(d);
2696         dependencies += sep;
2697         dependencies += d;
2698         sep = ";";
2699       }
2700       e2.Element("AdditionalDependencies", dependencies);
2701     }
2702   }
2703
2704   for (std::string const& config : this->Configurations) {
2705     std::string configUpper = cmSystemTools::UpperCase(config);
2706     std::string configDefines = defines;
2707     std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
2708     if (cmValue ccdefs = sf.GetProperty(defPropName)) {
2709       if (!configDefines.empty()) {
2710         configDefines += ";";
2711       }
2712       configDependentDefines |=
2713         cmGeneratorExpression::Find(*ccdefs) != std::string::npos;
2714       configDefines += *ccdefs;
2715     }
2716
2717     // We have pch state in the following situation:
2718     // 1. We have SKIP_PRECOMPILE_HEADERS == true
2719     // 2. We are creating the pre-compiled header
2720     // 3. We are a different language than the linker language AND pch is
2721     //    enabled.
2722     std::string const& linkLanguage =
2723       this->GeneratorTarget->GetLinkerLanguage(config);
2724     std::string const& pchSource =
2725       this->GeneratorTarget->GetPchSource(config, lang);
2726     const bool skipPCH =
2727       pchSource.empty() || sf.GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS");
2728     const bool makePCH = (sf.GetFullPath() == pchSource);
2729     const bool useSharedPCH = !skipPCH && (lang == linkLanguage);
2730     const bool useDifferentLangPCH = !skipPCH && (lang != linkLanguage);
2731     const bool useNoPCH = skipPCH && (lang != linkLanguage) &&
2732       !this->GeneratorTarget->GetPchHeader(config, linkLanguage).empty();
2733     const bool needsPCHFlags =
2734       (makePCH || useSharedPCH || useDifferentLangPCH || useNoPCH);
2735
2736     // if we have flags or defines for this config then
2737     // use them
2738     if (!flags.empty() || !options.empty() || !configDefines.empty() ||
2739         !includes.empty() || compileAs || noWinRT || !options.empty() ||
2740         needsPCHFlags) {
2741       cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
2742       cmIDEFlagTable const* flagtable = nullptr;
2743       const std::string& srclang = source->GetLanguage();
2744       if (srclang == "C" || srclang == "CXX") {
2745         flagtable = gg->GetClFlagTable();
2746       } else if (srclang == "ASM_MASM" &&
2747                  this->GlobalGenerator->IsMasmEnabled()) {
2748         flagtable = gg->GetMasmFlagTable();
2749       } else if (lang == "ASM_NASM" &&
2750                  this->GlobalGenerator->IsNasmEnabled()) {
2751         flagtable = gg->GetNasmFlagTable();
2752       } else if (srclang == "RC") {
2753         flagtable = gg->GetRcFlagTable();
2754       } else if (srclang == "CSharp") {
2755         flagtable = gg->GetCSharpFlagTable();
2756       }
2757       cmGeneratorExpressionInterpreter genexInterpreter(
2758         this->LocalGenerator, config, this->GeneratorTarget, lang);
2759       cmVS10GeneratorOptions clOptions(
2760         this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
2761         flagtable, this);
2762       if (compileAs) {
2763         clOptions.AddFlag("CompileAs", compileAs);
2764       }
2765       if (noWinRT) {
2766         clOptions.AddFlag("CompileAsWinRT", "false");
2767       }
2768       if (configDependentFlags) {
2769         clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
2770       } else {
2771         clOptions.Parse(flags);
2772       }
2773
2774       if (needsPCHFlags) {
2775         // Add precompile headers compile options.
2776         if (makePCH) {
2777           clOptions.AddFlag("PrecompiledHeader", "Create");
2778           std::string pchHeader =
2779             this->GeneratorTarget->GetPchHeader(config, lang);
2780           clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2781           std::string pchFile =
2782             this->GeneratorTarget->GetPchFile(config, lang);
2783           clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2784           clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2785         } else if (useNoPCH) {
2786           clOptions.AddFlag("PrecompiledHeader", "NotUsing");
2787         } else if (useSharedPCH) {
2788           std::string pchHeader =
2789             this->GeneratorTarget->GetPchHeader(config, lang);
2790           clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2791         } else if (useDifferentLangPCH) {
2792           clOptions.AddFlag("PrecompiledHeader", "Use");
2793           std::string pchHeader =
2794             this->GeneratorTarget->GetPchHeader(config, lang);
2795           clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
2796           std::string pchFile =
2797             this->GeneratorTarget->GetPchFile(config, lang);
2798           clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
2799           clOptions.AddFlag("ForcedIncludeFiles", pchHeader);
2800         }
2801       }
2802
2803       if (!options.empty()) {
2804         std::string expandedOptions;
2805         if (configDependentOptions) {
2806           this->LocalGenerator->AppendCompileOptions(
2807             expandedOptions,
2808             genexInterpreter.Evaluate(options, "COMPILE_OPTIONS"));
2809         } else {
2810           this->LocalGenerator->AppendCompileOptions(expandedOptions, options);
2811         }
2812         clOptions.Parse(expandedOptions);
2813       }
2814       if (clOptions.HasFlag("DisableSpecificWarnings")) {
2815         clOptions.AppendFlag("DisableSpecificWarnings",
2816                              "%(DisableSpecificWarnings)");
2817       }
2818       if (clOptions.HasFlag("ForcedIncludeFiles")) {
2819         clOptions.AppendFlag("ForcedIncludeFiles", "%(ForcedIncludeFiles)");
2820       }
2821       if (configDependentDefines) {
2822         clOptions.AddDefines(
2823           genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
2824       } else {
2825         clOptions.AddDefines(configDefines);
2826       }
2827       std::vector<std::string> includeList;
2828       if (configDependentIncludes) {
2829         this->LocalGenerator->AppendIncludeDirectories(
2830           includeList,
2831           genexInterpreter.Evaluate(includes, "INCLUDE_DIRECTORIES"), *source);
2832       } else {
2833         this->LocalGenerator->AppendIncludeDirectories(includeList, includes,
2834                                                        *source);
2835       }
2836       clOptions.AddIncludes(includeList);
2837       clOptions.SetConfiguration(config);
2838       OptionsHelper oh(clOptions, e2);
2839       oh.PrependInheritedString("AdditionalOptions");
2840       oh.OutputAdditionalIncludeDirectories(lang);
2841       oh.OutputFlagMap();
2842       oh.OutputPreprocessorDefinitions(lang);
2843     }
2844   }
2845   if (this->IsXamlSource(source->GetFullPath())) {
2846     const std::string& fileName = source->GetFullPath();
2847     e2.Element("DependentUpon",
2848                fileName.substr(0, fileName.find_last_of(".")));
2849   }
2850   if (this->ProjectType == VsProjectType::csproj) {
2851     std::string f = source->GetFullPath();
2852     using CsPropMap = std::map<std::string, std::string>;
2853     CsPropMap sourceFileTags;
2854     this->GetCSharpSourceProperties(&sf, sourceFileTags);
2855     // write source file specific tags
2856     if (!sourceFileTags.empty()) {
2857       this->WriteCSharpSourceProperties(e2, sourceFileTags);
2858     }
2859   }
2860 }
2861
2862 void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
2863   Elem& e2, std::vector<size_t> const& exclude_configs)
2864 {
2865   for (size_t ci : exclude_configs) {
2866     e2.WritePlatformConfigTag("ExcludedFromBuild",
2867                               "'$(Configuration)|$(Platform)'=='" +
2868                                 this->Configurations[ci] + "|" +
2869                                 this->Platform + "'",
2870                               "true");
2871   }
2872 }
2873
2874 void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions(
2875   Elem& e0)
2876 {
2877   cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
2878   if (ttype > cmStateEnums::GLOBAL_TARGET) {
2879     return;
2880   }
2881   if (this->ProjectType == VsProjectType::csproj) {
2882     return;
2883   }
2884
2885   Elem e1(e0, "PropertyGroup");
2886   e1.Element("_ProjectFileVersion", "10.0.20506.1");
2887   for (std::string const& config : this->Configurations) {
2888     const std::string cond = this->CalcCondition(config);
2889
2890     if (ttype >= cmStateEnums::UTILITY) {
2891       e1.WritePlatformConfigTag(
2892         "IntDir", cond, "$(Platform)\\$(Configuration)\\$(ProjectName)\\");
2893     } else {
2894       std::string intermediateDir = cmStrCat(
2895         this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/',
2896         config, '/');
2897       std::string outDir;
2898       std::string targetNameFull;
2899       if (ttype == cmStateEnums::OBJECT_LIBRARY) {
2900         outDir = intermediateDir;
2901         targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib");
2902       } else {
2903         outDir = this->GeneratorTarget->GetDirectory(config) + "/";
2904         targetNameFull = this->GeneratorTarget->GetFullName(config);
2905       }
2906       ConvertToWindowsSlash(intermediateDir);
2907       ConvertToWindowsSlash(outDir);
2908
2909       e1.WritePlatformConfigTag("OutDir", cond, outDir);
2910
2911       e1.WritePlatformConfigTag("IntDir", cond, intermediateDir);
2912
2913       if (cmValue sdkExecutableDirectories = this->Makefile->GetDefinition(
2914             "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) {
2915         e1.WritePlatformConfigTag("ExecutablePath", cond,
2916                                   *sdkExecutableDirectories);
2917       }
2918
2919       if (cmValue sdkIncludeDirectories = this->Makefile->GetDefinition(
2920             "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) {
2921         e1.WritePlatformConfigTag("IncludePath", cond, *sdkIncludeDirectories);
2922       }
2923
2924       if (cmValue sdkReferenceDirectories = this->Makefile->GetDefinition(
2925             "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) {
2926         e1.WritePlatformConfigTag("ReferencePath", cond,
2927                                   *sdkReferenceDirectories);
2928       }
2929
2930       if (cmValue sdkLibraryDirectories = this->Makefile->GetDefinition(
2931             "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) {
2932         e1.WritePlatformConfigTag("LibraryPath", cond, *sdkLibraryDirectories);
2933       }
2934
2935       if (cmValue sdkLibraryWDirectories = this->Makefile->GetDefinition(
2936             "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) {
2937         e1.WritePlatformConfigTag("LibraryWPath", cond,
2938                                   *sdkLibraryWDirectories);
2939       }
2940
2941       if (cmValue sdkSourceDirectories =
2942             this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) {
2943         e1.WritePlatformConfigTag("SourcePath", cond, *sdkSourceDirectories);
2944       }
2945
2946       if (cmValue sdkExcludeDirectories = this->Makefile->GetDefinition(
2947             "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) {
2948         e1.WritePlatformConfigTag("ExcludePath", cond, *sdkExcludeDirectories);
2949       }
2950
2951       std::string name =
2952         cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
2953       e1.WritePlatformConfigTag("TargetName", cond, name);
2954
2955       std::string ext =
2956         cmSystemTools::GetFilenameLastExtension(targetNameFull);
2957       if (ext.empty()) {
2958         // An empty TargetExt causes a default extension to be used.
2959         // A single "." appears to be treated as an empty extension.
2960         ext = ".";
2961       }
2962       e1.WritePlatformConfigTag("TargetExt", cond, ext);
2963
2964       this->OutputLinkIncremental(e1, config);
2965     }
2966
2967     if (ttype <= cmStateEnums::UTILITY) {
2968       if (cmValue workingDir = this->GeneratorTarget->GetProperty(
2969             "VS_DEBUGGER_WORKING_DIRECTORY")) {
2970         std::string genWorkingDir = cmGeneratorExpression::Evaluate(
2971           *workingDir, this->LocalGenerator, config);
2972         e1.WritePlatformConfigTag("LocalDebuggerWorkingDirectory", cond,
2973                                   genWorkingDir);
2974       }
2975
2976       if (cmValue environment =
2977             this->GeneratorTarget->GetProperty("VS_DEBUGGER_ENVIRONMENT")) {
2978         std::string genEnvironment = cmGeneratorExpression::Evaluate(
2979           *environment, this->LocalGenerator, config);
2980         e1.WritePlatformConfigTag("LocalDebuggerEnvironment", cond,
2981                                   genEnvironment);
2982       }
2983
2984       if (cmValue debuggerCommand =
2985             this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) {
2986         std::string genDebuggerCommand = cmGeneratorExpression::Evaluate(
2987           *debuggerCommand, this->LocalGenerator, config);
2988         e1.WritePlatformConfigTag("LocalDebuggerCommand", cond,
2989                                   genDebuggerCommand);
2990       }
2991
2992       if (cmValue commandArguments = this->GeneratorTarget->GetProperty(
2993             "VS_DEBUGGER_COMMAND_ARGUMENTS")) {
2994         std::string genCommandArguments = cmGeneratorExpression::Evaluate(
2995           *commandArguments, this->LocalGenerator, config);
2996         e1.WritePlatformConfigTag("LocalDebuggerCommandArguments", cond,
2997                                   genCommandArguments);
2998       }
2999     }
3000   }
3001 }
3002
3003 void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
3004   Elem& e1, std::string const& configName)
3005 {
3006   if (!this->MSTools) {
3007     return;
3008   }
3009   if (this->ProjectType == VsProjectType::csproj) {
3010     return;
3011   }
3012   // static libraries and things greater than modules do not need
3013   // to set this option
3014   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
3015       this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
3016     return;
3017   }
3018   Options& linkOptions = *(this->LinkOptions[configName]);
3019   const std::string cond = this->CalcCondition(configName);
3020
3021   if (this->IPOEnabledConfigurations.count(configName) == 0) {
3022     const char* incremental = linkOptions.GetFlag("LinkIncremental");
3023     e1.WritePlatformConfigTag("LinkIncremental", cond,
3024                               (incremental ? incremental : "true"));
3025   }
3026   linkOptions.RemoveFlag("LinkIncremental");
3027
3028   const char* manifest = linkOptions.GetFlag("GenerateManifest");
3029   e1.WritePlatformConfigTag("GenerateManifest", cond,
3030                             (manifest ? manifest : "true"));
3031   linkOptions.RemoveFlag("GenerateManifest");
3032
3033   // Some link options belong here.  Use them now and remove them so that
3034   // WriteLinkOptions does not use them.
3035   static const std::vector<std::string> flags{ "LinkDelaySign",
3036                                                "LinkKeyFile" };
3037   for (const std::string& flag : flags) {
3038     if (const char* value = linkOptions.GetFlag(flag)) {
3039       e1.WritePlatformConfigTag(flag, cond, value);
3040       linkOptions.RemoveFlag(flag);
3041     }
3042   }
3043 }
3044
3045 std::vector<std::string> cmVisualStudio10TargetGenerator::GetIncludes(
3046   std::string const& config, std::string const& lang) const
3047 {
3048   std::vector<std::string> includes;
3049   this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
3050                                               lang, config);
3051   for (std::string& i : includes) {
3052     ConvertToWindowsSlash(i);
3053   }
3054   return includes;
3055 }
3056
3057 bool cmVisualStudio10TargetGenerator::ComputeClOptions()
3058 {
3059   for (std::string const& c : this->Configurations) {
3060     if (!this->ComputeClOptions(c)) {
3061       return false;
3062     }
3063   }
3064   return true;
3065 }
3066
3067 bool cmVisualStudio10TargetGenerator::ComputeClOptions(
3068   std::string const& configName)
3069 {
3070   // much of this was copied from here:
3071   // copied from cmLocalVisualStudio7Generator.cxx 805
3072   // TODO: Integrate code below with cmLocalVisualStudio7Generator.
3073
3074   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3075   std::unique_ptr<Options> pOptions;
3076   switch (this->ProjectType) {
3077     case VsProjectType::vcxproj:
3078       pOptions = cm::make_unique<Options>(
3079         this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
3080       break;
3081     case VsProjectType::csproj:
3082       pOptions =
3083         cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
3084                                  gg->GetCSharpFlagTable());
3085       break;
3086     default:
3087       break;
3088   }
3089   Options& clOptions = *pOptions;
3090
3091   std::string flags;
3092   const std::string& linkLanguage =
3093     this->GeneratorTarget->GetLinkerLanguage(configName);
3094   if (linkLanguage.empty()) {
3095     cmSystemTools::Error(
3096       "CMake can not determine linker language for target: " + this->Name);
3097     return false;
3098   }
3099
3100   // Choose a language whose flags to use for ClCompile.
3101   static const char* clLangs[] = { "CXX", "C", "Fortran" };
3102   std::string langForClCompile;
3103   if (this->ProjectType == VsProjectType::csproj) {
3104     langForClCompile = "CSharp";
3105   } else if (cm::contains(clLangs, linkLanguage)) {
3106     langForClCompile = linkLanguage;
3107   } else {
3108     std::set<std::string> languages;
3109     this->GeneratorTarget->GetLanguages(languages, configName);
3110     for (const char* l : clLangs) {
3111       if (languages.count(l)) {
3112         langForClCompile = l;
3113         break;
3114       }
3115     }
3116   }
3117   this->LangForClCompile = langForClCompile;
3118   if (!langForClCompile.empty()) {
3119     this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3120                                            langForClCompile, configName);
3121     this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
3122                                             langForClCompile, configName);
3123   }
3124
3125   // Put the IPO enabled configurations into a set.
3126   if (this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName)) {
3127     this->IPOEnabledConfigurations.insert(configName);
3128   }
3129
3130   // Check if ASan is enabled.
3131   if (flags.find("/fsanitize=address") != std::string::npos) {
3132     this->ASanEnabledConfigurations.insert(configName);
3133   }
3134
3135   // Precompile Headers
3136   std::string pchHeader =
3137     this->GeneratorTarget->GetPchHeader(configName, linkLanguage);
3138   if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3139       pchHeader.empty()) {
3140     clOptions.AddFlag("PrecompiledHeader", "NotUsing");
3141   } else if (this->MSTools && VsProjectType::vcxproj == this->ProjectType &&
3142              !pchHeader.empty()) {
3143     clOptions.AddFlag("PrecompiledHeader", "Use");
3144     clOptions.AddFlag("PrecompiledHeaderFile", pchHeader);
3145     std::string pchFile =
3146       this->GeneratorTarget->GetPchFile(configName, linkLanguage);
3147     clOptions.AddFlag("PrecompiledHeaderOutputFile", pchFile);
3148   }
3149
3150   // Get preprocessor definitions for this directory.
3151   std::string defineFlags = this->Makefile->GetDefineFlags();
3152   if (this->MSTools) {
3153     if (this->ProjectType == VsProjectType::vcxproj) {
3154       clOptions.FixExceptionHandlingDefault();
3155       if (this->GlobalGenerator->GetVersion() >=
3156           cmGlobalVisualStudioGenerator::VSVersion::VS15) {
3157         // Toolsets that come with VS 2017 may now enable UseFullPaths
3158         // by default and there is no negative /FC option that projects
3159         // can use to switch it back.  Older toolsets disable this by
3160         // default anyway so this will not hurt them.  If the project
3161         // is using an explicit /FC option then parsing flags will
3162         // replace this setting with "true" below.
3163         clOptions.AddFlag("UseFullPaths", "false");
3164       }
3165       clOptions.AddFlag("AssemblerListingLocation", "$(IntDir)");
3166     }
3167   }
3168
3169   // check for managed C++ assembly compiler flag. This overrides any
3170   // /clr* compiler flags which may be defined in the flags variable(s).
3171   if (this->ProjectType != VsProjectType::csproj) {
3172     // Warn if /clr was added manually. This should not be done
3173     // anymore, because cmGeneratorTarget may not be aware that the
3174     // target uses C++/CLI.
3175     if (flags.find("/clr") != std::string::npos ||
3176         defineFlags.find("/clr") != std::string::npos) {
3177       if (configName == this->Configurations[0]) {
3178         std::string message = "For the target \"" +
3179           this->GeneratorTarget->GetName() +
3180           "\" the /clr compiler flag was added manually. " +
3181           "Set usage of C++/CLI by setting COMMON_LANGUAGE_RUNTIME "
3182           "target property.";
3183         this->Makefile->IssueMessage(MessageType::WARNING, message);
3184       }
3185     }
3186     if (cmValue clr =
3187           this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
3188       std::string clrString = *clr;
3189       if (!clrString.empty()) {
3190         clrString = ":" + clrString;
3191       }
3192       flags += " /clr" + clrString;
3193     }
3194   }
3195
3196   // Get includes for this target
3197   if (!this->LangForClCompile.empty()) {
3198     auto includeList = this->GetIncludes(configName, this->LangForClCompile);
3199
3200     auto sysIncludeFlag = this->Makefile->GetDefinition(
3201       cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile));
3202
3203     if (sysIncludeFlag) {
3204       bool gotOneSys = false;
3205       for (auto i : includeList) {
3206         cmSystemTools::ConvertToUnixSlashes(i);
3207         if (this->GeneratorTarget->IsSystemIncludeDirectory(
3208               i, configName, this->LangForClCompile)) {
3209           auto flag = cmTrimWhitespace(*sysIncludeFlag);
3210           if (this->MSTools) {
3211             cmSystemTools::ReplaceString(flag, "-external:I", "/external:I");
3212           }
3213           clOptions.AppendFlagString("AdditionalOptions",
3214                                      cmStrCat(flag, " \"", i, '"'));
3215           gotOneSys = true;
3216         } else {
3217           clOptions.AddInclude(i);
3218         }
3219       }
3220
3221       if (gotOneSys) {
3222         if (auto sysIncludeFlagWarning = this->Makefile->GetDefinition(
3223               cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", this->LangForClCompile,
3224                        "_WARNING"))) {
3225           flags = cmStrCat(flags, ' ', *sysIncludeFlagWarning);
3226         }
3227       }
3228     } else {
3229       clOptions.AddIncludes(includeList);
3230     }
3231   }
3232
3233   clOptions.Parse(flags);
3234   clOptions.Parse(defineFlags);
3235   std::vector<std::string> targetDefines;
3236   switch (this->ProjectType) {
3237     case VsProjectType::vcxproj:
3238       if (!langForClCompile.empty()) {
3239         this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3240                                                      langForClCompile);
3241       }
3242       break;
3243     case VsProjectType::csproj:
3244       this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3245                                                    "CSharp");
3246       cm::erase_if(targetDefines, [](std::string const& def) {
3247         return def.find('=') != std::string::npos;
3248       });
3249       break;
3250     default:
3251       break;
3252   }
3253   clOptions.AddDefines(targetDefines);
3254
3255   if (this->ProjectType == VsProjectType::csproj) {
3256     clOptions.AppendFlag("DefineConstants", targetDefines);
3257   }
3258
3259   if (this->MSTools) {
3260     clOptions.SetVerboseMakefile(
3261       this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
3262   }
3263
3264   // Add C-specific flags expressible in a ClCompile meant for C++.
3265   if (langForClCompile == "CXX") {
3266     std::set<std::string> languages;
3267     this->GeneratorTarget->GetLanguages(languages, configName);
3268     if (languages.count("C")) {
3269       std::string flagsC;
3270       this->LocalGenerator->AddCompileOptions(flagsC, this->GeneratorTarget,
3271                                               "C", configName);
3272       Options optC(this->LocalGenerator, Options::Compiler,
3273                    gg->GetClFlagTable());
3274       optC.Parse(flagsC);
3275       if (const char* stdC = optC.GetFlag("LanguageStandard_C")) {
3276         clOptions.AddFlag("LanguageStandard_C", stdC);
3277       }
3278     }
3279   }
3280
3281   // Add a definition for the configuration name.
3282   std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3283   clOptions.AddDefine(configDefine);
3284   if (const std::string* exportMacro =
3285         this->GeneratorTarget->GetExportMacro()) {
3286     clOptions.AddDefine(*exportMacro);
3287   }
3288
3289   if (this->MSTools) {
3290     // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT
3291     if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
3292       clOptions.AddFlag("CompileAsWinRT", "true");
3293       // For WinRT components, add the _WINRT_DLL define to produce a lib
3294       if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
3295           this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
3296         clOptions.AddDefine("_WINRT_DLL");
3297       }
3298     } else if (this->GlobalGenerator->TargetsWindowsStore() ||
3299                this->GlobalGenerator->TargetsWindowsPhone() ||
3300                this->Makefile->IsOn("CMAKE_VS_WINRT_BY_DEFAULT")) {
3301       if (!clOptions.IsWinRt()) {
3302         clOptions.AddFlag("CompileAsWinRT", "false");
3303       }
3304     }
3305     if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
3306       if (cmIsOn(winRT)) {
3307         this->TargetCompileAsWinRT = true;
3308       }
3309     }
3310   }
3311
3312   if (this->ProjectType != VsProjectType::csproj && clOptions.IsManaged()) {
3313     this->Managed = true;
3314     std::string managedType = clOptions.GetFlag("CompileAsManaged");
3315     if (managedType == "Safe" || managedType == "Pure") {
3316       // force empty calling convention if safe clr is used
3317       clOptions.AddFlag("CallingConvention", "");
3318     }
3319     // The default values of these flags are incompatible to
3320     // managed assemblies. We have to force valid values if
3321     // the target is a managed C++ target.
3322     clOptions.AddFlag("ExceptionHandling", "Async");
3323     clOptions.AddFlag("BasicRuntimeChecks", "Default");
3324   }
3325   if (this->ProjectType == VsProjectType::csproj) {
3326     // /nowin32manifest overrides /win32manifest: parameter
3327     if (clOptions.HasFlag("NoWin32Manifest")) {
3328       clOptions.RemoveFlag("ApplicationManifest");
3329     }
3330   }
3331
3332   if (const char* s = clOptions.GetFlag("SpectreMitigation")) {
3333     this->SpectreMitigation[configName] = s;
3334     clOptions.RemoveFlag("SpectreMitigation");
3335   }
3336
3337   // Remove any target-wide -TC or -TP flag added by the project.
3338   // Such flags are unnecessary and break our model of language selection.
3339   if (langForClCompile == "C" || langForClCompile == "CXX") {
3340     clOptions.RemoveFlag("CompileAs");
3341   }
3342
3343   this->ClOptions[configName] = std::move(pOptions);
3344   return true;
3345 }
3346
3347 void cmVisualStudio10TargetGenerator::WriteClOptions(
3348   Elem& e1, std::string const& configName)
3349 {
3350   Options& clOptions = *(this->ClOptions[configName]);
3351   if (this->ProjectType == VsProjectType::csproj) {
3352     return;
3353   }
3354   Elem e2(e1, "ClCompile");
3355   OptionsHelper oh(clOptions, e2);
3356   oh.PrependInheritedString("AdditionalOptions");
3357   oh.OutputAdditionalIncludeDirectories(this->LangForClCompile);
3358   oh.OutputFlagMap();
3359   oh.OutputPreprocessorDefinitions(this->LangForClCompile);
3360
3361   if (this->NsightTegra) {
3362     if (cmValue processMax =
3363           this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
3364       e2.Element("ProcessMax", *processMax);
3365     }
3366   }
3367
3368   if (this->Android) {
3369     e2.Element("ObjectFileName", "$(IntDir)%(filename).o");
3370   } else if (this->MSTools) {
3371     cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
3372     const char* toolset = this->GlobalGenerator->GetPlatformToolset();
3373     cmValue noCompileBatching =
3374       this->GeneratorTarget->GetProperty("VS_NO_COMPILE_BATCHING");
3375     if (noCompileBatching.IsOn() || (toolset && clangToolset.find(toolset))) {
3376       e2.Element("ObjectFileName", "$(IntDir)%(filename).obj");
3377     } else {
3378       e2.Element("ObjectFileName", "$(IntDir)");
3379     }
3380
3381     // If not in debug mode, write the DebugInformationFormat field
3382     // without value so PDBs don't get generated uselessly. Each tag
3383     // goes on its own line because Visual Studio corrects it this
3384     // way when saving the project after CMake generates it.
3385     if (!clOptions.IsDebug()) {
3386       Elem e3(e2, "DebugInformationFormat");
3387       e3.SetHasElements();
3388     }
3389
3390     // Specify the compiler program database file if configured.
3391     std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3392     if (!pdb.empty()) {
3393       if (this->GlobalGenerator->IsCudaEnabled()) {
3394         // CUDA does not quote paths with spaces correctly when forwarding
3395         // this to the host compiler.  Use a relative path to avoid spaces.
3396         // FIXME: We can likely do this even when CUDA is not involved,
3397         // but for now we will make a minimal change.
3398         pdb = this->ConvertPath(pdb, true);
3399       }
3400       ConvertToWindowsSlash(pdb);
3401       e2.Element("ProgramDataBaseFileName", pdb);
3402     }
3403
3404     // add AdditionalUsingDirectories
3405     if (this->AdditionalUsingDirectories.count(configName) > 0) {
3406       std::string dirs;
3407       for (auto u : this->AdditionalUsingDirectories[configName]) {
3408         if (!dirs.empty()) {
3409           dirs.append(";");
3410         }
3411         dirs.append(u);
3412       }
3413       e2.Element("AdditionalUsingDirectories", dirs);
3414     }
3415   }
3416 }
3417
3418 bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
3419 {
3420   for (std::string const& c : this->Configurations) {
3421     if (!this->ComputeRcOptions(c)) {
3422       return false;
3423     }
3424   }
3425   return true;
3426 }
3427
3428 bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
3429   std::string const& configName)
3430 {
3431   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3432   auto pOptions = cm::make_unique<Options>(
3433     this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
3434   Options& rcOptions = *pOptions;
3435
3436   std::string CONFIG = cmSystemTools::UpperCase(configName);
3437   std::string rcConfigFlagsVar = "CMAKE_RC_FLAGS_" + CONFIG;
3438   std::string flags = this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS") +
3439     " " + this->Makefile->GetSafeDefinition(rcConfigFlagsVar);
3440
3441   rcOptions.Parse(flags);
3442
3443   // For historical reasons, add the C preprocessor defines to RC.
3444   Options& clOptions = *(this->ClOptions[configName]);
3445   rcOptions.AddDefines(clOptions.GetDefines());
3446
3447   // Get includes for this target
3448   rcOptions.AddIncludes(this->GetIncludes(configName, "RC"));
3449
3450   this->RcOptions[configName] = std::move(pOptions);
3451   return true;
3452 }
3453
3454 void cmVisualStudio10TargetGenerator::WriteRCOptions(
3455   Elem& e1, std::string const& configName)
3456 {
3457   if (!this->MSTools) {
3458     return;
3459   }
3460   Elem e2(e1, "ResourceCompile");
3461
3462   OptionsHelper rcOptions(*(this->RcOptions[configName]), e2);
3463   rcOptions.OutputPreprocessorDefinitions("RC");
3464   rcOptions.OutputAdditionalIncludeDirectories("RC");
3465   rcOptions.PrependInheritedString("AdditionalOptions");
3466   rcOptions.OutputFlagMap();
3467 }
3468
3469 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
3470 {
3471   if (!this->GlobalGenerator->IsCudaEnabled()) {
3472     return true;
3473   }
3474   for (std::string const& c : this->Configurations) {
3475     if (this->GeneratorTarget->IsLanguageUsed("CUDA", c) &&
3476         !this->ComputeCudaOptions(c)) {
3477       return false;
3478     }
3479   }
3480   return true;
3481 }
3482
3483 bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
3484   std::string const& configName)
3485 {
3486   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3487   auto pOptions = cm::make_unique<Options>(
3488     this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3489   Options& cudaOptions = *pOptions;
3490
3491   auto cudaVersion = this->GlobalGenerator->GetPlatformToolsetCudaString();
3492
3493   // Get compile flags for CUDA in this directory.
3494   std::string flags;
3495   this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget, "CUDA",
3496                                          configName);
3497   this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
3498                                           configName);
3499
3500   // Get preprocessor definitions for this directory.
3501   std::string defineFlags = this->Makefile->GetDefineFlags();
3502
3503   cudaOptions.Parse(flags);
3504   cudaOptions.Parse(defineFlags);
3505   cudaOptions.ParseFinish();
3506
3507   // If we haven't explicitly enabled GPU debug information
3508   // explicitly disable it
3509   if (!cudaOptions.HasFlag("GPUDebugInfo")) {
3510     cudaOptions.AddFlag("GPUDebugInfo", "false");
3511   }
3512
3513   // The extension on object libraries the CUDA gives isn't
3514   // consistent with how MSVC generates object libraries for C+, so set
3515   // the default to not have any extension
3516   cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).obj");
3517
3518   if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
3519     cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
3520   }
3521   bool notPtx = true;
3522   if (this->GeneratorTarget->GetPropertyAsBool("CUDA_PTX_COMPILATION")) {
3523     cudaOptions.AddFlag("NvccCompilation", "ptx");
3524     // We drop the %(Extension) component as CMake expects all PTX files
3525     // to not have the source file extension at all
3526     cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
3527     notPtx = false;
3528
3529     if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
3530                                       cudaVersion, "9.0") &&
3531         cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, cudaVersion,
3532                                       "11.5")) {
3533       // The DriverApi flag before 11.5 ( verified back to 9.0 ) which controls
3534       // PTX compilation doesn't propagate user defines causing
3535       // target_compile_definitions to behave differently for VS +
3536       // PTX compared to other generators so we patch the rules
3537       // to normalize behavior
3538       cudaOptions.AddFlag("DriverApiCommandLineTemplate",
3539                           "%(BaseCommandLineTemplate) [CompileOut] [FastMath] "
3540                           "[Defines] \"%(FullPath)\"");
3541     }
3542   }
3543
3544   if (notPtx &&
3545       cmSystemTools::VersionCompareGreaterEq(
3546         "8.0", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3547     // Explicitly state that we want this file to be treated as a
3548     // CUDA file no matter what the file extensions is
3549     // This is only needed for < CUDA 9
3550     cudaOptions.AppendFlagString("AdditionalOptions", "-x cu");
3551   }
3552
3553   // Specify the compiler program database file if configured.
3554   std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
3555   if (!pdb.empty()) {
3556     // CUDA does not make the directory if it is non-standard.
3557     std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb);
3558     cmSystemTools::MakeDirectory(pdbDir);
3559     if (cmSystemTools::VersionCompareGreaterEq(
3560           "9.2", this->GlobalGenerator->GetPlatformToolsetCudaString())) {
3561       // CUDA does not have a field for this and does not honor the
3562       // ProgramDataBaseFileName field in ClCompile.  Work around this
3563       // limitation by creating the directory and passing the flag ourselves.
3564       pdb = this->ConvertPath(pdb, true);
3565       ConvertToWindowsSlash(pdb);
3566       std::string const clFd = "-Xcompiler=\"-Fd\\\"" + pdb + "\\\"\"";
3567       cudaOptions.AppendFlagString("AdditionalOptions", clFd);
3568     }
3569   }
3570
3571   // CUDA automatically passes the proper '--machine' flag to nvcc
3572   // for the current architecture, but does not reflect this default
3573   // in the user-visible IDE settings.  Set it explicitly.
3574   if (this->Platform == "x64") {
3575     cudaOptions.AddFlag("TargetMachinePlatform", "64");
3576   }
3577
3578   // Convert the host compiler options to the toolset's abstractions
3579   // using a secondary flag table.
3580   cudaOptions.ClearTables();
3581   cudaOptions.AddTable(gg->GetCudaHostFlagTable());
3582   cudaOptions.Reparse("AdditionalCompilerOptions");
3583
3584   // `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
3585   // Pass them through -Xcompiler in AdditionalOptions instead.
3586   if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
3587     std::string aco = acoPtr;
3588     cudaOptions.RemoveFlag("AdditionalCompilerOptions");
3589     if (!aco.empty()) {
3590       aco = this->LocalGenerator->EscapeForShell(aco, false);
3591       cudaOptions.AppendFlagString("AdditionalOptions", "-Xcompiler=" + aco);
3592     }
3593   }
3594
3595   cudaOptions.FixCudaCodeGeneration();
3596
3597   std::vector<std::string> targetDefines;
3598   this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
3599                                                "CUDA");
3600   cudaOptions.AddDefines(targetDefines);
3601
3602   // Add a definition for the configuration name.
3603   std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
3604   cudaOptions.AddDefine(configDefine);
3605   if (const std::string* exportMacro =
3606         this->GeneratorTarget->GetExportMacro()) {
3607     cudaOptions.AddDefine(*exportMacro);
3608   }
3609
3610   // Get includes for this target
3611   cudaOptions.AddIncludes(this->GetIncludes(configName, "CUDA"));
3612   cudaOptions.AddFlag("UseHostInclude", "false");
3613
3614   // Add runtime library selection flag.
3615   std::string const& cudaRuntime =
3616     this->GeneratorTarget->GetRuntimeLinkLibrary("CUDA", configName);
3617   if (cudaRuntime == "STATIC") {
3618     cudaOptions.AddFlag("CudaRuntime", "Static");
3619   } else if (cudaRuntime == "SHARED") {
3620     cudaOptions.AddFlag("CudaRuntime", "Shared");
3621   } else if (cudaRuntime == "NONE") {
3622     cudaOptions.AddFlag("CudaRuntime", "None");
3623   }
3624
3625   this->CudaOptions[configName] = std::move(pOptions);
3626   return true;
3627 }
3628
3629 void cmVisualStudio10TargetGenerator::WriteCudaOptions(
3630   Elem& e1, std::string const& configName)
3631 {
3632   if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled() ||
3633       !this->GeneratorTarget->IsLanguageUsed("CUDA", configName)) {
3634     return;
3635   }
3636   Elem e2(e1, "CudaCompile");
3637
3638   OptionsHelper cudaOptions(*(this->CudaOptions[configName]), e2);
3639   cudaOptions.OutputAdditionalIncludeDirectories("CUDA");
3640   cudaOptions.OutputPreprocessorDefinitions("CUDA");
3641   cudaOptions.PrependInheritedString("AdditionalOptions");
3642   cudaOptions.OutputFlagMap();
3643 }
3644
3645 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
3646 {
3647   if (!this->GlobalGenerator->IsCudaEnabled()) {
3648     return true;
3649   }
3650   for (std::string const& c : this->Configurations) {
3651     if (!this->ComputeCudaLinkOptions(c)) {
3652       return false;
3653     }
3654   }
3655   return true;
3656 }
3657
3658 bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
3659   std::string const& configName)
3660 {
3661   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3662   auto pOptions = cm::make_unique<Options>(
3663     this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
3664   Options& cudaLinkOptions = *pOptions;
3665
3666   cmGeneratorTarget::DeviceLinkSetter setter(*this->GeneratorTarget);
3667
3668   // Determine if we need to do a device link
3669   const bool doDeviceLinking = requireDeviceLinking(
3670     *this->GeneratorTarget, *this->LocalGenerator, configName);
3671
3672   cudaLinkOptions.AddFlag("PerformDeviceLink",
3673                           doDeviceLinking ? "true" : "false");
3674
3675   // Add extra flags for device linking
3676   cudaLinkOptions.AppendFlagString(
3677     "AdditionalOptions",
3678     this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_FLAGS"));
3679   cudaLinkOptions.AppendFlagString(
3680     "AdditionalOptions",
3681     this->Makefile->GetSafeDefinition("_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS"));
3682
3683   std::vector<std::string> linkOpts;
3684   std::string linkFlags;
3685   this->GeneratorTarget->GetLinkOptions(linkOpts, configName, "CUDA");
3686   // LINK_OPTIONS are escaped.
3687   this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
3688   cudaLinkOptions.AppendFlagString("AdditionalOptions", linkFlags);
3689
3690   // For static libraries that have device linking enabled compute
3691   // the  libraries
3692   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY &&
3693       doDeviceLinking) {
3694     cmComputeLinkInformation* pcli =
3695       this->GeneratorTarget->GetLinkInformation(configName);
3696     if (!pcli) {
3697       cmSystemTools::Error(
3698         "CMake can not compute cmComputeLinkInformation for target: " +
3699         this->Name);
3700       return false;
3701     }
3702
3703     cmComputeLinkInformation& cli = *pcli;
3704     cmLinkLineDeviceComputer computer(
3705       this->LocalGenerator,
3706       this->LocalGenerator->GetStateSnapshot().GetDirectory());
3707     std::vector<BT<std::string>> btLibVec;
3708     computer.ComputeLinkLibraries(cli, std::string{}, btLibVec);
3709     std::vector<std::string> libVec;
3710     for (auto const& item : btLibVec) {
3711       libVec.emplace_back(item.Value);
3712     }
3713
3714     cudaLinkOptions.AddFlag("AdditionalDependencies", libVec);
3715   }
3716
3717   this->CudaLinkOptions[configName] = std::move(pOptions);
3718   return true;
3719 }
3720
3721 void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
3722   Elem& e1, std::string const& configName)
3723 {
3724   if (this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
3725     return;
3726   }
3727
3728   if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
3729     return;
3730   }
3731
3732   Elem e2(e1, "CudaLink");
3733   OptionsHelper cudaLinkOptions(*(this->CudaLinkOptions[configName]), e2);
3734   cudaLinkOptions.OutputFlagMap();
3735 }
3736
3737 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
3738 {
3739   if (!this->GlobalGenerator->IsMasmEnabled()) {
3740     return true;
3741   }
3742   for (std::string const& c : this->Configurations) {
3743     if (!this->ComputeMasmOptions(c)) {
3744       return false;
3745     }
3746   }
3747   return true;
3748 }
3749
3750 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
3751   std::string const& configName)
3752 {
3753   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3754   auto pOptions = cm::make_unique<Options>(
3755     this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
3756   Options& masmOptions = *pOptions;
3757
3758   std::string flags;
3759   this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3760                                          "ASM_MASM", configName);
3761
3762   masmOptions.Parse(flags);
3763
3764   // Get includes for this target
3765   masmOptions.AddIncludes(this->GetIncludes(configName, "ASM_MASM"));
3766
3767   this->MasmOptions[configName] = std::move(pOptions);
3768   return true;
3769 }
3770
3771 void cmVisualStudio10TargetGenerator::WriteMasmOptions(
3772   Elem& e1, std::string const& configName)
3773 {
3774   if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
3775     return;
3776   }
3777   Elem e2(e1, "MASM");
3778
3779   // Preprocessor definitions and includes are shared with clOptions.
3780   OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
3781   clOptions.OutputPreprocessorDefinitions("ASM_MASM");
3782
3783   OptionsHelper masmOptions(*(this->MasmOptions[configName]), e2);
3784   masmOptions.OutputAdditionalIncludeDirectories("ASM_MASM");
3785   masmOptions.PrependInheritedString("AdditionalOptions");
3786   masmOptions.OutputFlagMap();
3787 }
3788
3789 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
3790 {
3791   if (!this->GlobalGenerator->IsNasmEnabled()) {
3792     return true;
3793   }
3794   for (std::string const& c : this->Configurations) {
3795     if (!this->ComputeNasmOptions(c)) {
3796       return false;
3797     }
3798   }
3799   return true;
3800 }
3801
3802 bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
3803   std::string const& configName)
3804 {
3805   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3806   auto pOptions = cm::make_unique<Options>(
3807     this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
3808   Options& nasmOptions = *pOptions;
3809
3810   std::string flags;
3811   this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget,
3812                                          "ASM_NASM", configName);
3813   flags += " -f";
3814   flags += this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_OBJECT_FORMAT");
3815   nasmOptions.Parse(flags);
3816
3817   // Get includes for this target
3818   nasmOptions.AddIncludes(this->GetIncludes(configName, "ASM_NASM"));
3819
3820   this->NasmOptions[configName] = std::move(pOptions);
3821   return true;
3822 }
3823
3824 void cmVisualStudio10TargetGenerator::WriteNasmOptions(
3825   Elem& e1, std::string const& configName)
3826 {
3827   if (!this->GlobalGenerator->IsNasmEnabled()) {
3828     return;
3829   }
3830   Elem e2(e1, "NASM");
3831
3832   OptionsHelper nasmOptions(*(this->NasmOptions[configName]), e2);
3833   nasmOptions.OutputAdditionalIncludeDirectories("ASM_NASM");
3834   nasmOptions.OutputFlagMap();
3835   nasmOptions.PrependInheritedString("AdditionalOptions");
3836   nasmOptions.OutputPreprocessorDefinitions("ASM_NASM");
3837
3838   // Preprocessor definitions and includes are shared with clOptions.
3839   OptionsHelper clOptions(*(this->ClOptions[configName]), e2);
3840   clOptions.OutputPreprocessorDefinitions("ASM_NASM");
3841 }
3842
3843 void cmVisualStudio10TargetGenerator::WriteLibOptions(
3844   Elem& e1, std::string const& config)
3845 {
3846   if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
3847       this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
3848     return;
3849   }
3850
3851   const std::string& linkLanguage =
3852     this->GeneratorTarget->GetLinkClosure(config)->LinkerLanguage;
3853
3854   std::string libflags;
3855   this->LocalGenerator->GetStaticLibraryFlags(libflags, config, linkLanguage,
3856                                               this->GeneratorTarget);
3857   if (!libflags.empty()) {
3858     Elem e2(e1, "Lib");
3859     cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
3860     cmVS10GeneratorOptions libOptions(this->LocalGenerator,
3861                                       cmVisualStudioGeneratorOptions::Linker,
3862                                       gg->GetLibFlagTable(), this);
3863     libOptions.Parse(libflags);
3864     OptionsHelper oh(libOptions, e2);
3865     oh.PrependInheritedString("AdditionalOptions");
3866     oh.OutputFlagMap();
3867   }
3868
3869   // We cannot generate metadata for static libraries.  WindowsPhone
3870   // and WindowsStore tools look at GenerateWindowsMetadata in the
3871   // Link tool options even for static libraries.
3872   if (this->GlobalGenerator->TargetsWindowsPhone() ||
3873       this->GlobalGenerator->TargetsWindowsStore()) {
3874     Elem e2(e1, "Link");
3875     e2.Element("GenerateWindowsMetadata", "false");
3876   }
3877 }
3878
3879 void cmVisualStudio10TargetGenerator::WriteManifestOptions(
3880   Elem& e1, std::string const& config)
3881 {
3882   if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
3883       this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
3884       this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
3885     return;
3886   }
3887
3888   std::vector<cmSourceFile const*> manifest_srcs;
3889   this->GeneratorTarget->GetManifests(manifest_srcs, config);
3890
3891   cmValue dpiAware = this->GeneratorTarget->GetProperty("VS_DPI_AWARE");
3892
3893   if (!manifest_srcs.empty() || dpiAware) {
3894     Elem e2(e1, "Manifest");
3895     if (!manifest_srcs.empty()) {
3896       std::ostringstream oss;
3897       for (cmSourceFile const* mi : manifest_srcs) {
3898         std::string m = this->ConvertPath(mi->GetFullPath(), false);
3899         ConvertToWindowsSlash(m);
3900         oss << m << ";";
3901       }
3902       e2.Element("AdditionalManifestFiles", oss.str());
3903     }
3904     if (dpiAware) {
3905       if (*dpiAware == "PerMonitor") {
3906         e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware");
3907       } else if (cmIsOn(*dpiAware)) {
3908         e2.Element("EnableDpiAwareness", "true");
3909       } else if (cmIsOff(*dpiAware)) {
3910         e2.Element("EnableDpiAwareness", "false");
3911       } else {
3912         cmSystemTools::Error("Bad parameter for VS_DPI_AWARE: " + *dpiAware);
3913       }
3914     }
3915   }
3916 }
3917
3918 void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
3919   Elem& e1, std::string const& configName)
3920 {
3921   // Look through the sources for AndroidManifest.xml and use
3922   // its location as the root source directory.
3923   std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
3924   {
3925     for (cmGeneratorTarget::AllConfigSource const& source :
3926          this->GeneratorTarget->GetAllConfigSources()) {
3927       if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
3928           "androidmanifest.xml" ==
3929             cmSystemTools::LowerCase(source.Source->GetLocation().GetName())) {
3930         rootDir = source.Source->GetLocation().GetDirectory();
3931         break;
3932       }
3933     }
3934   }
3935
3936   // Tell MSBuild to launch Ant.
3937   Elem e2(e1, "AntBuild");
3938   {
3939     std::string antBuildPath = rootDir;
3940     ConvertToWindowsSlash(antBuildPath);
3941     e2.Element("AntBuildPath", antBuildPath);
3942   }
3943
3944   if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
3945     e2.Element("SkipAntStep", "true");
3946   }
3947
3948   if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
3949     e2.Element("EnableProGuard", "true");
3950   }
3951
3952   if (cmValue proGuardConfigLocation =
3953         this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
3954     e2.Element("ProGuardConfigLocation", *proGuardConfigLocation);
3955   }
3956
3957   if (cmValue securePropertiesLocation =
3958         this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
3959     e2.Element("SecurePropertiesLocation", *securePropertiesLocation);
3960   }
3961
3962   if (cmValue nativeLibDirectoriesExpression =
3963         this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
3964     std::string nativeLibDirs = cmGeneratorExpression::Evaluate(
3965       *nativeLibDirectoriesExpression, this->LocalGenerator, configName);
3966     e2.Element("NativeLibDirectories", nativeLibDirs);
3967   }
3968
3969   if (cmValue nativeLibDependenciesExpression =
3970         this->GeneratorTarget->GetProperty(
3971           "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
3972     std::string nativeLibDeps = cmGeneratorExpression::Evaluate(
3973       *nativeLibDependenciesExpression, this->LocalGenerator, configName);
3974     e2.Element("NativeLibDependencies", nativeLibDeps);
3975   }
3976
3977   if (cmValue javaSourceDir =
3978         this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
3979     e2.Element("JavaSourceDir", *javaSourceDir);
3980   }
3981
3982   if (cmValue jarDirectoriesExpression =
3983         this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
3984     std::string jarDirectories = cmGeneratorExpression::Evaluate(
3985       *jarDirectoriesExpression, this->LocalGenerator, configName);
3986     e2.Element("JarDirectories", jarDirectories);
3987   }
3988
3989   if (cmValue jarDeps =
3990         this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
3991     e2.Element("JarDependencies", *jarDeps);
3992   }
3993
3994   if (cmValue assetsDirectories =
3995         this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
3996     e2.Element("AssetsDirectories", *assetsDirectories);
3997   }
3998
3999   {
4000     std::string manifest_xml = rootDir + "/AndroidManifest.xml";
4001     ConvertToWindowsSlash(manifest_xml);
4002     e2.Element("AndroidManifestLocation", manifest_xml);
4003   }
4004
4005   if (cmValue antAdditionalOptions =
4006         this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
4007     e2.Element("AdditionalOptions",
4008                *antAdditionalOptions + " %(AdditionalOptions)");
4009   }
4010 }
4011
4012 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
4013 {
4014   if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
4015       this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
4016       this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4017     for (std::string const& c : this->Configurations) {
4018       if (!this->ComputeLinkOptions(c)) {
4019         return false;
4020       }
4021     }
4022   }
4023   return true;
4024 }
4025
4026 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
4027   std::string const& config)
4028 {
4029   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4030   auto pOptions = cm::make_unique<Options>(
4031     this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this);
4032   Options& linkOptions = *pOptions;
4033
4034   cmGeneratorTarget::LinkClosure const* linkClosure =
4035     this->GeneratorTarget->GetLinkClosure(config);
4036
4037   const std::string& linkLanguage = linkClosure->LinkerLanguage;
4038   if (linkLanguage.empty()) {
4039     cmSystemTools::Error(
4040       "CMake can not determine linker language for target: " + this->Name);
4041     return false;
4042   }
4043
4044   std::string CONFIG = cmSystemTools::UpperCase(config);
4045
4046   const char* linkType = "SHARED";
4047   if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
4048     linkType = "MODULE";
4049   }
4050   if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4051     linkType = "EXE";
4052   }
4053   std::string flags;
4054   std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS");
4055   flags += " ";
4056   flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase);
4057   std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG;
4058   flags += " ";
4059   flags += this->Makefile->GetRequiredDefinition(linkFlagVar);
4060   cmValue targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS");
4061   if (targetLinkFlags) {
4062     flags += " ";
4063     flags += *targetLinkFlags;
4064   }
4065   std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG);
4066   if (cmValue flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) {
4067     flags += " ";
4068     flags += *flagsConfig;
4069   }
4070
4071   std::vector<std::string> opts;
4072   this->GeneratorTarget->GetLinkOptions(opts, config, linkLanguage);
4073   // LINK_OPTIONS are escaped.
4074   this->LocalGenerator->AppendCompileOptions(flags, opts);
4075
4076   cmComputeLinkInformation* pcli =
4077     this->GeneratorTarget->GetLinkInformation(config);
4078   if (!pcli) {
4079     cmSystemTools::Error(
4080       "CMake can not compute cmComputeLinkInformation for target: " +
4081       this->Name);
4082     return false;
4083   }
4084   cmComputeLinkInformation& cli = *pcli;
4085
4086   std::vector<std::string> libVec;
4087   std::vector<std::string> vsTargetVec;
4088   this->AddLibraries(cli, libVec, vsTargetVec, config);
4089   std::string standardLibsVar =
4090     cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
4091   std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar);
4092   cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
4093   linkOptions.AddFlag("AdditionalDependencies", libVec);
4094
4095   // Populate TargetsFileAndConfigsVec
4096   for (std::string const& ti : vsTargetVec) {
4097     this->AddTargetsFileAndConfigPair(ti, config);
4098   }
4099
4100   std::vector<std::string> const& ldirs = cli.GetDirectories();
4101   std::vector<std::string> linkDirs;
4102   for (std::string const& d : ldirs) {
4103     // first just full path
4104     linkDirs.push_back(d);
4105     // next path with configuration type Debug, Release, etc
4106     linkDirs.push_back(d + "/$(Configuration)");
4107   }
4108   linkDirs.push_back("%(AdditionalLibraryDirectories)");
4109   linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
4110
4111   cmGeneratorTarget::Names targetNames;
4112   if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4113     targetNames = this->GeneratorTarget->GetExecutableNames(config);
4114   } else {
4115     targetNames = this->GeneratorTarget->GetLibraryNames(config);
4116   }
4117
4118   if (this->MSTools) {
4119     if (this->GeneratorTarget->IsWin32Executable(config)) {
4120       if (this->GlobalGenerator->TargetsWindowsCE()) {
4121         linkOptions.AddFlag("SubSystem", "WindowsCE");
4122         if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4123           if (this->ClOptions[config]->UsingUnicode()) {
4124             linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
4125           } else {
4126             linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
4127           }
4128         }
4129       } else {
4130         linkOptions.AddFlag("SubSystem", "Windows");
4131       }
4132     } else {
4133       if (this->GlobalGenerator->TargetsWindowsCE()) {
4134         linkOptions.AddFlag("SubSystem", "WindowsCE");
4135         if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4136           if (this->ClOptions[config]->UsingUnicode()) {
4137             linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
4138           } else {
4139             linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
4140           }
4141         }
4142       } else {
4143         linkOptions.AddFlag("SubSystem", "Console");
4144       };
4145     }
4146
4147     if (cmValue stackVal = this->Makefile->GetDefinition(
4148           "CMAKE_" + linkLanguage + "_STACK_SIZE")) {
4149       linkOptions.AddFlag("StackReserveSize", *stackVal);
4150     }
4151
4152     linkOptions.AddFlag("GenerateDebugInformation", "false");
4153
4154     std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config),
4155                                '/', targetNames.PDB);
4156     if (!targetNames.ImportLibrary.empty()) {
4157       std::string imLib =
4158         cmStrCat(this->GeneratorTarget->GetDirectory(
4159                    config, cmStateEnums::ImportLibraryArtifact),
4160                  '/', targetNames.ImportLibrary);
4161
4162       linkOptions.AddFlag("ImportLibrary", imLib);
4163     }
4164     linkOptions.AddFlag("ProgramDataBaseFile", pdb);
4165
4166     // A Windows Runtime component uses internal .NET metadata,
4167     // so does not have an import library.
4168     if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
4169         this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
4170       linkOptions.AddFlag("GenerateWindowsMetadata", "true");
4171     } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
4172                this->GlobalGenerator->TargetsWindowsStore()) {
4173       // WindowsPhone and WindowsStore components are in an app container
4174       // and produce WindowsMetadata.  If we are not producing a WINRT
4175       // component, then do not generate the metadata here.
4176       linkOptions.AddFlag("GenerateWindowsMetadata", "false");
4177     }
4178
4179     if (this->GlobalGenerator->TargetsWindowsPhone() &&
4180         this->GlobalGenerator->GetSystemVersion() == "8.0") {
4181       // WindowsPhone 8.0 does not have ole32.
4182       linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
4183     }
4184   } else if (this->NsightTegra) {
4185     linkOptions.AddFlag("SoName", targetNames.SharedObject);
4186   }
4187
4188   linkOptions.Parse(flags);
4189   linkOptions.FixManifestUACFlags();
4190
4191   if (this->MSTools) {
4192     cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4193       this->GeneratorTarget->GetModuleDefinitionInfo(config);
4194     if (mdi && !mdi->DefFile.empty()) {
4195       linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile);
4196     }
4197     linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
4198                            "%(IgnoreSpecificDefaultLibraries)");
4199   }
4200
4201   // VS 2015 without all updates has a v140 toolset whose
4202   // GenerateDebugInformation expects No/Debug instead of false/true.
4203   if (gg->GetPlatformToolsetNeedsDebugEnum()) {
4204     if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4205       if (strcmp(debug, "false") == 0) {
4206         linkOptions.AddFlag("GenerateDebugInformation", "No");
4207       } else if (strcmp(debug, "true") == 0) {
4208         linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4209       }
4210     }
4211   }
4212
4213   // Managed code cannot be linked with /DEBUG:FASTLINK
4214   if (this->Managed) {
4215     if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
4216       if (strcmp(debug, "DebugFastLink") == 0) {
4217         linkOptions.AddFlag("GenerateDebugInformation", "Debug");
4218       }
4219     }
4220   }
4221
4222   this->LinkOptions[config] = std::move(pOptions);
4223   return true;
4224 }
4225
4226 bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
4227 {
4228   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
4229     for (std::string const& c : this->Configurations) {
4230       if (!this->ComputeLibOptions(c)) {
4231         return false;
4232       }
4233     }
4234   }
4235   return true;
4236 }
4237
4238 bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
4239   std::string const& config)
4240 {
4241   cmComputeLinkInformation* pcli =
4242     this->GeneratorTarget->GetLinkInformation(config);
4243   if (!pcli) {
4244     cmSystemTools::Error(
4245       "CMake can not compute cmComputeLinkInformation for target: " +
4246       this->Name);
4247     return false;
4248   }
4249
4250   cmComputeLinkInformation& cli = *pcli;
4251   using ItemVector = cmComputeLinkInformation::ItemVector;
4252   const ItemVector& libs = cli.GetItems();
4253   for (cmComputeLinkInformation::Item const& l : libs) {
4254     if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
4255         cmVS10IsTargetsFile(l.Value.Value)) {
4256       std::string path =
4257         this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4258       ConvertToWindowsSlash(path);
4259       this->AddTargetsFileAndConfigPair(path, config);
4260     }
4261   }
4262
4263   return true;
4264 }
4265
4266 void cmVisualStudio10TargetGenerator::WriteLinkOptions(
4267   Elem& e1, std::string const& config)
4268 {
4269   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
4270       this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
4271     return;
4272   }
4273   if (this->ProjectType == VsProjectType::csproj) {
4274     return;
4275   }
4276
4277   {
4278     Elem e2(e1, "Link");
4279     OptionsHelper linkOptions(*(this->LinkOptions[config]), e2);
4280     linkOptions.PrependInheritedString("AdditionalOptions");
4281     linkOptions.OutputFlagMap();
4282   }
4283
4284   if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
4285         this->GeneratorTarget)) {
4286     Elem e2(e1, "ProjectReference");
4287     e2.Element("LinkLibraryDependencies", "false");
4288   }
4289 }
4290
4291 void cmVisualStudio10TargetGenerator::AddLibraries(
4292   const cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
4293   std::vector<std::string>& vsTargetVec, const std::string& config)
4294 {
4295   using ItemVector = cmComputeLinkInformation::ItemVector;
4296   ItemVector const& libs = cli.GetItems();
4297   for (cmComputeLinkInformation::Item const& l : libs) {
4298     if (l.Target) {
4299       auto managedType = l.Target->GetManagedType(config);
4300       if (managedType != cmGeneratorTarget::ManagedType::Native &&
4301           this->GeneratorTarget->GetManagedType(config) !=
4302             cmGeneratorTarget::ManagedType::Native &&
4303           l.Target->IsImported() &&
4304           l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
4305         auto location = l.Target->GetFullPath(config);
4306         if (!location.empty()) {
4307           ConvertToWindowsSlash(location);
4308           switch (this->ProjectType) {
4309             case VsProjectType::csproj:
4310               // If the target we want to "link" to is an imported managed
4311               // target and this is a C# project, we add a hint reference. This
4312               // reference is written to project file in
4313               // WriteDotNetReferences().
4314               this->DotNetHintReferences[config].push_back(
4315                 DotNetHintReference(l.Target->GetName(), location));
4316               break;
4317             case VsProjectType::vcxproj:
4318               // Add path of assembly to list of using-directories, so the
4319               // managed assembly can be used by '#using <assembly.dll>' in
4320               // code.
4321               this->AdditionalUsingDirectories[config].insert(
4322                 cmSystemTools::GetFilenamePath(location));
4323               break;
4324             default:
4325               // In .proj files, we wouldn't be referencing libraries.
4326               break;
4327           }
4328         }
4329       }
4330       // Do not allow C# targets to be added to the LIB listing. LIB files are
4331       // used for linking C++ dependencies. C# libraries do not have lib files.
4332       // Instead, they compile down to C# reference libraries (DLL files). The
4333       // `<ProjectReference>` elements added to the vcxproj are enough for the
4334       // IDE to deduce the DLL file required by other C# projects that need its
4335       // reference library.
4336       if (managedType == cmGeneratorTarget::ManagedType::Managed) {
4337         continue;
4338       }
4339     }
4340
4341     if (l.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
4342       std::string path =
4343         this->LocalGenerator->MaybeRelativeToCurBinDir(l.Value.Value);
4344       ConvertToWindowsSlash(path);
4345       if (cmVS10IsTargetsFile(l.Value.Value)) {
4346         vsTargetVec.push_back(path);
4347       } else {
4348         libVec.push_back(l.HasFeature() ? l.GetFormattedItem(path).Value
4349                                         : path);
4350       }
4351     } else if (!l.Target ||
4352                l.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
4353       libVec.push_back(l.Value.Value);
4354     }
4355   }
4356 }
4357
4358 void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
4359   std::string const& targetsFile, std::string const& config)
4360 {
4361   for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) {
4362     if (cmSystemTools::ComparePath(targetsFile, i.File)) {
4363       if (!cm::contains(i.Configs, config)) {
4364         i.Configs.push_back(config);
4365       }
4366       return;
4367     }
4368   }
4369   TargetsFileAndConfigs entry;
4370   entry.File = targetsFile;
4371   entry.Configs.push_back(config);
4372   this->TargetsFileAndConfigsVec.push_back(entry);
4373 }
4374
4375 void cmVisualStudio10TargetGenerator::WriteMidlOptions(
4376   Elem& e1, std::string const& configName)
4377 {
4378   if (!this->MSTools) {
4379     return;
4380   }
4381   if (this->ProjectType == VsProjectType::csproj) {
4382     return;
4383   }
4384   if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
4385     return;
4386   }
4387
4388   // This processes *any* of the .idl files specified in the project's file
4389   // list (and passed as the item metadata %(Filename) expressing the rule
4390   // input filename) into output files at the per-config *build* dir
4391   // ($(IntDir)) each.
4392   //
4393   // IOW, this MIDL section is intended to provide a fully generic syntax
4394   // content suitable for most cases (read: if you get errors, then it's quite
4395   // probable that the error is on your side of the .idl setup).
4396   //
4397   // Also, note that the marked-as-generated _i.c file in the Visual Studio
4398   // generator case needs to be referred to as $(IntDir)\foo_i.c at the
4399   // project's file list, otherwise the compiler-side processing won't pick it
4400   // up (for non-directory form, it ends up looking in project binary dir
4401   // only).  Perhaps there's something to be done to make this more automatic
4402   // on the CMake side?
4403   std::vector<std::string> const includes =
4404     this->GetIncludes(configName, "MIDL");
4405   std::ostringstream oss;
4406   for (std::string const& i : includes) {
4407     oss << i << ";";
4408   }
4409   oss << "%(AdditionalIncludeDirectories)";
4410
4411   Elem e2(e1, "Midl");
4412   e2.Element("AdditionalIncludeDirectories", oss.str());
4413   e2.Element("OutputDirectory", "$(ProjectDir)/$(IntDir)");
4414   e2.Element("HeaderFileName", "%(Filename).h");
4415   e2.Element("TypeLibraryName", "%(Filename).tlb");
4416   e2.Element("InterfaceIdentifierFileName", "%(Filename)_i.c");
4417   e2.Element("ProxyFileName", "%(Filename)_p.c");
4418 }
4419
4420 void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups(Elem& e0)
4421 {
4422   if (this->ProjectType == VsProjectType::csproj) {
4423     return;
4424   }
4425   for (const std::string& c : this->Configurations) {
4426     Elem e1(e0, "ItemDefinitionGroup");
4427     e1.Attribute("Condition", this->CalcCondition(c));
4428
4429     //    output cl compile flags <ClCompile></ClCompile>
4430     if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
4431       this->WriteClOptions(e1, c);
4432       //    output rc compile flags <ResourceCompile></ResourceCompile>
4433       this->WriteRCOptions(e1, c);
4434       this->WriteCudaOptions(e1, c);
4435       this->WriteMasmOptions(e1, c);
4436       this->WriteNasmOptions(e1, c);
4437     }
4438     //    output midl flags       <Midl></Midl>
4439     this->WriteMidlOptions(e1, c);
4440     // write events
4441     if (this->ProjectType != VsProjectType::csproj) {
4442       this->WriteEvents(e1, c);
4443     }
4444     //    output link flags       <Link></Link>
4445     this->WriteLinkOptions(e1, c);
4446     this->WriteCudaLinkOptions(e1, c);
4447     //    output lib flags       <Lib></Lib>
4448     this->WriteLibOptions(e1, c);
4449     //    output manifest flags  <Manifest></Manifest>
4450     this->WriteManifestOptions(e1, c);
4451     if (this->NsightTegra &&
4452         this->GeneratorTarget->Target->IsAndroidGuiExecutable()) {
4453       this->WriteAntBuildOptions(e1, c);
4454     }
4455   }
4456 }
4457
4458 void cmVisualStudio10TargetGenerator::WriteEvents(
4459   Elem& e1, std::string const& configName)
4460 {
4461   bool addedPrelink = false;
4462   cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
4463     this->GeneratorTarget->GetModuleDefinitionInfo(configName);
4464   if (mdi && mdi->DefFileGenerated) {
4465     addedPrelink = true;
4466     std::vector<cmCustomCommand> commands =
4467       this->GeneratorTarget->GetPreLinkCommands();
4468     this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
4469                                                   commands, configName);
4470     this->WriteEvent(e1, "PreLinkEvent", commands, configName);
4471   }
4472   if (!addedPrelink) {
4473     this->WriteEvent(e1, "PreLinkEvent",
4474                      this->GeneratorTarget->GetPreLinkCommands(), configName);
4475   }
4476   this->WriteEvent(e1, "PreBuildEvent",
4477                    this->GeneratorTarget->GetPreBuildCommands(), configName);
4478   this->WriteEvent(e1, "PostBuildEvent",
4479                    this->GeneratorTarget->GetPostBuildCommands(), configName);
4480 }
4481
4482 void cmVisualStudio10TargetGenerator::WriteEvent(
4483   Elem& e1, const std::string& name,
4484   std::vector<cmCustomCommand> const& commands, std::string const& configName)
4485 {
4486   if (commands.empty()) {
4487     return;
4488   }
4489   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
4490   std::string script;
4491   const char* pre = "";
4492   std::string comment;
4493   bool stdPipesUTF8 = false;
4494   for (cmCustomCommand const& cc : commands) {
4495     cmCustomCommandGenerator ccg(cc, configName, lg);
4496     if (!ccg.HasOnlyEmptyCommandLines()) {
4497       comment += pre;
4498       comment += lg->ConstructComment(ccg);
4499       script += pre;
4500       pre = "\n";
4501       script += lg->ConstructScript(ccg);
4502
4503       stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
4504     }
4505   }
4506   if (!script.empty()) {
4507     script += lg->FinishConstructScript(this->ProjectType);
4508   }
4509   comment = cmVS10EscapeComment(comment);
4510   if (this->ProjectType != VsProjectType::csproj) {
4511     Elem e2(e1, name);
4512     if (stdPipesUTF8) {
4513       this->WriteStdOutEncodingUtf8(e2);
4514     }
4515     e2.Element("Message", comment);
4516     e2.Element("Command", script);
4517   } else {
4518     std::string strippedComment = comment;
4519     strippedComment.erase(
4520       std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
4521       strippedComment.end());
4522     std::ostringstream oss;
4523     if (!comment.empty() && !strippedComment.empty()) {
4524       oss << "echo " << comment << "\n";
4525     }
4526     oss << script << "\n";
4527     e1.Element(name, oss.str());
4528   }
4529 }
4530
4531 void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0)
4532 {
4533   cmGlobalGenerator::TargetDependSet const& unordered =
4534     this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
4535   using OrderedTargetDependSet =
4536     cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
4537   OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
4538   Elem e1(e0, "ItemGroup");
4539   e1.SetHasElements();
4540   for (cmGeneratorTarget const* dt : depends) {
4541     if (!dt->IsInBuildSystem()) {
4542       continue;
4543     }
4544     // skip fortran targets as they can not be processed by MSBuild
4545     // the only reference will be in the .sln file
4546     if (this->GlobalGenerator->TargetIsFortranOnly(dt)) {
4547       continue;
4548     }
4549     cmLocalGenerator* lg = dt->GetLocalGenerator();
4550     std::string name = dt->GetName();
4551     std::string path;
4552     if (cmValue p = dt->GetProperty("EXTERNAL_MSPROJECT")) {
4553       path = *p;
4554     } else {
4555       path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(),
4556                       computeProjectFileExtension(dt));
4557     }
4558     ConvertToWindowsSlash(path);
4559     Elem e2(e1, "ProjectReference");
4560     e2.Attribute("Include", path);
4561     e2.Element("Project", "{" + this->GlobalGenerator->GetGUID(name) + "}");
4562     e2.Element("Name", name);
4563     this->WriteDotNetReferenceCustomTags(e2, name);
4564     if (dt->IsCSharpOnly() || cmHasLiteralSuffix(path, "csproj")) {
4565       e2.Element("SkipGetTargetFrameworkProperties", "true");
4566     }
4567     // Don't reference targets that don't produce any output.
4568     else if (this->Configurations.empty() ||
4569              dt->GetManagedType(this->Configurations[0]) ==
4570                cmGeneratorTarget::ManagedType::Undefined) {
4571       e2.Element("ReferenceOutputAssembly", "false");
4572       e2.Element("CopyToOutputDirectory", "Never");
4573     }
4574   }
4575 }
4576
4577 void cmVisualStudio10TargetGenerator::WritePlatformExtensions(Elem& e1)
4578 {
4579   // This only applies to Windows 10 apps
4580   if (this->GlobalGenerator->TargetsWindowsStore() &&
4581       cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
4582     cmValue desktopExtensionsVersion =
4583       this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
4584     if (desktopExtensionsVersion) {
4585       this->WriteSinglePlatformExtension(e1, "WindowsDesktop",
4586                                          *desktopExtensionsVersion);
4587     }
4588     cmValue mobileExtensionsVersion =
4589       this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
4590     if (mobileExtensionsVersion) {
4591       this->WriteSinglePlatformExtension(e1, "WindowsMobile",
4592                                          *mobileExtensionsVersion);
4593     }
4594   }
4595 }
4596
4597 void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
4598   Elem& e1, std::string const& extension, std::string const& version)
4599 {
4600   const std::string s = "$([Microsoft.Build.Utilities.ToolLocationHelper]"
4601                         "::GetPlatformExtensionSDKLocation(`" +
4602     extension + ", Version=" + version +
4603     "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
4604     "$(ExtensionSDKDirectoryRoot), null))"
4605     "\\DesignTime\\CommonConfiguration\\Neutral\\" +
4606     extension + ".props";
4607
4608   Elem e2(e1, "Import");
4609   e2.Attribute("Project", s);
4610   e2.Attribute("Condition", "exists('" + s + "')");
4611 }
4612
4613 void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0)
4614 {
4615   std::vector<std::string> sdkReferences;
4616   std::unique_ptr<Elem> spe1;
4617   if (cmValue vsSDKReferences =
4618         this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
4619     cmExpandList(*vsSDKReferences, sdkReferences);
4620     spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
4621     for (std::string const& ri : sdkReferences) {
4622       Elem(*spe1, "SDKReference").Attribute("Include", ri);
4623     }
4624   }
4625
4626   // This only applies to Windows 10 apps
4627   if (this->GlobalGenerator->TargetsWindowsStore() &&
4628       cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
4629     cmValue desktopExtensionsVersion =
4630       this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
4631     cmValue mobileExtensionsVersion =
4632       this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
4633     cmValue iotExtensionsVersion =
4634       this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
4635
4636     if (desktopExtensionsVersion || mobileExtensionsVersion ||
4637         iotExtensionsVersion) {
4638       if (!spe1) {
4639         spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
4640       }
4641       if (desktopExtensionsVersion) {
4642         this->WriteSingleSDKReference(*spe1, "WindowsDesktop",
4643                                       *desktopExtensionsVersion);
4644       }
4645       if (mobileExtensionsVersion) {
4646         this->WriteSingleSDKReference(*spe1, "WindowsMobile",
4647                                       *mobileExtensionsVersion);
4648       }
4649       if (iotExtensionsVersion) {
4650         this->WriteSingleSDKReference(*spe1, "WindowsIoT",
4651                                       *iotExtensionsVersion);
4652       }
4653     }
4654   }
4655 }
4656
4657 void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
4658   Elem& e1, std::string const& extension, std::string const& version)
4659 {
4660   Elem(e1, "SDKReference")
4661     .Attribute("Include", extension + ", Version=" + version);
4662 }
4663
4664 void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile(
4665   Elem& e0)
4666 {
4667   if ((this->GlobalGenerator->TargetsWindowsStore() ||
4668        this->GlobalGenerator->TargetsWindowsPhone()) &&
4669       (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
4670     std::string pfxFile;
4671     for (cmGeneratorTarget::AllConfigSource const& source :
4672          this->GeneratorTarget->GetAllConfigSources()) {
4673       if (source.Kind == cmGeneratorTarget::SourceKindCertificate) {
4674         pfxFile = this->ConvertPath(source.Source->GetFullPath(), false);
4675         ConvertToWindowsSlash(pfxFile);
4676         break;
4677       }
4678     }
4679
4680     if (this->IsMissingFiles &&
4681         !(this->GlobalGenerator->TargetsWindowsPhone() &&
4682           this->GlobalGenerator->GetSystemVersion() == "8.0")) {
4683       // Move the manifest to a project directory to avoid clashes
4684       std::string artifactDir =
4685         this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
4686       ConvertToWindowsSlash(artifactDir);
4687       Elem e1(e0, "PropertyGroup");
4688       e1.Element("AppxPackageArtifactsDir", artifactDir + "\\");
4689       std::string resourcePriFile =
4690         this->DefaultArtifactDir + "/resources.pri";
4691       ConvertToWindowsSlash(resourcePriFile);
4692       e1.Element("ProjectPriFullPath", resourcePriFile);
4693
4694       // If we are missing files and we don't have a certificate and
4695       // aren't targeting WP8.0, add a default certificate
4696       if (pfxFile.empty()) {
4697         std::string templateFolder =
4698           cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
4699         pfxFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
4700         cmSystemTools::CopyAFile(templateFolder + "/Windows_TemporaryKey.pfx",
4701                                  pfxFile, false);
4702         ConvertToWindowsSlash(pfxFile);
4703         this->AddedFiles.push_back(pfxFile);
4704         this->AddedDefaultCertificate = true;
4705       }
4706
4707       e1.Element("PackageCertificateKeyFile", pfxFile);
4708       std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
4709       if (!thumb.empty()) {
4710         e1.Element("PackageCertificateThumbprint", thumb);
4711       }
4712     } else if (!pfxFile.empty()) {
4713       Elem e1(e0, "PropertyGroup");
4714       e1.Element("PackageCertificateKeyFile", pfxFile);
4715       std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
4716       if (!thumb.empty()) {
4717         e1.Element("PackageCertificateThumbprint", thumb);
4718       }
4719     }
4720   }
4721 }
4722
4723 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSources()
4724 {
4725   for (cmGeneratorTarget::AllConfigSource const& source :
4726        this->GeneratorTarget->GetAllConfigSources()) {
4727     this->ClassifyAllConfigSource(source);
4728   }
4729 }
4730
4731 void cmVisualStudio10TargetGenerator::ClassifyAllConfigSource(
4732   cmGeneratorTarget::AllConfigSource const& acs)
4733 {
4734   switch (acs.Kind) {
4735     case cmGeneratorTarget::SourceKindResx: {
4736       // Build and save the name of the corresponding .h file
4737       // This relationship will be used later when building the project files.
4738       // Both names would have been auto generated from Visual Studio
4739       // where the user supplied the file name and Visual Studio
4740       // appended the suffix.
4741       std::string resx = acs.Source->ResolveFullPath();
4742       std::string hFileName = resx.substr(0, resx.find_last_of('.')) + ".h";
4743       this->ExpectedResxHeaders.insert(hFileName);
4744     } break;
4745     case cmGeneratorTarget::SourceKindXaml: {
4746       // Build and save the name of the corresponding .h and .cpp file
4747       // This relationship will be used later when building the project files.
4748       // Both names would have been auto generated from Visual Studio
4749       // where the user supplied the file name and Visual Studio
4750       // appended the suffix.
4751       std::string xaml = acs.Source->ResolveFullPath();
4752       std::string hFileName = xaml + ".h";
4753       std::string cppFileName = xaml + ".cpp";
4754       this->ExpectedXamlHeaders.insert(hFileName);
4755       this->ExpectedXamlSources.insert(cppFileName);
4756     } break;
4757     default:
4758       break;
4759   }
4760 }
4761
4762 bool cmVisualStudio10TargetGenerator::IsResxHeader(
4763   const std::string& headerFile)
4764 {
4765   return this->ExpectedResxHeaders.count(headerFile) > 0;
4766 }
4767
4768 bool cmVisualStudio10TargetGenerator::IsXamlHeader(
4769   const std::string& headerFile)
4770 {
4771   return this->ExpectedXamlHeaders.count(headerFile) > 0;
4772 }
4773
4774 bool cmVisualStudio10TargetGenerator::IsXamlSource(
4775   const std::string& sourceFile)
4776 {
4777   return this->ExpectedXamlSources.count(sourceFile) > 0;
4778 }
4779
4780 void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1)
4781 {
4782   cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
4783   bool isAppContainer = false;
4784   bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
4785   bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
4786   bool const isAndroid = this->GlobalGenerator->TargetsAndroid();
4787   std::string const& rev = this->GlobalGenerator->GetApplicationTypeRevision();
4788   if (isWindowsPhone || isWindowsStore) {
4789     e1.Element("ApplicationType",
4790                (isWindowsPhone ? "Windows Phone" : "Windows Store"));
4791     e1.Element("DefaultLanguage", "en-US");
4792     if (rev == "10.0") {
4793       e1.Element("ApplicationTypeRevision", rev);
4794       // Visual Studio 14.0 is necessary for building 10.0 apps
4795       e1.Element("MinimumVisualStudioVersion", "14.0");
4796
4797       if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4798         isAppContainer = true;
4799       }
4800     } else if (rev == "8.1") {
4801       e1.Element("ApplicationTypeRevision", rev);
4802       // Visual Studio 12.0 is necessary for building 8.1 apps
4803       e1.Element("MinimumVisualStudioVersion", "12.0");
4804
4805       if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4806         isAppContainer = true;
4807       }
4808     } else if (rev == "8.0") {
4809       e1.Element("ApplicationTypeRevision", rev);
4810       // Visual Studio 11.0 is necessary for building 8.0 apps
4811       e1.Element("MinimumVisualStudioVersion", "11.0");
4812
4813       if (isWindowsStore &&
4814           this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
4815         isAppContainer = true;
4816       } else if (isWindowsPhone &&
4817                  this->GeneratorTarget->GetType() ==
4818                    cmStateEnums::EXECUTABLE) {
4819         e1.Element("XapOutputs", "true");
4820         e1.Element("XapFilename",
4821                    this->Name + "_$(Configuration)_$(Platform).xap");
4822       }
4823     }
4824   } else if (isAndroid) {
4825     e1.Element("ApplicationType", "Android");
4826     e1.Element("ApplicationTypeRevision",
4827                gg->GetAndroidApplicationTypeRevision());
4828   }
4829   if (isAppContainer) {
4830     e1.Element("AppContainerApplication", "true");
4831   } else if (!isAndroid) {
4832     if (this->Platform == "ARM64") {
4833       e1.Element("WindowsSDKDesktopARM64Support", "true");
4834     } else if (this->Platform == "ARM") {
4835       e1.Element("WindowsSDKDesktopARMSupport", "true");
4836     }
4837   }
4838   std::string const& targetPlatformVersion =
4839     gg->GetWindowsTargetPlatformVersion();
4840   if (!targetPlatformVersion.empty()) {
4841     e1.Element("WindowsTargetPlatformVersion", targetPlatformVersion);
4842   }
4843   cmValue targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
4844     "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
4845   if (targetPlatformMinVersion) {
4846     e1.Element("WindowsTargetPlatformMinVersion", *targetPlatformMinVersion);
4847   } else if (isWindowsStore && rev == "10.0") {
4848     // If the min version is not set, then use the TargetPlatformVersion
4849     if (!targetPlatformVersion.empty()) {
4850       e1.Element("WindowsTargetPlatformMinVersion", targetPlatformVersion);
4851     }
4852   }
4853
4854   // Added IoT Startup Task support
4855   if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
4856     e1.Element("ContainsStartupTask", "true");
4857   }
4858 }
4859
4860 void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
4861 {
4862   // For Windows and Windows Phone executables, we will assume that if a
4863   // manifest is not present that we need to add all the necessary files
4864   if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
4865     std::vector<cmGeneratorTarget::AllConfigSource> manifestSources =
4866       this->GeneratorTarget->GetAllConfigSources(
4867         cmGeneratorTarget::SourceKindAppManifest);
4868     std::string const& v = this->GlobalGenerator->GetSystemVersion();
4869     if (this->GlobalGenerator->TargetsWindowsPhone()) {
4870       if (v == "8.0") {
4871         // Look through the sources for WMAppManifest.xml
4872         bool foundManifest = false;
4873         for (cmGeneratorTarget::AllConfigSource const& source :
4874              this->GeneratorTarget->GetAllConfigSources()) {
4875           if (source.Kind == cmGeneratorTarget::SourceKindExtra &&
4876               "wmappmanifest.xml" ==
4877                 cmSystemTools::LowerCase(
4878                   source.Source->GetLocation().GetName())) {
4879             foundManifest = true;
4880             break;
4881           }
4882         }
4883         if (!foundManifest) {
4884           this->IsMissingFiles = true;
4885         }
4886       } else if (v == "8.1") {
4887         if (manifestSources.empty()) {
4888           this->IsMissingFiles = true;
4889         }
4890       }
4891     } else if (this->GlobalGenerator->TargetsWindowsStore()) {
4892       if (manifestSources.empty()) {
4893         if (v == "8.0") {
4894           this->IsMissingFiles = true;
4895         } else if (v == "8.1" || cmHasLiteralPrefix(v, "10.0")) {
4896           this->IsMissingFiles = true;
4897         }
4898       }
4899     }
4900   }
4901 }
4902
4903 void cmVisualStudio10TargetGenerator::WriteMissingFiles(Elem& e1)
4904 {
4905   std::string const& v = this->GlobalGenerator->GetSystemVersion();
4906   if (this->GlobalGenerator->TargetsWindowsPhone()) {
4907     if (v == "8.0") {
4908       this->WriteMissingFilesWP80(e1);
4909     } else if (v == "8.1") {
4910       this->WriteMissingFilesWP81(e1);
4911     }
4912   } else if (this->GlobalGenerator->TargetsWindowsStore()) {
4913     if (v == "8.0") {
4914       this->WriteMissingFilesWS80(e1);
4915     } else if (v == "8.1") {
4916       this->WriteMissingFilesWS81(e1);
4917     } else if (cmHasLiteralPrefix(v, "10.0")) {
4918       this->WriteMissingFilesWS10_0(e1);
4919     }
4920   }
4921 }
4922
4923 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80(Elem& e1)
4924 {
4925   std::string templateFolder =
4926     cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
4927
4928   // For WP80, the manifest needs to be in the same folder as the project
4929   // this can cause an overwrite problem if projects aren't organized in
4930   // folders
4931   std::string manifestFile =
4932     this->LocalGenerator->GetCurrentBinaryDirectory() + "/WMAppManifest.xml";
4933   std::string artifactDir =
4934     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
4935   ConvertToWindowsSlash(artifactDir);
4936   std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
4937   std::string targetNameXML =
4938     cmVS10EscapeXML(this->GeneratorTarget->GetName());
4939
4940   cmGeneratedFileStream fout(manifestFile);
4941   fout.SetCopyIfDifferent(true);
4942
4943   /* clang-format off */
4944   fout <<
4945     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
4946     "<Deployment"
4947     " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
4948     " AppPlatformVersion=\"8.0\">\n"
4949     "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
4950     "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
4951     " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
4952     " Version=\"1.0.0.0\" Genre=\"apps.normal\"  Author=\"CMake\""
4953     " Description=\"Default CMake App\" Publisher=\"CMake\""
4954     " PublisherID=\"{" << this->GUID << "}\">\n"
4955     "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
4956        << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
4957     "\t\t<Capabilities/>\n"
4958     "\t\t<Tasks>\n"
4959     "\t\t\t<DefaultTask Name=\"_default\""
4960     " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
4961     "\t\t</Tasks>\n"
4962     "\t\t<Tokens>\n"
4963     "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
4964     " TaskName=\"_default\">\n"
4965     "\t\t\t\t<TemplateFlip>\n"
4966     "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
4967        << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
4968     "\t\t\t\t\t<Count>0</Count>\n"
4969     "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
4970        << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
4971     "\t\t\t\t</TemplateFlip>\n"
4972     "\t\t\t</PrimaryToken>\n"
4973     "\t\t</Tokens>\n"
4974     "\t\t<ScreenResolutions>\n"
4975     "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
4976     "\t\t</ScreenResolutions>\n"
4977     "\t</App>\n"
4978     "</Deployment>\n";
4979   /* clang-format on */
4980
4981   std::string sourceFile = this->ConvertPath(manifestFile, false);
4982   ConvertToWindowsSlash(sourceFile);
4983   {
4984     Elem e2(e1, "Xml");
4985     e2.Attribute("Include", sourceFile);
4986     e2.Element("SubType", "Designer");
4987   }
4988   this->AddedFiles.push_back(sourceFile);
4989
4990   std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
4991   cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
4992                            false);
4993   ConvertToWindowsSlash(smallLogo);
4994   Elem(e1, "Image").Attribute("Include", smallLogo);
4995   this->AddedFiles.push_back(smallLogo);
4996
4997   std::string logo = this->DefaultArtifactDir + "/Logo.png";
4998   cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
4999   ConvertToWindowsSlash(logo);
5000   Elem(e1, "Image").Attribute("Include", logo);
5001   this->AddedFiles.push_back(logo);
5002
5003   std::string applicationIcon =
5004     this->DefaultArtifactDir + "/ApplicationIcon.png";
5005   cmSystemTools::CopyAFile(templateFolder + "/ApplicationIcon.png",
5006                            applicationIcon, false);
5007   ConvertToWindowsSlash(applicationIcon);
5008   Elem(e1, "Image").Attribute("Include", applicationIcon);
5009   this->AddedFiles.push_back(applicationIcon);
5010 }
5011
5012 void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81(Elem& e1)
5013 {
5014   std::string manifestFile =
5015     this->DefaultArtifactDir + "/package.appxManifest";
5016   std::string artifactDir =
5017     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5018   ConvertToWindowsSlash(artifactDir);
5019   std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5020   std::string targetNameXML =
5021     cmVS10EscapeXML(this->GeneratorTarget->GetName());
5022
5023   cmGeneratedFileStream fout(manifestFile);
5024   fout.SetCopyIfDifferent(true);
5025
5026   /* clang-format off */
5027   fout <<
5028     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5029     "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5030     " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
5031     " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
5032     "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5033     " Version=\"1.0.0.0\" />\n"
5034     "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
5035     " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5036     "\t<Properties>\n"
5037     "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5038     "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5039     "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5040     "\t</Properties>\n"
5041     "\t<Prerequisites>\n"
5042     "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
5043     "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
5044     "\t</Prerequisites>\n"
5045     "\t<Resources>\n"
5046     "\t\t<Resource Language=\"x-generate\" />\n"
5047     "\t</Resources>\n"
5048     "\t<Applications>\n"
5049     "\t\t<Application Id=\"App\""
5050     " Executable=\"" << targetNameXML << ".exe\""
5051     " EntryPoint=\"" << targetNameXML << ".App\">\n"
5052     "\t\t\t<m2:VisualElements\n"
5053     "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5054     "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5055     "\t\t\t\tBackgroundColor=\"#336699\"\n"
5056     "\t\t\t\tForegroundText=\"light\"\n"
5057     "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5058     "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5059     "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5060     "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5061     "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5062     "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5063     "\t\t\t\t</m2:DefaultTile>\n"
5064     "\t\t\t\t<m2:SplashScreen"
5065     " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5066     "\t\t\t</m2:VisualElements>\n"
5067     "\t\t</Application>\n"
5068     "\t</Applications>\n"
5069     "</Package>\n";
5070   /* clang-format on */
5071
5072   this->WriteCommonMissingFiles(e1, manifestFile);
5073 }
5074
5075 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80(Elem& e1)
5076 {
5077   std::string manifestFile =
5078     this->DefaultArtifactDir + "/package.appxManifest";
5079   std::string artifactDir =
5080     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5081   ConvertToWindowsSlash(artifactDir);
5082   std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5083   std::string targetNameXML =
5084     cmVS10EscapeXML(this->GeneratorTarget->GetName());
5085
5086   cmGeneratedFileStream fout(manifestFile);
5087   fout.SetCopyIfDifferent(true);
5088
5089   /* clang-format off */
5090   fout <<
5091     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5092     "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
5093     "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5094     " Version=\"1.0.0.0\" />\n"
5095     "\t<Properties>\n"
5096     "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5097     "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5098     "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5099     "\t</Properties>\n"
5100     "\t<Prerequisites>\n"
5101     "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
5102     "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
5103     "\t</Prerequisites>\n"
5104     "\t<Resources>\n"
5105     "\t\t<Resource Language=\"x-generate\" />\n"
5106     "\t</Resources>\n"
5107     "\t<Applications>\n"
5108     "\t\t<Application Id=\"App\""
5109     " Executable=\"" << targetNameXML << ".exe\""
5110     " EntryPoint=\"" << targetNameXML << ".App\">\n"
5111     "\t\t\t<VisualElements"
5112     " DisplayName=\"" << targetNameXML << "\""
5113     " Description=\"" << targetNameXML << "\""
5114     " BackgroundColor=\"#336699\" ForegroundText=\"light\""
5115     " Logo=\"" << artifactDirXML << "\\Logo.png\""
5116     " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5117     "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
5118     " ShortName=\"" << targetNameXML << "\" />\n"
5119     "\t\t\t\t<SplashScreen"
5120     " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5121     "\t\t\t</VisualElements>\n"
5122     "\t\t</Application>\n"
5123     "\t</Applications>\n"
5124     "</Package>\n";
5125   /* clang-format on */
5126
5127   this->WriteCommonMissingFiles(e1, manifestFile);
5128 }
5129
5130 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81(Elem& e1)
5131 {
5132   std::string manifestFile =
5133     this->DefaultArtifactDir + "/package.appxManifest";
5134   std::string artifactDir =
5135     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5136   ConvertToWindowsSlash(artifactDir);
5137   std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5138   std::string targetNameXML =
5139     cmVS10EscapeXML(this->GeneratorTarget->GetName());
5140
5141   cmGeneratedFileStream fout(manifestFile);
5142   fout.SetCopyIfDifferent(true);
5143
5144   /* clang-format off */
5145   fout <<
5146     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5147     "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
5148     " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
5149     "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5150     " Version=\"1.0.0.0\" />\n"
5151     "\t<Properties>\n"
5152     "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5153     "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5154     "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5155     "\t</Properties>\n"
5156     "\t<Prerequisites>\n"
5157     "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
5158     "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
5159     "\t</Prerequisites>\n"
5160     "\t<Resources>\n"
5161     "\t\t<Resource Language=\"x-generate\" />\n"
5162     "\t</Resources>\n"
5163     "\t<Applications>\n"
5164     "\t\t<Application Id=\"App\""
5165     " Executable=\"" << targetNameXML << ".exe\""
5166     " EntryPoint=\"" << targetNameXML << ".App\">\n"
5167     "\t\t\t<m2:VisualElements\n"
5168     "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5169     "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5170     "\t\t\t\tBackgroundColor=\"#336699\"\n"
5171     "\t\t\t\tForegroundText=\"light\"\n"
5172     "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5173     "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
5174     "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
5175     "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
5176     "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
5177     "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
5178     "\t\t\t\t</m2:DefaultTile>\n"
5179     "\t\t\t\t<m2:SplashScreen"
5180     " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5181     "\t\t\t</m2:VisualElements>\n"
5182     "\t\t</Application>\n"
5183     "\t</Applications>\n"
5184     "</Package>\n";
5185   /* clang-format on */
5186
5187   this->WriteCommonMissingFiles(e1, manifestFile);
5188 }
5189
5190 void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0(Elem& e1)
5191 {
5192   std::string manifestFile =
5193     this->DefaultArtifactDir + "/package.appxManifest";
5194   std::string artifactDir =
5195     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
5196   ConvertToWindowsSlash(artifactDir);
5197   std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
5198   std::string targetNameXML =
5199     cmVS10EscapeXML(this->GeneratorTarget->GetName());
5200
5201   cmGeneratedFileStream fout(manifestFile);
5202   fout.SetCopyIfDifferent(true);
5203
5204   /* clang-format off */
5205   fout <<
5206     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
5207     "<Package\n\t"
5208     "xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
5209     "\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
5210     "\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
5211     "\n\tIgnorableNamespaces=\"uap mp\">\n\n"
5212     "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
5213     " Version=\"1.0.0.0\" />\n"
5214     "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
5215     "\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
5216     "\t<Properties>\n"
5217     "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
5218     "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
5219     "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
5220     "\t</Properties>\n"
5221     "\t<Dependencies>\n"
5222     "\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
5223     "MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
5224     "\t</Dependencies>\n"
5225
5226     "\t<Resources>\n"
5227     "\t\t<Resource Language=\"x-generate\" />\n"
5228     "\t</Resources>\n"
5229     "\t<Applications>\n"
5230     "\t\t<Application Id=\"App\""
5231     " Executable=\"" << targetNameXML << ".exe\""
5232     " EntryPoint=\"" << targetNameXML << ".App\">\n"
5233     "\t\t\t<uap:VisualElements\n"
5234     "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
5235     "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
5236     "\t\t\t\tBackgroundColor=\"#336699\"\n"
5237     "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
5238     "\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
5239     "\\SmallLogo44x44.png\">\n"
5240     "\t\t\t\t<uap:SplashScreen"
5241     " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
5242     "\t\t\t</uap:VisualElements>\n"
5243     "\t\t</Application>\n"
5244     "\t</Applications>\n"
5245     "</Package>\n";
5246   /* clang-format on */
5247
5248   this->WriteCommonMissingFiles(e1, manifestFile);
5249 }
5250
5251 void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
5252   Elem& e1, const std::string& manifestFile)
5253 {
5254   std::string templateFolder =
5255     cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
5256
5257   std::string sourceFile = this->ConvertPath(manifestFile, false);
5258   ConvertToWindowsSlash(sourceFile);
5259   {
5260     Elem e2(e1, "AppxManifest");
5261     e2.Attribute("Include", sourceFile);
5262     e2.Element("SubType", "Designer");
5263   }
5264   this->AddedFiles.push_back(sourceFile);
5265
5266   std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
5267   cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
5268                            false);
5269   ConvertToWindowsSlash(smallLogo);
5270   Elem(e1, "Image").Attribute("Include", smallLogo);
5271   this->AddedFiles.push_back(smallLogo);
5272
5273   std::string smallLogo44 = this->DefaultArtifactDir + "/SmallLogo44x44.png";
5274   cmSystemTools::CopyAFile(templateFolder + "/SmallLogo44x44.png", smallLogo44,
5275                            false);
5276   ConvertToWindowsSlash(smallLogo44);
5277   Elem(e1, "Image").Attribute("Include", smallLogo44);
5278   this->AddedFiles.push_back(smallLogo44);
5279
5280   std::string logo = this->DefaultArtifactDir + "/Logo.png";
5281   cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
5282   ConvertToWindowsSlash(logo);
5283   Elem(e1, "Image").Attribute("Include", logo);
5284   this->AddedFiles.push_back(logo);
5285
5286   std::string storeLogo = this->DefaultArtifactDir + "/StoreLogo.png";
5287   cmSystemTools::CopyAFile(templateFolder + "/StoreLogo.png", storeLogo,
5288                            false);
5289   ConvertToWindowsSlash(storeLogo);
5290   Elem(e1, "Image").Attribute("Include", storeLogo);
5291   this->AddedFiles.push_back(storeLogo);
5292
5293   std::string splashScreen = this->DefaultArtifactDir + "/SplashScreen.png";
5294   cmSystemTools::CopyAFile(templateFolder + "/SplashScreen.png", splashScreen,
5295                            false);
5296   ConvertToWindowsSlash(splashScreen);
5297   Elem(e1, "Image").Attribute("Include", splashScreen);
5298   this->AddedFiles.push_back(splashScreen);
5299
5300   if (this->AddedDefaultCertificate) {
5301     // This file has already been added to the build so don't copy it
5302     std::string keyFile =
5303       this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
5304     ConvertToWindowsSlash(keyFile);
5305     Elem(e1, "None").Attribute("Include", keyFile);
5306   }
5307 }
5308
5309 bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
5310 {
5311   HANDLE h =
5312     CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
5313                 FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
5314                 FILE_FLAG_BACKUP_SEMANTICS, 0);
5315   if (!h) {
5316     return false;
5317   }
5318
5319   FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
5320   if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
5321     CloseHandle(h);
5322     return false;
5323   }
5324
5325   CloseHandle(h);
5326   return true;
5327 }
5328
5329 void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
5330   cmSourceFile const* sf, std::map<std::string, std::string>& tags)
5331 {
5332   if (this->ProjectType == VsProjectType::csproj) {
5333     const cmPropertyMap& props = sf->GetProperties();
5334     for (const std::string& p : props.GetKeys()) {
5335       static const cm::string_view propNamePrefix = "VS_CSHARP_";
5336       if (cmHasPrefix(p, propNamePrefix)) {
5337         std::string tagName = p.substr(propNamePrefix.length());
5338         if (!tagName.empty()) {
5339           cmValue val = props.GetPropertyValue(p);
5340           if (cmNonempty(val)) {
5341             tags[tagName] = *val;
5342           } else {
5343             tags.erase(tagName);
5344           }
5345         }
5346       }
5347     }
5348   }
5349 }
5350
5351 void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
5352   Elem& e2, const std::map<std::string, std::string>& tags)
5353 {
5354   for (const auto& i : tags) {
5355     e2.Element(i.first, i.second);
5356   }
5357 }
5358
5359 std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
5360   cmSourceFile const* source)
5361 {
5362   // For out of source files, we first check if a matching source group
5363   // for this file exists, otherwise we check if the path relative to current
5364   // source- or binary-dir is used within the link and return that.
5365   // In case of .cs files we can't do that automatically for files in the
5366   // binary directory, because this leads to compilation errors.
5367   std::string link;
5368   std::string sourceGroupedFile;
5369   std::string const& fullFileName = source->GetFullPath();
5370   std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory();
5371   std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory();
5372   // unfortunately we have to copy the source groups, because
5373   // FindSourceGroup uses a regex which is modifying the group
5374   std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
5375   cmSourceGroup* sourceGroup =
5376     this->Makefile->FindSourceGroup(fullFileName, sourceGroups);
5377   if (sourceGroup && !sourceGroup->GetFullName().empty()) {
5378     sourceGroupedFile = sourceGroup->GetFullName() + "/" +
5379       cmsys::SystemTools::GetFilenameName(fullFileName);
5380     cmsys::SystemTools::ConvertToUnixSlashes(sourceGroupedFile);
5381   }
5382
5383   if (!sourceGroupedFile.empty() &&
5384       cmHasSuffix(fullFileName, sourceGroupedFile)) {
5385     link = sourceGroupedFile;
5386   } else if (cmHasPrefix(fullFileName, srcDir)) {
5387     link = fullFileName.substr(srcDir.length() + 1);
5388   } else if (!cmHasSuffix(fullFileName, ".cs") &&
5389              cmHasPrefix(fullFileName, binDir)) {
5390     link = fullFileName.substr(binDir.length() + 1);
5391   } else if (cmValue l = source->GetProperty("VS_CSHARP_Link")) {
5392     link = *l;
5393   }
5394
5395   ConvertToWindowsSlash(link);
5396   return link;
5397 }
5398
5399 std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
5400   const char* relativeFilePath) const
5401 {
5402   // Always search in the standard modules location.
5403   std::string path =
5404     cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath);
5405   ConvertToWindowsSlash(path);
5406
5407   return path;
5408 }
5409
5410 void cmVisualStudio10TargetGenerator::WriteStdOutEncodingUtf8(Elem& e1)
5411 {
5412   if (this->GlobalGenerator->IsUtf8EncodingSupported()) {
5413     e1.Element("UseUtf8Encoding", "Always");
5414   } else if (this->GlobalGenerator->IsStdOutEncodingSupported()) {
5415     e1.Element("StdOutEncoding", "UTF-8");
5416   }
5417 }
5418
5419 void cmVisualStudio10TargetGenerator::UpdateCache()
5420 {
5421   std::vector<std::string> packageReferences;
5422
5423   if (this->GeneratorTarget->HasPackageReferences()) {
5424     // Store a cache entry that later determines, if a package restore is
5425     // required.
5426     this->GeneratorTarget->Makefile->AddCacheDefinition(
5427       this->GeneratorTarget->GetName() + "_REQUIRES_VS_PACKAGE_RESTORE", "ON",
5428       "Value Computed by CMake", cmStateEnums::STATIC);
5429   } else {
5430     // If there are any dependencies that require package restore, inherit the
5431     // cache variable.
5432     cmGlobalGenerator::TargetDependSet const& unordered =
5433       this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
5434     using OrderedTargetDependSet =
5435       cmGlobalVisualStudioGenerator::OrderedTargetDependSet;
5436     OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
5437
5438     for (cmGeneratorTarget const* dt : depends) {
5439       if (dt->HasPackageReferences()) {
5440         this->GeneratorTarget->Makefile->AddCacheDefinition(
5441           this->GeneratorTarget->GetName() + "_REQUIRES_VS_PACKAGE_RESTORE",
5442           "ON", "Value Computed by CMake", cmStateEnums::STATIC);
5443       }
5444     }
5445   }
5446 }