cmGlobalVisualStudio10Generator.cxx 42.1 KB
Newer Older
1
2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmGlobalVisualStudio10Generator.h"
Brad King's avatar
Brad King committed
4

5
#include "cmAlgorithms.h"
6
#include "cmDocumentationEntry.h"
7
#include "cmGeneratorTarget.h"
8
9
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
10
#include "cmMessageType.h"
11
#include "cmSourceFile.h"
12
#include "cmVersion.h"
13
14
#include "cmVisualStudioSlnData.h"
#include "cmVisualStudioSlnParser.h"
15
#include "cmXMLWriter.h"
16
#include "cm_jsoncpp_reader.h"
17
18
#include "cmake.h"

19
20
21
#include "cmsys/FStream.hxx"
#include "cmsys/Glob.hxx"
#include "cmsys/RegularExpression.hxx"
22

23
24
#include <algorithm>

25
static const char vs10generatorName[] = "Visual Studio 10 2010";
26
static std::map<std::string, std::vector<cmIDEFlagTable>> loadedFlagJsonFiles;
27
28

// Map generator name without year to name with year.
29
static const char* cmVS10GenName(const std::string& name, std::string& genName)
30
{
31
32
  if (strncmp(name.c_str(), vs10generatorName,
              sizeof(vs10generatorName) - 6) != 0) {
33
    return 0;
34
  }
35
  const char* p = name.c_str() + sizeof(vs10generatorName) - 6;
36
  if (cmHasLiteralPrefix(p, " 2010")) {
37
    p += 5;
38
  }
39
40
41
  genName = std::string(vs10generatorName) + p;
  return p;
}
42

43
44
45
46
class cmGlobalVisualStudio10Generator::Factory
  : public cmGlobalGeneratorFactory
{
public:
47
  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
48
                                           cmake* cm) const override
49
  {
50
51
    std::string genName;
    const char* p = cmVS10GenName(name, genName);
52
53
54
55
    if (!p) {
      return 0;
    }
    if (!*p) {
56
      return new cmGlobalVisualStudio10Generator(cm, genName, "");
57
58
59
60
61
    }
    if (*p++ != ' ') {
      return 0;
    }
    if (strcmp(p, "Win64") == 0) {
62
      return new cmGlobalVisualStudio10Generator(cm, genName, "x64");
63
64
    }
    if (strcmp(p, "IA64") == 0) {
65
      return new cmGlobalVisualStudio10Generator(cm, genName, "Itanium");
66
    }
67
68
    return 0;
  }
69

70
  void GetDocumentation(cmDocumentationEntry& entry) const override
71
  {
72
    entry.Name = std::string(vs10generatorName) + " [arch]";
73
74
75
    entry.Brief = "Generates Visual Studio 2010 project files.  "
                  "Optional [arch] can be \"Win64\" or \"IA64\".";
  }
76

77
  void GetGenerators(std::vector<std::string>& names) const override
78
  {
79
80
81
    names.push_back(vs10generatorName);
    names.push_back(vs10generatorName + std::string(" IA64"));
    names.push_back(vs10generatorName + std::string(" Win64"));
82
  }
83

84
85
  bool SupportsToolset() const override { return true; }
  bool SupportsPlatform() const override { return true; }
86
87
88
89
90
91
92
};

cmGlobalGeneratorFactory* cmGlobalVisualStudio10Generator::NewFactory()
{
  return new Factory;
}

93
cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator(
94
95
96
  cmake* cm, const std::string& name,
  std::string const& platformInGeneratorName)
  : cmGlobalVisualStudio8Generator(cm, name, platformInGeneratorName)
97
{
98
99
100
  std::string vc10Express;
  this->ExpressEdition = cmSystemTools::ReadRegistryValue(
    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\10.0\\Setup\\VC;"
101
102
    "ProductDir",
    vc10Express, cmSystemTools::KeyWOW64_32);
103
  this->CudaEnabled = false;
104
  this->SystemIsWindowsCE = false;
105
106
  this->SystemIsWindowsPhone = false;
  this->SystemIsWindowsStore = false;
107
  this->MSBuildCommandInitialized = false;
108
109
110
111
112
113
114
115
116
117
  {
    std::string envPlatformToolset;
    if (cmSystemTools::GetEnv("PlatformToolset", envPlatformToolset) &&
        envPlatformToolset == "Windows7.1SDK") {
      // We are running from a Windows7.1SDK command prompt.
      this->DefaultPlatformToolset = "Windows7.1SDK";
    } else {
      this->DefaultPlatformToolset = "v100";
    }
  }
118
119
120
121
122
123
124
125
126
127
  this->DefaultCLFlagTableName = "v10";
  this->DefaultCSharpFlagTableName = "v10";
  this->DefaultLibFlagTableName = "v10";
  this->DefaultLinkFlagTableName = "v10";
  this->DefaultCudaFlagTableName = "v10";
  this->DefaultCudaHostFlagTableName = "v10";
  this->DefaultMasmFlagTableName = "v10";
  this->DefaultNasmFlagTableName = "v10";
  this->DefaultRCFlagTableName = "v10";

128
  this->Version = VS10;
129
  this->PlatformToolsetNeedsDebugEnum = false;
130
131
}

132
133
bool cmGlobalVisualStudio10Generator::MatchesGeneratorName(
  const std::string& name) const
134
135
{
  std::string genName;
136
  if (cmVS10GenName(name, genName)) {
137
    return genName == this->GetName();
138
  }
139
140
141
  return false;
}

142
143
bool cmGlobalVisualStudio10Generator::SetSystemName(std::string const& s,
                                                    cmMakefile* mf)
