resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmVSSetupHelper.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 "cmVSSetupHelper.h"
4
5 #include <utility>
6
7 #if !defined(CMAKE_BOOTSTRAP)
8 #  include <cm3p/json/reader.h>
9 #  include <cm3p/json/value.h>
10 #endif
11
12 #include "cmsys/Encoding.hxx"
13 #include "cmsys/FStream.hxx"
14
15 #include "cmStringAlgorithms.h"
16 #include "cmSystemTools.h"
17
18 #ifndef VSSetupConstants
19 #  define VSSetupConstants
20 /* clang-format off */
21 const IID IID_ISetupConfiguration = {
22   0x42843719, 0xDB4C, 0x46C2,
23   { 0x8E, 0x7C, 0x64, 0xF1, 0x81, 0x6E, 0xFD, 0x5B }
24 };
25 const IID IID_ISetupConfiguration2 = {
26   0x26AAB78C, 0x4A60, 0x49D6,
27   { 0xAF, 0x3B, 0x3C, 0x35, 0xBC, 0x93, 0x36, 0x5D }
28 };
29 const IID IID_ISetupPackageReference = {
30   0xda8d8a16, 0xb2b6, 0x4487,
31   { 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5 }
32 };
33 const IID IID_ISetupHelper = {
34   0x42b21b78, 0x6192, 0x463e,
35   { 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c }
36 };
37 const IID IID_IEnumSetupInstances = {
38   0x6380BCFF, 0x41D3, 0x4B2E,
39   { 0x8B, 0x2E, 0xBF, 0x8A, 0x68, 0x10, 0xC8, 0x48 }
40 };
41 const IID IID_ISetupInstance2 = {
42   0x89143C9A, 0x05AF, 0x49B0,
43   { 0xB7, 0x17, 0x72, 0xE2, 0x18, 0xA2, 0x18, 0x5C }
44 };
45 const IID IID_ISetupInstance = {
46   0xB41463C3, 0x8866, 0x43B5,
47   { 0xBC, 0x33, 0x2B, 0x06, 0x76, 0xF7, 0xF4, 0x2E }
48 };
49 const CLSID CLSID_SetupConfiguration = {
50   0x177F0C4A, 0x1CD3, 0x4DE7,
51   { 0xA3, 0x2C, 0x71, 0xDB, 0xBB, 0x9F, 0xA3, 0x6D }
52 };
53 /* clang-format on */
54 #endif
55
56 namespace {
57 const WCHAR* Win10SDKComponent =
58   L"Microsoft.VisualStudio.Component.Windows10SDK";
59 const WCHAR* Win81SDKComponent =
60   L"Microsoft.VisualStudio.Component.Windows81SDK";
61 const WCHAR* ComponentType = L"Component";
62
63 bool LoadVSInstanceVCToolsetVersion(VSInstanceInfo& vsInstanceInfo)
64 {
65   std::string const vcRoot = vsInstanceInfo.GetInstallLocation();
66   std::string vcToolsVersionFile =
67     vcRoot + "/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt";
68   std::string vcToolsVersion;
69   cmsys::ifstream fin(vcToolsVersionFile.c_str());
70   if (!fin || !cmSystemTools::GetLineFromStream(fin, vcToolsVersion)) {
71     return false;
72   }
73   vcToolsVersion = cmTrimWhitespace(vcToolsVersion);
74   std::string const vcToolsDir = vcRoot + "/VC/Tools/MSVC/" + vcToolsVersion;
75   if (!cmSystemTools::FileIsDirectory(vcToolsDir)) {
76     return false;
77   }
78   vsInstanceInfo.VCToolsetVersion = vcToolsVersion;
79   return true;
80 }
81 }
82
83 std::string VSInstanceInfo::GetInstallLocation() const
84 {
85   return this->VSInstallLocation;
86 }
87
88 cmVSSetupAPIHelper::cmVSSetupAPIHelper(unsigned int version)
89   : Version(version)
90   , setupConfig(NULL)
91   , setupConfig2(NULL)
92   , setupHelper(NULL)
93   , initializationFailure(false)
94 {
95   comInitialized = CoInitializeEx(NULL, 0);
96   if (SUCCEEDED(comInitialized)) {
97     Initialize();
98   } else {
99     initializationFailure = true;
100   }
101 }
102
103 cmVSSetupAPIHelper::~cmVSSetupAPIHelper()
104 {
105   setupHelper = NULL;
106   setupConfig2 = NULL;
107   setupConfig = NULL;
108   if (SUCCEEDED(comInitialized))
109     CoUninitialize();
110 }
111
112 bool cmVSSetupAPIHelper::SetVSInstance(std::string const& vsInstallLocation,
113                                        std::string const& vsInstallVersion)
114 {
115   this->SpecifiedVSInstallLocation = vsInstallLocation;
116   cmSystemTools::ConvertToUnixSlashes(this->SpecifiedVSInstallLocation);
117   this->SpecifiedVSInstallVersion = vsInstallVersion;
118   chosenInstanceInfo = VSInstanceInfo();
119   return this->EnumerateAndChooseVSInstance();
120 }
121
122 bool cmVSSetupAPIHelper::IsVSInstalled()
123 {
124   return this->EnumerateAndChooseVSInstance();
125 }
126
127 bool cmVSSetupAPIHelper::IsWin10SDKInstalled()
128 {
129   return (this->EnumerateAndChooseVSInstance() &&
130           chosenInstanceInfo.IsWin10SDKInstalled);
131 }
132
133 bool cmVSSetupAPIHelper::IsWin81SDKInstalled()
134 {
135   return (this->EnumerateAndChooseVSInstance() &&
136           chosenInstanceInfo.IsWin81SDKInstalled);
137 }
138
139 bool cmVSSetupAPIHelper::CheckInstalledComponent(
140   SmartCOMPtr<ISetupPackageReference> package, bool& bWin10SDK,
141   bool& bWin81SDK)
142 {
143   bool ret = false;
144   bWin10SDK = bWin81SDK = false;
145   SmartBSTR bstrId;
146   if (FAILED(package->GetId(&bstrId))) {
147     return ret;
148   }
149
150   SmartBSTR bstrType;
151   if (FAILED(package->GetType(&bstrType))) {
152     return ret;
153   }
154
155   std::wstring id = std::wstring(bstrId);
156   std::wstring type = std::wstring(bstrType);
157
158   // Checks for any version of Win10 SDK. The version is appended at the end of
159   // the
160   // component name ex: Microsoft.VisualStudio.Component.Windows10SDK.10240
161   if (id.find(Win10SDKComponent) != std::wstring::npos &&
162       type.compare(ComponentType) == 0) {
163     bWin10SDK = true;
164     ret = true;
165   }
166
167   if (id.compare(Win81SDKComponent) == 0 && type.compare(ComponentType) == 0) {
168     bWin81SDK = true;
169     ret = true;
170   }
171
172   return ret;
173 }
174
175 // Gather additional info such as if VCToolset, WinSDKs are installed, location
176 // of VS and version information.
177 bool cmVSSetupAPIHelper::GetVSInstanceInfo(
178   SmartCOMPtr<ISetupInstance2> pInstance, VSInstanceInfo& vsInstanceInfo)
179 {
180   if (pInstance == NULL)
181     return false;
182
183   InstanceState state;
184   if (FAILED(pInstance->GetState(&state))) {
185     return false;
186   }
187
188   SmartBSTR bstrVersion;
189   if (FAILED(pInstance->GetInstallationVersion(&bstrVersion))) {
190     return false;
191   } else {
192     vsInstanceInfo.Version =
193       cmsys::Encoding::ToNarrow(std::wstring(bstrVersion));
194   }
195
196   // Reboot may have been required before the installation path was created.
197   SmartBSTR bstrInstallationPath;
198   if ((eLocal & state) == eLocal) {
199     if (FAILED(pInstance->GetInstallationPath(&bstrInstallationPath))) {
200       return false;
201     } else {
202       vsInstanceInfo.VSInstallLocation =
203         cmsys::Encoding::ToNarrow(std::wstring(bstrInstallationPath));
204       cmSystemTools::ConvertToUnixSlashes(vsInstanceInfo.VSInstallLocation);
205     }
206   }
207
208   // Check if a compiler is installed with this instance.
209   if (!LoadVSInstanceVCToolsetVersion(vsInstanceInfo)) {
210     return false;
211   }
212
213   // Reboot may have been required before the product package was registered
214   // (last).
215   if ((eRegistered & state) == eRegistered) {
216     SmartCOMPtr<ISetupPackageReference> product;
217     if (FAILED(pInstance->GetProduct(&product)) || !product) {
218       return false;
219     }
220
221     LPSAFEARRAY lpsaPackages;
222     if (FAILED(pInstance->GetPackages(&lpsaPackages)) ||
223         lpsaPackages == NULL) {
224       return false;
225     }
226
227     int lower = lpsaPackages->rgsabound[0].lLbound;
228     int upper = lpsaPackages->rgsabound[0].cElements + lower;
229
230     IUnknown** ppData = (IUnknown**)lpsaPackages->pvData;
231     for (int i = lower; i < upper; i++) {
232       SmartCOMPtr<ISetupPackageReference> package = NULL;
233       if (FAILED(ppData[i]->QueryInterface(IID_ISetupPackageReference,
234                                            (void**)&package)) ||
235           package == NULL)
236         continue;
237
238       bool win10SDKInstalled = false;
239       bool win81SDkInstalled = false;
240       bool ret =
241         CheckInstalledComponent(package, win10SDKInstalled, win81SDkInstalled);
242       if (ret) {
243         vsInstanceInfo.IsWin10SDKInstalled |= win10SDKInstalled;
244         vsInstanceInfo.IsWin81SDKInstalled |= win81SDkInstalled;
245       }
246     }
247
248     SafeArrayDestroy(lpsaPackages);
249   }
250
251   return true;
252 }
253
254 bool cmVSSetupAPIHelper::GetVSInstanceInfo(std::string& vsInstallLocation)
255 {
256   vsInstallLocation.clear();
257   bool isInstalled = this->EnumerateAndChooseVSInstance();
258
259   if (isInstalled) {
260     vsInstallLocation = chosenInstanceInfo.GetInstallLocation();
261   }
262
263   return isInstalled;
264 }
265
266 bool cmVSSetupAPIHelper::GetVSInstanceVersion(std::string& vsInstanceVersion)
267 {
268   vsInstanceVersion.clear();
269   bool isInstalled = this->EnumerateAndChooseVSInstance();
270
271   if (isInstalled) {
272     vsInstanceVersion = chosenInstanceInfo.Version;
273   }
274
275   return isInstalled;
276 }
277
278 bool cmVSSetupAPIHelper::GetVCToolsetVersion(std::string& vsToolsetVersion)
279 {
280   vsToolsetVersion.clear();
281   bool isInstalled = this->EnumerateAndChooseVSInstance();
282
283   if (isInstalled) {
284     vsToolsetVersion = chosenInstanceInfo.VCToolsetVersion;
285   }
286
287   return isInstalled && !vsToolsetVersion.empty();
288 }
289
290 bool cmVSSetupAPIHelper::IsEWDKEnabled()
291 {
292   std::string envEnterpriseWDK, envDisableRegistryUse;
293   cmSystemTools::GetEnv("EnterpriseWDK", envEnterpriseWDK);
294   cmSystemTools::GetEnv("DisableRegistryUse", envDisableRegistryUse);
295   if (!cmSystemTools::Strucmp(envEnterpriseWDK.c_str(), "True") &&
296       !cmSystemTools::Strucmp(envDisableRegistryUse.c_str(), "True")) {
297     return true;
298   }
299
300   return false;
301 }
302
303 #if !defined(CMAKE_BOOTSTRAP)
304 namespace {
305 std::string FindVsWhereCommand()
306 {
307   std::string vswhere;
308   static const char* programFiles[] = { "ProgramFiles(x86)", "ProgramFiles" };
309   for (const char* pf : programFiles) {
310     if (cmSystemTools::GetEnv(pf, vswhere)) {
311       vswhere += "/Microsoft Visual Studio/Installer/vswhere.exe";
312       if (cmSystemTools::FileExists(vswhere)) {
313         return vswhere;
314       }
315     }
316   }
317   vswhere = "vswhere.exe";
318   return vswhere;
319 }
320 }
321 #endif
322
323 bool cmVSSetupAPIHelper::EnumerateVSInstancesWithVswhere(
324   std::vector<VSInstanceInfo>& VSInstances)
325 {
326 #if !defined(CMAKE_BOOTSTRAP)
327   // Construct vswhere command to get installed VS instances in JSON format
328   std::string vswhereExe = FindVsWhereCommand();
329   std::vector<std::string> vswhereCmd = { vswhereExe, "-format", "json" };
330
331   // Execute vswhere command and capture JSON output
332   std::string json_output;
333   int retVal = 1;
334   if (!cmSystemTools::RunSingleCommand(vswhereCmd, &json_output, &json_output,
335                                        &retVal, nullptr,
336                                        cmSystemTools::OUTPUT_NONE)) {
337     return false;
338   }
339
340   // Parse JSON output and iterate over elements
341   Json::CharReaderBuilder builder;
342   auto jsonReader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
343   Json::Value json;
344   std::string error;
345
346   if (!jsonReader->parse(json_output.data(),
347                          json_output.data() + json_output.size(), &json,
348                          &error)) {
349     return false;
350   }
351
352   for (const auto& item : json) {
353     VSInstanceInfo instance;
354     instance.Version = item["installationVersion"].asString();
355     instance.VSInstallLocation = item["installationPath"].asString();
356     instance.IsWin10SDKInstalled = true;
357     instance.IsWin81SDKInstalled = false;
358     cmSystemTools::ConvertToUnixSlashes(instance.VSInstallLocation);
359     if (LoadVSInstanceVCToolsetVersion(instance)) {
360       VSInstances.push_back(instance);
361     }
362   }
363   return true;
364 #else
365   static_cast<void>(VSInstances);
366   return false;
367 #endif
368 }
369
370 bool cmVSSetupAPIHelper::EnumerateVSInstancesWithCOM(
371   std::vector<VSInstanceInfo>& VSInstances)
372 {
373   if (initializationFailure || setupConfig == NULL || setupConfig2 == NULL ||
374       setupHelper == NULL)
375     return false;
376
377   SmartCOMPtr<IEnumSetupInstances> enumInstances = NULL;
378   if (FAILED(
379         setupConfig2->EnumInstances((IEnumSetupInstances**)&enumInstances)) ||
380       !enumInstances) {
381     return false;
382   }
383
384   SmartCOMPtr<ISetupInstance> instance;
385   while (SUCCEEDED(enumInstances->Next(1, &instance, NULL)) && instance) {
386     SmartCOMPtr<ISetupInstance2> instance2 = NULL;
387     if (FAILED(
388           instance->QueryInterface(IID_ISetupInstance2, (void**)&instance2)) ||
389         !instance2) {
390       instance = NULL;
391       continue;
392     }
393
394     VSInstanceInfo instanceInfo;
395     bool isInstalled = GetVSInstanceInfo(instance2, instanceInfo);
396     instance = instance2 = NULL;
397     if (isInstalled)
398       VSInstances.push_back(instanceInfo);
399   }
400   return true;
401 }
402
403 bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance()
404 {
405   bool isVSInstanceExists = false;
406   if (chosenInstanceInfo.VSInstallLocation.compare("") != 0) {
407     return true;
408   }
409
410   if (this->IsEWDKEnabled()) {
411     std::string envWindowsSdkDir81, envVSVersion, envVsInstallDir;
412
413     cmSystemTools::GetEnv("WindowsSdkDir_81", envWindowsSdkDir81);
414     cmSystemTools::GetEnv("VisualStudioVersion", envVSVersion);
415     cmSystemTools::GetEnv("VSINSTALLDIR", envVsInstallDir);
416     if (envVSVersion.empty() || envVsInstallDir.empty())
417       return false;
418
419     chosenInstanceInfo.VSInstallLocation = envVsInstallDir;
420     chosenInstanceInfo.Version = envVSVersion;
421     if (!LoadVSInstanceVCToolsetVersion(chosenInstanceInfo)) {
422       return false;
423     }
424     chosenInstanceInfo.IsWin10SDKInstalled = true;
425     chosenInstanceInfo.IsWin81SDKInstalled = !envWindowsSdkDir81.empty();
426     return true;
427   }
428
429   std::string envVSCommonToolsDir;
430   std::string envVSCommonToolsDirEnvName =
431     "VS" + std::to_string(this->Version) + "0COMNTOOLS";
432
433   if (cmSystemTools::GetEnv(envVSCommonToolsDirEnvName.c_str(),
434                             envVSCommonToolsDir)) {
435     cmSystemTools::ConvertToUnixSlashes(envVSCommonToolsDir);
436   }
437
438   std::string const wantVersion = std::to_string(this->Version) + '.';
439
440   bool specifiedLocationNotSpecifiedVersion = false;
441
442   SmartCOMPtr<ISetupInstance> instance;
443
444   std::vector<VSInstanceInfo> vecVSInstancesAll;
445
446   // Enumerate VS instances with either COM interface or Vswhere
447   if (!EnumerateVSInstancesWithCOM(vecVSInstancesAll) &&
448       !EnumerateVSInstancesWithVswhere(vecVSInstancesAll)) {
449     return false;
450   }
451
452   std::vector<VSInstanceInfo> vecVSInstances;
453   for (const auto& instanceInfo : vecVSInstancesAll) {
454     // We are looking for a specific major version.
455     if (instanceInfo.Version.size() < wantVersion.size() ||
456         instanceInfo.Version.substr(0, wantVersion.size()) != wantVersion) {
457       continue;
458     }
459
460     if (!this->SpecifiedVSInstallLocation.empty()) {
461       // We are looking for a specific instance.
462       std::string currentVSLocation = instanceInfo.GetInstallLocation();
463       if (cmSystemTools::ComparePath(currentVSLocation,
464                                      this->SpecifiedVSInstallLocation)) {
465         if (this->SpecifiedVSInstallVersion.empty() ||
466             instanceInfo.Version == this->SpecifiedVSInstallVersion) {
467           chosenInstanceInfo = instanceInfo;
468           return true;
469         }
470         specifiedLocationNotSpecifiedVersion = true;
471       }
472     } else if (!this->SpecifiedVSInstallVersion.empty()) {
473       // We are looking for a specific version.
474       if (instanceInfo.Version == this->SpecifiedVSInstallVersion) {
475         chosenInstanceInfo = instanceInfo;
476         return true;
477       }
478     } else {
479       // We are not looking for a specific instance.
480       // If we've been given a hint then use it.
481       if (!envVSCommonToolsDir.empty()) {
482         std::string currentVSLocation =
483           cmStrCat(instanceInfo.GetInstallLocation(), "/Common7/Tools");
484         if (cmSystemTools::ComparePath(currentVSLocation,
485                                        envVSCommonToolsDir)) {
486           chosenInstanceInfo = instanceInfo;
487           return true;
488         }
489       }
490       // Otherwise, add this to the list of candidates.
491       vecVSInstances.push_back(instanceInfo);
492     }
493   }
494
495   if (!this->SpecifiedVSInstallLocation.empty() &&
496       !specifiedLocationNotSpecifiedVersion) {
497     // The VS Installer does not know about the specified location.
498     // Check for one directly on disk.
499     return this->LoadSpecifiedVSInstanceFromDisk();
500   }
501
502   if (vecVSInstances.size() > 0) {
503     isVSInstanceExists = true;
504     int index = ChooseVSInstance(vecVSInstances);
505     chosenInstanceInfo = vecVSInstances[index];
506   }
507
508   return isVSInstanceExists;
509 }
510
511 int cmVSSetupAPIHelper::ChooseVSInstance(
512   const std::vector<VSInstanceInfo>& vecVSInstances)
513 {
514   if (vecVSInstances.size() == 0)
515     return -1;
516
517   if (vecVSInstances.size() == 1)
518     return 0;
519
520   unsigned int chosenIndex = 0;
521   for (unsigned int i = 1; i < vecVSInstances.size(); i++) {
522     // If the current has Win10 SDK but not the chosen one, then choose the
523     // current VS instance
524     if (!vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
525         vecVSInstances[i].IsWin10SDKInstalled) {
526       chosenIndex = i;
527       continue;
528     }
529
530     // If the chosen one has Win10 SDK but the current one is not, then look at
531     // the next VS instance even the current
532     // instance version may be higher
533     if (vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
534         !vecVSInstances[i].IsWin10SDKInstalled) {
535       continue;
536     }
537
538     // If both chosen one and current one doesn't have Win10 SDK but the
539     // current one has Win8.1 SDK installed,
540     // then choose the current one
541     if (!vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
542         !vecVSInstances[i].IsWin10SDKInstalled &&
543         !vecVSInstances[chosenIndex].IsWin81SDKInstalled &&
544         vecVSInstances[i].IsWin81SDKInstalled) {
545       chosenIndex = i;
546       continue;
547     }
548
549     // If there is no difference in WinSDKs then look for the highest version
550     // of installed VS
551     if ((vecVSInstances[chosenIndex].IsWin10SDKInstalled ==
552          vecVSInstances[i].IsWin10SDKInstalled) &&
553         (vecVSInstances[chosenIndex].IsWin81SDKInstalled ==
554          vecVSInstances[i].IsWin81SDKInstalled) &&
555         vecVSInstances[chosenIndex].Version < vecVSInstances[i].Version) {
556       chosenIndex = i;
557       continue;
558     }
559   }
560
561   return chosenIndex;
562 }
563
564 bool cmVSSetupAPIHelper::LoadSpecifiedVSInstanceFromDisk()
565 {
566   if (!cmSystemTools::FileIsDirectory(this->SpecifiedVSInstallLocation)) {
567     return false;
568   }
569   VSInstanceInfo vsInstanceInfo;
570   vsInstanceInfo.VSInstallLocation = this->SpecifiedVSInstallLocation;
571   // FIXME: Is there a better way to get SDK information?
572   vsInstanceInfo.IsWin10SDKInstalled = true;
573   vsInstanceInfo.IsWin81SDKInstalled = false;
574
575   if (!this->SpecifiedVSInstallVersion.empty()) {
576     // Assume the version specified by the user is correct.
577     vsInstanceInfo.Version = this->SpecifiedVSInstallVersion;
578   } else {
579     return false;
580   }
581
582   if (!LoadVSInstanceVCToolsetVersion(vsInstanceInfo)) {
583     return false;
584   }
585
586   chosenInstanceInfo = std::move(vsInstanceInfo);
587   return true;
588 }
589
590 bool cmVSSetupAPIHelper::Initialize()
591 {
592   if (initializationFailure)
593     return false;
594
595   if (FAILED(comInitialized)) {
596     initializationFailure = true;
597     return false;
598   }
599
600   if (FAILED(setupConfig.CoCreateInstance(CLSID_SetupConfiguration, NULL,
601                                           IID_ISetupConfiguration,
602                                           CLSCTX_INPROC_SERVER)) ||
603       setupConfig == NULL) {
604     initializationFailure = true;
605     return false;
606   }
607
608   if (FAILED(setupConfig.QueryInterface(IID_ISetupConfiguration2,
609                                         (void**)&setupConfig2)) ||
610       setupConfig2 == NULL) {
611     initializationFailure = true;
612     return false;
613   }
614
615   if (FAILED(
616         setupConfig.QueryInterface(IID_ISetupHelper, (void**)&setupHelper)) ||
617       setupHelper == NULL) {
618     initializationFailure = true;
619     return false;
620   }
621
622   initializationFailure = false;
623   return true;
624 }