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