resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmLocalVisualStudio7Generator.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 "cmLocalVisualStudio7Generator.h"
4
5 #include <algorithm>
6 #include <cassert>
7 #include <cstring>
8 #include <functional>
9 #include <sstream>
10 #include <utility>
11
12 #include <cm/memory>
13 #include <cmext/algorithm>
14
15 #include <windows.h>
16
17 #include <cm3p/expat.h>
18
19 #include "cmsys/FStream.hxx"
20
21 #include "cmComputeLinkInformation.h"
22 #include "cmCustomCommand.h"
23 #include "cmCustomCommandGenerator.h"
24 #include "cmCustomCommandLines.h"
25 #include "cmGeneratedFileStream.h"
26 #include "cmGeneratorExpression.h"
27 #include "cmGeneratorTarget.h"
28 #include "cmGlobalGenerator.h"
29 #include "cmGlobalVisualStudio7Generator.h"
30 #include "cmGlobalVisualStudioGenerator.h"
31 #include "cmListFileCache.h"
32 #include "cmMakefile.h"
33 #include "cmOutputConverter.h"
34 #include "cmPolicies.h"
35 #include "cmSourceFile.h"
36 #include "cmSourceGroup.h"
37 #include "cmStateTypes.h"
38 #include "cmStringAlgorithms.h"
39 #include "cmSystemTools.h"
40 #include "cmTarget.h"
41 #include "cmTargetDepend.h"
42 #include "cmValue.h"
43 #include "cmVsProjectType.h"
44 #include "cmXMLParser.h"
45 #include "cmake.h"
46
47 static bool cmLVS7G_IsFAT(const char* dir);
48
49 class cmLocalVisualStudio7GeneratorInternals
50 {
51 public:
52   cmLocalVisualStudio7GeneratorInternals(cmLocalVisualStudio7Generator* e)
53     : LocalGenerator(e)
54   {
55   }
56   using ItemVector = cmComputeLinkInformation::ItemVector;
57   void OutputLibraries(std::ostream& fout, ItemVector const& libs);
58   void OutputObjects(std::ostream& fout, cmGeneratorTarget* t,
59                      std::string const& config, const char* isep = 0);
60
61 private:
62   cmLocalVisualStudio7Generator* LocalGenerator;
63 };
64
65 class cmLocalVisualStudio7Generator::AllConfigSources
66 {
67 public:
68   std::vector<cmGeneratorTarget::AllConfigSource> Sources;
69   std::map<cmSourceFile const*, size_t> Index;
70 };
71
72 extern cmVS7FlagTable cmLocalVisualStudio7GeneratorFlagTable[];
73
74 cmLocalVisualStudio7Generator::cmLocalVisualStudio7Generator(
75   cmGlobalGenerator* gg, cmMakefile* mf)
76   : cmLocalVisualStudioGenerator(gg, mf)
77   , Internal(cm::make_unique<cmLocalVisualStudio7GeneratorInternals>(this))
78 {
79 }
80
81 cmLocalVisualStudio7Generator::~cmLocalVisualStudio7Generator() = default;
82
83 void cmLocalVisualStudio7Generator::AddHelperCommands()
84 {
85   // Now create GUIDs for targets
86   const auto& tgts = this->GetGeneratorTargets();
87   for (const auto& l : tgts) {
88     if (!l->IsInBuildSystem()) {
89       continue;
90     }
91     cmValue path = l->GetProperty("EXTERNAL_MSPROJECT");
92     if (path) {
93       this->ReadAndStoreExternalGUID(l->GetName(), path->c_str());
94     }
95   }
96
97   this->FixGlobalTargets();
98 }
99
100 void cmLocalVisualStudio7Generator::Generate()
101 {
102   // Create the project file for each target.
103   for (cmGeneratorTarget* gt :
104        this->GlobalGenerator->GetLocalGeneratorTargetsInOrder(this)) {
105     if (!gt->IsInBuildSystem() || gt->GetProperty("EXTERNAL_MSPROJECT")) {
106       continue;
107     }
108
109     auto& gtVisited = this->GetSourcesVisited(gt);
110     auto& deps = this->GlobalGenerator->GetTargetDirectDepends(gt);
111     for (auto& d : deps) {
112       // Take the union of visited source files of custom commands
113       auto depVisited = this->GetSourcesVisited(d);
114       gtVisited.insert(depVisited.begin(), depVisited.end());
115     }
116
117     this->GenerateTarget(gt);
118   }
119
120   this->WriteStampFiles();
121 }
122
123 void cmLocalVisualStudio7Generator::FixGlobalTargets()
124 {
125   // Visual Studio .NET 2003 Service Pack 1 will not run post-build
126   // commands for targets in which no sources are built.  Add dummy
127   // rules to force these targets to build.
128   const auto& tgts = this->GetGeneratorTargets();
129   for (auto& l : tgts) {
130     if (l->GetType() == cmStateEnums::GLOBAL_TARGET) {
131       cmCustomCommandLines force_commands =
132         cmMakeSingleCommandLine({ "cd", "." });
133       std::string force = cmStrCat(this->GetCurrentBinaryDirectory(),
134                                    "/CMakeFiles/", l->GetName(), "_force");
135       if (cmSourceFile* sf =
136             this->Makefile->GetOrCreateGeneratedSource(force)) {
137         sf->SetProperty("SYMBOLIC", "1");
138       }
139       auto cc = cm::make_unique<cmCustomCommand>();
140       cc->SetOutputs(force);
141       cc->SetCommandLines(force_commands);
142       cc->SetComment(" ");
143       cc->SetCMP0116Status(cmPolicies::NEW);
144       if (cmSourceFile* file =
145             this->AddCustomCommandToOutput(std::move(cc), true)) {
146         l->AddSource(file->ResolveFullPath());
147       }
148     }
149   }
150 }
151
152 void cmLocalVisualStudio7Generator::WriteStampFiles()
153 {
154   // Touch a timestamp file used to determine when the project file is
155   // out of date.
156   std::string stampName =
157     cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
158   cmSystemTools::MakeDirectory(stampName);
159   stampName += "/generate.stamp";
160   cmsys::ofstream stamp(stampName.c_str());
161   stamp << "# CMake generation timestamp file for this directory.\n";
162
163   // Create a helper file so CMake can determine when it is run
164   // through the rule created by CreateVCProjBuildRule whether it
165   // really needs to regenerate the project.  This file lists its own
166   // dependencies.  If any file listed in it is newer than itself then
167   // CMake must rerun.  Otherwise the project files are up to date and
168   // the stamp file can just be touched.
169   std::string depName = cmStrCat(stampName, ".depend");
170   cmsys::ofstream depFile(depName.c_str());
171   depFile << "# CMake generation dependency list for this directory.\n";
172
173   std::vector<std::string> listFiles(this->Makefile->GetListFiles());
174   cmake* cm = this->GlobalGenerator->GetCMakeInstance();
175   if (cm->DoWriteGlobVerifyTarget()) {
176     listFiles.push_back(cm->GetGlobVerifyStamp());
177   }
178
179   // Sort the list of input files and remove duplicates.
180   std::sort(listFiles.begin(), listFiles.end(), std::less<std::string>());
181   std::vector<std::string>::iterator new_end =
182     std::unique(listFiles.begin(), listFiles.end());
183   listFiles.erase(new_end, listFiles.end());
184
185   for (const std::string& lf : listFiles) {
186     depFile << lf << "\n";
187   }
188 }
189
190 void cmLocalVisualStudio7Generator::GenerateTarget(cmGeneratorTarget* target)
191 {
192   std::string const& lname = target->GetName();
193   cmGlobalVisualStudioGenerator* gg =
194     static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
195   this->FortranProject = gg->TargetIsFortranOnly(target);
196   this->WindowsCEProject = gg->TargetsWindowsCE();
197
198   // Intel Fortran always uses VS9 format ".vfproj" files.
199   cmGlobalVisualStudioGenerator::VSVersion realVersion = gg->GetVersion();
200   if (this->FortranProject &&
201       gg->GetVersion() >= cmGlobalVisualStudioGenerator::VSVersion::VS11) {
202     gg->SetVersion(cmGlobalVisualStudioGenerator::VSVersion::VS9);
203   }
204
205   // add to the list of projects
206   target->Target->SetProperty("GENERATOR_FILE_NAME", lname);
207   // create the dsp.cmake file
208   std::string fname;
209   fname = cmStrCat(this->GetCurrentBinaryDirectory(), '/', lname);
210   if (this->FortranProject) {
211     fname += ".vfproj";
212   } else {
213     fname += ".vcproj";
214   }
215
216   // Generate the project file and replace it atomically with
217   // copy-if-different.  We use a separate timestamp so that the IDE
218   // does not reload project files unnecessarily.
219   cmGeneratedFileStream fout(fname.c_str());
220   fout.SetCopyIfDifferent(true);
221   this->WriteVCProjFile(fout, lname, target);
222   if (fout.Close()) {
223     this->GlobalGenerator->FileReplacedDuringGenerate(fname);
224   }
225
226   gg->SetVersion(realVersion);
227 }
228
229 cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule()
230 {
231   if (this->GlobalGenerator->GlobalSettingIsOn(
232         "CMAKE_SUPPRESS_REGENERATION")) {
233     return nullptr;
234   }
235
236   std::string makefileIn =
237     cmStrCat(this->GetCurrentSourceDirectory(), "/CMakeLists.txt");
238   if (cmSourceFile* file = this->Makefile->GetSource(makefileIn)) {
239     if (file->GetCustomCommand()) {
240       return file;
241     }
242   }
243   if (!cmSystemTools::FileExists(makefileIn)) {
244     return nullptr;
245   }
246
247   std::vector<std::string> listFiles = this->Makefile->GetListFiles();
248   cmake* cm = this->GlobalGenerator->GetCMakeInstance();
249   if (cm->DoWriteGlobVerifyTarget()) {
250     listFiles.push_back(cm->GetGlobVerifyStamp());
251   }
252
253   // Sort the list of input files and remove duplicates.
254   std::sort(listFiles.begin(), listFiles.end(), std::less<std::string>());
255   std::vector<std::string>::iterator new_end =
256     std::unique(listFiles.begin(), listFiles.end());
257   listFiles.erase(new_end, listFiles.end());
258
259   std::string argS = cmStrCat("-S", this->GetSourceDirectory());
260   std::string argB = cmStrCat("-B", this->GetBinaryDirectory());
261   std::string stampName =
262     cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/generate.stamp");
263   cmCustomCommandLines commandLines =
264     cmMakeSingleCommandLine({ cmSystemTools::GetCMakeCommand(), argS, argB,
265                               "--check-stamp-file", stampName });
266   std::string comment = cmStrCat("Building Custom Rule ", makefileIn);
267   auto cc = cm::make_unique<cmCustomCommand>();
268   cc->SetOutputs(stampName);
269   cc->SetMainDependency(makefileIn);
270   cc->SetDepends(listFiles);
271   cc->SetCommandLines(commandLines);
272   cc->SetComment(comment.c_str());
273   cc->SetCMP0116Status(cmPolicies::NEW);
274   cc->SetEscapeOldStyle(false);
275   cc->SetStdPipesUTF8(true);
276   this->AddCustomCommandToOutput(std::move(cc), true);
277   if (cmSourceFile* file = this->Makefile->GetSource(makefileIn)) {
278     // Finalize the source file path now since we're adding this after
279     // the generator validated all project-named sources.
280     file->ResolveFullPath();
281     return file;
282   } else {
283     cmSystemTools::Error("Error adding rule for " + makefileIn);
284     return nullptr;
285   }
286 }
287
288 void cmLocalVisualStudio7Generator::WriteConfigurations(
289   std::ostream& fout, std::vector<std::string> const& configs,
290   const std::string& libName, cmGeneratorTarget* target)
291 {
292   fout << "\t<Configurations>\n";
293   for (std::string const& config : configs) {
294     this->WriteConfiguration(fout, config, libName, target);
295   }
296   fout << "\t</Configurations>\n";
297 }
298 cmVS7FlagTable cmLocalVisualStudio7GeneratorFortranFlagTable[] = {
299   { "Preprocess", "fpp", "Run Preprocessor on files", "preprocessYes", 0 },
300   { "Preprocess", "nofpp", "Run Preprocessor on files", "preprocessNo", 0 },
301   { "SuppressStartupBanner", "nologo", "SuppressStartupBanner", "true", 0 },
302   { "SourceFileFormat", "fixed", "Use Fixed Format", "fileFormatFixed", 0 },
303   { "SourceFileFormat", "free", "Use Free Format", "fileFormatFree", 0 },
304   { "DebugInformationFormat", "debug:full", "full debug", "debugEnabled", 0 },
305   { "DebugInformationFormat", "debug:minimal", "line numbers",
306     "debugLineInfoOnly", 0 },
307   { "Optimization", "Od", "disable optimization", "optimizeDisabled", 0 },
308   { "Optimization", "O1", "min space", "optimizeMinSpace", 0 },
309   { "Optimization", "O3", "full optimize", "optimizeFull", 0 },
310   { "GlobalOptimizations", "Og", "global optimize", "true", 0 },
311   { "InlineFunctionExpansion", "Ob0", "", "expandDisable", 0 },
312   { "InlineFunctionExpansion", "Ob1", "", "expandOnlyInline", 0 },
313   { "FavorSizeOrSpeed", "Os", "", "favorSize", 0 },
314   { "OmitFramePointers", "Oy-", "", "false", 0 },
315   { "OptimizeForProcessor", "GB", "", "procOptimizeBlended", 0 },
316   { "OptimizeForProcessor", "G5", "", "procOptimizePentium", 0 },
317   { "OptimizeForProcessor", "G6", "", "procOptimizePentiumProThruIII", 0 },
318   { "UseProcessorExtensions", "QzxK", "", "codeForStreamingSIMD", 0 },
319   { "OptimizeForProcessor", "QaxN", "", "codeForPentium4", 0 },
320   { "OptimizeForProcessor", "QaxB", "", "codeForPentiumM", 0 },
321   { "OptimizeForProcessor", "QaxP", "", "codeForCodeNamedPrescott", 0 },
322   { "OptimizeForProcessor", "QaxT", "", "codeForCore2Duo", 0 },
323   { "OptimizeForProcessor", "QxK", "", "codeExclusivelyStreamingSIMD", 0 },
324   { "OptimizeForProcessor", "QxN", "", "codeExclusivelyPentium4", 0 },
325   { "OptimizeForProcessor", "QxB", "", "codeExclusivelyPentiumM", 0 },
326   { "OptimizeForProcessor", "QxP", "", "codeExclusivelyCodeNamedPrescott", 0 },
327   { "OptimizeForProcessor", "QxT", "", "codeExclusivelyCore2Duo", 0 },
328   { "OptimizeForProcessor", "QxO", "", "codeExclusivelyCore2StreamingSIMD",
329     0 },
330   { "OptimizeForProcessor", "QxS", "", "codeExclusivelyCore2StreamingSIMD4",
331     0 },
332   { "OpenMP", "Qopenmp", "", "OpenMPParallelCode", 0 },
333   { "OpenMP", "Qopenmp-stubs", "", "OpenMPSequentialCode", 0 },
334   { "Traceback", "traceback", "", "true", 0 },
335   { "Traceback", "notraceback", "", "false", 0 },
336   { "FloatingPointExceptionHandling", "fpe:0", "", "fpe0", 0 },
337   { "FloatingPointExceptionHandling", "fpe:1", "", "fpe1", 0 },
338   { "FloatingPointExceptionHandling", "fpe:3", "", "fpe3", 0 },
339
340   { "MultiProcessorCompilation", "MP", "", "true",
341     cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
342   { "ProcessorNumber", "MP", "Multi-processor Compilation", "",
343     cmVS7FlagTable::UserValueRequired },
344
345   { "ModulePath", "module:", "", "", cmVS7FlagTable::UserValueRequired },
346   { "LoopUnrolling", "Qunroll:", "", "", cmVS7FlagTable::UserValueRequired },
347   { "AutoParallelThreshold", "Qpar-threshold:", "", "",
348     cmVS7FlagTable::UserValueRequired },
349   { "HeapArrays", "heap-arrays:", "", "", cmVS7FlagTable::UserValueRequired },
350   { "ObjectText", "bintext:", "", "", cmVS7FlagTable::UserValueRequired },
351   { "Parallelization", "Qparallel", "", "true", 0 },
352   { "PrefetchInsertion", "Qprefetch-", "", "false", 0 },
353   { "BufferedIO", "assume:buffered_io", "", "true", 0 },
354   { "CallingConvention", "iface:stdcall", "", "callConventionStdCall", 0 },
355   { "CallingConvention", "iface:cref", "", "callConventionCRef", 0 },
356   { "CallingConvention", "iface:stdref", "", "callConventionStdRef", 0 },
357   { "CallingConvention", "iface:stdcall", "", "callConventionStdCall", 0 },
358   { "CallingConvention", "iface:cvf", "", "callConventionCVF", 0 },
359   { "EnableRecursion", "recursive", "", "true", 0 },
360   { "ReentrantCode", "reentrancy", "", "true", 0 },
361   // done up to Language
362   { "", "", "", "", 0 }
363 };
364 // fill the table here currently the comment field is not used for
365 // anything other than documentation NOTE: Make sure the longer
366 // commandFlag comes FIRST!
367 cmVS7FlagTable cmLocalVisualStudio7GeneratorFlagTable[] = {
368   // option flags (some flags map to the same option)
369   { "BasicRuntimeChecks", "GZ", "Stack frame checks", "1", 0 },
370   { "BasicRuntimeChecks", "RTCsu", "Both stack and uninitialized checks", "3",
371     0 },
372   { "BasicRuntimeChecks", "RTCs", "Stack frame checks", "1", 0 },
373   { "BasicRuntimeChecks", "RTCu", "Uninitialized Variables ", "2", 0 },
374   { "BasicRuntimeChecks", "RTC1", "Both stack and uninitialized checks", "3",
375     0 },
376   { "DebugInformationFormat", "Z7", "debug format", "1", 0 },
377   { "DebugInformationFormat", "Zd", "debug format", "2", 0 },
378   { "DebugInformationFormat", "Zi", "debug format", "3", 0 },
379   { "DebugInformationFormat", "ZI", "debug format", "4", 0 },
380   { "EnableEnhancedInstructionSet", "arch:SSE2", "Use sse2 instructions", "2",
381     0 },
382   { "EnableEnhancedInstructionSet", "arch:SSE", "Use sse instructions", "1",
383     0 },
384   { "FloatingPointModel", "fp:precise", "Use precise floating point model",
385     "0", 0 },
386   { "FloatingPointModel", "fp:strict", "Use strict floating point model", "1",
387     0 },
388   { "FloatingPointModel", "fp:fast", "Use fast floating point model", "2", 0 },
389   { "FavorSizeOrSpeed", "Ot", "Favor fast code", "1", 0 },
390   { "FavorSizeOrSpeed", "Os", "Favor small code", "2", 0 },
391   { "CompileAs", "TC", "Compile as c code", "1", 0 },
392   { "CompileAs", "TP", "Compile as c++ code", "2", 0 },
393   { "Optimization", "Od", "Non Debug", "0", 0 },
394   { "Optimization", "O1", "Min Size", "1", 0 },
395   { "Optimization", "O2", "Max Speed", "2", 0 },
396   { "Optimization", "Ox", "Max Optimization", "3", 0 },
397   { "OptimizeForProcessor", "GB", "Blended processor mode", "0", 0 },
398   { "OptimizeForProcessor", "G5", "Pentium", "1", 0 },
399   { "OptimizeForProcessor", "G6", "PPro PII PIII", "2", 0 },
400   { "OptimizeForProcessor", "G7", "Pentium 4 or Athlon", "3", 0 },
401   { "InlineFunctionExpansion", "Ob0", "no inlines", "0", 0 },
402   { "InlineFunctionExpansion", "Ob1", "when inline keyword", "1", 0 },
403   { "InlineFunctionExpansion", "Ob2", "any time you can inline", "2", 0 },
404   { "RuntimeLibrary", "MTd", "Multithreaded debug", "1", 0 },
405   { "RuntimeLibrary", "MT", "Multithreaded", "0", 0 },
406   { "RuntimeLibrary", "MDd", "Multithreaded dll debug", "3", 0 },
407   { "RuntimeLibrary", "MD", "Multithreaded dll", "2", 0 },
408   { "RuntimeLibrary", "MLd", "Single Thread debug", "5", 0 },
409   { "RuntimeLibrary", "ML", "Single Thread", "4", 0 },
410   { "StructMemberAlignment", "Zp16", "struct align 16 byte ", "5", 0 },
411   { "StructMemberAlignment", "Zp1", "struct align 1 byte ", "1", 0 },
412   { "StructMemberAlignment", "Zp2", "struct align 2 byte ", "2", 0 },
413   { "StructMemberAlignment", "Zp4", "struct align 4 byte ", "3", 0 },
414   { "StructMemberAlignment", "Zp8", "struct align 8 byte ", "4", 0 },
415   { "WarningLevel", "W0", "Warning level", "0", 0 },
416   { "WarningLevel", "W1", "Warning level", "1", 0 },
417   { "WarningLevel", "W2", "Warning level", "2", 0 },
418   { "WarningLevel", "W3", "Warning level", "3", 0 },
419   { "WarningLevel", "W4", "Warning level", "4", 0 },
420   { "DisableSpecificWarnings", "wd", "Disable specific warnings", "",
421     cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
422
423   // Precompiled header and related options.  Note that the
424   // UsePrecompiledHeader entries are marked as "Continue" so that the
425   // corresponding PrecompiledHeaderThrough entry can be found.
426   { "UsePrecompiledHeader", "Yc", "Create Precompiled Header", "1",
427     cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
428   { "PrecompiledHeaderThrough", "Yc", "Precompiled Header Name", "",
429     cmVS7FlagTable::UserValueRequired },
430   { "UsePrecompiledHeader", "Y-", "Don't use precompiled header", "0", 0 },
431   { "PrecompiledHeaderFile", "Fp", "Generated Precompiled Header", "",
432     cmVS7FlagTable::UserValue },
433   // The YX and Yu options are in a per-global-generator table because
434   // their values differ based on the VS IDE version.
435   { "ForcedIncludeFiles", "FI", "Forced include files", "",
436     cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SemicolonAppendable },
437
438   { "AssemblerListingLocation", "Fa", "ASM List Location", "",
439     cmVS7FlagTable::UserValue },
440   { "ProgramDataBaseFileName", "Fd", "Program Database File Name", "",
441     cmVS7FlagTable::UserValue },
442
443   // boolean flags
444   { "BufferSecurityCheck", "GS", "Buffer security check", "true", 0 },
445   { "BufferSecurityCheck", "GS-", "Turn off Buffer security check", "false",
446     0 },
447   { "Detect64BitPortabilityProblems", "Wp64",
448     "Detect 64-bit Portability Problems", "true", 0 },
449   { "EnableFiberSafeOptimizations", "GT", "Enable Fiber-safe Optimizations",
450     "true", 0 },
451   { "EnableFunctionLevelLinking", "Gy", "EnableFunctionLevelLinking", "true",
452     0 },
453   { "EnableIntrinsicFunctions", "Oi", "EnableIntrinsicFunctions", "true", 0 },
454   { "GlobalOptimizations", "Og", "Global Optimize", "true", 0 },
455   { "ImproveFloatingPointConsistency", "Op", "ImproveFloatingPointConsistency",
456     "true", 0 },
457   { "MinimalRebuild", "Gm", "minimal rebuild", "true", 0 },
458   { "OmitFramePointers", "Oy", "OmitFramePointers", "true", 0 },
459   { "OptimizeForWindowsApplication", "GA", "Optimize for windows", "true", 0 },
460   { "RuntimeTypeInfo", "GR", "Turn on Run time type information for c++",
461     "true", 0 },
462   { "RuntimeTypeInfo", "GR-", "Turn off Run time type information for c++",
463     "false", 0 },
464   { "SmallerTypeCheck", "RTCc", "smaller type check", "true", 0 },
465   { "SuppressStartupBanner", "nologo", "SuppressStartupBanner", "true", 0 },
466   { "WholeProgramOptimization", "GL", "Enables whole program optimization",
467     "true", 0 },
468   { "WholeProgramOptimization", "GL-", "Disables whole program optimization",
469     "false", 0 },
470   { "WarnAsError", "WX", "Treat warnings as errors", "true", 0 },
471   { "BrowseInformation", "FR", "Generate browse information", "1", 0 },
472   { "StringPooling", "GF", "Enable StringPooling", "true", 0 },
473   { "", "", "", "", 0 }
474 };
475
476 cmVS7FlagTable cmLocalVisualStudio7GeneratorLinkFlagTable[] = {
477   // option flags (some flags map to the same option)
478   { "GenerateManifest", "MANIFEST:NO", "disable manifest generation", "false",
479     0 },
480   { "GenerateManifest", "MANIFEST", "enable manifest generation", "true", 0 },
481   { "LinkIncremental", "INCREMENTAL:NO", "link incremental", "1", 0 },
482   { "LinkIncremental", "INCREMENTAL:YES", "link incremental", "2", 0 },
483   { "CLRUnmanagedCodeCheck", "CLRUNMANAGEDCODECHECK:NO", "", "false", 0 },
484   { "CLRUnmanagedCodeCheck", "CLRUNMANAGEDCODECHECK", "", "true", 0 },
485   { "DataExecutionPrevention", "NXCOMPAT:NO",
486     "Not known to work with Windows Data Execution Prevention", "1", 0 },
487   { "DataExecutionPrevention", "NXCOMPAT",
488     "Known to work with Windows Data Execution Prevention", "2", 0 },
489   { "DelaySign", "DELAYSIGN:NO", "", "false", 0 },
490   { "DelaySign", "DELAYSIGN", "", "true", 0 },
491   { "EntryPointSymbol", "ENTRY:", "sets the starting address", "",
492     cmVS7FlagTable::UserValue },
493   { "IgnoreDefaultLibraryNames", "NODEFAULTLIB:", "default libs to ignore", "",
494     cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
495   { "IgnoreAllDefaultLibraries", "NODEFAULTLIB", "ignore all default libs",
496     "true", 0 },
497   { "FixedBaseAddress", "FIXED:NO", "Generate a relocation section", "1", 0 },
498   { "FixedBaseAddress", "FIXED", "Image must be loaded at a fixed address",
499     "2", 0 },
500   { "EnableCOMDATFolding", "OPT:NOICF", "Do not remove redundant COMDATs", "1",
501     0 },
502   { "EnableCOMDATFolding", "OPT:ICF", "Remove redundant COMDATs", "2", 0 },
503   { "ResourceOnlyDLL", "NOENTRY", "Create DLL with no entry point", "true",
504     0 },
505   { "OptimizeReferences", "OPT:NOREF", "Keep unreferenced data", "1", 0 },
506   { "OptimizeReferences", "OPT:REF", "Eliminate unreferenced data", "2", 0 },
507   { "Profile", "PROFILE", "", "true", 0 },
508   { "RandomizedBaseAddress", "DYNAMICBASE:NO",
509     "Image may not be rebased at load-time", "1", 0 },
510   { "RandomizedBaseAddress", "DYNAMICBASE",
511     "Image may be rebased at load-time", "2", 0 },
512   { "SetChecksum", "RELEASE", "Enable setting checksum in header", "true", 0 },
513   { "SupportUnloadOfDelayLoadedDLL", "DELAY:UNLOAD", "", "true", 0 },
514   { "TargetMachine", "MACHINE:I386", "Machine x86", "1", 0 },
515   { "TargetMachine", "MACHINE:X86", "Machine x86", "1", 0 },
516   { "TargetMachine", "MACHINE:AM33", "Machine AM33", "2", 0 },
517   { "TargetMachine", "MACHINE:ARM", "Machine ARM", "3", 0 },
518   { "TargetMachine", "MACHINE:EBC", "Machine EBC", "4", 0 },
519   { "TargetMachine", "MACHINE:IA64", "Machine IA64", "5", 0 },
520   { "TargetMachine", "MACHINE:M32R", "Machine M32R", "6", 0 },
521   { "TargetMachine", "MACHINE:MIPS", "Machine MIPS", "7", 0 },
522   { "TargetMachine", "MACHINE:MIPS16", "Machine MIPS16", "8", 0 },
523   { "TargetMachine", "MACHINE:MIPSFPU)", "Machine MIPSFPU", "9", 0 },
524   { "TargetMachine", "MACHINE:MIPSFPU16", "Machine MIPSFPU16", "10", 0 },
525   { "TargetMachine", "MACHINE:MIPSR41XX", "Machine MIPSR41XX", "11", 0 },
526   { "TargetMachine", "MACHINE:SH3", "Machine SH3", "12", 0 },
527   { "TargetMachine", "MACHINE:SH3DSP", "Machine SH3DSP", "13", 0 },
528   { "TargetMachine", "MACHINE:SH4", "Machine SH4", "14", 0 },
529   { "TargetMachine", "MACHINE:SH5", "Machine SH5", "15", 0 },
530   { "TargetMachine", "MACHINE:THUMB", "Machine THUMB", "16", 0 },
531   { "TargetMachine", "MACHINE:X64", "Machine x64", "17", 0 },
532   { "TargetMachine", "MACHINE:ARM64", "Machine ARM64", "18", 0 },
533   { "TurnOffAssemblyGeneration", "NOASSEMBLY",
534     "No assembly even if CLR information is present in objects.", "true", 0 },
535   { "ModuleDefinitionFile", "DEF:", "add an export def file", "",
536     cmVS7FlagTable::UserValue },
537   { "GenerateMapFile", "MAP", "enable generation of map file", "true", 0 },
538   { "", "", "", "", 0 }
539 };
540
541 cmVS7FlagTable cmLocalVisualStudio7GeneratorFortranLinkFlagTable[] = {
542   { "LinkIncremental", "INCREMENTAL:NO", "link incremental",
543     "linkIncrementalNo", 0 },
544   { "LinkIncremental", "INCREMENTAL:YES", "link incremental",
545     "linkIncrementalYes", 0 },
546   { "EnableCOMDATFolding", "OPT:NOICF", "Do not remove redundant COMDATs",
547     "optNoFolding", 0 },
548   { "EnableCOMDATFolding", "OPT:ICF", "Remove redundant COMDATs", "optFolding",
549     0 },
550   { "OptimizeReferences", "OPT:NOREF", "Keep unreferenced data",
551     "optNoReferences", 0 },
552   { "OptimizeReferences", "OPT:REF", "Eliminate unreferenced data",
553     "optReferences", 0 },
554   { "", "", "", "", 0 }
555 };
556
557 // Helper class to write build event <Tool .../> elements.
558 class cmLocalVisualStudio7Generator::EventWriter
559 {
560 public:
561   EventWriter(cmLocalVisualStudio7Generator* lg, const std::string& config,
562               std::ostream& os)
563     : LG(lg)
564     , Config(config)
565     , Stream(os)
566     , First(true)
567   {
568   }
569   void Start(const char* tool)
570   {
571     this->First = true;
572     this->Stream << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"";
573   }
574   void Finish()
575   {
576     // If any commands were generated, finish constructing them.
577     if (!this->First) {
578       std::string finishScript =
579         this->LG->FinishConstructScript(VsProjectType::vcxproj);
580       this->Stream << this->LG->EscapeForXML(finishScript) << "\"";
581     }
582
583     this->Stream << "/>\n";
584   }
585   void Write(std::vector<cmCustomCommand> const& ccs)
586   {
587     for (cmCustomCommand const& command : ccs) {
588       this->Write(command);
589     }
590   }
591   void Write(cmCustomCommand const& cc)
592   {
593     cmCustomCommandGenerator ccg(cc, this->Config, this->LG);
594     if (this->First) {
595       const char* comment = ccg.GetComment();
596       if (comment && *comment) {
597         this->Stream << "\nDescription=\"" << this->LG->EscapeForXML(comment)
598                      << "\"";
599       }
600       this->Stream << "\nCommandLine=\"";
601       this->First = false;
602     } else {
603       this->Stream << this->LG->EscapeForXML("\n");
604     }
605     std::string script = this->LG->ConstructScript(ccg);
606     this->Stream << this->LG->EscapeForXML(script);
607   }
608
609 private:
610   cmLocalVisualStudio7Generator* LG;
611   std::string Config;
612   std::ostream& Stream;
613   bool First;
614 };
615
616 void cmLocalVisualStudio7Generator::WriteConfiguration(
617   std::ostream& fout, const std::string& configName,
618   const std::string& libName, cmGeneratorTarget* target)
619 {
620   std::string mfcFlag;
621   if (cmValue p = this->Makefile->GetDefinition("CMAKE_MFC_FLAG")) {
622     mfcFlag = cmGeneratorExpression::Evaluate(*p, this, configName);
623   } else {
624     mfcFlag = "0";
625   }
626   cmGlobalVisualStudio7Generator* gg =
627     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
628   fout << "\t\t<Configuration\n"
629        << "\t\t\tName=\"" << configName << "|" << gg->GetPlatformName()
630        << "\"\n";
631   // This is an internal type to Visual Studio, it seems that:
632   // 4 == static library
633   // 2 == dll
634   // 1 == executable
635   // 10 == utility
636   const char* configType = "10";
637   const char* projectType = 0;
638   bool targetBuilds = true;
639
640   switch (target->GetType()) {
641     case cmStateEnums::OBJECT_LIBRARY:
642       targetBuilds = false; // no manifest tool for object library
643       CM_FALLTHROUGH;
644     case cmStateEnums::STATIC_LIBRARY:
645       projectType = "typeStaticLibrary";
646       configType = "4";
647       break;
648     case cmStateEnums::SHARED_LIBRARY:
649     case cmStateEnums::MODULE_LIBRARY:
650       projectType = "typeDynamicLibrary";
651       configType = "2";
652       break;
653     case cmStateEnums::EXECUTABLE:
654       configType = "1";
655       break;
656     case cmStateEnums::UTILITY:
657     case cmStateEnums::GLOBAL_TARGET:
658     case cmStateEnums::INTERFACE_LIBRARY:
659       configType = "10";
660       CM_FALLTHROUGH;
661     case cmStateEnums::UNKNOWN_LIBRARY:
662       targetBuilds = false;
663       break;
664   }
665   if (this->FortranProject && projectType) {
666     configType = projectType;
667   }
668   std::string flags;
669   std::string langForClCompile;
670   if (target->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
671     const std::string& linkLanguage =
672       (this->FortranProject ? std::string("Fortran")
673                             : target->GetLinkerLanguage(configName));
674     if (linkLanguage.empty()) {
675       cmSystemTools::Error(
676         "CMake can not determine linker language for target: " +
677         target->GetName());
678       return;
679     }
680     langForClCompile = linkLanguage;
681     if (langForClCompile == "C" || langForClCompile == "CXX" ||
682         langForClCompile == "Fortran") {
683       this->AddLanguageFlags(flags, target, cmBuildStep::Compile,
684                              langForClCompile, configName);
685     }
686     // set the correct language
687     if (linkLanguage == "C") {
688       flags += " /TC ";
689     }
690     if (linkLanguage == "CXX") {
691       flags += " /TP ";
692     }
693
694     // Add the target-specific flags.
695     this->AddCompileOptions(flags, target, langForClCompile, configName);
696
697     // Check IPO related warning/error.
698     target->IsIPOEnabled(linkLanguage, configName);
699   }
700
701   if (this->FortranProject) {
702     switch (cmOutputConverter::GetFortranFormat(
703       target->GetSafeProperty("Fortran_FORMAT"))) {
704       case cmOutputConverter::FortranFormatFixed:
705         flags += " -fixed";
706         break;
707       case cmOutputConverter::FortranFormatFree:
708         flags += " -free";
709         break;
710       default:
711         break;
712     }
713
714     switch (cmOutputConverter::GetFortranPreprocess(
715       target->GetSafeProperty("Fortran_PREPROCESS"))) {
716       case cmOutputConverter::FortranPreprocess::Needed:
717         flags += " -fpp";
718         break;
719       case cmOutputConverter::FortranPreprocess::NotNeeded:
720         flags += " -nofpp";
721         break;
722       default:
723         break;
724     }
725   }
726
727   // Get preprocessor definitions for this directory.
728   std::string defineFlags = this->Makefile->GetDefineFlags();
729   Options::Tool t = Options::Compiler;
730   cmVS7FlagTable const* table = cmLocalVisualStudio7GeneratorFlagTable;
731   if (this->FortranProject) {
732     t = Options::FortranCompiler;
733     table = cmLocalVisualStudio7GeneratorFortranFlagTable;
734   }
735   Options targetOptions(this, t, table, gg->ExtraFlagTable);
736   targetOptions.FixExceptionHandlingDefault();
737   targetOptions.AddFlag("AssemblerListingLocation", "$(IntDir)\\");
738   targetOptions.Parse(flags);
739   targetOptions.Parse(defineFlags);
740   targetOptions.ParseFinish();
741   if (!langForClCompile.empty()) {
742     std::vector<std::string> targetDefines;
743     target->GetCompileDefinitions(targetDefines, configName, langForClCompile);
744     targetOptions.AddDefines(targetDefines);
745
746     std::vector<std::string> targetIncludes;
747     this->GetIncludeDirectories(targetIncludes, target, langForClCompile,
748                                 configName);
749     targetOptions.AddIncludes(targetIncludes);
750   }
751   targetOptions.SetVerboseMakefile(
752     this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
753
754   // Add a definition for the configuration name.
755   std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"');
756   targetOptions.AddDefine(configDefine);
757
758   // Add the export symbol definition for shared library objects.
759   if (const std::string* exportMacro = target->GetExportMacro()) {
760     targetOptions.AddDefine(*exportMacro);
761   }
762
763   // The intermediate directory name consists of a directory for the
764   // target and a subdirectory for the configuration name.
765   std::string intermediateDir =
766     cmStrCat(this->GetTargetDirectory(target), '/', configName);
767
768   if (target->GetType() < cmStateEnums::UTILITY) {
769     std::string const& outDir =
770       target->GetType() == cmStateEnums::OBJECT_LIBRARY
771       ? intermediateDir
772       : target->GetDirectory(configName);
773     /* clang-format off */
774     fout << "\t\t\tOutputDirectory=\""
775          << this->ConvertToXMLOutputPathSingle(outDir) << "\"\n";
776     /* clang-format on */
777   }
778
779   /* clang-format off */
780   fout << "\t\t\tIntermediateDirectory=\""
781        << this->ConvertToXMLOutputPath(intermediateDir)
782        << "\"\n"
783        << "\t\t\tConfigurationType=\"" << configType << "\"\n"
784        << "\t\t\tUseOfMFC=\"" << mfcFlag << "\"\n"
785        << "\t\t\tATLMinimizesCRunTimeLibraryUsage=\"false\"\n";
786   /* clang-format on */
787
788   if (this->FortranProject) {
789     // Intel Fortran >= 15.0 uses TargetName property.
790     std::string const targetNameFull = target->GetFullName(configName);
791     std::string const targetName =
792       cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
793     std::string const targetExt =
794       target->GetType() == cmStateEnums::OBJECT_LIBRARY
795       ? ".lib"
796       : cmSystemTools::GetFilenameLastExtension(targetNameFull);
797     /* clang-format off */
798     fout <<
799       "\t\t\tTargetName=\"" << this->EscapeForXML(targetName) << "\"\n"
800       "\t\t\tTargetExt=\"" << this->EscapeForXML(targetExt) << "\"\n"
801       ;
802     /* clang-format on */
803   }
804
805   // If unicode is enabled change the character set to unicode, if not
806   // then default to MBCS.
807   if (targetOptions.UsingUnicode()) {
808     fout << "\t\t\tCharacterSet=\"1\">\n";
809   } else if (targetOptions.UsingSBCS()) {
810     fout << "\t\t\tCharacterSet=\"0\">\n";
811   } else {
812     fout << "\t\t\tCharacterSet=\"2\">\n";
813   }
814   const char* tool = "VCCLCompilerTool";
815   if (this->FortranProject) {
816     tool = "VFFortranCompilerTool";
817   }
818   fout << "\t\t\t<Tool\n"
819        << "\t\t\t\tName=\"" << tool << "\"\n";
820   if (this->FortranProject) {
821     cmValue target_mod_dir = target->GetProperty("Fortran_MODULE_DIRECTORY");
822     std::string modDir;
823     if (target_mod_dir) {
824       modDir = this->MaybeRelativeToCurBinDir(*target_mod_dir);
825     } else {
826       modDir = ".";
827     }
828     fout << "\t\t\t\tModulePath=\"" << this->ConvertToXMLOutputPath(modDir)
829          << "\\$(ConfigurationName)\"\n";
830   }
831   targetOptions.OutputAdditionalIncludeDirectories(
832     fout, 4, this->FortranProject ? "Fortran" : langForClCompile);
833   targetOptions.OutputFlagMap(fout, 4);
834   targetOptions.OutputPreprocessorDefinitions(fout, 4, langForClCompile);
835   fout << "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n";
836   if (target->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
837     // Specify the compiler program database file if configured.
838     std::string pdb = target->GetCompilePDBPath(configName);
839     if (!pdb.empty()) {
840       fout << "\t\t\t\tProgramDataBaseFileName=\""
841            << this->ConvertToXMLOutputPathSingle(pdb) << "\"\n";
842     }
843   }
844   fout << "/>\n"; // end of <Tool Name=VCCLCompilerTool
845   if (gg->IsMasmEnabled() && !this->FortranProject) {
846     Options masmOptions(this, Options::MasmCompiler, 0, 0);
847     /* clang-format off */
848     fout <<
849       "\t\t\t<Tool\n"
850       "\t\t\t\tName=\"MASM\"\n"
851       ;
852     /* clang-format on */
853     targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "ASM_MASM");
854     // Use same preprocessor definitions as VCCLCompilerTool.
855     targetOptions.OutputPreprocessorDefinitions(fout, 4, "ASM_MASM");
856     masmOptions.OutputFlagMap(fout, 4);
857     /* clang-format off */
858     fout <<
859       "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n"
860       "\t\t\t/>\n";
861     /* clang-format on */
862   }
863   tool = "VCCustomBuildTool";
864   if (this->FortranProject) {
865     tool = "VFCustomBuildTool";
866   }
867   fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"/>\n";
868   tool = "VCResourceCompilerTool";
869   if (this->FortranProject) {
870     tool = "VFResourceCompilerTool";
871   }
872   fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"\n";
873   targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "RC");
874   // add the -D flags to the RC tool
875   targetOptions.OutputPreprocessorDefinitions(fout, 4, "RC");
876   fout << "\t\t\t/>\n";
877   tool = "VCMIDLTool";
878   if (this->FortranProject) {
879     tool = "VFMIDLTool";
880   }
881   fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"\n";
882   targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "MIDL");
883   fout << "\t\t\t\tMkTypLibCompatible=\"false\"\n";
884   if (gg->GetPlatformName() == "x64") {
885     fout << "\t\t\t\tTargetEnvironment=\"3\"\n";
886   } else if (gg->GetPlatformName() == "ia64") {
887     fout << "\t\t\t\tTargetEnvironment=\"2\"\n";
888   } else {
889     fout << "\t\t\t\tTargetEnvironment=\"1\"\n";
890   }
891   fout << "\t\t\t\tGenerateStublessProxies=\"true\"\n";
892   fout << "\t\t\t\tTypeLibraryName=\"$(InputName).tlb\"\n";
893   fout << "\t\t\t\tOutputDirectory=\"$(IntDir)\"\n";
894   fout << "\t\t\t\tHeaderFileName=\"$(InputName).h\"\n";
895   fout << "\t\t\t\tDLLDataFileName=\"\"\n";
896   fout << "\t\t\t\tInterfaceIdentifierFileName=\"$(InputName)_i.c\"\n";
897   fout << "\t\t\t\tProxyFileName=\"$(InputName)_p.c\"/>\n";
898   // end of <Tool Name=VCMIDLTool
899
900   // Add manifest tool settings.
901   if (targetBuilds) {
902     const char* manifestTool = "VCManifestTool";
903     if (this->FortranProject) {
904       manifestTool = "VFManifestTool";
905     }
906     /* clang-format off */
907     fout <<
908       "\t\t\t<Tool\n"
909       "\t\t\t\tName=\"" << manifestTool << "\"";
910     /* clang-format on */
911
912     std::vector<cmSourceFile const*> manifest_srcs;
913     target->GetManifests(manifest_srcs, configName);
914     if (!manifest_srcs.empty()) {
915       fout << "\n\t\t\t\tAdditionalManifestFiles=\"";
916       for (cmSourceFile const* manifest : manifest_srcs) {
917         std::string m = manifest->GetFullPath();
918         fout << this->ConvertToXMLOutputPath(m) << ";";
919       }
920       fout << "\"";
921     }
922
923     // Check if we need the FAT32 workaround.
924     // Check the filesystem type where the target will be written.
925     if (cmLVS7G_IsFAT(target->GetDirectory(configName).c_str())) {
926       // Add a flag telling the manifest tool to use a workaround
927       // for FAT32 file systems, which can cause an empty manifest
928       // to be embedded into the resulting executable.  See CMake
929       // bug #2617.
930       fout << "\n\t\t\t\tUseFAT32Workaround=\"true\"";
931     }
932     fout << "/>\n";
933   }
934
935   this->OutputTargetRules(fout, configName, target, libName);
936   this->OutputBuildTool(fout, configName, target, targetOptions);
937   this->OutputDeploymentDebuggerTool(fout, configName, target);
938   fout << "\t\t</Configuration>\n";
939 }
940
941 std::string cmLocalVisualStudio7Generator::GetBuildTypeLinkerFlags(
942   std::string rootLinkerFlags, const std::string& configName)
943 {
944   std::string configTypeUpper = cmSystemTools::UpperCase(configName);
945   std::string extraLinkOptionsBuildTypeDef =
946     rootLinkerFlags + "_" + configTypeUpper;
947
948   const std::string& extraLinkOptionsBuildType =
949     this->Makefile->GetRequiredDefinition(extraLinkOptionsBuildTypeDef);
950
951   return extraLinkOptionsBuildType;
952 }
953
954 void cmLocalVisualStudio7Generator::OutputBuildTool(
955   std::ostream& fout, const std::string& configName, cmGeneratorTarget* target,
956   const Options& targetOptions)
957 {
958   cmGlobalVisualStudio7Generator* gg =
959     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
960   std::string temp;
961   std::string extraLinkOptions;
962   if (target->GetType() == cmStateEnums::EXECUTABLE) {
963     extraLinkOptions =
964       this->Makefile->GetRequiredDefinition("CMAKE_EXE_LINKER_FLAGS") + " " +
965       GetBuildTypeLinkerFlags("CMAKE_EXE_LINKER_FLAGS", configName);
966   }
967   if (target->GetType() == cmStateEnums::SHARED_LIBRARY) {
968     extraLinkOptions =
969       this->Makefile->GetRequiredDefinition("CMAKE_SHARED_LINKER_FLAGS") +
970       " " + GetBuildTypeLinkerFlags("CMAKE_SHARED_LINKER_FLAGS", configName);
971   }
972   if (target->GetType() == cmStateEnums::MODULE_LIBRARY) {
973     extraLinkOptions =
974       this->Makefile->GetRequiredDefinition("CMAKE_MODULE_LINKER_FLAGS") +
975       " " + GetBuildTypeLinkerFlags("CMAKE_MODULE_LINKER_FLAGS", configName);
976   }
977
978   cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
979   if (targetLinkFlags) {
980     extraLinkOptions += " ";
981     extraLinkOptions += *targetLinkFlags;
982   }
983   std::string configTypeUpper = cmSystemTools::UpperCase(configName);
984   std::string linkFlagsConfig = cmStrCat("LINK_FLAGS_", configTypeUpper);
985   targetLinkFlags = target->GetProperty(linkFlagsConfig);
986   if (targetLinkFlags) {
987     extraLinkOptions += " ";
988     extraLinkOptions += *targetLinkFlags;
989   }
990
991   std::vector<std::string> opts;
992   target->GetLinkOptions(opts, configName,
993                          target->GetLinkerLanguage(configName));
994   // LINK_OPTIONS are escaped.
995   this->AppendCompileOptions(extraLinkOptions, opts);
996
997   Options linkOptions(this, Options::Linker);
998   if (this->FortranProject) {
999     linkOptions.AddTable(cmLocalVisualStudio7GeneratorFortranLinkFlagTable);
1000   }
1001   linkOptions.AddTable(cmLocalVisualStudio7GeneratorLinkFlagTable);
1002
1003   linkOptions.Parse(extraLinkOptions);
1004   cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
1005     target->GetModuleDefinitionInfo(configName);
1006   if (mdi && !mdi->DefFile.empty()) {
1007     std::string defFile =
1008       this->ConvertToOutputFormat(mdi->DefFile, cmOutputConverter::SHELL);
1009     linkOptions.AddFlag("ModuleDefinitionFile", defFile);
1010   }
1011
1012   switch (target->GetType()) {
1013     case cmStateEnums::UNKNOWN_LIBRARY:
1014       break;
1015     case cmStateEnums::OBJECT_LIBRARY: {
1016       std::string libpath =
1017         cmStrCat(this->GetTargetDirectory(target), '/', configName, '/',
1018                  target->GetName(), ".lib");
1019       const char* tool =
1020         this->FortranProject ? "VFLibrarianTool" : "VCLibrarianTool";
1021       fout << "\t\t\t<Tool\n"
1022            << "\t\t\t\tName=\"" << tool << "\"\n";
1023       fout << "\t\t\t\tOutputFile=\""
1024            << this->ConvertToXMLOutputPathSingle(libpath) << "\"/>\n";
1025       break;
1026     }
1027     case cmStateEnums::STATIC_LIBRARY: {
1028       std::string targetNameFull = target->GetFullName(configName);
1029       std::string libpath =
1030         cmStrCat(target->GetDirectory(configName), '/', targetNameFull);
1031       const char* tool = "VCLibrarianTool";
1032       if (this->FortranProject) {
1033         tool = "VFLibrarianTool";
1034       }
1035       fout << "\t\t\t<Tool\n"
1036            << "\t\t\t\tName=\"" << tool << "\"\n";
1037
1038       if (this->FortranProject) {
1039         std::ostringstream libdeps;
1040         this->Internal->OutputObjects(libdeps, target, configName);
1041         if (!libdeps.str().empty()) {
1042           fout << "\t\t\t\tAdditionalDependencies=\"" << libdeps.str()
1043                << "\"\n";
1044         }
1045       }
1046       std::string libflags;
1047       this->GetStaticLibraryFlags(
1048         libflags, configName, target->GetLinkerLanguage(configName), target);
1049       if (!libflags.empty()) {
1050         fout << "\t\t\t\tAdditionalOptions=\"" << this->EscapeForXML(libflags)
1051              << "\"\n";
1052       }
1053       fout << "\t\t\t\tOutputFile=\""
1054            << this->ConvertToXMLOutputPathSingle(libpath) << "\"/>\n";
1055       break;
1056     }
1057     case cmStateEnums::SHARED_LIBRARY:
1058     case cmStateEnums::MODULE_LIBRARY: {
1059       cmGeneratorTarget::Names targetNames =
1060         target->GetLibraryNames(configName);
1061
1062       // Compute the link library and directory information.
1063       cmComputeLinkInformation* pcli = target->GetLinkInformation(configName);
1064       if (!pcli) {
1065         return;
1066       }
1067       cmComputeLinkInformation& cli = *pcli;
1068       std::string linkLanguage = cli.GetLinkLanguage();
1069
1070       // Compute the variable name to lookup standard libraries for this
1071       // language.
1072       std::string standardLibsVar =
1073         cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
1074       const char* tool = "VCLinkerTool";
1075       if (this->FortranProject) {
1076         tool = "VFLinkerTool";
1077       }
1078       fout << "\t\t\t<Tool\n"
1079            << "\t\t\t\tName=\"" << tool << "\"\n";
1080       if (!gg->NeedLinkLibraryDependencies(target)) {
1081         fout << "\t\t\t\tLinkLibraryDependencies=\"false\"\n";
1082       }
1083       // Use the NOINHERIT macro to avoid getting VS project default
1084       // libraries which may be set by the user to something bad.
1085       fout << "\t\t\t\tAdditionalDependencies=\"$(NOINHERIT) "
1086            << this->Makefile->GetSafeDefinition(standardLibsVar);
1087       if (this->FortranProject) {
1088         this->Internal->OutputObjects(fout, target, configName, " ");
1089       }
1090       fout << " ";
1091       this->Internal->OutputLibraries(fout, cli.GetItems());
1092       fout << "\"\n";
1093       temp =
1094         cmStrCat(target->GetDirectory(configName), '/', targetNames.Output);
1095       fout << "\t\t\t\tOutputFile=\""
1096            << this->ConvertToXMLOutputPathSingle(temp) << "\"\n";
1097       this->WriteTargetVersionAttribute(fout, target);
1098       linkOptions.OutputFlagMap(fout, 4);
1099       fout << "\t\t\t\tAdditionalLibraryDirectories=\"";
1100       this->OutputLibraryDirectories(fout, cli.GetDirectories());
1101       fout << "\"\n";
1102       temp =
1103         cmStrCat(target->GetPDBDirectory(configName), '/', targetNames.PDB);
1104       fout << "\t\t\t\tProgramDatabaseFile=\""
1105            << this->ConvertToXMLOutputPathSingle(temp) << "\"\n";
1106       if (targetOptions.IsDebug()) {
1107         fout << "\t\t\t\tGenerateDebugInformation=\"true\"\n";
1108       }
1109       if (this->WindowsCEProject) {
1110         if (this->GetVersion() <
1111             cmGlobalVisualStudioGenerator::VSVersion::VS9) {
1112           fout << "\t\t\t\tSubSystem=\"9\"\n";
1113         } else {
1114           fout << "\t\t\t\tSubSystem=\"8\"\n";
1115         }
1116       }
1117       std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE");
1118       cmValue stackVal = this->Makefile->GetDefinition(stackVar);
1119       if (stackVal) {
1120         fout << "\t\t\t\tStackReserveSize=\"" << *stackVal << "\"\n";
1121       }
1122       if (!targetNames.ImportLibrary.empty()) {
1123         temp = cmStrCat(target->GetDirectory(
1124                           configName, cmStateEnums::ImportLibraryArtifact),
1125                         '/', targetNames.ImportLibrary);
1126         fout << "\t\t\t\tImportLibrary=\""
1127              << this->ConvertToXMLOutputPathSingle(temp) << "\"";
1128       }
1129       if (this->FortranProject) {
1130         fout << "\n\t\t\t\tLinkDLL=\"true\"";
1131       }
1132       fout << "/>\n";
1133     } break;
1134     case cmStateEnums::EXECUTABLE: {
1135       cmGeneratorTarget::Names targetNames =
1136         target->GetExecutableNames(configName);
1137
1138       // Compute the link library and directory information.
1139       cmComputeLinkInformation* pcli = target->GetLinkInformation(configName);
1140       if (!pcli) {
1141         return;
1142       }
1143       cmComputeLinkInformation& cli = *pcli;
1144       std::string linkLanguage = cli.GetLinkLanguage();
1145
1146       bool isWin32Executable = target->IsWin32Executable(configName);
1147
1148       // Compute the variable name to lookup standard libraries for this
1149       // language.
1150       std::string standardLibsVar =
1151         cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES");
1152       const char* tool = "VCLinkerTool";
1153       if (this->FortranProject) {
1154         tool = "VFLinkerTool";
1155       }
1156       fout << "\t\t\t<Tool\n"
1157            << "\t\t\t\tName=\"" << tool << "\"\n";
1158       if (!gg->NeedLinkLibraryDependencies(target)) {
1159         fout << "\t\t\t\tLinkLibraryDependencies=\"false\"\n";
1160       }
1161       // Use the NOINHERIT macro to avoid getting VS project default
1162       // libraries which may be set by the user to something bad.
1163       fout << "\t\t\t\tAdditionalDependencies=\"$(NOINHERIT) "
1164            << this->Makefile->GetSafeDefinition(standardLibsVar);
1165       if (this->FortranProject) {
1166         this->Internal->OutputObjects(fout, target, configName, " ");
1167       }
1168       fout << " ";
1169       this->Internal->OutputLibraries(fout, cli.GetItems());
1170       fout << "\"\n";
1171       temp =
1172         cmStrCat(target->GetDirectory(configName), '/', targetNames.Output);
1173       fout << "\t\t\t\tOutputFile=\""
1174            << this->ConvertToXMLOutputPathSingle(temp) << "\"\n";
1175       this->WriteTargetVersionAttribute(fout, target);
1176       linkOptions.OutputFlagMap(fout, 4);
1177       fout << "\t\t\t\tAdditionalLibraryDirectories=\"";
1178       this->OutputLibraryDirectories(fout, cli.GetDirectories());
1179       fout << "\"\n";
1180       std::string path = this->ConvertToXMLOutputPathSingle(
1181         target->GetPDBDirectory(configName));
1182       fout << "\t\t\t\tProgramDatabaseFile=\"" << path << "/"
1183            << targetNames.PDB << "\"\n";
1184       if (targetOptions.IsDebug()) {
1185         fout << "\t\t\t\tGenerateDebugInformation=\"true\"\n";
1186       }
1187       if (this->WindowsCEProject) {
1188         if (this->GetVersion() <
1189             cmGlobalVisualStudioGenerator::VSVersion::VS9) {
1190           fout << "\t\t\t\tSubSystem=\"9\"\n";
1191         } else {
1192           fout << "\t\t\t\tSubSystem=\"8\"\n";
1193         }
1194
1195         if (!linkOptions.GetFlag("EntryPointSymbol")) {
1196           const char* entryPointSymbol = targetOptions.UsingUnicode()
1197             ? (isWin32Executable ? "wWinMainCRTStartup" : "mainWCRTStartup")
1198             : (isWin32Executable ? "WinMainCRTStartup" : "mainACRTStartup");
1199           fout << "\t\t\t\tEntryPointSymbol=\"" << entryPointSymbol << "\"\n";
1200         }
1201       } else if (this->FortranProject) {
1202         fout << "\t\t\t\tSubSystem=\""
1203              << (isWin32Executable ? "subSystemWindows" : "subSystemConsole")
1204              << "\"\n";
1205       } else {
1206         fout << "\t\t\t\tSubSystem=\"" << (isWin32Executable ? "2" : "1")
1207              << "\"\n";
1208       }
1209       std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE");
1210       cmValue stackVal = this->Makefile->GetDefinition(stackVar);
1211       if (stackVal) {
1212         fout << "\t\t\t\tStackReserveSize=\"" << *stackVal << "\"";
1213       }
1214       temp = cmStrCat(
1215         target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact),
1216         '/', targetNames.ImportLibrary);
1217       fout << "\t\t\t\tImportLibrary=\""
1218            << this->ConvertToXMLOutputPathSingle(temp) << "\"/>\n";
1219       break;
1220     }
1221     case cmStateEnums::UTILITY:
1222     case cmStateEnums::GLOBAL_TARGET:
1223     case cmStateEnums::INTERFACE_LIBRARY:
1224       break;
1225   }
1226 }
1227
1228 static std::string cmLocalVisualStudio7GeneratorEscapeForXML(
1229   const std::string& s)
1230 {
1231   std::string ret = s;
1232   cmSystemTools::ReplaceString(ret, "&", "&amp;");
1233   cmSystemTools::ReplaceString(ret, "\"", "&quot;");
1234   cmSystemTools::ReplaceString(ret, "<", "&lt;");
1235   cmSystemTools::ReplaceString(ret, ">", "&gt;");
1236   cmSystemTools::ReplaceString(ret, "\n", "&#x0D;&#x0A;");
1237   return ret;
1238 }
1239
1240 static std::string GetEscapedPropertyIfValueNotNULL(const char* propertyValue)
1241 {
1242   return propertyValue == nullptr
1243     ? std::string()
1244     : cmLocalVisualStudio7GeneratorEscapeForXML(propertyValue);
1245 }
1246
1247 void cmLocalVisualStudio7Generator::OutputDeploymentDebuggerTool(
1248   std::ostream& fout, std::string const& config, cmGeneratorTarget* target)
1249 {
1250   if (this->WindowsCEProject) {
1251     cmValue dir = target->GetProperty("DEPLOYMENT_REMOTE_DIRECTORY");
1252     cmValue additionalFiles =
1253       target->GetProperty("DEPLOYMENT_ADDITIONAL_FILES");
1254
1255     if (!dir && !additionalFiles) {
1256       return;
1257     }
1258
1259     fout << "\t\t\t<DeploymentTool\n"
1260             "\t\t\t\tForceDirty=\"-1\"\n"
1261             "\t\t\t\tRemoteDirectory=\""
1262          << GetEscapedPropertyIfValueNotNULL(dir->c_str())
1263          << "\"\n"
1264             "\t\t\t\tRegisterOutput=\"0\"\n"
1265             "\t\t\t\tAdditionalFiles=\""
1266          << GetEscapedPropertyIfValueNotNULL(additionalFiles->c_str())
1267          << "\"/>\n";
1268
1269     if (dir) {
1270       std::string const exe = *dir + "\\" + target->GetFullName(config);
1271
1272       fout << "\t\t\t<DebuggerTool\n"
1273               "\t\t\t\tRemoteExecutable=\""
1274            << this->EscapeForXML(exe)
1275            << "\"\n"
1276               "\t\t\t\tArguments=\"\"\n"
1277               "\t\t\t/>\n";
1278     }
1279   }
1280 }
1281
1282 void cmLocalVisualStudio7Generator::WriteTargetVersionAttribute(
1283   std::ostream& fout, cmGeneratorTarget* gt)
1284 {
1285   int major;
1286   int minor;
1287   gt->GetTargetVersion(major, minor);
1288   fout << "\t\t\t\tVersion=\"" << major << "." << minor << "\"\n";
1289 }
1290
1291 void cmLocalVisualStudio7GeneratorInternals::OutputLibraries(
1292   std::ostream& fout, ItemVector const& libs)
1293 {
1294   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
1295   for (auto const& lib : libs) {
1296     if (lib.IsPath == cmComputeLinkInformation::ItemIsPath::Yes) {
1297       std::string rel = lg->MaybeRelativeToCurBinDir(lib.Value.Value);
1298       rel = lg->ConvertToXMLOutputPath(rel);
1299       fout << (lib.HasFeature() ? lib.GetFormattedItem(rel).Value : rel)
1300            << " ";
1301     } else if (!lib.Target ||
1302                lib.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
1303       fout << lib.Value.Value << " ";
1304     }
1305   }
1306 }
1307
1308 void cmLocalVisualStudio7GeneratorInternals::OutputObjects(
1309   std::ostream& fout, cmGeneratorTarget* gt, std::string const& configName,
1310   const char* isep)
1311 {
1312   // VS < 8 does not support per-config source locations so we
1313   // list object library content on the link line instead.
1314   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
1315
1316   std::vector<cmSourceFile const*> objs;
1317   gt->GetExternalObjects(objs, configName);
1318
1319   const char* sep = isep ? isep : "";
1320   for (cmSourceFile const* obj : objs) {
1321     if (!obj->GetObjectLibrary().empty()) {
1322       std::string const& objFile = obj->GetFullPath();
1323       std::string rel = lg->MaybeRelativeToCurBinDir(objFile);
1324       fout << sep << lg->ConvertToXMLOutputPath(rel);
1325       sep = " ";
1326     }
1327   }
1328 }
1329
1330 void cmLocalVisualStudio7Generator::OutputLibraryDirectories(
1331   std::ostream& fout, std::vector<std::string> const& dirs)
1332 {
1333   const char* comma = "";
1334   for (std::string dir : dirs) {
1335     // Remove any trailing slash and skip empty paths.
1336     if (dir.back() == '/') {
1337       dir = dir.substr(0, dir.size() - 1);
1338     }
1339     if (dir.empty()) {
1340       continue;
1341     }
1342
1343     // Switch to a relative path specification if it is shorter.
1344     if (cmSystemTools::FileIsFullPath(dir)) {
1345       std::string rel = this->MaybeRelativeToCurBinDir(dir);
1346       if (rel.size() < dir.size()) {
1347         dir = rel;
1348       }
1349     }
1350
1351     // First search a configuration-specific subdirectory and then the
1352     // original directory.
1353     fout << comma
1354          << this->ConvertToXMLOutputPath(dir + "/$(ConfigurationName)") << ","
1355          << this->ConvertToXMLOutputPath(dir);
1356     comma = ",";
1357   }
1358 }
1359
1360 void cmLocalVisualStudio7Generator::WriteVCProjFile(std::ostream& fout,
1361                                                     const std::string& libName,
1362                                                     cmGeneratorTarget* target)
1363 {
1364   std::vector<std::string> configs =
1365     this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
1366
1367   // We may be modifying the source groups temporarily, so make a copy.
1368   std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
1369
1370   AllConfigSources sources;
1371   sources.Sources = target->GetAllConfigSources();
1372
1373   // Add CMakeLists.txt file with rule to re-run CMake for user convenience.
1374   if (target->GetType() != cmStateEnums::GLOBAL_TARGET &&
1375       target->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
1376     if (cmSourceFile* sf = this->CreateVCProjBuildRule()) {
1377       cmGeneratorTarget::AllConfigSource acs;
1378       acs.Source = sf;
1379       acs.Kind = cmGeneratorTarget::SourceKindCustomCommand;
1380       for (size_t ci = 0; ci < configs.size(); ++ci) {
1381         acs.Configs.push_back(ci);
1382       }
1383       bool haveCMakeLists = false;
1384       for (cmGeneratorTarget::AllConfigSource& si : sources.Sources) {
1385         if (si.Source == sf) {
1386           haveCMakeLists = true;
1387           // Replace the explicit source reference with our generated one.
1388           si = acs;
1389           break;
1390         }
1391       }
1392       if (!haveCMakeLists) {
1393         sources.Sources.emplace_back(std::move(acs));
1394       }
1395     }
1396   }
1397
1398   for (size_t si = 0; si < sources.Sources.size(); ++si) {
1399     cmSourceFile const* sf = sources.Sources[si].Source;
1400     sources.Index[sf] = si;
1401     if (!sf->GetObjectLibrary().empty()) {
1402       if (this->FortranProject) {
1403         // Intel Fortran does not support per-config source locations
1404         // so we list object library content on the link line instead.
1405         // See OutputObjects.
1406         continue;
1407       }
1408     }
1409     // Add the file to the list of sources.
1410     std::string const source = sf->GetFullPath();
1411     cmSourceGroup* sourceGroup =
1412       this->Makefile->FindSourceGroup(source, sourceGroups);
1413     sourceGroup->AssignSource(sf);
1414   }
1415
1416   // open the project
1417   this->WriteProjectStart(fout, libName, target, sourceGroups);
1418   // write the configuration information
1419   this->WriteConfigurations(fout, configs, libName, target);
1420
1421   fout << "\t<Files>\n";
1422
1423   // Loop through every source group.
1424   for (unsigned int i = 0; i < sourceGroups.size(); ++i) {
1425     cmSourceGroup sg = sourceGroups[i];
1426     this->WriteGroup(&sg, target, fout, libName, configs, sources);
1427   }
1428
1429   fout << "\t</Files>\n";
1430
1431   // Write the VCProj file's footer.
1432   this->WriteVCProjFooter(fout, target);
1433 }
1434
1435 struct cmLVS7GFileConfig
1436 {
1437   std::string ObjectName;
1438   std::string CompileFlags;
1439   std::string CompileDefs;
1440   std::string CompileDefsConfig;
1441   std::string AdditionalDeps;
1442   std::string IncludeDirs;
1443   bool ExcludedFromBuild;
1444 };
1445
1446 class cmLocalVisualStudio7GeneratorFCInfo
1447 {
1448 public:
1449   cmLocalVisualStudio7GeneratorFCInfo(
1450     cmLocalVisualStudio7Generator* lg, cmGeneratorTarget* target,
1451     cmGeneratorTarget::AllConfigSource const& acs,
1452     std::vector<std::string> const& configs);
1453   std::map<std::string, cmLVS7GFileConfig> FileConfigMap;
1454 };
1455
1456 cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo(
1457   cmLocalVisualStudio7Generator* lg, cmGeneratorTarget* gt,
1458   cmGeneratorTarget::AllConfigSource const& acs,
1459   std::vector<std::string> const& configs)
1460 {
1461   cmSourceFile const& sf = *acs.Source;
1462   std::string objectName;
1463   if (gt->HasExplicitObjectName(&sf)) {
1464     objectName = gt->GetObjectName(&sf);
1465   }
1466
1467   // Compute per-source, per-config information.
1468   size_t ci = 0;
1469   for (std::string const& config : configs) {
1470     std::string configUpper = cmSystemTools::UpperCase(config);
1471     cmLVS7GFileConfig fc;
1472
1473     std::string lang =
1474       lg->GlobalGenerator->GetLanguageFromExtension(sf.GetExtension().c_str());
1475     const std::string& sourceLang = lg->GetSourceFileLanguage(sf);
1476     bool needForceLang = false;
1477     // source file does not match its extension language
1478     if (lang != sourceLang) {
1479       needForceLang = true;
1480       lang = sourceLang;
1481     }
1482
1483     cmGeneratorExpressionInterpreter genexInterpreter(lg, config, gt, lang);
1484
1485     bool needfc = false;
1486     if (!objectName.empty()) {
1487       fc.ObjectName = objectName;
1488       needfc = true;
1489     }
1490     const std::string COMPILE_FLAGS("COMPILE_FLAGS");
1491     if (cmValue cflags = sf.GetProperty(COMPILE_FLAGS)) {
1492       fc.CompileFlags = genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS);
1493       needfc = true;
1494     }
1495     const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
1496     if (cmValue coptions = sf.GetProperty(COMPILE_OPTIONS)) {
1497       lg->AppendCompileOptions(
1498         fc.CompileFlags,
1499         genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
1500       needfc = true;
1501     }
1502     // Add precompile headers compile options.
1503     const std::string pchSource = gt->GetPchSource(config, lang);
1504     if (!pchSource.empty() && !sf.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
1505       std::string pchOptions;
1506       if (sf.GetFullPath() == pchSource) {
1507         pchOptions = gt->GetPchCreateCompileOptions(config, lang);
1508       } else {
1509         pchOptions = gt->GetPchUseCompileOptions(config, lang);
1510       }
1511
1512       lg->AppendCompileOptions(
1513         fc.CompileFlags,
1514         genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
1515       needfc = true;
1516     }
1517
1518     if (lg->FortranProject) {
1519       switch (cmOutputConverter::GetFortranPreprocess(
1520         sf.GetSafeProperty("Fortran_PREPROCESS"))) {
1521         case cmOutputConverter::FortranPreprocess::Needed:
1522           fc.CompileFlags = cmStrCat("-fpp ", fc.CompileFlags);
1523           needfc = true;
1524           break;
1525         case cmOutputConverter::FortranPreprocess::NotNeeded:
1526           fc.CompileFlags = cmStrCat("-nofpp ", fc.CompileFlags);
1527           needfc = true;
1528           break;
1529         default:
1530           break;
1531       }
1532
1533       switch (cmOutputConverter::GetFortranFormat(
1534         sf.GetSafeProperty("Fortran_FORMAT"))) {
1535         case cmOutputConverter::FortranFormatFixed:
1536           fc.CompileFlags = "-fixed " + fc.CompileFlags;
1537           needfc = true;
1538           break;
1539         case cmOutputConverter::FortranFormatFree:
1540           fc.CompileFlags = "-free " + fc.CompileFlags;
1541           needfc = true;
1542           break;
1543         default:
1544           break;
1545       }
1546     }
1547     const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
1548     if (cmValue cdefs = sf.GetProperty(COMPILE_DEFINITIONS)) {
1549       fc.CompileDefs = genexInterpreter.Evaluate(*cdefs, COMPILE_DEFINITIONS);
1550       needfc = true;
1551     }
1552     std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
1553     if (cmValue ccdefs = sf.GetProperty(defPropName)) {
1554       fc.CompileDefsConfig =
1555         genexInterpreter.Evaluate(*ccdefs, COMPILE_DEFINITIONS);
1556       needfc = true;
1557     }
1558
1559     const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
1560     if (cmValue cincs = sf.GetProperty(INCLUDE_DIRECTORIES)) {
1561       fc.IncludeDirs = genexInterpreter.Evaluate(*cincs, INCLUDE_DIRECTORIES);
1562       needfc = true;
1563     }
1564
1565     // Check for extra object-file dependencies.
1566     if (cmValue deps = sf.GetProperty("OBJECT_DEPENDS")) {
1567       std::vector<std::string> depends = cmExpandedList(*deps);
1568       const char* sep = "";
1569       for (const std::string& d : depends) {
1570         fc.AdditionalDeps += sep;
1571         fc.AdditionalDeps += lg->ConvertToXMLOutputPath(d);
1572         sep = ";";
1573         needfc = true;
1574       }
1575     }
1576
1577     const std::string& linkLanguage = gt->GetLinkerLanguage(config);
1578     // If HEADER_FILE_ONLY is set, we must suppress this generation in
1579     // the project file
1580     fc.ExcludedFromBuild = sf.GetPropertyAsBool("HEADER_FILE_ONLY") ||
1581       !cm::contains(acs.Configs, ci) ||
1582       (gt->GetPropertyAsBool("UNITY_BUILD") &&
1583        sf.GetProperty("UNITY_SOURCE_FILE") &&
1584        !sf.GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION"));
1585     if (fc.ExcludedFromBuild) {
1586       needfc = true;
1587     }
1588
1589     // if the source file does not match the linker language
1590     // then force c or c++
1591     if (needForceLang || (linkLanguage != lang)) {
1592       if (lang == "CXX") {
1593         // force a C++ file type
1594         fc.CompileFlags += " /TP ";
1595         needfc = true;
1596       } else if (lang == "C") {
1597         // force to c
1598         fc.CompileFlags += " /TC ";
1599         needfc = true;
1600       }
1601     }
1602
1603     if (needfc) {
1604       this->FileConfigMap[config] = fc;
1605     }
1606     ++ci;
1607   }
1608 }
1609
1610 std::string cmLocalVisualStudio7Generator::ComputeLongestObjectDirectory(
1611   cmGeneratorTarget const* target) const
1612 {
1613   std::vector<std::string> configs =
1614     target->Target->GetMakefile()->GetGeneratorConfigs(
1615       cmMakefile::ExcludeEmptyConfig);
1616
1617   // Compute the maximum length configuration name.
1618   std::string config_max;
1619   for (std::vector<std::string>::iterator i = configs.begin();
1620        i != configs.end(); ++i) {
1621     if (i->size() > config_max.size()) {
1622       config_max = *i;
1623     }
1624   }
1625
1626   // Compute the maximum length full path to the intermediate
1627   // files directory for any configuration.  This is used to construct
1628   // object file names that do not produce paths that are too long.
1629   std::string dir_max =
1630     cmStrCat(this->GetCurrentBinaryDirectory(), '/',
1631              this->GetTargetDirectory(target), '/', config_max, '/');
1632   return dir_max;
1633 }
1634
1635 bool cmLocalVisualStudio7Generator::WriteGroup(
1636   const cmSourceGroup* sg, cmGeneratorTarget* target, std::ostream& fout,
1637   const std::string& libName, std::vector<std::string> const& configs,
1638   AllConfigSources const& sources)
1639 {
1640   cmGlobalVisualStudio7Generator* gg =
1641     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
1642   const std::vector<const cmSourceFile*>& sourceFiles = sg->GetSourceFiles();
1643   std::vector<cmSourceGroup> const& children = sg->GetGroupChildren();
1644
1645   // Write the children to temporary output.
1646   bool hasChildrenWithSources = false;
1647   std::ostringstream tmpOut;
1648   for (unsigned int i = 0; i < children.size(); ++i) {
1649     if (this->WriteGroup(&children[i], target, tmpOut, libName, configs,
1650                          sources)) {
1651       hasChildrenWithSources = true;
1652     }
1653   }
1654
1655   // If the group is empty, don't write it at all.
1656   if (sourceFiles.empty() && !hasChildrenWithSources) {
1657     return false;
1658   }
1659
1660   // If the group has a name, write the header.
1661   std::string const& name = sg->GetName();
1662   if (!name.empty()) {
1663     this->WriteVCProjBeginGroup(fout, name.c_str(), "");
1664   }
1665
1666   auto& sourcesVisited = this->GetSourcesVisited(target);
1667
1668   // Loop through each source in the source group.
1669   for (const cmSourceFile* sf : sourceFiles) {
1670     std::string source = sf->GetFullPath();
1671
1672     if (source != libName || target->GetType() == cmStateEnums::UTILITY ||
1673         target->GetType() == cmStateEnums::GLOBAL_TARGET ||
1674         target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
1675       // Look up the source kind and configs.
1676       std::map<cmSourceFile const*, size_t>::const_iterator map_it =
1677         sources.Index.find(sf);
1678       // The map entry must exist because we populated it earlier.
1679       assert(map_it != sources.Index.end());
1680       cmGeneratorTarget::AllConfigSource const& acs =
1681         sources.Sources[map_it->second];
1682
1683       FCInfo fcinfo(this, target, acs, configs);
1684
1685       fout << "\t\t\t<File\n";
1686       std::string d = this->ConvertToXMLOutputPathSingle(source);
1687       // Tell MS-Dev what the source is.  If the compiler knows how to
1688       // build it, then it will.
1689       fout << "\t\t\t\tRelativePath=\"" << d << "\">\n";
1690       if (cmCustomCommand const* command = sf->GetCustomCommand()) {
1691         if (sourcesVisited.insert(sf).second) {
1692           this->WriteCustomRule(fout, configs, source.c_str(), *command,
1693                                 fcinfo);
1694         }
1695       } else if (!fcinfo.FileConfigMap.empty()) {
1696         const char* aCompilerTool = "VCCLCompilerTool";
1697         std::string ppLang = "CXX";
1698         if (this->FortranProject) {
1699           aCompilerTool = "VFFortranCompilerTool";
1700         }
1701         std::string const& lang = sf->GetLanguage();
1702         std::string ext = sf->GetExtension();
1703         ext = cmSystemTools::LowerCase(ext);
1704         if (ext == "idl") {
1705           aCompilerTool = "VCMIDLTool";
1706           if (this->FortranProject) {
1707             aCompilerTool = "VFMIDLTool";
1708           }
1709         }
1710         if (ext == "rc") {
1711           aCompilerTool = "VCResourceCompilerTool";
1712           ppLang = "RC";
1713           if (this->FortranProject) {
1714             aCompilerTool = "VFResourceCompilerTool";
1715           }
1716         }
1717         if (ext == "def") {
1718           aCompilerTool = "VCCustomBuildTool";
1719           if (this->FortranProject) {
1720             aCompilerTool = "VFCustomBuildTool";
1721           }
1722         }
1723         if (gg->IsMasmEnabled() && !this->FortranProject &&
1724             lang == "ASM_MASM") {
1725           aCompilerTool = "MASM";
1726         }
1727         if (acs.Kind == cmGeneratorTarget::SourceKindExternalObject) {
1728           aCompilerTool = "VCCustomBuildTool";
1729         }
1730         for (auto const& fci : fcinfo.FileConfigMap) {
1731           cmLVS7GFileConfig const& fc = fci.second;
1732           fout << "\t\t\t\t<FileConfiguration\n"
1733                << "\t\t\t\t\tName=\"" << fci.first << "|"
1734                << gg->GetPlatformName() << "\"";
1735           if (fc.ExcludedFromBuild) {
1736             fout << " ExcludedFromBuild=\"true\"";
1737           }
1738           fout << ">\n";
1739           fout << "\t\t\t\t\t<Tool\n"
1740                << "\t\t\t\t\tName=\"" << aCompilerTool << "\"\n";
1741           if (!fc.CompileFlags.empty() || !fc.CompileDefs.empty() ||
1742               !fc.CompileDefsConfig.empty() || !fc.IncludeDirs.empty()) {
1743             Options::Tool tool = Options::Compiler;
1744             cmVS7FlagTable const* table =
1745               cmLocalVisualStudio7GeneratorFlagTable;
1746             if (this->FortranProject) {
1747               tool = Options::FortranCompiler;
1748               table = cmLocalVisualStudio7GeneratorFortranFlagTable;
1749             }
1750             Options fileOptions(this, tool, table, gg->ExtraFlagTable);
1751             fileOptions.Parse(fc.CompileFlags);
1752             fileOptions.AddDefines(fc.CompileDefs);
1753             fileOptions.AddDefines(fc.CompileDefsConfig);
1754             // validate source level include directories
1755             std::vector<std::string> includes;
1756             this->AppendIncludeDirectories(includes, fc.IncludeDirs, *sf);
1757             fileOptions.AddIncludes(includes);
1758             fileOptions.OutputFlagMap(fout, 5);
1759             fileOptions.OutputAdditionalIncludeDirectories(
1760               fout, 5,
1761               ppLang == "CXX" && this->FortranProject ? "Fortran" : ppLang);
1762             fileOptions.OutputPreprocessorDefinitions(fout, 5, ppLang);
1763           }
1764           if (!fc.AdditionalDeps.empty()) {
1765             fout << "\t\t\t\t\tAdditionalDependencies=\"" << fc.AdditionalDeps
1766                  << "\"\n";
1767           }
1768           if (!fc.ObjectName.empty()) {
1769             fout << "\t\t\t\t\tObjectFile=\"$(IntDir)/" << fc.ObjectName
1770                  << "\"\n";
1771           }
1772           fout << "\t\t\t\t\t/>\n"
1773                << "\t\t\t\t</FileConfiguration>\n";
1774         }
1775       }
1776       fout << "\t\t\t</File>\n";
1777     }
1778   }
1779
1780   // If the group has children with source files, write the children.
1781   if (hasChildrenWithSources) {
1782     fout << tmpOut.str();
1783   }
1784
1785   // If the group has a name, write the footer.
1786   if (!name.empty()) {
1787     this->WriteVCProjEndGroup(fout);
1788   }
1789
1790   return true;
1791 }
1792
1793 void cmLocalVisualStudio7Generator::WriteCustomRule(
1794   std::ostream& fout, std::vector<std::string> const& configs,
1795   const char* source, const cmCustomCommand& command, FCInfo& fcinfo)
1796 {
1797   cmGlobalVisualStudio7Generator* gg =
1798     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
1799
1800   // Write the rule for each configuration.
1801   const char* compileTool = "VCCLCompilerTool";
1802   if (this->FortranProject) {
1803     compileTool = "VFCLCompilerTool";
1804   }
1805   const char* customTool = "VCCustomBuildTool";
1806   if (this->FortranProject) {
1807     customTool = "VFCustomBuildTool";
1808   }
1809   for (std::string const& config : configs) {
1810     cmCustomCommandGenerator ccg(command, config, this);
1811     cmLVS7GFileConfig const& fc = fcinfo.FileConfigMap[config];
1812     fout << "\t\t\t\t<FileConfiguration\n";
1813     fout << "\t\t\t\t\tName=\"" << config << "|" << gg->GetPlatformName()
1814          << "\">\n";
1815     if (!fc.CompileFlags.empty()) {
1816       fout << "\t\t\t\t\t<Tool\n"
1817            << "\t\t\t\t\tName=\"" << compileTool << "\"\n"
1818            << "\t\t\t\t\tAdditionalOptions=\""
1819            << this->EscapeForXML(fc.CompileFlags) << "\"/>\n";
1820     }
1821
1822     std::string comment = this->ConstructComment(ccg);
1823     std::string script = this->ConstructScript(ccg);
1824     if (this->FortranProject) {
1825       cmSystemTools::ReplaceString(script, "$(Configuration)", config);
1826     }
1827     script += this->FinishConstructScript(VsProjectType::vcxproj);
1828     /* clang-format off */
1829     fout << "\t\t\t\t\t<Tool\n"
1830          << "\t\t\t\t\tName=\"" << customTool << "\"\n"
1831          << "\t\t\t\t\tDescription=\""
1832          << this->EscapeForXML(comment) << "\"\n"
1833          << "\t\t\t\t\tCommandLine=\""
1834          << this->EscapeForXML(script) << "\"\n"
1835          << "\t\t\t\t\tAdditionalDependencies=\"";
1836     /* clang-format on */
1837     if (ccg.GetDepends().empty()) {
1838       // There are no real dependencies.  Produce an artificial one to
1839       // make sure the rule runs reliably.
1840       if (!cmSystemTools::FileExists(source)) {
1841         cmsys::ofstream depout(source);
1842         depout << "Artificial dependency for a custom command.\n";
1843       }
1844       fout << this->ConvertToXMLOutputPath(source);
1845     } else {
1846       // Write out the dependencies for the rule.
1847       for (std::string const& d : ccg.GetDepends()) {
1848         // Get the real name of the dependency in case it is a CMake target.
1849         std::string dep;
1850         if (this->GetRealDependency(d, config, dep)) {
1851           fout << this->ConvertToXMLOutputPath(dep) << ";";
1852         }
1853       }
1854     }
1855     fout << "\"\n";
1856     fout << "\t\t\t\t\tOutputs=\"";
1857     if (ccg.GetOutputs().empty()) {
1858       fout << source << "_force";
1859     } else {
1860       // Write a rule for the output generated by this command.
1861       const char* sep = "";
1862       for (std::string const& output : ccg.GetOutputs()) {
1863         fout << sep << this->ConvertToXMLOutputPathSingle(output);
1864         sep = ";";
1865       }
1866     }
1867     fout << "\"/>\n";
1868     fout << "\t\t\t\t</FileConfiguration>\n";
1869   }
1870 }
1871
1872 void cmLocalVisualStudio7Generator::WriteVCProjBeginGroup(std::ostream& fout,
1873                                                           const char* group,
1874                                                           const char*)
1875 {
1876   /* clang-format off */
1877   fout << "\t\t<Filter\n"
1878        << "\t\t\tName=\"" << group << "\"\n"
1879        << "\t\t\tFilter=\"\">\n";
1880   /* clang-format on */
1881 }
1882
1883 void cmLocalVisualStudio7Generator::WriteVCProjEndGroup(std::ostream& fout)
1884 {
1885   fout << "\t\t</Filter>\n";
1886 }
1887
1888 // look for custom rules on a target and collect them together
1889 void cmLocalVisualStudio7Generator::OutputTargetRules(
1890   std::ostream& fout, const std::string& configName, cmGeneratorTarget* target,
1891   const std::string& /*libName*/)
1892 {
1893   if (target->GetType() > cmStateEnums::GLOBAL_TARGET) {
1894     return;
1895   }
1896   EventWriter event(this, configName, fout);
1897
1898   // Add pre-build event.
1899   const char* tool =
1900     this->FortranProject ? "VFPreBuildEventTool" : "VCPreBuildEventTool";
1901   event.Start(tool);
1902   event.Write(target->GetPreBuildCommands());
1903   event.Finish();
1904
1905   // Add pre-link event.
1906   tool = this->FortranProject ? "VFPreLinkEventTool" : "VCPreLinkEventTool";
1907   event.Start(tool);
1908   bool addedPrelink = false;
1909   cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
1910     target->GetModuleDefinitionInfo(configName);
1911   if (mdi && mdi->DefFileGenerated) {
1912     addedPrelink = true;
1913     std::vector<cmCustomCommand> commands = target->GetPreLinkCommands();
1914     cmGlobalVisualStudioGenerator* gg =
1915       static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
1916     gg->AddSymbolExportCommand(target, commands, configName);
1917     event.Write(commands);
1918   }
1919   if (!addedPrelink) {
1920     event.Write(target->GetPreLinkCommands());
1921   }
1922   std::unique_ptr<cmCustomCommand> pcc(
1923     this->MaybeCreateImplibDir(target, configName, this->FortranProject));
1924   if (pcc.get()) {
1925     event.Write(*pcc);
1926   }
1927   event.Finish();
1928
1929   // Add post-build event.
1930   tool =
1931     this->FortranProject ? "VFPostBuildEventTool" : "VCPostBuildEventTool";
1932   event.Start(tool);
1933   event.Write(target->GetPostBuildCommands());
1934   event.Finish();
1935 }
1936
1937 void cmLocalVisualStudio7Generator::WriteProjectSCC(std::ostream& fout,
1938                                                     cmGeneratorTarget* target)
1939 {
1940   // if we have all the required Source code control tags
1941   // then add that to the project
1942   cmValue vsProjectname = target->GetProperty("VS_SCC_PROJECTNAME");
1943   cmValue vsLocalpath = target->GetProperty("VS_SCC_LOCALPATH");
1944   cmValue vsProvider = target->GetProperty("VS_SCC_PROVIDER");
1945
1946   if (vsProvider && vsLocalpath && vsProjectname) {
1947     /* clang-format off */
1948     fout << "\tSccProjectName=\"" << *vsProjectname << "\"\n"
1949          << "\tSccLocalPath=\"" << *vsLocalpath << "\"\n"
1950          << "\tSccProvider=\"" << *vsProvider << "\"\n";
1951     /* clang-format on */
1952
1953     cmValue vsAuxPath = target->GetProperty("VS_SCC_AUXPATH");
1954     if (vsAuxPath) {
1955       fout << "\tSccAuxPath=\"" << *vsAuxPath << "\"\n";
1956     }
1957   }
1958 }
1959
1960 void cmLocalVisualStudio7Generator::WriteProjectStartFortran(
1961   std::ostream& fout, const std::string& libName, cmGeneratorTarget* target)
1962 {
1963
1964   cmGlobalVisualStudio7Generator* gg =
1965     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
1966   /* clang-format off */
1967   fout << "<?xml version=\"1.0\" encoding = \""
1968        << gg->Encoding() << "\"?>\n"
1969        << "<VisualStudioProject\n"
1970        << "\tProjectCreator=\"Intel Fortran\"\n"
1971        << "\tVersion=\"" << gg->GetIntelProjectVersion() << "\"\n";
1972   /* clang-format on */
1973   cmValue p = target->GetProperty("VS_KEYWORD");
1974   const char* keyword = p ? p->c_str() : "Console Application";
1975   const char* projectType = 0;
1976   switch (target->GetType()) {
1977     case cmStateEnums::OBJECT_LIBRARY:
1978     case cmStateEnums::STATIC_LIBRARY:
1979       projectType = "typeStaticLibrary";
1980       if (keyword) {
1981         keyword = "Static Library";
1982       }
1983       break;
1984     case cmStateEnums::SHARED_LIBRARY:
1985     case cmStateEnums::MODULE_LIBRARY:
1986       projectType = "typeDynamicLibrary";
1987       if (!keyword) {
1988         keyword = "Dll";
1989       }
1990       break;
1991     case cmStateEnums::EXECUTABLE:
1992       if (!keyword) {
1993         keyword = "Console Application";
1994       }
1995       projectType = 0;
1996       break;
1997     case cmStateEnums::UTILITY:
1998     case cmStateEnums::GLOBAL_TARGET:
1999     case cmStateEnums::INTERFACE_LIBRARY:
2000     case cmStateEnums::UNKNOWN_LIBRARY:
2001       break;
2002   }
2003   if (projectType) {
2004     fout << "\tProjectType=\"" << projectType << "\"\n";
2005   }
2006   this->WriteProjectSCC(fout, target);
2007   /* clang-format off */
2008   fout<< "\tKeyword=\"" << keyword << "\">\n"
2009        << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\">\n"
2010        << "\t<Platforms>\n"
2011        << "\t\t<Platform\n\t\t\tName=\"" << gg->GetPlatformName() << "\"/>\n"
2012        << "\t</Platforms>\n";
2013   /* clang-format on */
2014 }
2015
2016 void cmLocalVisualStudio7Generator::WriteProjectStart(
2017   std::ostream& fout, const std::string& libName, cmGeneratorTarget* target,
2018   std::vector<cmSourceGroup>&)
2019 {
2020   if (this->FortranProject) {
2021     this->WriteProjectStartFortran(fout, libName, target);
2022     return;
2023   }
2024
2025   cmGlobalVisualStudio7Generator* gg =
2026     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
2027
2028   /* clang-format off */
2029   fout << "<?xml version=\"1.0\" encoding = \""
2030        << gg->Encoding() << "\"?>\n"
2031        << "<VisualStudioProject\n"
2032        << "\tProjectType=\"Visual C++\"\n";
2033   /* clang-format on */
2034   fout << "\tVersion=\"" << (static_cast<uint16_t>(gg->GetVersion()) / 10)
2035        << ".00\"\n";
2036   cmValue p = target->GetProperty("PROJECT_LABEL");
2037   const std::string projLabel = p ? *p : libName;
2038   p = target->GetProperty("VS_KEYWORD");
2039   const std::string keyword = p ? *p : "Win32Proj";
2040   fout << "\tName=\"" << projLabel << "\"\n";
2041   fout << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\"\n";
2042   this->WriteProjectSCC(fout, target);
2043   if (cmValue targetFrameworkVersion =
2044         target->GetProperty("VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
2045     fout << "\tTargetFrameworkVersion=\"" << *targetFrameworkVersion << "\"\n";
2046   }
2047   /* clang-format off */
2048   fout << "\tKeyword=\"" << keyword << "\">\n"
2049        << "\t<Platforms>\n"
2050        << "\t\t<Platform\n\t\t\tName=\"" << gg->GetPlatformName() << "\"/>\n"
2051        << "\t</Platforms>\n";
2052   /* clang-format on */
2053   if (gg->IsMasmEnabled()) {
2054     /* clang-format off */
2055     fout <<
2056       "\t<ToolFiles>\n"
2057       "\t\t<DefaultToolFile\n"
2058       "\t\t\tFileName=\"masm.rules\"\n"
2059       "\t\t/>\n"
2060       "\t</ToolFiles>\n"
2061       ;
2062     /* clang-format on */
2063   }
2064 }
2065
2066 void cmLocalVisualStudio7Generator::WriteVCProjFooter(
2067   std::ostream& fout, cmGeneratorTarget* target)
2068 {
2069   fout << "\t<Globals>\n";
2070
2071   for (std::string const& key : target->GetPropertyKeys()) {
2072     if (cmHasLiteralPrefix(key, "VS_GLOBAL_")) {
2073       std::string name = key.substr(10);
2074       if (!name.empty()) {
2075         /* clang-format off */
2076         fout << "\t\t<Global\n"
2077              << "\t\t\tName=\"" << name << "\"\n"
2078              << "\t\t\tValue=\"" << target->GetProperty(key) << "\"\n"
2079              << "\t\t/>\n";
2080         /* clang-format on */
2081       }
2082     }
2083   }
2084
2085   fout << "\t</Globals>\n"
2086        << "</VisualStudioProject>\n";
2087 }
2088
2089 std::string cmLocalVisualStudio7Generator::EscapeForXML(const std::string& s)
2090 {
2091   return cmLocalVisualStudio7GeneratorEscapeForXML(s);
2092 }
2093
2094 std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPath(
2095   const std::string& path)
2096 {
2097   std::string ret =
2098     this->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
2099   cmSystemTools::ReplaceString(ret, "&", "&amp;");
2100   cmSystemTools::ReplaceString(ret, "\"", "&quot;");
2101   cmSystemTools::ReplaceString(ret, "<", "&lt;");
2102   cmSystemTools::ReplaceString(ret, ">", "&gt;");
2103   return ret;
2104 }
2105
2106 std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPathSingle(
2107   const std::string& path)
2108 {
2109   std::string ret =
2110     this->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
2111   cmSystemTools::ReplaceString(ret, "\"", "");
2112   cmSystemTools::ReplaceString(ret, "&", "&amp;");
2113   cmSystemTools::ReplaceString(ret, "<", "&lt;");
2114   cmSystemTools::ReplaceString(ret, ">", "&gt;");
2115   return ret;
2116 }
2117
2118 void cmVS7GeneratorOptions::OutputFlag(std::ostream& fout, int indent,
2119                                        const std::string& flag,
2120                                        const std::string& content)
2121 {
2122   fout.fill('\t');
2123   fout.width(indent);
2124   // write an empty string to get the fill level indent to print
2125   fout << "";
2126   fout << flag << "=\"";
2127   fout << cmLocalVisualStudio7GeneratorEscapeForXML(content);
2128   fout << "\"\n";
2129 }
2130
2131 // This class is used to parse an existing vs 7 project
2132 // and extract the GUID
2133 class cmVS7XMLParser : public cmXMLParser
2134 {
2135 public:
2136   virtual void EndElement(const std::string& /* name */) {}
2137   virtual void StartElement(const std::string& name, const char** atts)
2138   {
2139     // once the GUID is found do nothing
2140     if (!this->GUID.empty()) {
2141       return;
2142     }
2143     int i = 0;
2144     if ("VisualStudioProject" == name) {
2145       while (atts[i]) {
2146         if (strcmp(atts[i], "ProjectGUID") == 0) {
2147           if (atts[i + 1]) {
2148             this->GUID = atts[i + 1];
2149             if (this->GUID[0] == '{') {
2150               // remove surrounding curly brackets
2151               this->GUID = this->GUID.substr(1, this->GUID.size() - 2);
2152             }
2153           } else {
2154             this->GUID.clear();
2155           }
2156           return;
2157         }
2158         ++i;
2159       }
2160     }
2161   }
2162   int InitializeParser()
2163   {
2164     int ret = cmXMLParser::InitializeParser();
2165     if (ret == 0) {
2166       return ret;
2167     }
2168     // visual studio projects have a strange encoding, but it is
2169     // really utf-8
2170     XML_SetEncoding(static_cast<XML_Parser>(this->Parser), "utf-8");
2171     return 1;
2172   }
2173   std::string GUID;
2174 };
2175
2176 void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID(
2177   const std::string& name, const char* path)
2178 {
2179   cmVS7XMLParser parser;
2180   parser.ParseFile(path);
2181   // if we can not find a GUID then we will generate one later
2182   if (parser.GUID.empty()) {
2183     return;
2184   }
2185   std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
2186   // save the GUID in the cache
2187   this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry(
2188     guidStoreName, parser.GUID, "Stored GUID", cmStateEnums::INTERNAL);
2189 }
2190
2191 std::string cmLocalVisualStudio7Generator::GetTargetDirectory(
2192   cmGeneratorTarget const* target) const
2193 {
2194   std::string dir = cmStrCat(target->GetName(), ".dir");
2195   return dir;
2196 }
2197
2198 static bool cmLVS7G_IsFAT(const char* dir)
2199 {
2200   if (dir[0] && dir[1] == ':') {
2201     char volRoot[4] = "_:/";
2202     volRoot[0] = dir[0];
2203     char fsName[16];
2204     if (GetVolumeInformationA(volRoot, 0, 0, 0, 0, 0, fsName, 16) &&
2205         strstr(fsName, "FAT") != 0) {
2206       return true;
2207     }
2208   }
2209   return false;
2210 }