MSVCPaths.cpp 25 KB

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