144
{
145
146
  this->SystemName = s;
  this->SystemVersion = mf->GetSafeDefinition("CMAKE_SYSTEM_VERSION");
147
  if (!this->InitializeSystem(mf)) {
148
    return false;
149
  }
150
151
152
  return this->cmGlobalVisualStudio8Generator::SetSystemName(s, mf);
}

153
154
bool cmGlobalVisualStudio10Generator::SetGeneratorPlatform(
  std::string const& p, cmMakefile* mf)
155
{
156
  if (!this->cmGlobalVisualStudio8Generator::SetGeneratorPlatform(p, mf)) {
157
    return false;
158
159
160
161
  }
  if (this->GetPlatformName() == "Itanium" ||
      this->GetPlatformName() == "x64") {
    if (this->IsExpressEdition() && !this->Find64BitTools(mf)) {
162
163
      return false;
    }
164
  }
165
  return true;
166
167
}

168
169
170
171
172
173
174
static void cmCudaToolVersion(std::string& s)
{
  // "CUDA x.y.props" => "x.y"
  s = s.substr(5);
  s = s.substr(0, s.size() - 6);
}

175
176
bool cmGlobalVisualStudio10Generator::SetGeneratorToolset(
  std::string const& ts, cmMakefile* mf)
177
{
178
  if (this->SystemIsWindowsCE && ts.empty() &&
179
      this->DefaultPlatformToolset.empty()) {
180
    std::ostringstream e;
181
182
    e << this->GetName() << " Windows CE version '" << this->SystemVersion
      << "' requires CMAKE_GENERATOR_TOOLSET to be set.";
183
    mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
184
    return false;
185
  }
186

187
188
189
  if (!this->ParseGeneratorToolset(ts, mf)) {
    return false;
  }
190
191
192
193
194

  if (!this->FindVCTargetsPath(mf)) {
    return false;
  }

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  if (cmHasLiteralPrefix(this->GetPlatformToolsetString(), "v140")) {
    // The GenerateDebugInformation link setting for the v140 toolset
    // in VS 2015 was originally an enum with "No" and "Debug" values,
    // differing from the "false" and "true" values used in older toolsets.
    // A VS 2015 update changed it back.  Parse the "link.xml" file to
    // discover which one we need.
    std::string const link_xml = this->VCTargetsPath + "/1033/link.xml";
    cmsys::ifstream fin(link_xml.c_str());
    std::string line;
    while (fin && cmSystemTools::GetLineFromStream(fin, line)) {
      if (line.find(" Switch=\"DEBUG\" ") != std::string::npos) {
        this->PlatformToolsetNeedsDebugEnum =
          line.find(" Name=\"Debug\" ") != std::string::npos;
        break;
      }
    }
  }

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
  if (this->GeneratorToolsetCuda.empty()) {
    // Find the highest available version of the CUDA tools.
    std::vector<std::string> cudaTools;
    std::string const bcDir = this->VCTargetsPath + "/BuildCustomizations";
    cmsys::Glob gl;
    gl.SetRelative(bcDir.c_str());
    if (gl.FindFiles(bcDir + "/CUDA *.props")) {
      cudaTools = gl.GetFiles();
    }
    if (!cudaTools.empty()) {
      std::for_each(cudaTools.begin(), cudaTools.end(), cmCudaToolVersion);
      std::sort(cudaTools.begin(), cudaTools.end(),
                cmSystemTools::VersionCompareGreater);
      this->GeneratorToolsetCuda = cudaTools.at(0);
    }
  }

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
  if (!this->GeneratorToolsetVersion.empty() &&
      this->GeneratorToolsetVersion != "Test Toolset Version") {
    // If a specific minor version of the toolset was requested, verify that it
    // is compatible to the major version and that is exists on disk.
    // If not clear the value.
    std::string version = this->GeneratorToolsetVersion;
    cmsys::RegularExpression regex("[0-9][0-9]\\.[0-9][0-9]");
    if (regex.find(version)) {
      version = "v" + version.erase(2, 1);
    } else {
      // Version not recognized. Clear it.
      version.clear();
    }

    if (version.find(this->GetPlatformToolsetString()) != 0) {
      std::ostringstream e;
      /* clang-format off */
      e <<
        "Generator\n"
        "  " << this->GetName() << "\n"
        "given toolset and version specification\n"
        "  " << this->GetPlatformToolsetString() << ",version=" <<
        this->GeneratorToolsetVersion << "\n"
        "contains an invalid version specification."
      ;
      /* clang-format on */
256
      mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
257
258
259
260
261

      // Clear the configured tool-set
      this->GeneratorToolsetVersion.clear();
    }

262
263
264
265
    bool const isDefaultToolset =
      this->IsDefaultToolset(this->GeneratorToolsetVersion);
    if (isDefaultToolset) {
      // If the given version is the default toolset, remove the setting
266
      this->GeneratorToolsetVersion.clear();
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    } else {
      std::string const toolsetPath = this->GetAuxiliaryToolset();
      if (!toolsetPath.empty() && !cmSystemTools::FileExists(toolsetPath)) {

        std::ostringstream e;
        /* clang-format off */
        e <<
          "Generator\n"
          "  " << this->GetName() << "\n"
          "given toolset and version specification\n"
          "  " << this->GetPlatformToolsetString() << ",version=" <<
          this->GeneratorToolsetVersion << "\n"
          "does not seem to be installed at\n" <<
          "  " << toolsetPath;
        ;
        /* clang-format on */
283
        mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
284
285
286
287

        // Clear the configured tool-set
        this->GeneratorToolsetVersion.clear();
      }
288
289
290
    }
  }

291
  if (const char* toolset = this->GetPlatformToolset()) {
292
    mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET", toolset);
293
  }
294
295
296
  if (const char* version = this->GetPlatformToolsetVersion()) {
    mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET_VERSION", version);
  }
297
298
299
  if (const char* hostArch = this->GetPlatformToolsetHostArchitecture()) {
    mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE", hostArch);
  }
300
301
302
  if (const char* cuda = this->GetPlatformToolsetCuda()) {
    mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET_CUDA", cuda);
  }
303
304
305
306
307
308
  return true;
}

