1 //===-- MSVCPaths.cpp - MSVC path-parsing helpers -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/WindowsDriver/MSVCPaths.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Option/Arg.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/ConvertUTF.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/VersionTuple.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <string>
27 
28 #ifdef _WIN32
29 #define WIN32_LEAN_AND_MEAN
30 #define NOGDI
31 #ifndef NOMINMAX
32 #define NOMINMAX
33 #endif
34 #include <windows.h>
35 #endif
36 
37 #ifdef _MSC_VER
38 // Don't support SetupApi on MinGW.
39 #define USE_MSVC_SETUP_API
40 
41 // Make sure this comes before MSVCSetupApi.h
42 #include <comdef.h>
43 
44 #include "llvm/Support/COM.h"
45 #ifdef __clang__
46 #pragma clang diagnostic push
47 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
48 #endif
49 #include "llvm/WindowsDriver/MSVCSetupApi.h"
50 #ifdef __clang__
51 #pragma clang diagnostic pop
52 #endif
53 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration, __uuidof(ISetupConfiguration));
54 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration2, __uuidof(ISetupConfiguration2));
55 _COM_SMARTPTR_TYPEDEF(ISetupHelper, __uuidof(ISetupHelper));
56 _COM_SMARTPTR_TYPEDEF(IEnumSetupInstances, __uuidof(IEnumSetupInstances));
57 _COM_SMARTPTR_TYPEDEF(ISetupInstance, __uuidof(ISetupInstance));
58 _COM_SMARTPTR_TYPEDEF(ISetupInstance2, __uuidof(ISetupInstance2));
59 #endif
60 
61 static std::string
62 getHighestNumericTupleInDirectory(llvm::vfs::FileSystem &VFS,
63                                   llvm::StringRef Directory) {
64   std::string Highest;
65   llvm::VersionTuple HighestTuple;
66 
67   std::error_code EC;
68   for (llvm::vfs::directory_iterator DirIt = VFS.dir_begin(Directory, EC),
69                                      DirEnd;
70        !EC && DirIt != DirEnd; DirIt.increment(EC)) {
71     auto Status = VFS.status(DirIt->path());
72     if (!Status || !Status->isDirectory())
73       continue;
74     llvm::StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
75     llvm::VersionTuple Tuple;
76     if (Tuple.tryParse(CandidateName)) // tryParse() returns true on error.
77       continue;
78     if (Tuple > HighestTuple) {
79       HighestTuple = Tuple;
80       Highest = CandidateName.str();
81     }
82   }
83 
84   return Highest;
85 }
86 
87 static bool getWindows10SDKVersionFromPath(llvm::vfs::FileSystem &VFS,
88                                            const std::string &SDKPath,
89                                            std::string &SDKVersion) {
90   llvm::SmallString<128> IncludePath(SDKPath);
91   llvm::sys::path::append(IncludePath, "Include");
92   SDKVersion = getHighestNumericTupleInDirectory(VFS, IncludePath);
93   return !SDKVersion.empty();
94 }
95 
96 static bool getWindowsSDKDirViaCommandLine(
97     llvm::vfs::FileSystem &VFS, llvm::Optional<llvm::StringRef> WinSdkDir,
98     llvm::Optional<llvm::StringRef> WinSdkVersion,
99     llvm::Optional<llvm::StringRef> WinSysRoot, std::string &Path, int &Major,
100     std::string &Version) {
101   if (WinSdkDir.hasValue() || WinSysRoot.hasValue()) {
102     // Don't validate the input; trust the value supplied by the user.
103     // The motivation is to prevent unnecessary file and registry access.
104     llvm::VersionTuple SDKVersion;
105     if (WinSdkVersion.hasValue())
106       SDKVersion.tryParse(*WinSdkVersion);
107 
108     if (WinSysRoot.hasValue()) {
109       llvm::SmallString<128> SDKPath(*WinSysRoot);
110       llvm::sys::path::append(SDKPath, "Windows Kits");
111       if (!SDKVersion.empty())
112         llvm::sys::path::append(SDKPath, llvm::Twine(SDKVersion.getMajor()));
113       else
114         llvm::sys::path::append(
115             SDKPath, getHighestNumericTupleInDirectory(VFS, SDKPath));
116       Path = std::string(SDKPath.str());
117     } else {
118       Path = WinSdkDir->str();
119     }
120 
121     if (!SDKVersion.empty()) {
122       Major = SDKVersion.getMajor();
123       Version = SDKVersion.getAsString();
124     } else if (getWindows10SDKVersionFromPath(VFS, Path, Version)) {
125       Major = 10;
126     }
127     return true;
128   }
129   return false;
130 }
131 
132 #ifdef _WIN32
133 static bool readFullStringValue(HKEY hkey, const char *valueName,
134                                 std::string &value) {
135   std::wstring WideValueName;
136   if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
137     return false;
138 
139   DWORD result = 0;
140   DWORD valueSize = 0;
141   DWORD type = 0;
142   // First just query for the required size.
143   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
144                             &valueSize);
145   if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
146     return false;
147   std::vector<BYTE> buffer(valueSize);
148   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
149                             &valueSize);
150   if (result == ERROR_SUCCESS) {
151     std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
152                            valueSize / sizeof(wchar_t));
153     if (valueSize && WideValue.back() == L'\0') {
154       WideValue.pop_back();
155     }
156     // The destination buffer must be empty as an invariant of the conversion
157     // function; but this function is sometimes called in a loop that passes in
158     // the same buffer, however. Simply clear it out so we can overwrite it.
159     value.clear();
160     return llvm::convertWideToUTF8(WideValue, value);
161   }
162   return false;
163 }
164 #endif
165 
166 /// Read registry string.
167 /// This also supports a means to look for high-versioned keys by use
168 /// of a $VERSION placeholder in the key path.
169 /// $VERSION in the key path is a placeholder for the version number,
170 /// causing the highest value path to be searched for and used.
171 /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
172 /// There can be additional characters in the component.  Only the numeric
173 /// characters are compared.  This function only searches HKLM.
174 static bool getSystemRegistryString(const char *keyPath, const char *valueName,
175                                     std::string &value, std::string *phValue) {
176 #ifndef _WIN32
177   return false;
178 #else
179   HKEY hRootKey = HKEY_LOCAL_MACHINE;
180   HKEY hKey = NULL;
181   long lResult;
182   bool returnValue = false;
183 
184   const char *placeHolder = strstr(keyPath, "$VERSION");
185   std::string bestName;
186   // If we have a $VERSION placeholder, do the highest-version search.
187   if (placeHolder) {
188     const char *keyEnd = placeHolder - 1;
189     const char *nextKey = placeHolder;
190     // Find end of previous key.
191     while ((keyEnd > keyPath) && (*keyEnd != '\\'))
192       keyEnd--;
193     // Find end of key containing $VERSION.
194     while (*nextKey && (*nextKey != '\\'))
195       nextKey++;
196     size_t partialKeyLength = keyEnd - keyPath;
197     char partialKey[256];
198     if (partialKeyLength >= sizeof(partialKey))
199       partialKeyLength = sizeof(partialKey) - 1;
200     strncpy(partialKey, keyPath, partialKeyLength);
201     partialKey[partialKeyLength] = '\0';
202     HKEY hTopKey = NULL;
203     lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
204                             &hTopKey);
205     if (lResult == ERROR_SUCCESS) {
206       char keyName[256];
207       double bestValue = 0.0;
208       DWORD index, size = sizeof(keyName) - 1;
209       for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
210                                     NULL, NULL) == ERROR_SUCCESS;
211            index++) {
212         const char *sp = keyName;
213         while (*sp && !llvm::isDigit(*sp))
214           sp++;
215         if (!*sp)
216           continue;
217         const char *ep = sp + 1;
218         while (*ep && (llvm::isDigit(*ep) || (*ep == '.')))
219           ep++;
220         char numBuf[32];
221         strncpy(numBuf, sp, sizeof(numBuf) - 1);
222         numBuf[sizeof(numBuf) - 1] = '\0';
223         double dvalue = strtod(numBuf, NULL);
224         if (dvalue > bestValue) {
225           // Test that InstallDir is indeed there before keeping this index.
226           // Open the chosen key path remainder.
227           bestName = keyName;
228           // Append rest of key.
229           bestName.append(nextKey);
230           lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
231                                   KEY_READ | KEY_WOW64_32KEY, &hKey);
232           if (lResult == ERROR_SUCCESS) {
233             if (readFullStringValue(hKey, valueName, value)) {
234               bestValue = dvalue;
235               if (phValue)
236                 *phValue = bestName;
237               returnValue = true;
238             }
239             RegCloseKey(hKey);
240           }
241         }
242         size = sizeof(keyName) - 1;
243       }
244       RegCloseKey(hTopKey);
245     }
246   } else {
247     lResult =
248         RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
249     if (lResult == ERROR_SUCCESS) {
250       if (readFullStringValue(hKey, valueName, value))
251         returnValue = true;
252       if (phValue)
253         phValue->clear();
254       RegCloseKey(hKey);
255     }
256   }
257   return returnValue;
258 #endif // _WIN32
259 }
260 
261 namespace llvm {
262 
263 const char *archToWindowsSDKArch(Triple::ArchType Arch) {
264   switch (Arch) {
265   case Triple::ArchType::x86:
266     return "x86";
267   case Triple::ArchType::x86_64:
268     return "x64";
269   case Triple::ArchType::arm:
270     return "arm";
271   case Triple::ArchType::aarch64:
272     return "arm64";
273   default:
274     return "";
275   }
276 }
277 
278 const char *archToLegacyVCArch(Triple::ArchType Arch) {
279   switch (Arch) {
280   case Triple::ArchType::x86:
281     // x86 is default in legacy VC toolchains.
282     // e.g. x86 libs are directly in /lib as opposed to /lib/x86.
283     return "";
284   case Triple::ArchType::x86_64:
285     return "amd64";
286   case Triple::ArchType::arm:
287     return "arm";
288   case Triple::ArchType::aarch64:
289     return "arm64";
290   default:
291     return "";
292   }
293 }
294 
295 const char *archToDevDivInternalArch(Triple::ArchType Arch) {
296   switch (Arch) {
297   case Triple::ArchType::x86:
298     return "i386";
299   case Triple::ArchType::x86_64:
300     return "amd64";
301   case Triple::ArchType::arm:
302     return "arm";
303   case Triple::ArchType::aarch64:
304     return "arm64";
305   default:
306     return "";
307   }
308 }
309 
310 bool appendArchToWindowsSDKLibPath(int SDKMajor, SmallString<128> LibPath,
311                                    Triple::ArchType Arch, std::string &path) {
312   if (SDKMajor >= 8) {
313     sys::path::append(LibPath, archToWindowsSDKArch(Arch));
314   } else {
315     switch (Arch) {
316     // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
317     case Triple::x86:
318       break;
319     case Triple::x86_64:
320       sys::path::append(LibPath, "x64");
321       break;
322     case Triple::arm:
323       // It is not necessary to link against Windows SDK 7.x when targeting ARM.
324       return false;
325     default:
326       return false;
327     }
328   }
329 
330   path = std::string(LibPath.str());
331   return true;
332 }
333 
334 std::string getSubDirectoryPath(SubDirectoryType Type, ToolsetLayout VSLayout,
335                                 const std::string &VCToolChainPath,
336                                 Triple::ArchType TargetArch,
337                                 StringRef SubdirParent) {
338   const char *SubdirName;
339   const char *IncludeName;
340   switch (VSLayout) {
341   case ToolsetLayout::OlderVS:
342     SubdirName = archToLegacyVCArch(TargetArch);
343     IncludeName = "include";
344     break;
345   case ToolsetLayout::VS2017OrNewer:
346     SubdirName = archToWindowsSDKArch(TargetArch);
347     IncludeName = "include";
348     break;
349   case ToolsetLayout::DevDivInternal:
350     SubdirName = archToDevDivInternalArch(TargetArch);
351     IncludeName = "inc";
352     break;
353   }
354 
355   SmallString<256> Path(VCToolChainPath);
356   if (!SubdirParent.empty())
357     sys::path::append(Path, SubdirParent);
358 
359   switch (Type) {
360   case SubDirectoryType::Bin:
361     if (VSLayout == ToolsetLayout::VS2017OrNewer) {
362       const bool HostIsX64 = Triple(sys::getProcessTriple()).isArch64Bit();
363       const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
364       sys::path::append(Path, "bin", HostName, SubdirName);
365     } else { // OlderVS or DevDivInternal
366       sys::path::append(Path, "bin", SubdirName);
367     }
368     break;
369   case SubDirectoryType::Include:
370     sys::path::append(Path, IncludeName);
371     break;
372   case SubDirectoryType::Lib:
373     sys::path::append(Path, "lib", SubdirName);
374     break;
375   }
376   return std::string(Path.str());
377 }
378 
379 bool useUniversalCRT(ToolsetLayout VSLayout, const std::string &VCToolChainPath,
380                      Triple::ArchType TargetArch, vfs::FileSystem &VFS) {
381   SmallString<128> TestPath(getSubDirectoryPath(
382       SubDirectoryType::Include, VSLayout, VCToolChainPath, TargetArch));
383   sys::path::append(TestPath, "stdlib.h");
384   return !VFS.exists(TestPath);
385 }
386 
387 bool getWindowsSDKDir(vfs::FileSystem &VFS, Optional<StringRef> WinSdkDir,
388                       Optional<StringRef> WinSdkVersion,
389                       Optional<StringRef> WinSysRoot, std::string &Path,
390                       int &Major, std::string &WindowsSDKIncludeVersion,
391                       std::string &WindowsSDKLibVersion) {
392   // Trust /winsdkdir and /winsdkversion if present.
393   if (getWindowsSDKDirViaCommandLine(VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
394                                      Path, Major, WindowsSDKIncludeVersion)) {
395     WindowsSDKLibVersion = WindowsSDKIncludeVersion;
396     return true;
397   }
398 
399   // FIXME: Try env vars (%WindowsSdkDir%, %UCRTVersion%) before going to
400   // registry.
401 
402   // Try the Windows registry.
403   std::string RegistrySDKVersion;
404   if (!getSystemRegistryString(
405           "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
406           "InstallationFolder", Path, &RegistrySDKVersion))
407     return false;
408   if (Path.empty() || RegistrySDKVersion.empty())
409     return false;
410 
411   WindowsSDKIncludeVersion.clear();
412   WindowsSDKLibVersion.clear();
413   Major = 0;
414   std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
415   if (Major <= 7)
416     return true;
417   if (Major == 8) {
418     // Windows SDK 8.x installs libraries in a folder whose names depend on the
419     // version of the OS you're targeting.  By default choose the newest, which
420     // usually corresponds to the version of the OS you've installed the SDK on.
421     const char *Tests[] = {"winv6.3", "win8", "win7"};
422     for (const char *Test : Tests) {
423       SmallString<128> TestPath(Path);
424       sys::path::append(TestPath, "Lib", Test);
425       if (VFS.exists(TestPath)) {
426         WindowsSDKLibVersion = Test;
427         break;
428       }
429     }
430     return !WindowsSDKLibVersion.empty();
431   }
432   if (Major == 10) {
433     if (!getWindows10SDKVersionFromPath(VFS, Path, WindowsSDKIncludeVersion))
434       return false;
435     WindowsSDKLibVersion = WindowsSDKIncludeVersion;
436     return true;
437   }
438   // Unsupported SDK version
439   return false;
440 }
441 
442 bool getUniversalCRTSdkDir(vfs::FileSystem &VFS, Optional<StringRef> WinSdkDir,
443                            Optional<StringRef> WinSdkVersion,
444                            Optional<StringRef> WinSysRoot, std::string &Path,
445                            std::string &UCRTVersion) {
446   // If /winsdkdir is passed, use it as location for the UCRT too.
447   // FIXME: Should there be a dedicated /ucrtdir to override /winsdkdir?
448   int Major;
449   if (getWindowsSDKDirViaCommandLine(VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
450                                      Path, Major, UCRTVersion))
451     return true;
452 
453   // FIXME: Try env vars (%UniversalCRTSdkDir%, %UCRTVersion%) before going to
454   // registry.
455 
456   // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
457   // for the specific key "KitsRoot10". So do we.
458   if (!getSystemRegistryString(
459           "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
460           Path, nullptr))
461     return false;
462 
463   return getWindows10SDKVersionFromPath(VFS, Path, UCRTVersion);
464 }
465 
466 bool findVCToolChainViaCommandLine(vfs::FileSystem &VFS,
467                                    Optional<StringRef> VCToolsDir,
468                                    Optional<StringRef> VCToolsVersion,
469                                    Optional<StringRef> WinSysRoot,
470                                    std::string &Path, ToolsetLayout &VSLayout) {
471   // Don't validate the input; trust the value supplied by the user.
472   // The primary motivation is to prevent unnecessary file and registry access.
473   if (VCToolsDir.hasValue() || WinSysRoot.hasValue()) {
474     if (WinSysRoot.hasValue()) {
475       SmallString<128> ToolsPath(*WinSysRoot);
476       sys::path::append(ToolsPath, "VC", "Tools", "MSVC");
477       std::string ToolsVersion;
478       if (VCToolsVersion.hasValue())
479         ToolsVersion = VCToolsVersion->str();
480       else
481         ToolsVersion = getHighestNumericTupleInDirectory(VFS, ToolsPath);
482       sys::path::append(ToolsPath, ToolsVersion);
483       Path = std::string(ToolsPath.str());
484     } else {
485       Path = VCToolsDir->str();
486     }
487     VSLayout = ToolsetLayout::VS2017OrNewer;
488     return true;
489   }
490   return false;
491 }
492 
493 bool findVCToolChainViaEnvironment(vfs::FileSystem &VFS, std::string &Path,
494                                    ToolsetLayout &VSLayout) {
495   // These variables are typically set by vcvarsall.bat
496   // when launching a developer command prompt.
497   if (Optional<std::string> VCToolsInstallDir =
498           sys::Process::GetEnv("VCToolsInstallDir")) {
499     // This is only set by newer Visual Studios, and it leads straight to
500     // the toolchain directory.
501     Path = std::move(*VCToolsInstallDir);
502     VSLayout = ToolsetLayout::VS2017OrNewer;
503     return true;
504   }
505   if (Optional<std::string> VCInstallDir =
506           sys::Process::GetEnv("VCINSTALLDIR")) {
507     // If the previous variable isn't set but this one is, then we've found
508     // an older Visual Studio. This variable is set by newer Visual Studios too,
509     // so this check has to appear second.
510     // In older Visual Studios, the VC directory is the toolchain.
511     Path = std::move(*VCInstallDir);
512     VSLayout = ToolsetLayout::OlderVS;
513     return true;
514   }
515 
516   // We couldn't find any VC environment variables. Let's walk through PATH and
517   // see if it leads us to a VC toolchain bin directory. If it does, pick the
518   // first one that we find.
519   if (Optional<std::string> PathEnv = sys::Process::GetEnv("PATH")) {
520     SmallVector<StringRef, 8> PathEntries;
521     StringRef(*PathEnv).split(PathEntries, sys::EnvPathSeparator);
522     for (StringRef PathEntry : PathEntries) {
523       if (PathEntry.empty())
524         continue;
525 
526       SmallString<256> ExeTestPath;
527 
528       // If cl.exe doesn't exist, then this definitely isn't a VC toolchain.
529       ExeTestPath = PathEntry;
530       sys::path::append(ExeTestPath, "cl.exe");
531       if (!VFS.exists(ExeTestPath))
532         continue;
533 
534       // cl.exe existing isn't a conclusive test for a VC toolchain; clang also
535       // has a cl.exe. So let's check for link.exe too.
536       ExeTestPath = PathEntry;
537       sys::path::append(ExeTestPath, "link.exe");
538       if (!VFS.exists(ExeTestPath))
539         continue;
540 
541       // whatever/VC/bin --> old toolchain, VC dir is toolchain dir.
542       StringRef TestPath = PathEntry;
543       bool IsBin = sys::path::filename(TestPath).equals_insensitive("bin");
544       if (!IsBin) {
545         // Strip any architecture subdir like "amd64".
546         TestPath = sys::path::parent_path(TestPath);
547         IsBin = sys::path::filename(TestPath).equals_insensitive("bin");
548       }
549       if (IsBin) {
550         StringRef ParentPath = sys::path::parent_path(TestPath);
551         StringRef ParentFilename = sys::path::filename(ParentPath);
552         if (ParentFilename.equals_insensitive("VC")) {
553           Path = std::string(ParentPath);
554           VSLayout = ToolsetLayout::OlderVS;
555           return true;
556         }
557         if (ParentFilename.equals_insensitive("x86ret") ||
558             ParentFilename.equals_insensitive("x86chk") ||
559             ParentFilename.equals_insensitive("amd64ret") ||
560             ParentFilename.equals_insensitive("amd64chk")) {
561           Path = std::string(ParentPath);
562           VSLayout = ToolsetLayout::DevDivInternal;
563           return true;
564         }
565 
566       } else {
567         // This could be a new (>=VS2017) toolchain. If it is, we should find
568         // path components with these prefixes when walking backwards through
569         // the path.
570         // Note: empty strings match anything.
571         StringRef ExpectedPrefixes[] = {"",     "Host",  "bin", "",
572                                         "MSVC", "Tools", "VC"};
573 
574         auto It = sys::path::rbegin(PathEntry);
575         auto End = sys::path::rend(PathEntry);
576         for (StringRef Prefix : ExpectedPrefixes) {
577           if (It == End)
578             goto NotAToolChain;
579           if (!It->startswith_insensitive(Prefix))
580             goto NotAToolChain;
581           ++It;
582         }
583 
584         // We've found a new toolchain!
585         // Back up 3 times (/bin/Host/arch) to get the root path.
586         StringRef ToolChainPath(PathEntry);
587         for (int i = 0; i < 3; ++i)
588           ToolChainPath = sys::path::parent_path(ToolChainPath);
589 
590         Path = std::string(ToolChainPath);
591         VSLayout = ToolsetLayout::VS2017OrNewer;
592         return true;
593       }
594 
595     NotAToolChain:
596       continue;
597     }
598   }
599   return false;
600 }
601 
602 bool findVCToolChainViaSetupConfig(vfs::FileSystem &VFS, std::string &Path,
603                                    ToolsetLayout &VSLayout) {
604 #if !defined(USE_MSVC_SETUP_API)
605   return false;
606 #else
607   // FIXME: This really should be done once in the top-level program's main
608   // function, as it may have already been initialized with a different
609   // threading model otherwise.
610   sys::InitializeCOMRAII COM(sys::COMThreadingMode::SingleThreaded);
611   HRESULT HR;
612 
613   // _com_ptr_t will throw a _com_error if a COM calls fail.
614   // The LLVM coding standards forbid exception handling, so we'll have to
615   // stop them from being thrown in the first place.
616   // The destructor will put the regular error handler back when we leave
617   // this scope.
618   struct SuppressCOMErrorsRAII {
619     static void __stdcall handler(HRESULT hr, IErrorInfo *perrinfo) {}
620 
621     SuppressCOMErrorsRAII() { _set_com_error_handler(handler); }
622 
623     ~SuppressCOMErrorsRAII() { _set_com_error_handler(_com_raise_error); }
624 
625   } COMErrorSuppressor;
626 
627   ISetupConfigurationPtr Query;
628   HR = Query.CreateInstance(__uuidof(SetupConfiguration));
629   if (FAILED(HR))
630     return false;
631 
632   IEnumSetupInstancesPtr EnumInstances;
633   HR = ISetupConfiguration2Ptr(Query)->EnumAllInstances(&EnumInstances);
634   if (FAILED(HR))
635     return false;
636 
637   ISetupInstancePtr Instance;
638   HR = EnumInstances->Next(1, &Instance, nullptr);
639   if (HR != S_OK)
640     return false;
641 
642   ISetupInstancePtr NewestInstance;
643   Optional<uint64_t> NewestVersionNum;
644   do {
645     bstr_t VersionString;
646     uint64_t VersionNum;
647     HR = Instance->GetInstallationVersion(VersionString.GetAddress());
648     if (FAILED(HR))
649       continue;
650     HR = ISetupHelperPtr(Query)->ParseVersion(VersionString, &VersionNum);
651     if (FAILED(HR))
652       continue;
653     if (!NewestVersionNum || (VersionNum > NewestVersionNum)) {
654       NewestInstance = Instance;
655       NewestVersionNum = VersionNum;
656     }
657   } while ((HR = EnumInstances->Next(1, &Instance, nullptr)) == S_OK);
658 
659   if (!NewestInstance)
660     return false;
661 
662   bstr_t VCPathWide;
663   HR = NewestInstance->ResolvePath(L"VC", VCPathWide.GetAddress());
664   if (FAILED(HR))
665     return false;
666 
667   std::string VCRootPath;
668   convertWideToUTF8(std::wstring(VCPathWide), VCRootPath);
669 
670   SmallString<256> ToolsVersionFilePath(VCRootPath);
671   sys::path::append(ToolsVersionFilePath, "Auxiliary", "Build",
672                     "Microsoft.VCToolsVersion.default.txt");
673 
674   auto ToolsVersionFile = MemoryBuffer::getFile(ToolsVersionFilePath);
675   if (!ToolsVersionFile)
676     return false;
677 
678   SmallString<256> ToolchainPath(VCRootPath);
679   sys::path::append(ToolchainPath, "Tools", "MSVC",
680                     ToolsVersionFile->get()->getBuffer().rtrim());
681   auto Status = VFS.status(ToolchainPath);
682   if (!Status || !Status->isDirectory())
683     return false;
684 
685   Path = std::string(ToolchainPath.str());
686   VSLayout = ToolsetLayout::VS2017OrNewer;
687   return true;
688 #endif
689 }
690 
691 bool findVCToolChainViaRegistry(std::string &Path, ToolsetLayout &VSLayout) {
692   std::string VSInstallPath;
693   if (getSystemRegistryString(R"(SOFTWARE\Microsoft\VisualStudio\$VERSION)",
694                               "InstallDir", VSInstallPath, nullptr) ||
695       getSystemRegistryString(R"(SOFTWARE\Microsoft\VCExpress\$VERSION)",
696                               "InstallDir", VSInstallPath, nullptr)) {
697     if (!VSInstallPath.empty()) {
698       SmallString<256> VCPath(StringRef(VSInstallPath.c_str(),
699                                         VSInstallPath.find(R"(\Common7\IDE)")));
700       sys::path::append(VCPath, "VC");
701 
702       Path = std::string(VCPath.str());
703       VSLayout = ToolsetLayout::OlderVS;
704       return true;
705     }
706   }
707   return false;
708 }
709 
710 } // namespace llvm
711