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