bool cmGlobalVisualStudio10Generator::ParseGeneratorToolset(
  std::string const& ts, cmMakefile* mf)
{
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
  std::vector<std::string> const fields = cmSystemTools::tokenize(ts, ",");
  std::vector<std::string>::const_iterator fi = fields.begin();
  if (fi == fields.end()) {
    return true;
  }

  // The first field may be the VS platform toolset.
  if (fi->find('=') == fi->npos) {
    this->GeneratorToolset = *fi;
    ++fi;
  }

  std::set<std::string> handled;

  // The rest of the fields must be key=value pairs.
  for (; fi != fields.end(); ++fi) {
    std::string::size_type pos = fi->find('=');
    if (pos == fi->npos) {
      std::ostringstream e;
      /* clang-format off */
      e <<
        "Generator\n"
        "  " << this->GetName() << "\n"
        "given toolset specification\n"
        "  " << ts << "\n"
        "that contains a field after the first ',' with no '='."
        ;
      /* clang-format on */
337
      mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
      return false;
    }
    std::string const key = fi->substr(0, pos);
    std::string const value = fi->substr(pos + 1);
    if (!handled.insert(key).second) {
      std::ostringstream e;
      /* clang-format off */
      e <<
        "Generator\n"
        "  " << this->GetName() << "\n"
        "given toolset specification\n"
        "  " << ts << "\n"
        "that contains duplicate field key '" << key << "'."
        ;
      /* clang-format on */
353
      mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
354
355
356
357
358
359
360
361
362
363
364
365
366
      return false;
    }
    if (!this->ProcessGeneratorToolsetField(key, value)) {
      std::ostringstream e;
      /* clang-format off */
      e <<
        "Generator\n"
        "  " << this->GetName() << "\n"
        "given toolset specification\n"
        "  " << ts << "\n"
        "that contains invalid field '" << *fi << "'."
        ;
      /* clang-format on */
367
      mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
368
369
      return false;
    }
370
371
  }

372
373
374
  return true;
}

375
376
377
bool cmGlobalVisualStudio10Generator::ProcessGeneratorToolsetField(
  std::string const& key, std::string const& value)
{
378
379
380
381
  if (key == "cuda") {
    this->GeneratorToolsetCuda = value;
    return true;
  }
382
383
384
385
  if (key == "version") {
    this->GeneratorToolsetVersion = value;
    return true;
  }
386
387
388
  return false;
}

389
bool cmGlobalVisualStudio10Generator::InitializeSystem(cmMakefile* mf)
390
{
391
392
  if (this->SystemName == "Windows") {
    if (!this->InitializeWindows(mf)) {
393
394
      return false;
    }
395
  } else if (this->SystemName == "WindowsCE") {
396
    this->SystemIsWindowsCE = true;
397
    if (!this->InitializeWindowsCE(mf)) {
398
399
      return false;
    }
400
  } else if (this->SystemName == "WindowsPhone") {
401
    this->SystemIsWindowsPhone = true;
402
    if (!this->InitializeWindowsPhone(mf)) {
403
      return false;
404
    }
405
  } else if (this->SystemName == "WindowsStore") {
406
    this->SystemIsWindowsStore = true;
407
    if (!this->InitializeWindowsStore(mf)) {
408
      return false;
409
    }
410
  } else if (this->SystemName == "Android") {
411
    if (this->PlatformInGeneratorName) {
412
      std::ostringstream e;
413
414
      e << "CMAKE_SYSTEM_NAME is 'Android' but CMAKE_GENERATOR "
        << "specifies a platform too: '" << this->GetName() << "'";
415
      mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
416
      return false;
417
    }
418
    std::string v = this->GetInstalledNsightTegraVersion();
419
    if (v.empty()) {
420
      mf->IssueMessage(MessageType::FATAL_ERROR,
421
422
423
                       "CMAKE_SYSTEM_NAME is 'Android' but "
                       "'NVIDIA Nsight Tegra Visual Studio Edition' "
                       "is not installed.");
424
      return false;
425
    }
426
427
428
429
    this->DefaultPlatformName = "Tegra-Android";
    this->DefaultPlatformToolset = "Default";
    this->NsightTegraVersion = v;
    mf->AddDefinition("CMAKE_VS_NsightTegra_VERSION", v.c_str());
430
  }
431

432
433
434
  return true;
}

435
436
437
438
439
bool cmGlobalVisualStudio10Generator::InitializeWindows(cmMakefile*)
{
  return true;
}

440
441
bool cmGlobalVisualStudio10Generator::InitializeWindowsCE(cmMakefile* mf)
{
442
  if (this->PlatformInGeneratorName) {
443
    std::ostringstream e;
444
445
    e << "CMAKE_SYSTEM_NAME is 'WindowsCE' but CMAKE_GENERATOR "
      << "specifies a platform too: '" << this->GetName() << "'";
446
    mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
447
    return false;
448
  }
449
450
451
452
453
454

  this->DefaultPlatformToolset = this->SelectWindowsCEToolset();

  return true;
}

