blob: 5ffa576c3c70d2077f23a4a38a15cc0d29565fcd [file] [log] [blame]
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmVisualStudio10TargetGenerator.h"
#include <iterator>
#include <set>
#include <cm/memory>
#include "windows.h"
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalVisualStudio10Generator.h"
#include "cmLinkLineDeviceComputer.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
#include "cmVisualStudioGeneratorOptions.h"
static void ConvertToWindowsSlash(std::string& s);
static std::string cmVS10EscapeXML(std::string arg)
{
cmSystemTools::ReplaceString(arg, "&", "&amp;");
cmSystemTools::ReplaceString(arg, "<", "&lt;");
cmSystemTools::ReplaceString(arg, ">", "&gt;");
return arg;
}
static std::string cmVS10EscapeAttr(std::string arg)
{
cmSystemTools::ReplaceString(arg, "&", "&amp;");
cmSystemTools::ReplaceString(arg, "<", "&lt;");
cmSystemTools::ReplaceString(arg, ">", "&gt;");
cmSystemTools::ReplaceString(arg, "\"", "&quot;");
cmSystemTools::ReplaceString(arg, "\n", "&#10;");
return arg;
}
struct cmVisualStudio10TargetGenerator::Elem
{
std::ostream& S;
const int Indent;
bool HasElements = false;
bool HasContent = false;
std::string Tag;
Elem(std::ostream& s, const std::string& tag)
: S(s)
, Indent(0)
, Tag(tag)
{
this->StartElement();
}
Elem(const Elem&) = delete;
Elem(Elem& par, const std::string& tag)
: S(par.S)
, Indent(par.Indent + 1)
, Tag(tag)
{
par.SetHasElements();
this->StartElement();
}
void SetHasElements()
{
if (!HasElements) {
this->S << ">\n";
HasElements = true;
}
}
std::ostream& WriteString(const char* line);
void StartElement() { this->WriteString("<") << this->Tag; }
void Element(const std::string& tag, const std::string& val)
{
Elem(*this, tag).Content(val);
}
Elem& Attribute(const char* an, const std::string& av)
{
this->S << " " << an << "=\"" << cmVS10EscapeAttr(av) << "\"";
return *this;
}
void Content(const std::string& val)
{
if (!this->HasContent) {
this->S << ">";
this->HasContent = true;
}
this->S << cmVS10EscapeXML(val);
}
~Elem()
{
// Do not emit element which has not been started
if (Tag.empty()) {
return;
}
if (HasElements) {
this->WriteString("</") << this->Tag << ">";
if (this->Indent > 0) {
this->S << '\n';
} else {
// special case: don't print EOL at EOF
}
} else if (HasContent) {
this->S << "</" << this->Tag << ">\n";
} else {
this->S << " />\n";
}
}
void WritePlatformConfigTag(const std::string& tag, const std::string& cond,
const std::string& content);
};
class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions
{
public:
using Elem = cmVisualStudio10TargetGenerator::Elem;
cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
cmVS7FlagTable const* table,
cmVisualStudio10TargetGenerator* g = nullptr)
: cmVisualStudioGeneratorOptions(lg, tool, table)
, TargetGenerator(g)
{
}
void OutputFlag(std::ostream& /*fout*/, int /*indent*/,
const std::string& tag, const std::string& content) override
{
if (!this->GetConfiguration().empty()) {
// if there are configuration specific flags, then
// use the configuration specific tag for PreprocessorDefinitions
const std::string cond =
this->TargetGenerator->CalcCondition(this->GetConfiguration());
this->Parent->WritePlatformConfigTag(tag, cond, content);
} else {
this->Parent->Element(tag, content);
}
}
private:
cmVisualStudio10TargetGenerator* const TargetGenerator;
Elem* Parent = nullptr;
friend cmVisualStudio10TargetGenerator::OptionsHelper;
};
struct cmVisualStudio10TargetGenerator::OptionsHelper
{
cmVS10GeneratorOptions& O;
OptionsHelper(cmVS10GeneratorOptions& o, Elem& e)
: O(o)
{
O.Parent = &e;
}
~OptionsHelper() { O.Parent = nullptr; }
void OutputPreprocessorDefinitions(const std::string& lang)
{
O.OutputPreprocessorDefinitions(O.Parent->S, O.Parent->Indent + 1, lang);
}
void OutputAdditionalIncludeDirectories(const std::string& lang)
{
O.OutputAdditionalIncludeDirectories(O.Parent->S, O.Parent->Indent + 1,
lang);
}
void OutputFlagMap() { O.OutputFlagMap(O.Parent->S, O.Parent->Indent + 1); }
void PrependInheritedString(std::string const& key)
{
O.PrependInheritedString(key);
}
};
static std::string cmVS10EscapeComment(std::string comment)
{
// MSBuild takes the CDATA of a <Message></Message> element and just
// does "echo $CDATA" with no escapes. We must encode the string.
// http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
std::string echoable;
for (char c : comment) {
switch (c) {
case '\r':
break;
case '\n':
echoable += '\t';
break;
case '"': /* no break */
case '|': /* no break */
case '&': /* no break */
case '<': /* no break */
case '>': /* no break */
case '^':
echoable += '^'; /* no break */
CM_FALLTHROUGH;
default:
echoable += c;
break;
}
}
return echoable;
}
static bool cmVS10IsTargetsFile(std::string const& path)
{
std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
}
static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
{
std::string res;
res = ".vcxproj";
if (t->IsCSharpOnly()) {
res = ".csproj";
}
return res;
}
cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
: GeneratorTarget(target)
, Makefile(target->Target->GetMakefile())
, Platform(gg->GetPlatformName())
, Name(target->GetName())
, GUID(gg->GetGUID(this->Name))
, GlobalGenerator(gg)
, LocalGenerator(
(cmLocalVisualStudio10Generator*)target->GetLocalGenerator())
{
this->Makefile->GetConfigurations(this->Configurations);
this->NsightTegra = gg->IsNsightTegra();
for (int i = 0; i < 4; ++i) {
this->NsightTegraVersion[i] = 0;
}
sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
&this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
&this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
this->MSTools = !this->NsightTegra;
this->Managed = false;
this->TargetCompileAsWinRT = false;
this->IsMissingFiles = false;
this->DefaultArtifactDir =
this->LocalGenerator->GetCurrentBinaryDirectory() + "/" +
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->InSourceBuild = (this->Makefile->GetCurrentSourceDirectory() ==
this->Makefile->GetCurrentBinaryDirectory());
}
cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
{
}
std::string cmVisualStudio10TargetGenerator::CalcCondition(
const std::string& config) const
{
std::ostringstream oss;
oss << "'$(Configuration)|$(Platform)'=='";
oss << config << "|" << this->Platform;
oss << "'";
// handle special case for 32 bit C# targets
if (this->ProjectType == csproj && this->Platform == "Win32") {
oss << " Or ";
oss << "'$(Configuration)|$(Platform)'=='";
oss << config << "|x86";
oss << "'";
}
return oss.str();
}
void cmVisualStudio10TargetGenerator::Elem::WritePlatformConfigTag(
const std::string& tag, const std::string& cond, const std::string& content)
{
Elem(*this, tag).Attribute("Condition", cond).Content(content);
}
std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString(
const char* line)
{
this->S.fill(' ');
this->S.width(this->Indent * 2);
// write an empty string to get the fill level indent to print
this->S << "";
this->S << line;
return this->S;
}
#define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
#define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
#define VS10_CXX_USER_PROPS \
"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
#define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
#define VS10_CSharp_DEFAULT_PROPS \
"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
// This does not seem to exist by default, it's just provided for consistency
// in case users want to have default custom props for C# targets
#define VS10_CSharp_USER_PROPS \
"$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
#define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
#define VS10_CSharp_NETCF_TARGETS \
"$(MSBuildExtensionsPath)\\Microsoft\\$(TargetFrameworkIdentifier)\\" \
"$(TargetFrameworkTargetsVersion)\\Microsoft.$(TargetFrameworkIdentifier)" \
".CSharp.targets"
void cmVisualStudio10TargetGenerator::Generate()
{
// do not generate external ms projects
if (this->GeneratorTarget->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
this->GeneratorTarget->GetProperty("EXTERNAL_MSPROJECT")) {
return;
}
const std::string ProjectFileExtension =
computeProjectFileExtension(this->GeneratorTarget);
if (ProjectFileExtension == ".vcxproj") {
this->ProjectType = vcxproj;
this->Managed = false;
} else if (ProjectFileExtension == ".csproj") {
if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
std::string message = "The C# target \"" +
this->GeneratorTarget->GetName() +
"\" is of type STATIC_LIBRARY. This is discouraged (and may be "
"disabled in future). Make it a SHARED library instead.";
this->Makefile->IssueMessage(MessageType::DEPRECATION_WARNING, message);
}
this->ProjectType = csproj;
this->Managed = true;
}
// Tell the global generator the name of the project file
this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
this->Name.c_str());
this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
ProjectFileExtension.c_str());
this->DotNetHintReferences.clear();
this->AdditionalUsingDirectories.clear();
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
if (!this->ComputeClOptions()) {
return;
}
if (!this->ComputeRcOptions()) {
return;
}
if (!this->ComputeCudaOptions()) {
return;
}
if (!this->ComputeCudaLinkOptions()) {
return;
}
if (!this->ComputeMasmOptions()) {
return;
}
if (!this->ComputeNasmOptions()) {
return;
}
if (!this->ComputeLinkOptions()) {
return;
}
if (!this->ComputeLibOptions()) {
return;
}
}
std::string path =
cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
this->Name, ProjectFileExtension);
cmGeneratedFileStream BuildFileStream(path);
const std::string PathToProjectFile = path;
BuildFileStream.SetCopyIfDifferent(true);
// Write the encoding header into the file
char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
BuildFileStream.write(magic, 3);
BuildFileStream << "<?xml version=\"1.0\" encoding=\""
<< this->GlobalGenerator->Encoding() << "\"?>"
<< "\n";
{
Elem e0(BuildFileStream, "Project");
e0.Attribute("DefaultTargets", "Build");
const char* toolsVersion = this->GlobalGenerator->GetToolsVersion();
if (this->GlobalGenerator->GetVersion() ==
cmGlobalVisualStudioGenerator::VS12 &&
this->GlobalGenerator->TargetsWindowsCE()) {
toolsVersion = "4.0";
}
e0.Attribute("ToolsVersion", toolsVersion);
e0.Attribute("xmlns",
"http://schemas.microsoft.com/developer/msbuild/2003");
if (this->NsightTegra) {
Elem e1(e0, "PropertyGroup");
e1.Attribute("Label", "NsightTegraProject");
const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0];
const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1];
if (nsightTegraMajorVersion >= 2) {
if (nsightTegraMajorVersion > 3 ||
(nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
e1.Element("NsightTegraProjectRevisionNumber", "11");
} else {
// Nsight Tegra 2.0 uses project revision 9.
e1.Element("NsightTegraProjectRevisionNumber", "9");
}
// Tell newer versions to upgrade silently when loading.
e1.Element("NsightTegraUpgradeOnceWithoutPrompt", "true");
} else {
// Require Nsight Tegra 1.6 for JCompile support.
e1.Element("NsightTegraProjectRevisionNumber", "7");
}
}
if (const char* hostArch =
this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
Elem e1(e0, "PropertyGroup");
e1.Element("PreferredToolArchitecture", hostArch);
}
if (this->ProjectType != csproj) {
this->WriteProjectConfigurations(e0);
}
{
Elem e1(e0, "PropertyGroup");
e1.Attribute("Label", "Globals");
e1.Element("ProjectGuid", "{" + this->GUID + "}");
if (this->MSTools &&
this->GeneratorTarget->GetType() <= cmStateEnums::GLOBAL_TARGET) {
this->WriteApplicationTypeSettings(e1);
this->VerifyNecessaryFiles();
}
const char* vsProjectTypes =
this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
if (vsProjectTypes) {
const char* tagName = "ProjectTypes";
if (this->ProjectType == csproj) {
tagName = "ProjectTypeGuids";
}
e1.Element(tagName, vsProjectTypes);
}
const char* vsProjectName =
this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
const char* vsLocalPath =
this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
const char* vsProvider =
this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
if (vsProjectName && vsLocalPath && vsProvider) {
e1.Element("SccProjectName", vsProjectName);
e1.Element("SccLocalPath", vsLocalPath);
e1.Element("SccProvider", vsProvider);
const char* vsAuxPath =
this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
if (vsAuxPath) {
e1.Element("SccAuxPath", vsAuxPath);
}
}
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
e1.Element("WinMDAssembly", "true");
}
const char* vsGlobalKeyword =
this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
if (!vsGlobalKeyword) {
e1.Element("Keyword", "Win32Proj");
} else {
e1.Element("Keyword", vsGlobalKeyword);
}
const char* vsGlobalRootNamespace =
this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
if (vsGlobalRootNamespace) {
e1.Element("RootNamespace", vsGlobalRootNamespace);
}
e1.Element("Platform", this->Platform);
const char* projLabel =
this->GeneratorTarget->GetProperty("PROJECT_LABEL");
if (!projLabel) {
projLabel = this->Name.c_str();
}
e1.Element("ProjectName", projLabel);
{
// TODO: add deprecation warning for VS_* property?
const char* targetFrameworkVersion =
this->GeneratorTarget->GetProperty(
"VS_DOTNET_TARGET_FRAMEWORK_VERSION");
if (!targetFrameworkVersion) {
targetFrameworkVersion = this->GeneratorTarget->GetProperty(
"DOTNET_TARGET_FRAMEWORK_VERSION");
}
if (!targetFrameworkVersion && this->ProjectType == csproj &&
this->GlobalGenerator->TargetsWindowsCE() &&
this->GlobalGenerator->GetVersion() ==
cmGlobalVisualStudioGenerator::VS12) {
// VS12 .NETCF default to .NET framework 3.9
targetFrameworkVersion = "v3.9";
}
if (targetFrameworkVersion) {
e1.Element("TargetFrameworkVersion", targetFrameworkVersion);
}
if (this->ProjectType == vcxproj &&
this->GlobalGenerator->TargetsWindowsCE()) {
e1.Element("EnableRedirectPlatform", "true");
e1.Element("RedirectPlatformValue", this->Platform);
}
if (this->ProjectType == csproj &&
this->GlobalGenerator->TargetsWindowsCE()) {
const char* targetFrameworkId = this->GeneratorTarget->GetProperty(
"VS_TARGET_FRAMEWORK_IDENTIFIER");
if (!targetFrameworkId) {
targetFrameworkId = "WindowsEmbeddedCompact";
}
e1.Element("TargetFrameworkIdentifier", targetFrameworkId);
const char* targetFrameworkVer = this->GeneratorTarget->GetProperty(
"VS_TARGET_FRAMEWORKS_TARGET_VERSION");
if (!targetFrameworkVer) {
targetFrameworkVer = "v8.0";
}
e1.Element("TargetFrameworkTargetsVersion", targetFrameworkVer);
}
if (!this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString()
.empty()) {
e1.Element(
"CudaToolkitCustomDir",
this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString() +
"nvcc");
}
}
// Disable the project upgrade prompt that is displayed the first time a
// project using an older toolset version is opened in a newer version of
// the IDE (respected by VS 2013 and above).
if (this->GlobalGenerator->GetVersion() >=
cmGlobalVisualStudioGenerator::VS12) {
e1.Element("VCProjectUpgraderObjectName", "NoUpgrade");
}
if (const char* vcTargetsPath =
this->GlobalGenerator->GetCustomVCTargetsPath()) {
e1.Element("VCTargetsPath", vcTargetsPath);
}
std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
for (std::string const& keyIt : keys) {
static const char* prefix = "VS_GLOBAL_";
if (keyIt.find(prefix) != 0)
continue;
std::string globalKey = keyIt.substr(strlen(prefix));
// Skip invalid or separately-handled properties.
if (globalKey.empty() || globalKey == "PROJECT_TYPES" ||
globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") {
continue;
}
const char* value = this->GeneratorTarget->GetProperty(keyIt);
if (!value)
continue;
e1.Element(globalKey, value);
}
if (this->Managed) {
std::string outputType;
switch (this->GeneratorTarget->GetType()) {
case cmStateEnums::OBJECT_LIBRARY:
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::SHARED_LIBRARY:
outputType = "Library";
break;
case cmStateEnums::MODULE_LIBRARY:
outputType = "Module";
break;
case cmStateEnums::EXECUTABLE:
if (this->GeneratorTarget->Target->GetPropertyAsBool(
"WIN32_EXECUTABLE")) {
outputType = "WinExe";
} else {
outputType = "Exe";
}
break;
case cmStateEnums::UTILITY:
case cmStateEnums::GLOBAL_TARGET:
outputType = "Utility";
break;
case cmStateEnums::UNKNOWN_LIBRARY:
case cmStateEnums::INTERFACE_LIBRARY:
break;
}
e1.Element("OutputType", outputType);
e1.Element("AppDesignerFolder", "Properties");
}
}
switch (this->ProjectType) {
case vcxproj:
if (this->GlobalGenerator->GetPlatformToolsetVersion()) {
Elem(e0, "Import")
.Attribute("Project",
this->GlobalGenerator->GetAuxiliaryToolset());
}
Elem(e0, "Import").Attribute("Project", VS10_CXX_DEFAULT_PROPS);
break;
case csproj:
Elem(e0, "Import")
.Attribute("Project", VS10_CSharp_DEFAULT_PROPS)
.Attribute("Condition", "Exists('" VS10_CSharp_DEFAULT_PROPS "')");
break;
}
this->WriteProjectConfigurationValues(e0);
if (this->ProjectType == vcxproj) {
Elem(e0, "Import").Attribute("Project", VS10_CXX_PROPS);
}
{
Elem e1(e0, "ImportGroup");
e1.Attribute("Label", "ExtensionSettings");
e1.SetHasElements();
if (this->GlobalGenerator->IsCudaEnabled()) {
auto customDir =
this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
std::string cudaPath = customDir.empty()
? "$(VCTargetsPath)\\BuildCustomizations\\"
: customDir +
"CUDAVisualStudioIntegration\\extras\\"
"visual_studio_integration\\MSBuildExtensions\\";
Elem(e1, "Import")
.Attribute("Project",
std::move(cudaPath) + "CUDA " +
this->GlobalGenerator->GetPlatformToolsetCuda() +
".props");
}
if (this->GlobalGenerator->IsMasmEnabled()) {
Elem(e1, "Import")
.Attribute("Project",
"$(VCTargetsPath)\\BuildCustomizations\\masm.props");
}
if (this->GlobalGenerator->IsNasmEnabled()) {
// Always search in the standard modules location.
std::string propsTemplate =
GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
std::string propsLocal =
cmStrCat(this->DefaultArtifactDir, "\\nasm.props");
ConvertToWindowsSlash(propsLocal);
this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true,
true);
Elem(e1, "Import").Attribute("Project", propsLocal);
}
}
{
Elem e1(e0, "ImportGroup");
e1.Attribute("Label", "PropertySheets");
std::string props;
switch (this->ProjectType) {
case vcxproj:
props = VS10_CXX_USER_PROPS;
break;
case csproj:
props = VS10_CSharp_USER_PROPS;
break;
}
if (const char* p =
this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
props = p;
}
if (!props.empty()) {
ConvertToWindowsSlash(props);
Elem(e1, "Import")
.Attribute("Project", props)
.Attribute("Condition", "exists('" + props + "')")
.Attribute("Label", "LocalAppDataPlatform");
}
this->WritePlatformExtensions(e1);
}
this->WriteDotNetDocumentationFile(e0);
Elem(e0, "PropertyGroup").Attribute("Label", "UserMacros");
this->WriteWinRTPackageCertificateKeyFile(e0);
this->WritePathAndIncrementalLinkOptions(e0);
this->WriteCEDebugProjectConfigurationValues(e0);
this->WriteItemDefinitionGroups(e0);
this->WriteCustomCommands(e0);
this->WriteAllSources(e0);
this->WriteDotNetReferences(e0);
this->WritePackageReferences(e0);
this->WriteImports(e0);
this->WriteEmbeddedResourceGroup(e0);
this->WriteXamlFilesGroup(e0);
this->WriteWinRTReferences(e0);
this->WriteProjectReferences(e0);
this->WriteSDKReferences(e0);
switch (this->ProjectType) {
case vcxproj:
Elem(e0, "Import").Attribute("Project", VS10_CXX_TARGETS);
break;
case csproj:
if (this->GlobalGenerator->TargetsWindowsCE()) {
Elem(e0, "Import").Attribute("Project", VS10_CSharp_NETCF_TARGETS);
} else {
Elem(e0, "Import").Attribute("Project", VS10_CSharp_TARGETS);
}
break;
}
this->WriteTargetSpecificReferences(e0);
{
Elem e1(e0, "ImportGroup");
e1.Attribute("Label", "ExtensionTargets");
e1.SetHasElements();
this->WriteTargetsFileReferences(e1);
if (this->GlobalGenerator->IsCudaEnabled()) {
auto customDir =
this->GlobalGenerator->GetPlatformToolsetCudaCustomDirString();
std::string cudaPath = customDir.empty()
? "$(VCTargetsPath)\\BuildCustomizations\\"
: customDir +
"CUDAVisualStudioIntegration\\extras\\"
"visual_studio_integration\\MSBuildExtensions\\";
Elem(e1, "Import")
.Attribute("Project",
std::move(cudaPath) + "CUDA " +
this->GlobalGenerator->GetPlatformToolsetCuda() +
".targets");
}
if (this->GlobalGenerator->IsMasmEnabled()) {
Elem(e1, "Import")
.Attribute("Project",
"$(VCTargetsPath)\\BuildCustomizations\\masm.targets");
}
if (this->GlobalGenerator->IsNasmEnabled()) {
std::string nasmTargets =
GetCMakeFilePath("Templates/MSBuild/nasm.targets");
Elem(e1, "Import").Attribute("Project", nasmTargets);
}
}
if (this->ProjectType == csproj) {
for (std::string const& c : this->Configurations) {
Elem e1(e0, "PropertyGroup");
e1.Attribute("Condition", "'$(Configuration)' == '" + c + "'");
e1.SetHasElements();
this->WriteEvents(e1, c);
}
// make sure custom commands are executed before build (if necessary)
{
Elem e1(e0, "PropertyGroup");
std::ostringstream oss;
oss << "\n";
for (std::string const& i : this->CSharpCustomCommandNames) {
oss << " " << i << ";\n";
}
oss << " "
<< "$(BuildDependsOn)\n";
e1.Element("BuildDependsOn", oss.str());
}
}
}
if (BuildFileStream.Close()) {
this->GlobalGenerator->FileReplacedDuringGenerate(PathToProjectFile);
}
// The groups are stored in a separate file for VS 10
this->WriteGroups();
}
void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0)
{
std::vector<std::string> packageReferences;
if (const char* vsPackageReferences =
this->GeneratorTarget->GetProperty("VS_PACKAGE_REFERENCES")) {
cmExpandList(vsPackageReferences, packageReferences);
}
if (!packageReferences.empty()) {
Elem e1(e0, "ItemGroup");
for (std::string const& ri : packageReferences) {
size_t versionIndex = ri.find_last_of('_');
if (versionIndex != std::string::npos) {
WritePackageReference(e1, ri.substr(0, versionIndex),
ri.substr(versionIndex + 1));
}
}
}
}
void cmVisualStudio10TargetGenerator::WritePackageReference(
Elem& e1, std::string const& ref, std::string const& version)
{
Elem e2(e1, "PackageReference");
e2.Attribute("Include", ref);
e2.Attribute("Version", version);
}
void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0)
{
std::vector<std::string> references;
if (const char* vsDotNetReferences =
this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
cmExpandList(vsDotNetReferences, references);
}
cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
for (auto const& i : props.GetList()) {
if (i.first.find("VS_DOTNET_REFERENCE_") == 0) {
std::string name = i.first.substr(20);
if (!name.empty()) {
std::string path = i.second;
if (!cmsys::SystemTools::FileIsFullPath(path)) {
path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
}
ConvertToWindowsSlash(path);
this->DotNetHintReferences[""].push_back(
DotNetHintReference(name, path));
}
}
}
if (!references.empty() || !this->DotNetHintReferences.empty()) {
Elem e1(e0, "ItemGroup");
for (std::string const& ri : references) {
// if the entry from VS_DOTNET_REFERENCES is an existing file, generate
// a new hint-reference and name it from the filename
if (cmsys::SystemTools::FileExists(ri, true)) {
std::string name =
cmsys::SystemTools::GetFilenameWithoutLastExtension(ri);
std::string path = ri;
ConvertToWindowsSlash(path);
this->DotNetHintReferences[""].push_back(
DotNetHintReference(name, path));
} else {
this->WriteDotNetReference(e1, ri, "", "");
}
}
for (const auto& h : this->DotNetHintReferences) {
// DotNetHintReferences is also populated from AddLibraries().
// The configuration specific hint references are added there.
for (const auto& i : h.second) {
this->WriteDotNetReference(e1, i.first, i.second, h.first);
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteDotNetReference(
Elem& e1, std::string const& ref, std::string const& hint,
std::string const& config)
{
Elem e2(e1, "Reference");
// If 'config' is not empty, the reference is only added for the given
// configuration. This is used when referencing imported managed assemblies.
// See also cmVisualStudio10TargetGenerator::AddLibraries().
if (!config.empty()) {
e2.Attribute("Condition", this->CalcCondition(config));
}
e2.Attribute("Include", ref);
e2.Element("CopyLocalSatelliteAssemblies", "true");
e2.Element("ReferenceOutputAssembly", "true");
if (!hint.empty()) {
const char* privateReference = "True";
if (const char* value = this->GeneratorTarget->GetProperty(
"VS_DOTNET_REFERENCES_COPY_LOCAL")) {
if (cmIsOff(value)) {
privateReference = "False";
}
}
e2.Element("Private", privateReference);
e2.Element("HintPath", hint);
}
this->WriteDotNetReferenceCustomTags(e2, ref);
}
void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0)
{
const char* imports =
this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT");
if (imports) {
std::vector<std::string> argsSplit =
cmExpandedList(std::string(imports), false);
for (auto& path : argsSplit) {
if (!cmsys::SystemTools::FileIsFullPath(path)) {
path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
}
ConvertToWindowsSlash(path);
Elem e1(e0, "Import");
e1.Attribute("Project", path);
}
}
}
void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
Elem& e2, std::string const& ref)
{
static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
static const std::string refpropInfix = "_TAG_";
const std::string refPropFullPrefix = refpropPrefix + ref + refpropInfix;
using CustomTags = std::map<std::string, std::string>;
CustomTags tags;
cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
for (const auto& i : props.GetList()) {
if (i.first.find(refPropFullPrefix) == 0) {
std::string refTag = i.first.substr(refPropFullPrefix.length());
std::string refVal = i.second;
if (!refTag.empty() && !refVal.empty()) {
tags[refTag] = refVal;
}
}
}
for (auto const& tag : tags) {
e2.Element(tag.first, tag.second);
}
}
void cmVisualStudio10TargetGenerator::WriteDotNetDocumentationFile(Elem& e0)
{
std::string const documentationFile =
this->GeneratorTarget->GetSafeProperty("VS_DOTNET_DOCUMENTATION_FILE");
if (this->ProjectType == csproj && !documentationFile.empty()) {
Elem e1(e0, "PropertyGroup");
Elem e2(e1, "DocumentationFile");
e2.Content(documentationFile);
}
}
void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0)
{
std::vector<cmSourceFile const*> resxObjs;
this->GeneratorTarget->GetResxSources(resxObjs, "");
if (!resxObjs.empty()) {
Elem e1(e0, "ItemGroup");
std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
ConvertToWindowsSlash(srcDir);
for (cmSourceFile const* oi : resxObjs) {
std::string obj = oi->GetFullPath();
ConvertToWindowsSlash(obj);
bool useRelativePath = false;
if (this->ProjectType == csproj && this->InSourceBuild) {
// If we do an in-source build and the resource file is in a
// subdirectory
// of the .csproj file, we have to use relative pathnames, otherwise
// visual studio does not show the file in the IDE. Sorry.
if (obj.find(srcDir) == 0) {
obj = this->ConvertPath(obj, true);
ConvertToWindowsSlash(obj);
useRelativePath = true;
}
}
Elem e2(e1, "EmbeddedResource");
e2.Attribute("Include", obj);
if (this->ProjectType != csproj) {
std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
e2.Element("DependentUpon", hFileName);
for (std::string const& c : this->Configurations) {
std::string s;
if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
// Handle variant of VS_GLOBAL_<variable> for RootNamespace.
this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
s = "$(RootNamespace).";
}
s += "%(Filename).resources";
e2.WritePlatformConfigTag("LogicalName", this->CalcCondition(c), s);
}
} else {
std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
ConvertToWindowsSlash(binDir);
// If the resource was NOT added using a relative path (which should
// be the default), we have to provide a link here
if (!useRelativePath) {
std::string link;
if (obj.find(srcDir) == 0) {
link = obj.substr(srcDir.length() + 1);
} else if (obj.find(binDir) == 0) {
link = obj.substr(binDir.length() + 1);
} else {
link = cmsys::SystemTools::GetFilenameName(obj);
}
if (!link.empty()) {
e2.Element("Link", link);
}
}
// Determine if this is a generated resource from a .Designer.cs file
std::string designerResource =
cmSystemTools::GetFilenamePath(oi->GetFullPath()) + "/" +
cmSystemTools::GetFilenameWithoutLastExtension(oi->GetFullPath()) +
".Designer.cs";
if (cmsys::SystemTools::FileExists(designerResource)) {
std::string generator = "PublicResXFileCodeGenerator";
if (const char* g = oi->GetProperty("VS_RESOURCE_GENERATOR")) {
generator = g;
}
if (!generator.empty()) {
e2.Element("Generator", generator);
if (designerResource.find(srcDir) == 0) {
designerResource = designerResource.substr(srcDir.length() + 1);
} else if (designerResource.find(binDir) == 0) {
designerResource = designerResource.substr(binDir.length() + 1);
} else {
designerResource =
cmsys::SystemTools::GetFilenameName(designerResource);
}
ConvertToWindowsSlash(designerResource);
e2.Element("LastGenOutput", designerResource);
}
}
const cmPropertyMap& props = oi->GetProperties();
for (const std::string& p : props.GetKeys()) {
static const std::string propNamePrefix = "VS_CSHARP_";
if (p.find(propNamePrefix) == 0) {
std::string tagName = p.substr(propNamePrefix.length());
if (!tagName.empty()) {
std::string value = props.GetPropertyValue(p);
if (!value.empty()) {
e2.Element(tagName, value);
}
}
}
}
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0)
{
std::vector<cmSourceFile const*> xamlObjs;
this->GeneratorTarget->GetXamlSources(xamlObjs, "");
if (!xamlObjs.empty()) {
Elem e1(e0, "ItemGroup");
for (cmSourceFile const* oi : xamlObjs) {
std::string obj = oi->GetFullPath();
const char* xamlType;
const char* xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE");
if (xamlTypeProperty) {
xamlType = xamlTypeProperty;
} else {
xamlType = "Page";
}
Elem e2(e1, xamlType);
this->WriteSource(e2, oi);
e2.SetHasElements();
if (this->ProjectType == csproj && !this->InSourceBuild) {
// add <Link> tag to written XAML source if necessary
const std::string& srcDir =
this->Makefile->GetCurrentSourceDirectory();
const std::string& binDir =
this->Makefile->GetCurrentBinaryDirectory();
std::string link;
if (obj.find(srcDir) == 0) {
link = obj.substr(srcDir.length() + 1);
} else if (obj.find(binDir) == 0) {
link = obj.substr(binDir.length() + 1);
} else {
link = cmsys::SystemTools::GetFilenameName(obj);
}
if (!link.empty()) {
ConvertToWindowsSlash(link);
e2.Element("Link", link);
}
}
e2.Element("SubType", "Designer");
}
}
}
void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences(Elem& e0)
{
if (this->MSTools) {
if (this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0") {
Elem(e0, "Import")
.Attribute("Project",
"$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
"$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
"$(TargetPlatformVersion).targets");
}
}
}
void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences(Elem& e1)
{
for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) {
std::ostringstream oss;
oss << "Exists('" << tac.File << "')";
if (!tac.Configs.empty()) {
oss << " And (";
for (size_t j = 0; j < tac.Configs.size(); ++j) {
if (j > 0) {
oss << " Or ";
}
oss << "'$(Configuration)'=='" << tac.Configs[j] << "'";
}
oss << ")";
}
Elem(e1, "Import")
.Attribute("Project", tac.File)
.Attribute("Condition", oss.str());
}
}
void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0)
{
std::vector<std::string> references;
if (const char* vsWinRTReferences =
this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
cmExpandList(vsWinRTReferences, references);
}
if (this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0" &&
references.empty()) {
references.push_back("platform.winmd");
}
if (!references.empty()) {
Elem e1(e0, "ItemGroup");
for (std::string const& ri : references) {
Elem e2(e1, "Reference");
e2.Attribute("Include", ri);
e2.Element("IsWinMDFile", "true");
}
}
}
// ConfigurationType Application, Utility StaticLibrary DynamicLibrary
void cmVisualStudio10TargetGenerator::WriteProjectConfigurations(Elem& e0)
{
Elem e1(e0, "ItemGroup");
e1.Attribute("Label", "ProjectConfigurations");
for (std::string const& c : this->Configurations) {
Elem e2(e1, "ProjectConfiguration");
e2.Attribute("Include", c + "|" + this->Platform);
e2.Element("Configuration", c);
e2.Element("Platform", this->Platform);
}
}
void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues(Elem& e0)
{
for (std::string const& c : this->Configurations) {
Elem e1(e0, "PropertyGroup");
e1.Attribute("Condition", this->CalcCondition(c));
e1.Attribute("Label", "Configuration");
if (this->ProjectType != csproj) {
std::string configType;
if (const char* vsConfigurationType =
this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
configType = cmGeneratorExpression::Evaluate(vsConfigurationType,
this->LocalGenerator, c);
} else {
switch (this->GeneratorTarget->GetType()) {
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
configType = "DynamicLibrary";
break;
case cmStateEnums::OBJECT_LIBRARY:
case cmStateEnums::STATIC_LIBRARY:
configType = "StaticLibrary";
break;
case cmStateEnums::EXECUTABLE:
if (this->NsightTegra &&
!this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
// Android executables are .so too.
configType = "DynamicLibrary";
} else {
configType = "Application";
}
break;
case cmStateEnums::UTILITY:
case cmStateEnums::GLOBAL_TARGET:
if (this->NsightTegra) {
// Tegra-Android platform does not understand "Utility".
configType = "StaticLibrary";
} else {
configType = "Utility";
}
break;
case cmStateEnums::UNKNOWN_LIBRARY:
case cmStateEnums::INTERFACE_LIBRARY:
break;
}
}
e1.Element("ConfigurationType", configType);
}
if (this->MSTools) {
if (!this->Managed) {
this->WriteMSToolConfigurationValues(e1, c);
} else {
this->WriteMSToolConfigurationValuesManaged(e1, c);
}
} else if (this->NsightTegra) {
this->WriteNsightTegraConfigurationValues(e1, c);
}
}
}
void cmVisualStudio10TargetGenerator::WriteCEDebugProjectConfigurationValues(
Elem& e0)
{
if (!this->GlobalGenerator->TargetsWindowsCE()) {
return;
}
const char* additionalFiles =
this->GeneratorTarget->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
const char* remoteDirectory =
this->GeneratorTarget->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
if (!(additionalFiles || remoteDirectory)) {
return;
}
for (std::string const& c : this->Configurations) {
Elem e1(e0, "PropertyGroup");
e1.Attribute("Condition", this->CalcCondition(c));
if (remoteDirectory) {
e1.Element("RemoteDirectory", remoteDirectory);
}
if (additionalFiles) {
e1.Element("CEAdditionalFiles", additionalFiles);
}
}
}
void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
Elem& e1, std::string const& config)
{
cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
const char* mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG");
if (mfcFlag) {
std::string const mfcFlagValue = mfcFlag;
std::string useOfMfcValue = "false";
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
if (mfcFlagValue == "1") {
useOfMfcValue = "Static";
} else if (mfcFlagValue == "2") {
useOfMfcValue = "Dynamic";
}
}
e1.Element("UseOfMfc", useOfMfcValue);
}
if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
this->ClOptions[config]->UsingUnicode()) ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore() ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
e1.Element("CharacterSet", "Unicode");
} else if (this->GeneratorTarget->GetType() <=
cmStateEnums::OBJECT_LIBRARY &&
this->ClOptions[config]->UsingSBCS()) {
e1.Element("CharacterSet", "NotSet");
} else {
e1.Element("CharacterSet", "MultiByte");
}
if (const char* toolset = gg->GetPlatformToolset()) {
e1.Element("PlatformToolset", toolset);
}
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
e1.Element("WindowsAppContainer", "true");
}
if (this->IPOEnabledConfigurations.count(config) > 0) {
e1.Element("WholeProgramOptimization", "true");
}
{
auto s = this->SpectreMitigation.find(config);
if (s != this->SpectreMitigation.end()) {
e1.Element("SpectreMitigation", s->second);
}
}
}
void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
Elem& e1, std::string const& config)
{
if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
return;
}
cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
Options& o = *(this->ClOptions[config]);
if (o.IsDebug()) {
e1.Element("DebugSymbols", "true");
e1.Element("DefineDebug", "true");
}
std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
ConvertToWindowsSlash(outDir);
e1.Element("OutputPath", outDir);
if (o.HasFlag("Platform")) {
e1.Element("PlatformTarget", o.GetFlag("Platform"));
o.RemoveFlag("Platform");
}
if (const char* toolset = gg->GetPlatformToolset()) {
e1.Element("PlatformToolset", toolset);
}
std::string postfixName =
cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
std::string assemblyName = this->GeneratorTarget->GetOutputName(
config, cmStateEnums::RuntimeBinaryArtifact);
if (const char* postfix = this->GeneratorTarget->GetProperty(postfixName)) {
assemblyName += postfix;
}
e1.Element("AssemblyName", assemblyName);
if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
e1.Element("StartAction", "Program");
e1.Element("StartProgram", outDir + assemblyName + ".exe");
}
OptionsHelper oh(o, e1);
oh.OutputFlagMap();
}
//----------------------------------------------------------------------------
void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
Elem& e1, std::string const&)
{
cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
const char* toolset = gg->GetPlatformToolset();
e1.Element("NdkToolchainVersion", toolset ? toolset : "Default");
if (const char* minApi =
this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
e1.Element("AndroidMinAPI", "android-" + std::string(minApi));
}
if (const char* api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
e1.Element("AndroidTargetAPI", "android-" + std::string(api));
}
if (const char* cpuArch =
this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
e1.Element("AndroidArch", cpuArch);
}
if (const char* stlType =
this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
e1.Element("AndroidStlType", stlType);
}
}
void cmVisualStudio10TargetGenerator::WriteCustomCommands(Elem& e0)
{
this->CSharpCustomCommandNames.clear();
std::vector<cmSourceFile const*> customCommands;
this->GeneratorTarget->GetCustomCommands(customCommands, "");
for (cmSourceFile const* si : customCommands) {
this->WriteCustomCommand(e0, si);
}
// Add CMakeLists.txt file with rule to re-run CMake for user convenience.
if (this->GeneratorTarget->GetType() != cmStateEnums::GLOBAL_TARGET &&
this->GeneratorTarget->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
if (cmSourceFile const* sf =
this->LocalGenerator->CreateVCProjBuildRule()) {
// Write directly rather than through WriteCustomCommand because
// we do not want the de-duplication and it has no dependencies.
if (cmCustomCommand const* command = sf->GetCustomCommand()) {
this->WriteCustomRule(e0, sf, *command);
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteCustomCommand(
Elem& e0, cmSourceFile const* sf)
{
if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget)
.insert(sf)
.second) {
if (std::vector<cmSourceFile*> const* depends =
this->GeneratorTarget->GetSourceDepends(sf)) {
for (cmSourceFile const* di : *depends) {
this->WriteCustomCommand(e0, di);
}
}
if (cmCustomCommand const* command = sf->GetCustomCommand()) {
// C# projects write their <Target> within WriteCustomRule()
this->WriteCustomRule(e0, sf, *command);
}
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRule(
Elem& e0, cmSourceFile const* source, cmCustomCommand const& command)
{
std::string sourcePath = source->GetFullPath();
// VS 10 will always rebuild a custom command attached to a .rule
// file that doesn't exist so create the file explicitly.
if (source->GetPropertyAsBool("__CMAKE_RULE")) {
if (!cmSystemTools::FileExists(sourcePath)) {
// Make sure the path exists for the file
std::string path = cmSystemTools::GetFilenamePath(sourcePath);
cmSystemTools::MakeDirectory(path);
cmsys::ofstream fout(sourcePath.c_str());
if (fout) {
fout << "# generated from CMake\n";
fout.flush();
fout.close();
// Force given file to have a very old timestamp, thus
// preventing dependent rebuilds.
this->ForceOld(sourcePath);
} else {
std::string error =
cmStrCat("Could not create file: [", sourcePath, "] ");
cmSystemTools::Error(error + cmSystemTools::GetLastSystemError());
}
}
}
cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
std::unique_ptr<Elem> spe1;
std::unique_ptr<Elem> spe2;
if (this->ProjectType != csproj) {
spe1 = cm::make_unique<Elem>(e0, "ItemGroup");
spe2 = cm::make_unique<Elem>(*spe1, "CustomBuild");
this->WriteSource(*spe2, source);
spe2->SetHasElements();
} else {
Elem e1(e0, "ItemGroup");
Elem e2(e1, "None");
std::string link;
this->GetCSharpSourceLink(source, link);
this->WriteSource(e2, source);
e2.SetHasElements();
if (!link.empty()) {
e2.Element("Link", link);
}
}
for (std::string const& c : this->Configurations) {
cmCustomCommandGenerator ccg(command, c, lg);
std::string comment = lg->ConstructComment(ccg);
comment = cmVS10EscapeComment(comment);
std::string script = lg->ConstructScript(ccg);
// input files for custom command
std::stringstream additional_inputs;
{
const char* sep = "";
if (this->ProjectType == csproj) {
// csproj files do not attach the command to a specific file
// so the primary input must be listed explicitly.
additional_inputs << source->GetFullPath();
sep = ";";
}
// Avoid listing an input more than once.
std::set<std::string> unique_inputs;
// The source is either implicit an input or has been added above.
unique_inputs.insert(source->GetFullPath());
for (std::string const& d : ccg.GetDepends()) {
std::string dep;
if (lg->GetRealDependency(d, c, dep)) {
if (!unique_inputs.insert(dep).second) {
// already listed
continue;
}
ConvertToWindowsSlash(dep);
additional_inputs << sep << dep;
sep = ";";
}
}
if (this->ProjectType != csproj) {
additional_inputs << sep << "%(AdditionalInputs)";
}
}
// output files for custom command
std::stringstream outputs;
bool symbolic = false;
{
const char* sep = "";
for (std::string const& o : ccg.GetOutputs()) {
std::string out = o;
ConvertToWindowsSlash(out);
outputs << sep << out;
sep = ";";
if (!symbolic) {
if (cmSourceFile* sf = this->Makefile->GetSource(
o, cmSourceFileLocationKind::Known)) {
symbolic = sf->GetPropertyAsBool("SYMBOLIC");
}
}
}
}
if (this->ProjectType == csproj) {
std::string name = "CustomCommand_" + c + "_" +
cmSystemTools::ComputeStringMD5(sourcePath);
this->WriteCustomRuleCSharp(e0, c, name, script, additional_inputs.str(),
outputs.str(), comment);
} else {
this->WriteCustomRuleCpp(*spe2, c, script, additional_inputs.str(),
outputs.str(), comment, symbolic);
}
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
Elem& e2, std::string const& config, std::string const& script,
std::string const& additional_inputs, std::string const& outputs,
std::string const& comment, bool symbolic)
{
const std::string cond = this->CalcCondition(config);
e2.WritePlatformConfigTag("Message", cond, comment);
e2.WritePlatformConfigTag("Command", cond, script);
e2.WritePlatformConfigTag("AdditionalInputs", cond, additional_inputs);
e2.WritePlatformConfigTag("Outputs", cond, outputs);
if (this->LocalGenerator->GetVersion() >
cmGlobalVisualStudioGenerator::VS10) {
// VS >= 11 let us turn off linking of custom command outputs.
e2.WritePlatformConfigTag("LinkObjects", cond, "false");
}
if (symbolic &&
this->LocalGenerator->GetVersion() >=
cmGlobalVisualStudioGenerator::VS16) {
// VS >= 16.4 warn if outputs are not created, but one of our
// outputs is marked SYMBOLIC and not expected to be created.
e2.WritePlatformConfigTag("VerifyInputsAndOutputsExist", cond, "false");
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
Elem& e0, std::string const& config, std::string const& name,
std::string const& script, std::string const& inputs,
std::string const& outputs, std::string const& comment)
{
this->CSharpCustomCommandNames.insert(name);
Elem e1(e0, "Target");
e1.Attribute("Condition", this->CalcCondition(config));
e1.S << "\n Name=\"" << name << "\"";
e1.S << "\n Inputs=\"" << cmVS10EscapeAttr(inputs) << "\"";
e1.S << "\n Outputs=\"" << cmVS10EscapeAttr(outputs) << "\"";
if (!comment.empty()) {
Elem(e1, "Exec").Attribute("Command", "echo " + comment);
}
Elem(e1, "Exec").Attribute("Command", script);
}
std::string cmVisualStudio10TargetGenerator::ConvertPath(
std::string const& path, bool forceRelative)
{
return forceRelative
? cmSystemTools::RelativePath(
this->LocalGenerator->GetCurrentBinaryDirectory(), path)
: path;
}
static void ConvertToWindowsSlash(std::string& s)
{
// first convert all of the slashes
for (auto& ch : s) {
if (ch == '/') {
ch = '\\';
}
}
}
void cmVisualStudio10TargetGenerator::WriteGroups()
{
if (this->ProjectType == csproj) {
return;
}
// collect up group information
std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
this->GeneratorTarget->GetAllConfigSources();
std::set<cmSourceGroup const*> groupsUsed;
for (cmGeneratorTarget::AllConfigSource const& si : sources) {
std::string const& source = si.Source->GetFullPath();
cmSourceGroup* sourceGroup =
this->Makefile->FindSourceGroup(source, sourceGroups);
groupsUsed.insert(sourceGroup);
}
if (cmSourceFile const* srcCMakeLists =
this->LocalGenerator->CreateVCProjBuildRule()) {
std::string const& source = srcCMakeLists->GetFullPath();
cmSourceGroup* sourceGroup =
this->Makefile->FindSourceGroup(source, sourceGroups);
groupsUsed.insert(sourceGroup);
}
this->AddMissingSourceGroups(groupsUsed, sourceGroups);
// Write out group file
std::string path = cmStrCat(
this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name,
computeProjectFileExtension(this->GeneratorTarget), ".filters");
cmGeneratedFileStream fout(path);
fout.SetCopyIfDifferent(true);
char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
fout.write(magic, 3);
fout << "<?xml version=\"1.0\" encoding=\""
<< this->GlobalGenerator->Encoding() << "\"?>"
<< "\n";
{
Elem e0(fout, "Project");
e0.Attribute("ToolsVersion", this->GlobalGenerator->GetToolsVersion());
e0.Attribute("xmlns",
"http://schemas.microsoft.com/developer/msbuild/2003");
for (auto const& ti : this->Tools) {
this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups);
}
// Added files are images and the manifest.
if (!this->AddedFiles.empty()) {
Elem e1(e0, "ItemGroup");
e1.SetHasElements();
for (std::string const& oi : this->AddedFiles) {
std::string fileName =
cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi));
if (fileName == "wmappmanifest.xml") {
Elem e2(e1, "XML");
e2.Attribute("Include", oi);
e2.Element("Filter", "Resource Files");
} else if (cmSystemTools::GetFilenameExtension(fileName) ==
".appxmanifest") {
Elem e2(e1, "AppxManifest");
e2.Attribute("Include", oi);
e2.Element("Filter", "Resource Files");
} else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx") {
Elem e2(e1, "None");
e2.Attribute("Include", oi);
e2.Element("Filter", "Resource Files");
} else {
Elem e2(e1, "Image");
e2.Attribute("Include", oi);
e2.Element("Filter", "Resource Files");
}
}
}
std::vector<cmSourceFile const*> resxObjs;
this->GeneratorTarget->GetResxSources(resxObjs, "");
if (!resxObjs.empty()) {
Elem e1(e0, "ItemGroup");
for (cmSourceFile const* oi : resxObjs) {
std::string obj = oi->GetFullPath();
ConvertToWindowsSlash(obj);
Elem e2(e1, "EmbeddedResource");
e2.Attribute("Include", obj);
e2.Element("Filter", "Resource Files");
}
}
{
Elem e1(e0, "ItemGroup");
e1.SetHasElements();
std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(),
groupsUsed.end());
std::sort(groupsVec.begin(), groupsVec.end(),
[](cmSourceGroup const* l, cmSourceGroup const* r) {
return l->GetFullName() < r->GetFullName();
});
for (cmSourceGroup const* sg : groupsVec) {
std::string const& name = sg->GetFullName();
if (!name.empty()) {
std::string guidName = "SG_Filter_" + name;
std::string guid = this->GlobalGenerator->GetGUID(guidName);
Elem e2(e1, "Filter");
e2.Attribute("Include", name);
e2.Element("UniqueIdentifier", "{" + guid + "}");
}
}
if (!resxObjs.empty() || !this->AddedFiles.empty()) {
std::string guidName = "SG_Filter_Resource Files";
std::string guid = this->GlobalGenerator->GetGUID(guidName);
Elem e2(e1, "Filter");
e2.Attribute("Include", "Resource Files");
e2.Element("UniqueIdentifier", "{" + guid + "}");
e2.Element("Extensions",
"rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;"
"gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms");
}
}
}
fout << '\n';
if (fout.Close()) {
this->GlobalGenerator->FileReplacedDuringGenerate(path);
}
}
// Add to groupsUsed empty source groups that have non-empty children.
void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
std::set<cmSourceGroup const*>& groupsUsed,
const std::vector<cmSourceGroup>& allGroups)
{
for (cmSourceGroup const& current : allGroups) {
std::vector<cmSourceGroup> const& children = current.GetGroupChildren();
if (children.empty()) {
continue; // the group is really empty
}
this->AddMissingSourceGroups(groupsUsed, children);
if (groupsUsed.count(&current) > 0) {
continue; // group has already been added to set
}
// check if it least one of the group's descendants is not empty
// (at least one child must already have been added)
auto child_it = children.begin();
while (child_it != children.end()) {
if (groupsUsed.count(&(*child_it)) > 0) {
break; // found a child that was already added => add current group too
}
child_it++;
}
if (child_it == children.end()) {
continue; // no descendants have source files => ignore this group
}
groupsUsed.insert(&current);
}
}
void cmVisualStudio10TargetGenerator::WriteGroupSources(
Elem& e0, std::string const& name, ToolSources const& sources,
std::vector<cmSourceGroup>& sourceGroups)
{
Elem e1(e0, "ItemGroup");
e1.SetHasElements();
for (ToolSource const& s : sources) {
cmSourceFile const* sf = s.SourceFile;
std::string const& source = sf->GetFullPath();
cmSourceGroup* sourceGroup =
this->Makefile->FindSourceGroup(source, sourceGroups);
std::string const& filter = sourceGroup->GetFullName();
std::string path = this->ConvertPath(source, s.RelativePath);
ConvertToWindowsSlash(path);
Elem e2(e1, name);
e2.Attribute("Include", path);
if (!filter.empty()) {
e2.Element("Filter", filter);
}
}
}
void cmVisualStudio10TargetGenerator::WriteHeaderSource(Elem& e1,
cmSourceFile const* sf)
{
std::string const& fileName = sf->GetFullPath();
Elem e2(e1, "ClInclude");
this->WriteSource(e2, sf);
if (this->IsResxHeader(fileName)) {
e2.Element("FileType", "CppForm");
} else if (this->IsXamlHeader(fileName)) {
std::string xamlFileName = fileName.substr(0, fileName.find_last_of("."));
e2.Element("DependentUpon", xamlFileName);
}
}
void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1,
cmSourceFile const* sf)
{
bool toolHasSettings = false;
const char* tool = "None";
std::string shaderType;
std::string shaderEntryPoint;
std::string shaderModel;
std::string shaderAdditionalFlags;
std::string shaderDisableOptimizations;
std::string shaderEnableDebug;
std::string shaderObjectFileName;
std::string outputHeaderFile;
std::string variableName;
std::string settingsGenerator;
std::string settingsLastGenOutput;
std::string sourceLink;
std::string subType;
std::string copyToOutDir;
std::string includeInVsix;
std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
if (this->ProjectType == csproj) {
// EVERY extra source file must have a <Link>, otherwise it might not
// be visible in Visual Studio at all. The path relative to current
// source- or binary-dir is used within the link, if the file is
// in none of these paths, it is added with the plain filename without
// any path. This means the file will show up at root-level of the csproj
// (where CMakeLists.txt etc. are).
if (!this->InSourceBuild) {
toolHasSettings = true;
std::string fullFileName = sf->GetFullPath();
std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
if (fullFileName.find(binDir) != std::string::npos) {
sourceLink.clear();
} else if (fullFileName.find(srcDir) != std::string::npos) {
sourceLink = fullFileName.substr(srcDir.length() + 1);
} else {
// fallback: add plain filename without any path
sourceLink = cmsys::SystemTools::GetFilenameName(fullFileName);
}
if (!sourceLink.empty()) {
ConvertToWindowsSlash(sourceLink);
}
}
}
if (ext == "hlsl") {
tool = "FXCompile";
// Figure out the type of shader compiler to use.
if (const char* st = sf->GetProperty("VS_SHADER_TYPE")) {
shaderType = st;
toolHasSettings = true;
}
// Figure out which entry point to use if any
if (const char* se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
shaderEntryPoint = se;
toolHasSettings = true;
}
// Figure out which shader model to use if any
if (const char* sm = sf->GetProperty("VS_SHADER_MODEL")) {
shaderModel = sm;
toolHasSettings = true;
}
// Figure out which output header file to use if any
if (const char* ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
outputHeaderFile = ohf;
toolHasSettings = true;
}
// Figure out which variable name to use if any
if (const char* vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
variableName = vn;
toolHasSettings = true;
}
// Figure out if there's any additional flags to use
if (const char* saf = sf->GetProperty("VS_SHADER_FLAGS")) {
shaderAdditionalFlags = saf;
toolHasSettings = true;
}
// Figure out if debug information should be generated
if (const char* sed = sf->GetProperty("VS_SHADER_ENABLE_DEBUG")) {
shaderEnableDebug = sed;
toolHasSettings = true;
}
// Figure out if optimizations should be disabled
if (const char* sdo = sf->GetProperty("VS_SHADER_DISABLE_OPTIMIZATIONS")) {
shaderDisableOptimizations = sdo;
toolHasSettings = true;
}
if (const char* sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) {
shaderObjectFileName = sofn;
toolHasSettings = true;
}
} else if (ext == "jpg" || ext == "png") {
tool = "Image";
} else if (ext == "resw") {
tool = "PRIResource";
} else if (ext == "xml") {
tool = "XML";
} else if (ext == "natvis") {
tool = "Natvis";
} else if (ext == "settings") {
settingsLastGenOutput =
cmsys::SystemTools::GetFilenameName(sf->GetFullPath());
std::size_t pos = settingsLastGenOutput.find(".settings");
settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
settingsGenerator = "SettingsSingleFileGenerator";
toolHasSettings = true;
} else if (ext == "vsixmanifest") {
subType = "Designer";
}
if (const char* c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
tool = "Content";
copyToOutDir = c;
toolHasSettings = true;
}
if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
includeInVsix = "True";
tool = "Content";
toolHasSettings = true;
}
// Collect VS_CSHARP_* property values (if some are set)
std::map<std::string, std::string> sourceFileTags;
this->GetCSharpSourceProperties(sf, sourceFileTags);
if (this->NsightTegra) {
// Nsight Tegra needs specific file types to check up-to-dateness.
std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
if (name == "androidmanifest.xml" || name == "build.xml" ||
name == "proguard.cfg" || name == "proguard-project.txt" ||
ext == "properties") {
tool = "AndroidBuild";
} else if (ext == "java") {
tool = "JCompile";
} else if (ext == "asm" || ext == "s") {
tool = "ClCompile";
}
}
const char* toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
if (toolOverride && *toolOverride) {
tool = toolOverride;
}
std::string deployContent;
std::string deployLocation;
if (this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore()) {
const char* content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
if (content && *content) {
toolHasSettings = true;
deployContent = content;
const char* location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
if (location && *location) {
deployLocation = location;
}
}
}
Elem e2(e1, tool);
this->WriteSource(e2, sf);
if (toolHasSettings) {
e2.SetHasElements();
if (!deployContent.empty()) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(deployContent);
// Deployment location cannot be set on a configuration basis
if (!deployLocation.empty()) {
e2.Element("Link", deployLocation + "\\%(FileName)%(Extension)");
}
for (size_t i = 0; i != this->Configurations.size(); ++i) {
if (cge->Evaluate(this->LocalGenerator, this->Configurations[i]) ==
"1") {
e2.WritePlatformConfigTag("DeploymentContent",
"'$(Configuration)|$(Platform)'=='" +
this->Configurations[i] + "|" +
this->Platform + "'",
"true");
} else {
e2.WritePlatformConfigTag("ExcludedFromBuild",
"'$(Configuration)|$(Platform)'=='" +
this->Configurations[i] + "|" +
this->Platform + "'",
"true");
}
}
}
if (!shaderType.empty()) {
e2.Element("ShaderType", shaderType);
}
if (!shaderEntryPoint.empty()) {
e2.Element("EntryPointName", shaderEntryPoint);
}
if (!shaderModel.empty()) {
e2.Element("ShaderModel", shaderModel);
}
if (!outputHeaderFile.empty()) {
for (size_t i = 0; i != this->Configurations.size(); ++i) {
e2.WritePlatformConfigTag("HeaderFileOutput",
"'$(Configuration)|$(Platform)'=='" +
this->Configurations[i] + "|" +
this->Platform + "'",
outputHeaderFile);
}
}
if (!variableName.empty()) {
for (size_t i = 0; i != this->Configurations.size(); ++i) {
e2.WritePlatformConfigTag("VariableName",
"'$(Configuration)|$(Platform)'=='" +
this->Configurations[i] + "|" +
this->Platform + "'",
variableName);
}
}
if (!shaderEnableDebug.empty()) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(shaderEnableDebug);
for (size_t i = 0; i != this->Configurations.size(); ++i) {
const std::string& enableDebug =
cge->Evaluate(this->LocalGenerator, this->Configurations[i]);
if (!enableDebug.empty()) {
e2.WritePlatformConfigTag("EnableDebuggingInformation",
"'$(Configuration)|$(Platform)'=='" +
this->Configurations[i] + "|" +
this->Platform + "'",
cmIsOn(enableDebug) ? "true" : "false");
}
}
}
if (!shaderDisableOptimizations.empty()) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(shaderDisableOptimizations);
for (size_t i = 0; i != this->Configurations.size(); ++i) {
const std::string& disableOptimizations =
cge->Evaluate(this->LocalGenerator, this->Configurations[i]);
if (!disableOptimizations.empty()) {
e2.WritePlatformConfigTag(
"DisableOptimizations",
"'$(Configuration)|$(Platform)'=='" + this->Configurations[i] +
"|" + this->Platform + "'",
(cmIsOn(disableOptimizations) ? "true" : "false"));
}
}
}
if (!shaderObjectFileName.empty()) {
e2.Element("ObjectFileOutput", shaderObjectFileName);
}
if (!shaderAdditionalFlags.empty()) {
e2.Element("AdditionalOptions", shaderAdditionalFlags);
}
if (!settingsGenerator.empty()) {
e2.Element("Generator", settingsGenerator);
}
if (!settingsLastGenOutput.empty()) {
e2.Element("LastGenOutput", settingsLastGenOutput);
}
if (!sourceLink.empty()) {
e2.Element("Link", sourceLink);
}
if (!subType.empty()) {
e2.Element("SubType", subType);
}
if (!copyToOutDir.empty()) {
e2.Element("CopyToOutputDirectory", copyToOutDir);
}
if (!includeInVsix.empty()) {
e2.Element("IncludeInVSIX", includeInVsix);
}
// write source file specific tags
this->WriteCSharpSourceProperties(e2, sourceFileTags);
}
}
void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2,
cmSourceFile const* sf)
{
// Visual Studio tools append relative paths to the current dir, as in:
//
// c:\path\to\current\dir\..\..\..\relative\path\to\source.c
//
// and fail if this exceeds the maximum allowed path length. Our path
// conversion uses full paths when possible to allow deeper trees.
// However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
// we must use relative paths.
bool forceRelative = sf->GetLanguage() == "CUDA";
std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
if (this->LocalGenerator->GetVersion() ==
cmGlobalVisualStudioGenerator::VS10 &&
cmSystemTools::FileIsFullPath(sourceFile)) {
// Normal path conversion resulted in a full path. VS 10 (but not 11)
// refuses to show the property page in the IDE for a source file with a
// full path (not starting in a '.' or '/' AFAICT). CMake <= 2.8.4 used a
// relative path but to allow deeper build trees CMake 2.8.[5678] used a
// full path except for custom commands. Custom commands do not work
// without a relative path, but they do not seem to be involved in tools
// with the above behavior. For other sources we now use a relative path
// when the combined path will not be too long so property pages appear.
std::string sourceRel = this->ConvertPath(sf->GetFullPath(), true);
size_t const maxLen = 250;
if (sf->GetCustomCommand() ||
((this->LocalGenerator->GetCurrentBinaryDirectory().length() + 1 +
sourceRel.length()) <= maxLen)) {
forceRelative = true;
sourceFile = sourceRel;
} else {
this->GlobalGenerator->PathTooLong(this->GeneratorTarget, sf, sourceRel);
}
}
ConvertToWindowsSlash(sourceFile);
e2.Attribute("Include", sourceFile);
ToolSource toolSource = { sf, forceRelative };
this->Tools[e2.Tag].push_back(toolSource);
}
void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
{
if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
return;
}
const bool haveUnityBuild =
this->GeneratorTarget->GetPropertyAsBool("UNITY_BUILD");
if (haveUnityBuild &&
this->GlobalGenerator->GetVersion() >=
cmGlobalVisualStudioGenerator::VS15) {
Elem e1(e0, "PropertyGroup");
e1.Element("EnableUnitySupport", "true");
}
Elem e1(e0, "ItemGroup");
e1.SetHasElements();
std::vector<size_t> all_configs;
for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
all_configs.push_back(ci);
}
std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
this->GeneratorTarget->GetAllConfigSources();
cmSourceFile const* srcCMakeLists =
this->LocalGenerator->CreateVCProjBuildRule();
for (cmGeneratorTarget::AllConfigSource const& si : sources) {
if (si.Source == srcCMakeLists) {
// Skip explicit reference to CMakeLists.txt source.
continue;
}
const char* tool = nullptr;
switch (si.Kind) {
case cmGeneratorTarget::SourceKindAppManifest:
tool = "AppxManifest";
break;
case cmGeneratorTarget::SourceKindCertificate:
tool = "None";
break;
case cmGeneratorTarget::SourceKindCustomCommand:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindExternalObject:
tool = "Object";
if (this->LocalGenerator->GetVersion() <
cmGlobalVisualStudioGenerator::VS11) {
// For VS == 10 we cannot use LinkObjects to avoid linking custom
// command outputs. If an object file is generated in this target,
// then vs10 will use it in the build, and we have to list it as
// None instead of Object.
std::vector<cmSourceFile*> const* d =
this->GeneratorTarget->GetSourceDepends(si.Source);
if (d && !d->empty()) {
tool = "None";
}
}
break;
case cmGeneratorTarget::SourceKindExtra:
this->WriteExtraSource(e1, si.Source);
break;
case cmGeneratorTarget::SourceKindHeader:
case cmGeneratorTarget::SourceKindUnityBatched:
this->WriteHeaderSource(e1, si.Source);
break;
case cmGeneratorTarget::SourceKindIDL:
tool = "Midl";
break;
case cmGeneratorTarget::SourceKindManifest:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindModuleDefinition:
tool = "None";
break;
case cmGeneratorTarget::SourceKindObjectSource: {
const std::string& lang = si.Source->GetLanguage();
if (lang == "C" || lang == "CXX") {
tool = "ClCompile";
} else if (lang == "ASM_MASM" &&
this->GlobalGenerator->IsMasmEnabled()) {
tool = "MASM";
} else if (lang == "ASM_NASM" &&
this->GlobalGenerator->IsNasmEnabled()) {
tool = "NASM";
} else if (lang == "RC") {
tool = "ResourceCompile";
} else if (lang == "CSharp") {
tool = "Compile";
} else if (lang == "CUDA" && this->GlobalGenerator->IsCudaEnabled()) {
tool = "CudaCompile";
} else {
tool = "None";
}
} break;
case cmGeneratorTarget::SourceKindResx:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindXaml:
// Handled elsewhere.
break;
}
if (tool) {
// Compute set of configurations to exclude, if any.
std::vector<size_t> const& include_configs = si.Configs;
std::vector<size_t> exclude_configs;
std::set_difference(all_configs.begin(), all_configs.end(),
include_configs.begin(), include_configs.end(),
std::back_inserter(exclude_configs));
Elem e2(e1, tool);
this->WriteSource(e2, si.Source);
bool useNativeUnityBuild = false;
if (haveUnityBuild &&
this->GlobalGenerator->GetVersion() >=
cmGlobalVisualStudioGenerator::VS15) {
// Magic value taken from cmGlobalVisualStudioVersionedGenerator.cxx
static const std::string vs15 = "141";
std::string toolset =
this->GlobalGenerator->GetPlatformToolsetString();
cmSystemTools::ReplaceString(toolset, "v", "");
if (toolset.empty() ||
cmSystemTools::VersionCompareGreaterEq(toolset, vs15)) {
useNativeUnityBuild = true;
}
}
if (haveUnityBuild && strcmp(tool, "ClCompile") == 0 &&
si.Source->GetProperty("UNITY_SOURCE_FILE")) {
if (useNativeUnityBuild) {
e2.Attribute(
"IncludeInUnityFile",
si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")
? "false"
: "true");
e2.Attribute("CustomUnityFile", "true");
std::string unityDir = cmSystemTools::GetFilenamePath(
si.Source->GetProperty("UNITY_SOURCE_FILE"));
e2.Attribute("UnityFilesDirectory", unityDir);
} else {
// Visual Studio versions prior to 2017 do not know about unity
// builds, thus we exclude the files alredy part of unity sources.
if (!si.Source->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION")) {
exclude_configs = si.Configs;
}
}
}
if (si.Kind == cmGeneratorTarget::SourceKindObjectSource) {
this->OutputSourceSpecificFlags(e2, si.Source);
}
if (si.Source->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
e2.Element("PrecompiledHeader", "NotUsing");
}
if (!exclude_configs.empty()) {
this->WriteExcludeFromBuild(e2, exclude_configs);
}
}
}
if (this->IsMissingFiles) {
this->WriteMissingFiles(e1);
}
}
void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
Elem& e2, cmSourceFile const* source)
{
cmSourceFile const& sf = *source;
std::string objectName;
if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
objectName = this->GeneratorTarget->GetObjectName(&sf);
}
std::string flags;
bool configDependentFlags = false;
std::string options;
bool configDependentOptions = false;
std::string defines;
bool configDependentDefines = false;
std::string includes;
bool configDependentIncludes = false;
if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) {
configDependentFlags =
cmGeneratorExpression::Find(cflags) != std::string::npos;
flags += cflags;
}
if (const char* coptions = sf.GetProperty("COMPILE_OPTIONS")) {
configDependentOptions =
cmGeneratorExpression::Find(coptions) != std::string::npos;
options += coptions;
}
if (const char* cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
configDependentDefines =
cmGeneratorExpression::Find(cdefs) != std::string::npos;
defines += cdefs;
}
if (const char* cincludes = sf.GetProperty("INCLUDE_DIRECTORIES")) {
configDependentIncludes =
cmGeneratorExpression::Find(cincludes) != std::string::npos;
includes += cincludes;
}
std::string lang =
this->GlobalGenerator->GetLanguageFromExtension(sf.GetExtension().c_str());
std::string sourceLang = this->LocalGenerator->GetSourceFileLanguage(sf);
const std::string& linkLanguage =
this->GeneratorTarget->GetLinkerLanguage("");
bool needForceLang = false;
// source file does not match its extension language
if (lang != sourceLang) {
needForceLang = true;
lang = sourceLang;
}
// if the source file does not match the linker language
// then force c or c++
const char* compileAs = 0;
if (needForceLang || (linkLanguage != lang)) {
if (lang == "CXX") {
// force a C++ file type
compileAs = "CompileAsCpp";
} else if (lang == "C") {
// force to c
compileAs = "CompileAsC";
}
}
bool noWinRT = this->TargetCompileAsWinRT && lang == "C";
// for the first time we need a new line if there is something
// produced here.
if (!objectName.empty()) {
if (lang == "CUDA") {
e2.Element("CompileOut", "$(IntDir)/" + objectName);
} else {
e2.Element("ObjectFileName", "$(IntDir)/" + objectName);
}
}
for (std::string const& config : this->Configurations) {
std::string configUpper = cmSystemTools::UpperCase(config);
std::string configDefines = defines;
std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
if (const char* ccdefs = sf.GetProperty(defPropName)) {
if (!configDefines.empty()) {
configDefines += ";";
}
configDependentDefines |=
cmGeneratorExpression::Find(ccdefs) != std::string::npos;
configDefines += ccdefs;
}
// Add precompile headers compile options.
std::string customAndPchOptions = options;
const std::string pchSource =
this->GeneratorTarget->GetPchSource(config, lang);
if (!pchSource.empty() && !sf.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
std::string pchOptions;
if (sf.GetFullPath() == pchSource) {
pchOptions =
this->GeneratorTarget->GetPchCreateCompileOptions(config, lang);
} else {
pchOptions =
this->GeneratorTarget->GetPchUseCompileOptions(config, lang);
}
customAndPchOptions += pchOptions;
}
// if we have flags or defines for this config then
// use them
if (!flags.empty() || !options.empty() || !configDefines.empty() ||
!includes.empty() || compileAs || noWinRT ||
!customAndPchOptions.empty()) {
cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator;
cmIDEFlagTable const* flagtable = nullptr;
const std::string& srclang = source->GetLanguage();
if (srclang == "C" || srclang == "CXX") {
flagtable = gg->GetClFlagTable();
} else if (srclang == "ASM_MASM" &&
this->GlobalGenerator->IsMasmEnabled()) {
flagtable = gg->GetMasmFlagTable();
} else if (lang == "ASM_NASM" &&
this->GlobalGenerator->IsNasmEnabled()) {
flagtable = gg->GetNasmFlagTable();
} else if (srclang == "RC") {
flagtable = gg->GetRcFlagTable();
} else if (srclang == "CSharp") {
flagtable = gg->GetCSharpFlagTable();
}
cmGeneratorExpressionInterpreter genexInterpreter(
this->LocalGenerator, config, this->GeneratorTarget, lang);
cmVS10GeneratorOptions clOptions(
this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
flagtable, this);
if (compileAs) {
clOptions.AddFlag("CompileAs", compileAs);
}
if (noWinRT) {
clOptions.AddFlag("CompileAsWinRT", "false");
}
if (configDependentFlags) {
clOptions.Parse(genexInterpreter.Evaluate(flags, "COMPILE_FLAGS"));
} else {
clOptions.Parse(flags);
}
if (!customAndPchOptions.empty()) {
std::string expandedOptions;
if (configDependentOptions) {
this->LocalGenerator->AppendCompileOptions(
expandedOptions,
genexInterpreter.Evaluate(customAndPchOptions, "COMPILE_OPTIONS"));
} else {
this->LocalGenerator->AppendCompileOptions(expandedOptions,
customAndPchOptions);
}
clOptions.Parse(expandedOptions);
}
if (clOptions.HasFlag("DisableSpecificWarnings")) {
clOptions.AppendFlag("DisableSpecificWarnings",
"%(DisableSpecificWarnings)");
}
if (configDependentDefines) {
clOptions.AddDefines(
genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS"));
} else {