455
456
bool cmGlobalVisualStudio10Generator::InitializeWindowsPhone(cmMakefile* mf)
{
457
  std::ostringstream e;
458
  e << this->GetName() << " does not support Windows Phone.";
459
  mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
460
461
462
463
464
  return false;
}

bool cmGlobalVisualStudio10Generator::InitializeWindowsStore(cmMakefile* mf)
{
465
  std::ostringstream e;
466
  e << this->GetName() << " does not support Windows Store.";
467
  mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
468
469
470
  return false;
}

471
bool cmGlobalVisualStudio10Generator::SelectWindowsPhoneToolset(
472
473
  std::string& toolset) const
{
474
  toolset.clear();
475
476
477
  return false;
}

478
bool cmGlobalVisualStudio10Generator::SelectWindowsStoreToolset(
479
480
  std::string& toolset) const
{
481
  toolset.clear();
482
483
484
  return false;
}

485
486
std::string cmGlobalVisualStudio10Generator::SelectWindowsCEToolset() const
{
487
  if (this->SystemVersion == "8.0") {
488
    return "CE800";
489
  }
490
491
492
  return "";
}

493
///! Create a local generator appropriate to this Global Generator
494
cmLocalGenerator* cmGlobalVisualStudio10Generator::CreateLocalGenerator(
495
  cmMakefile* mf)
496
{
497
  return new cmLocalVisualStudio10Generator(this, mf);
498
499
}

500
501
void cmGlobalVisualStudio10Generator::Generate()
{
502
  this->LongestSource = LongestSourcePath();
503
  this->cmGlobalVisualStudio8Generator::Generate();
504
  if (this->LongestSource.Length > 0) {
505
    cmLocalGenerator* lg = this->LongestSource.Target->GetLocalGenerator();
506
    std::ostringstream e;
507
    /* clang-format off */
508
509
510
511
512
513
514
515
516
517
518
519
520
    e <<
      "The binary and/or source directory paths may be too long to generate "
      "Visual Studio 10 files for this project.  "
      "Consider choosing shorter directory names to build this project with "
      "Visual Studio 10.  "
      "A more detailed explanation follows."
      "\n"
      "There is a bug in the VS 10 IDE that renders property dialog fields "
      "blank for files referenced by full path in the project file.  "
      "However, CMake must reference at least one file by full path:\n"
      "  " << this->LongestSource.SourceFile->GetFullPath() << "\n"
      "This is because some Visual Studio tools would append the relative "
      "path to the end of the referencing directory path, as in:\n"
521
      "  " << lg->GetCurrentBinaryDirectory() << "/"
522
523
524
525
526
      << this->LongestSource.SourceRel << "\n"
      "and then incorrectly complain that the file does not exist because "
      "the path length is too long for some internal buffer or API.  "
      "To avoid this problem CMake must use a full path for this file "
      "which then triggers the VS 10 property dialog bug.";
527
    /* clang-format on */
528
    lg->IssueMessage(MessageType::WARNING, e.str().c_str());
529
  }
530
531
}

532
533
void cmGlobalVisualStudio10Generator::EnableLanguage(
  std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
534
{
535
536
  for (std::string const& it : lang) {
    if (it == "ASM_NASM") {
537
538
      this->NasmEnabled = true;
    }
539
    if (it == "CUDA") {
540
541
      this->CudaEnabled = true;
    }
542
543
  }
  this->AddPlatformDefinitions(mf);
544
545
546
  cmGlobalVisualStudio8Generator::EnableLanguage(lang, mf, optional);
}

547
const char* cmGlobalVisualStudio10Generator::GetPlatformToolset() const
548
{
549
550
  std::string const& toolset = this->GetPlatformToolsetString();
  if (toolset.empty()) {
Daniel Pfeifer's avatar
Daniel Pfeifer committed
551
    return nullptr;
552
553
  }
  return toolset.c_str();
554
555
556
557
}

std::string const& cmGlobalVisualStudio10Generator::GetPlatformToolsetString()
  const
558
{
559
  if (!this->GeneratorToolset.empty()) {
560
    return this->GeneratorToolset;
561
562
  }
  if (!this->DefaultPlatformToolset.empty()) {
563
    return this->DefaultPlatformToolset;
564
  }
565
566
  static std::string const empty;
  return empty;
567
568
}

569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
const char* cmGlobalVisualStudio10Generator::GetPlatformToolsetVersion() const
{
  std::string const& version = this->GetPlatformToolsetVersionString();
  if (version.empty()) {
    return nullptr;
  }
  return version.c_str();
}

std::string const&
cmGlobalVisualStudio10Generator::GetPlatformToolsetVersionString() const
{
  if (!this->GeneratorToolsetVersion.empty()) {
    return this->GeneratorToolsetVersion;
  }
  static std::string const empty;
  return empty;
}

588
589
590
591
592
593
const char*
cmGlobalVisualStudio10Generator::GetPlatformToolsetHostArchitecture() const
{
  if (!this->GeneratorToolsetHostArchitecture.empty()) {
    return this->GeneratorToolsetHostArchitecture.c_str();
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
594
  return nullptr;
595
596
}

597
598
599
600
601
const char* cmGlobalVisualStudio10Generator::GetPlatformToolsetCuda() const
{
  if (!this->GeneratorToolsetCuda.empty()) {
    return this->GeneratorToolsetCuda.c_str();
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
602
  return nullptr;
603
604
605
606
607
608
609
610
}

std::string const&
cmGlobalVisualStudio10Generator::GetPlatformToolsetCudaString() const
{
  return this->GeneratorToolsetCuda;
}

611
612
613
614
615
616
bool cmGlobalVisualStudio10Generator::IsDefaultToolset(
  const std::string&) const
{
  return true;
}

617
618
619
620
621
std::string cmGlobalVisualStudio10Generator::GetAuxiliaryToolset() const
{
  return {};
}

622
bool cmGlobalVisualStudio10Generator::FindMakeProgram(cmMakefile* mf)
623
{
624
625
626
  if (!this->cmGlobalVisualStudio8Generator::FindMakeProgram(mf)) {
    return false;
  }
627
628
  mf->AddDefinition("CMAKE_VS_MSBUILD_COMMAND",
                    this->GetMSBuildCommand().c_str());
629
  return true;
630
631
}

632
633
std::string const& cmGlobalVisualStudio10Generator::GetMSBuildCommand()
{
634
  if (!this->MSBuildCommandInitialized) {
635
636
    this->MSBuildCommandInitialized = true;
    this->MSBuildCommand = this->FindMSBuildCommand();
637
  }
638
639
640
641
642
643
  return this->MSBuildCommand;
}

std::string cmGlobalVisualStudio10Generator::FindMSBuildCommand()
{
  std::string msbuild;
644
645
646
647
  std::string mskey;

  // Search in standard location.
  mskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\";
648
649
  mskey += this->GetToolsVersion();
  mskey += ";MSBuildToolsPath";
650
651
  if (cmSystemTools::ReadRegistryValue(mskey.c_str(), msbuild,
                                       cmSystemTools::KeyWOW64_32)) {
652
    cmSystemTools::ConvertToUnixSlashes(msbuild);
653
654
655
656
    msbuild += "/MSBuild.exe";
    if (cmSystemTools::FileExists(msbuild, true)) {
      return msbuild;
    }
657
  }
658
659

  msbuild = "MSBuild.exe";
660
661
  return msbuild;
}
662

663
664
std::string cmGlobalVisualStudio10Generator::FindDevEnvCommand()
{
665
  if (this->ExpressEdition) {
666
667
668
669
    // Visual Studio Express >= 10 do not have "devenv.com" or
    // "VCExpress.exe" that we can use to build reliably.
    // Tell the caller it needs to use MSBuild instead.
    return "";
670
  }
671
672
673
674
675
  // Skip over the cmGlobalVisualStudio8Generator implementation because
  // we expect a real devenv and do not want to look for VCExpress.
  return this->cmGlobalVisualStudio71Generator::FindDevEnvCommand();
}

676
677
678
679
680
681
682
683
684
685
686
687
688
689
bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf)
{
  // Skip this in special cases within our own test suite.
  if (this->GetPlatformName() == "Test Platform" ||
      this->GetPlatformToolsetString() == "Test Toolset") {
    return true;
  }

  std::string wd;
  if (!this->ConfiguredFilesPath.empty()) {
    // In a try-compile we are given the outer CMakeFiles directory.
    wd = this->ConfiguredFilesPath;
  } else {
    wd = this->GetCMakeInstance()->GetHomeOutputDirectory();
690
    wd += "/CMakeFiles";
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
  }
  wd += "/";
  wd += cmVersion::GetCMakeVersion();

  // We record the result persistently in a file.
  std::string const txt = wd + "/VCTargetsPath.txt";

  // If we have a recorded result, use it.
  {
    cmsys::ifstream fin(txt.c_str());
    if (fin && cmSystemTools::GetLineFromStream(fin, this->VCTargetsPath) &&
        cmSystemTools::FileIsDirectory(this->VCTargetsPath)) {
      cmSystemTools::ConvertToUnixSlashes(this->VCTargetsPath);
      return true;
    }
  }

  // Prepare the work directory.
  if (!cmSystemTools::MakeDirectory(wd)) {
    std::string e = "Failed to make directory:\n  " + wd;
711
    mf->IssueMessage(MessageType::FATAL_ERROR, e.c_str());
712
713
714
715
716
717
718
719
720
721
722
    cmSystemTools::SetFatalErrorOccured();
    return false;
  }

  // Generate a project file for MSBuild to tell us the VCTargetsPath value.
  std::string const vcxproj = "VCTargetsPath.vcxproj";
  {
    std::string const vcxprojAbs = wd + "/" + vcxproj;
    cmsys::ofstream fout(vcxprojAbs.c_str());
    cmXMLWriter xw(fout);

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
    cmXMLDocument doc(xw);
    cmXMLElement eprj(doc, "Project");
    eprj.Attribute("DefaultTargets", "Build");
    eprj.Attribute("ToolsVersion", "4.0");
    eprj.Attribute("xmlns",
                   "http://schemas.microsoft.com/developer/msbuild/2003");
    if (this->IsNsightTegra()) {
      cmXMLElement epg(eprj, "PropertyGroup");
      epg.Attribute("Label", "NsightTegraProject");
      cmXMLElement(epg, "NsightTegraProjectRevisionNumber").Content("6");
    }
    {
      cmXMLElement eig(eprj, "ItemGroup");
      eig.Attribute("Label", "ProjectConfigurations");
      cmXMLElement epc(eig, "ProjectConfiguration");
      epc.Attribute("Include", "Debug|" + this->GetPlatformName());
      cmXMLElement(epc, "Configuration").Content("Debug");
      cmXMLElement(epc, "Platform").Content(this->GetPlatformName());
    }
    {
      cmXMLElement epg(eprj, "PropertyGroup");
      epg.Attribute("Label", "Globals");
      cmXMLElement(epg, "ProjectGuid")
        .Content("{F3FC6D86-508D-3FB1-96D2-995F08B142EC}");
      cmXMLElement(epg, "Keyword").Content("Win32Proj");
      cmXMLElement(epg, "Platform").Content(this->GetPlatformName());
      if (this->GetSystemName() == "WindowsPhone") {
        cmXMLElement(epg, "ApplicationType").Content("Windows Phone");
        cmXMLElement(epg, "ApplicationTypeRevision")
          .Content(this->GetSystemVersion());
      } else if (this->GetSystemName() == "WindowsStore") {
        cmXMLElement(epg, "ApplicationType").Content("Windows Store");
        cmXMLElement(epg, "ApplicationTypeRevision")
          .Content(this->GetSystemVersion());
      }
      if (!this->WindowsTargetPlatformVersion.empty()) {
        cmXMLElement(epg, "WindowsTargetPlatformVersion")
          .Content(this->WindowsTargetPlatformVersion);
      }
      if (this->GetPlatformName() == "ARM64") {
        cmXMLElement(epg, "WindowsSDKDesktopARM64Support").Content("true");
      } else if (this->GetPlatformName() == "ARM") {
        cmXMLElement(epg, "WindowsSDKDesktopARMSupport").Content("true");
      }
    }
    cmXMLElement(eprj, "Import")
      .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props");
770
    if (!this->GeneratorToolsetHostArchitecture.empty()) {
771
772
773
      cmXMLElement epg(eprj, "PropertyGroup");
      cmXMLElement(epg, "PreferredToolArchitecture")
        .Content(this->GeneratorToolsetHostArchitecture);
774
    }
775
776
777
778
779
780
781
782
783
784
785
786
787
    {
      cmXMLElement epg(eprj, "PropertyGroup");
      epg.Attribute("Label", "Configuration");
      {
        cmXMLElement ect(epg, "ConfigurationType");
        if (this->IsNsightTegra()) {
          // Tegra-Android platform does not understand "Utility".
          ect.Content("StaticLibrary");
        } else {
          ect.Content("Utility");
        }
      }
      cmXMLElement(epg, "CharacterSet").Content("MultiByte");
788
      if (this->IsNsightTegra()) {
789
790
        cmXMLElement(epg, "NdkToolchainVersion")
          .Content(this->GetPlatformToolsetString());
791
      } else {
792
793
        cmXMLElement(epg, "PlatformToolset")
          .Content(this->GetPlatformToolsetString());
794
      }
795
796
797
798
799
800
801
802
803
804
805
    }
    cmXMLElement(eprj, "Import")
      .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props");
    {
      cmXMLElement eidg(eprj, "ItemDefinitionGroup");
      cmXMLElement epbe(eidg, "PostBuildEvent");
      cmXMLElement(epbe, "Command")
        .Content("echo VCTargetsPath=$(VCTargetsPath)");
    }
    cmXMLElement(eprj, "Import")
      .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets");
806
807
808
809
810
  }

  std::vector<std::string> cmd;
  cmd.push_back(this->GetMSBuildCommand());
  cmd.push_back(vcxproj);
Brad King's avatar
Brad King committed
811
  cmd.push_back("/p:Configuration=Debug");
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
  cmd.push_back(std::string("/p:VisualStudioVersion=") +
                this->GetIDEVersion());
  std::string out;
  int ret = 0;
  cmsys::RegularExpression regex("\n *VCTargetsPath=([^%\r\n]+)[\r\n]");
  if (!cmSystemTools::RunSingleCommand(cmd, &out, &out, &ret, wd.c_str(),
                                       cmSystemTools::OUTPUT_NONE) ||
      ret != 0 || !regex.find(out)) {
    cmSystemTools::ReplaceString(out, "\n", "\n  ");
    std::ostringstream e;
    /* clang-format off */
    e <<
      "Failed to run MSBuild command:\n"
      "  " << cmd[0] << "\n"
      "to get the value of VCTargetsPath:\n"
      "  " << out << "\n"
      ;
    /* clang-format on */
    if (ret != 0) {
      e << "Exit code: " << ret << "\n";
    }
833
    mf->IssueMessage(MessageType::FATAL_ERROR, e.str().c_str());
834
835
836
837
838
839
840
841
842
843
844
845
846
    cmSystemTools::SetFatalErrorOccured();
    return false;
  }
  this->VCTargetsPath = regex.match(1);
  cmSystemTools::ConvertToUnixSlashes(this->VCTargetsPath);

  {
    cmsys::ofstream fout(txt.c_str());
    fout << this->VCTargetsPath << "\n";
  }
  return true;
}

847
void cmGlobalVisualStudio10Generator::GenerateBuildCommand(
848
849
850
  std::vector<std::string>& makeCommand, const std::string& makeProgram,
  const std::string& projectName, const std::string& projectDir,
  const std::string& targetName, const std::string& config, bool fast,
851
  int jobs, bool verbose, std::vector<std::string> const& makeOptions)
852
{
853
854
855
856
857
858
859
  // Select the caller- or user-preferred make program, else MSBuild.
  std::string makeProgramSelected =
    this->SelectMakeProgram(makeProgram, this->GetMSBuildCommand());

  // Check if the caller explicitly requested a devenv tool.
  std::string makeProgramLower = makeProgramSelected;
  cmSystemTools::LowerCase(makeProgramLower);
860
861
  bool useDevEnv = (makeProgramLower.find("devenv") != std::string::npos ||
                    makeProgramLower.find("vcexpress") != std::string::npos);
862
863
864
865
866

  // MSBuild is preferred (and required for VS Express), but if the .sln has
  // an Intel Fortran .vfproj then we have to use devenv. Parse it to find out.
  cmSlnData slnData;
  {
867
868
869
870
871
872
873
874
875
876
877
    std::string slnFile;
    if (!projectDir.empty()) {
      slnFile = projectDir;
      slnFile += "/";
    }
    slnFile += projectName;
    slnFile += ".sln";
    cmVisualStudioSlnParser parser;
    if (parser.ParseFile(slnFile, slnData,
                         cmVisualStudioSlnParser::DataGroupProjects)) {
      std::vector<cmSlnProjectEntry> slnProjects = slnData.GetProjects();
878
879
880
      for (std::vector<cmSlnProjectEntry>::const_iterator i =
             slnProjects.cbegin();
           !useDevEnv && i != slnProjects.cend(); ++i) {
881
882
883
        std::string proj = i->GetRelativePath();
        if (proj.size() > 7 && proj.substr(proj.size() - 7) == ".vfproj") {
          useDevEnv = true;
884
885
886
887
        }
      }
    }
  }
888
  if (useDevEnv) {
889
    // Use devenv to build solutions containing Intel Fortran projects.
890
    cmGlobalVisualStudio7Generator::GenerateBuildCommand(
891
      makeCommand, makeProgram, projectName, projectDir, targetName, config,
892
      fast, jobs, verbose, makeOptions);
893
    return;
894
  }
895

896
  makeCommand.push_back(makeProgramSelected);
897

898
  std::string realTarget = targetName;
899
  // msbuild.exe CxxOnly.sln /t:Build /p:Configuration=Debug /target:ALL_BUILD
900
  //                         /m
901
  if (realTarget.empty()) {
902
    realTarget = "ALL_BUILD";
903
904
905
  }
  if (realTarget == "clean") {
    makeCommand.push_back(std::string(projectName) + ".sln");
906
    makeCommand.push_back("/t:Clean");
907
  } else {
908
    std::string targetProject(realTarget);
909
    targetProject += ".vcxproj";
910
    if (targetProject.find('/') == std::string::npos) {
911
      // it might be in a subdir
912
      if (cmSlnProjectEntry const* proj =
913
            slnData.GetProjectByName(realTarget)) {
914
915
        targetProject = proj->GetRelativePath();
        cmSystemTools::ConvertToUnixSlashes(targetProject);
916
      }
917
    }
918
919
    makeCommand.push_back(targetProject);
  }
920
  std::string configArg = "/p:Configuration=";
921
  if (!config.empty()) {
922
    configArg += config;
923
  } else {
924
    configArg += "Debug";
925
  }
926
  makeCommand.push_back(configArg);
927
  makeCommand.push_back("/p:Platform=" + this->GetPlatformName());
928
  makeCommand.push_back(std::string("/p:VisualStudioVersion=") +
929
                        this->GetIDEVersion());
930
931
932
933
934
935
936
937
938
939
940

  if (jobs != cmake::NO_BUILD_PARALLEL_LEVEL) {
    if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
      makeCommand.push_back("/m");
    } else {
      makeCommand.push_back(std::string("/m:") + std::to_string(jobs));
    }
    // Having msbuild.exe and cl.exe using multiple jobs is discouraged
    makeCommand.push_back("/p:CL_MPCount=1");
  }

941
942
  makeCommand.insert(makeCommand.end(), makeOptions.begin(),
                     makeOptions.end());
943
}
944
945
946

bool cmGlobalVisualStudio10Generator::Find64BitTools(cmMakefile* mf)
{
947
948
949
950
  if (this->DefaultPlatformToolset == "v100") {
    // The v100 64-bit toolset does not exist in the express edition.
    this->DefaultPlatformToolset.clear();
  }
951
  if (this->GetPlatformToolset()) {
952
    return true;
953
  }
954
955
956
  // This edition does not come with 64-bit tools.  Look for them.
  //
  // TODO: Detect available tools?  x64\v100 exists but does not work?
957
  // HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0;VCTargetsPath
958
959
960
  // c:/Program Files (x86)/MSBuild/Microsoft.Cpp/v4.0/Platforms/
  //   {Itanium,Win32,x64}/PlatformToolsets/{v100,v90,Windows7.1SDK}
  std::string winSDK_7_1;
961
962
963
964
  if (cmSystemTools::ReadRegistryValue(
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\"
        "Windows\\v7.1;InstallationFolder",
        winSDK_7_1)) {
965
    std::ostringstream m;
966
967
    m << "Found Windows SDK v7.1: " << winSDK_7_1;
    mf->DisplayStatus(m.str().c_str(), -1);
968
    this->DefaultPlatformToolset = "Windows7.1SDK";
969
    return true;
970
  } else {
971
    std::ostringstream e;
972
    /* clang-format off */
973
974
975
    e << "Cannot enable 64-bit tools with Visual Studio 2010 Express.\n"
      << "Install the Microsoft Windows SDK v7.1 to get 64-bit tools:\n"
      << "  http://msdn.microsoft.com/en-us/windows/bb980924.aspx";
976
    /* clang-format on */
977
    mf->IssueMessage(MessageType::FATAL_ERROR, e.str().c_str());
978
979
    cmSystemTools::SetFatalErrorOccured();
    return false;
980
  }
981
}
982

983
984
std::string cmGlobalVisualStudio10Generator::GenerateRuleFile(
  std::string const& output) const
985
986
987
988
{
  // The VS 10 generator needs to create the .rule files on disk.
  // Hide them away under the CMakeFiles directory.
  std::string ruleDir = this->GetCMakeInstance()->GetHomeOutputDirectory();
989
  ruleDir += "/CMakeFiles";
990
991
992
993
994
995
996
997
  ruleDir += "/";
  ruleDir += cmSystemTools::ComputeStringMD5(
    cmSystemTools::GetFilenamePath(output).c_str());
  std::string ruleFile = ruleDir + "/";
  ruleFile += cmSystemTools::GetFilenameName(output);
  ruleFile += ".rule";
  return ruleFile;
}
998

999
1000
1001
void cmGlobalVisualStudio10Generator::PathTooLong(cmGeneratorTarget* target,
                                                  cmSourceFile const* sf,
                                                  std::string const& sfRel)
1002
{
1003
  size_t len =
1004
    (target->GetLocalGenerator()->GetCurrentBinaryDirectory().length() + 1 +
1005
1006
     sfRel.length());
  if (len > this->LongestSource.Length) {
1007
1008
1009
1010
    this->LongestSource.Length = len;
    this->LongestSource.Target = target;
    this->LongestSource.SourceFile = sf;
    this->LongestSource.SourceRel = sfRel;
1011
  }
1012
}
1013

1014
1015
1016
1017
1018
std::string cmGlobalVisualStudio10Generator::Encoding()
{
  return "utf-8";
}

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
const char* cmGlobalVisualStudio10Generator::GetToolsVersion() const
{
  switch (this->Version) {
    case cmGlobalVisualStudioGenerator::VS9:
    case cmGlobalVisualStudioGenerator::VS10:
    case cmGlobalVisualStudioGenerator::VS11:
      return "4.0";

      // in Visual Studio 2013 they detached the MSBuild tools version
      // from the .Net Framework version and instead made it have it's own
      // version number
    case cmGlobalVisualStudioGenerator::VS12:
      return "12.0";
    case cmGlobalVisualStudioGenerator::VS14:
      return "14.0";
    case cmGlobalVisualStudioGenerator::VS15:
      return "15.0";
1036
1037
    case cmGlobalVisualStudioGenerator::VS16:
      return "16.0";
1038
1039
1040
1041
  }
  return "";
}

1042
1043
1044
1045
1046
bool cmGlobalVisualStudio10Generator::IsNsightTegra() const
{
  return !this->NsightTegraVersion.empty();
}

1047
1048
1049
1050
1051
std::string cmGlobalVisualStudio10Generator::GetNsightTegraVersion() const
{
  return this->NsightTegraVersion;
}

1052
1053
1054
1055
1056
std::string cmGlobalVisualStudio10Generator::GetInstalledNsightTegraVersion()
{
  std::string version;
  cmSystemTools::ReadRegistryValue(
    "HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Nsight Tegra;"
1057
1058
    "Version",
    version, cmSystemTools::KeyWOW64_32);
1059
1060
  return version;
}
1061

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
static std::string cmLoadFlagTableString(Json::Value entry, const char* field)
{
  if (entry.isMember(field)) {
    auto string = entry[field];
    if (string.isConvertibleTo(Json::ValueType::stringValue)) {
      return string.asString();
    }
  }
  return "";
}

static unsigned int cmLoadFlagTableSpecial(Json::Value entry,
                                           const char* field)
{
  unsigned int value = 0;
  if (entry.isMember(field)) {
    auto specials = entry[field];
    if (specials.isArray()) {
      for (auto const& special : specials) {
        std::string s = special.asString();
        if (s == "UserValue") {
          value |= cmIDEFlagTable::UserValue;
        } else if (s == "UserIgnored") {
          value |= cmIDEFlagTable::UserIgnored;
        } else if (s == "UserRequired") {
          value |= cmIDEFlagTable::UserRequired;
        } else if (s == "Continue") {
          value |= cmIDEFlagTable::Continue;
        } else if (s == "SemicolonAppendable") {
          value |= cmIDEFlagTable::SemicolonAppendable;
        } else if (s == "UserFollowing") {
          value |= cmIDEFlagTable::UserFollowing;
        } else if (s == "CaseInsensitive") {
          value |= cmIDEFlagTable::CaseInsensitive;
        } else if (s == "SpaceAppendable") {
          value |= cmIDEFlagTable::SpaceAppendable;
        }
      }
    }
  }
  return value;
}

static cmIDEFlagTable const* cmLoadFlagTableJson(
  std::string const& flagJsonPath)
{
  cmIDEFlagTable* ret = nullptr;
  auto savedFlagIterator = loadedFlagJsonFiles.find(flagJsonPath);
  if (savedFlagIterator != loadedFlagJsonFiles.end()) {
    ret = savedFlagIterator->second.data();
  } else {
    Json::Reader reader;
    cmsys::ifstream stream;

    stream.open(flagJsonPath.c_str(), std::ios_base::in);
    if (stream) {
      Json::Value flags;
      if (reader.parse(stream, flags, false) && flags.isArray()) {
        std::vector<cmIDEFlagTable> flagTable;
        for (auto const& flag : flags) {
          cmIDEFlagTable flagEntry;
          flagEntry.IDEName = cmLoadFlagTableString(flag, "name");
          flagEntry.commandFlag = cmLoadFlagTableString(flag, "switch");
          flagEntry.comment = cmLoadFlagTableString(flag, "comment");
          flagEntry.value = cmLoadFlagTableString(flag, "value");
          flagEntry.special = cmLoadFlagTableSpecial(flag, "flags");
          flagTable.push_back(flagEntry);
        }
        cmIDEFlagTable endFlag{ "", "", "", "", 0 };
        flagTable.push_back(endFlag);