MSVCToolChain.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "ToolChains.h"
  10. #include "Tools.h"
  11. #include "clang/Basic/CharInfo.h"
  12. #include "clang/Basic/Version.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Driver/DriverDiagnostic.h"
  16. #include "clang/Driver/Options.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/Option/Arg.h"
  20. #include "llvm/Option/ArgList.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/Process.h"
  24. #include <cstdio>
  25. // Include the necessary headers to interface with the Windows registry and
  26. // environment.
  27. #if defined(LLVM_ON_WIN32)
  28. #define USE_WIN32
  29. #endif
  30. #ifdef USE_WIN32
  31. #define WIN32_LEAN_AND_MEAN
  32. #define NOGDI
  33. #ifndef NOMINMAX
  34. #define NOMINMAX
  35. #endif
  36. #include <windows.h>
  37. #endif
  38. using namespace clang::driver;
  39. using namespace clang::driver::toolchains;
  40. using namespace clang;
  41. using namespace llvm::opt;
  42. MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple& Triple,
  43. const ArgList &Args)
  44. : ToolChain(D, Triple, Args) {
  45. getProgramPaths().push_back(getDriver().getInstalledDir());
  46. if (getDriver().getInstalledDir() != getDriver().Dir)
  47. getProgramPaths().push_back(getDriver().Dir);
  48. }
  49. Tool *MSVCToolChain::buildLinker() const {
  50. return new tools::visualstudio::Linker(*this);
  51. }
  52. Tool *MSVCToolChain::buildAssembler() const {
  53. if (getTriple().isOSBinFormatMachO())
  54. return new tools::darwin::Assembler(*this);
  55. getDriver().Diag(clang::diag::err_no_external_assembler);
  56. return nullptr;
  57. }
  58. bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
  59. return true;
  60. }
  61. bool MSVCToolChain::IsUnwindTablesDefault() const {
  62. // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
  63. // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
  64. // how to generate them yet.
  65. return getArch() == llvm::Triple::x86_64;
  66. }
  67. bool MSVCToolChain::isPICDefault() const {
  68. return getArch() == llvm::Triple::x86_64;
  69. }
  70. bool MSVCToolChain::isPIEDefault() const {
  71. return false;
  72. }
  73. bool MSVCToolChain::isPICDefaultForced() const {
  74. return getArch() == llvm::Triple::x86_64;
  75. }
  76. #ifdef USE_WIN32
  77. static bool readFullStringValue(HKEY hkey, const char *valueName,
  78. std::string &value) {
  79. // FIXME: We should be using the W versions of the registry functions, but
  80. // doing so requires UTF8 / UTF16 conversions similar to how we handle command
  81. // line arguments. The UTF8 conversion functions are not exposed publicly
  82. // from LLVM though, so in order to do this we will probably need to create
  83. // a registry abstraction in LLVMSupport that is Windows only.
  84. DWORD result = 0;
  85. DWORD valueSize = 0;
  86. DWORD type = 0;
  87. // First just query for the required size.
  88. result = RegQueryValueEx(hkey, valueName, NULL, &type, NULL, &valueSize);
  89. if (result != ERROR_SUCCESS || type != REG_SZ)
  90. return false;
  91. std::vector<BYTE> buffer(valueSize);
  92. result = RegQueryValueEx(hkey, valueName, NULL, NULL, &buffer[0], &valueSize);
  93. if (result == ERROR_SUCCESS)
  94. value.assign(reinterpret_cast<const char *>(buffer.data()));
  95. return result;
  96. }
  97. #endif
  98. /// \brief Read registry string.
  99. /// This also supports a means to look for high-versioned keys by use
  100. /// of a $VERSION placeholder in the key path.
  101. /// $VERSION in the key path is a placeholder for the version number,
  102. /// causing the highest value path to be searched for and used.
  103. /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
  104. /// There can be additional characters in the component. Only the numeric
  105. /// characters are compared. This function only searches HKLM.
  106. static bool getSystemRegistryString(const char *keyPath, const char *valueName,
  107. std::string &value, std::string *phValue) {
  108. #ifndef USE_WIN32
  109. return false;
  110. #else
  111. HKEY hRootKey = HKEY_LOCAL_MACHINE;
  112. HKEY hKey = NULL;
  113. long lResult;
  114. bool returnValue = false;
  115. const char *placeHolder = strstr(keyPath, "$VERSION");
  116. std::string bestName;
  117. // If we have a $VERSION placeholder, do the highest-version search.
  118. if (placeHolder) {
  119. const char *keyEnd = placeHolder - 1;
  120. const char *nextKey = placeHolder;
  121. // Find end of previous key.
  122. while ((keyEnd > keyPath) && (*keyEnd != '\\'))
  123. keyEnd--;
  124. // Find end of key containing $VERSION.
  125. while (*nextKey && (*nextKey != '\\'))
  126. nextKey++;
  127. size_t partialKeyLength = keyEnd - keyPath;
  128. char partialKey[256];
  129. if (partialKeyLength > sizeof(partialKey))
  130. partialKeyLength = sizeof(partialKey);
  131. strncpy(partialKey, keyPath, partialKeyLength);
  132. partialKey[partialKeyLength] = '\0';
  133. HKEY hTopKey = NULL;
  134. lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
  135. &hTopKey);
  136. if (lResult == ERROR_SUCCESS) {
  137. char keyName[256];
  138. double bestValue = 0.0;
  139. DWORD index, size = sizeof(keyName) - 1;
  140. for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
  141. NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
  142. const char *sp = keyName;
  143. while (*sp && !isDigit(*sp))
  144. sp++;
  145. if (!*sp)
  146. continue;
  147. const char *ep = sp + 1;
  148. while (*ep && (isDigit(*ep) || (*ep == '.')))
  149. ep++;
  150. char numBuf[32];
  151. strncpy(numBuf, sp, sizeof(numBuf) - 1);
  152. numBuf[sizeof(numBuf) - 1] = '\0';
  153. double dvalue = strtod(numBuf, NULL);
  154. if (dvalue > bestValue) {
  155. // Test that InstallDir is indeed there before keeping this index.
  156. // Open the chosen key path remainder.
  157. bestName = keyName;
  158. // Append rest of key.
  159. bestName.append(nextKey);
  160. lResult = RegOpenKeyEx(hTopKey, bestName.c_str(), 0,
  161. KEY_READ | KEY_WOW64_32KEY, &hKey);
  162. if (lResult == ERROR_SUCCESS) {
  163. lResult = readFullStringValue(hKey, valueName, value);
  164. if (lResult == ERROR_SUCCESS) {
  165. bestValue = dvalue;
  166. if (phValue)
  167. *phValue = bestName;
  168. returnValue = true;
  169. }
  170. RegCloseKey(hKey);
  171. }
  172. }
  173. size = sizeof(keyName) - 1;
  174. }
  175. RegCloseKey(hTopKey);
  176. }
  177. } else {
  178. lResult =
  179. RegOpenKeyEx(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
  180. if (lResult == ERROR_SUCCESS) {
  181. lResult = readFullStringValue(hKey, valueName, value);
  182. if (lResult == ERROR_SUCCESS)
  183. returnValue = true;
  184. if (phValue)
  185. phValue->clear();
  186. RegCloseKey(hKey);
  187. }
  188. }
  189. return returnValue;
  190. #endif // USE_WIN32
  191. }
  192. /// \brief Get Windows SDK installation directory.
  193. bool MSVCToolChain::getWindowsSDKDir(std::string &path, int &major,
  194. int &minor) const {
  195. std::string sdkVersion;
  196. // Try the Windows registry.
  197. bool hasSDKDir = getSystemRegistryString(
  198. "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
  199. "InstallationFolder", path, &sdkVersion);
  200. if (!sdkVersion.empty())
  201. std::sscanf(sdkVersion.c_str(), "v%d.%d", &major, &minor);
  202. return hasSDKDir && !path.empty();
  203. }
  204. // Gets the library path required to link against the Windows SDK.
  205. bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
  206. std::string sdkPath;
  207. int sdkMajor = 0;
  208. int sdkMinor = 0;
  209. path.clear();
  210. if (!getWindowsSDKDir(sdkPath, sdkMajor, sdkMinor))
  211. return false;
  212. llvm::SmallString<128> libPath(sdkPath);
  213. llvm::sys::path::append(libPath, "Lib");
  214. if (sdkMajor <= 7) {
  215. switch (getArch()) {
  216. // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
  217. case llvm::Triple::x86:
  218. break;
  219. case llvm::Triple::x86_64:
  220. llvm::sys::path::append(libPath, "x64");
  221. break;
  222. case llvm::Triple::arm:
  223. // It is not necessary to link against Windows SDK 7.x when targeting ARM.
  224. return false;
  225. default:
  226. return false;
  227. }
  228. } else {
  229. // Windows SDK 8.x installs libraries in a folder whose names depend on the
  230. // version of the OS you're targeting. By default choose the newest, which
  231. // usually corresponds to the version of the OS you've installed the SDK on.
  232. const char *tests[] = {"winv6.3", "win8", "win7"};
  233. bool found = false;
  234. for (const char *test : tests) {
  235. llvm::SmallString<128> testPath(libPath);
  236. llvm::sys::path::append(testPath, test);
  237. if (llvm::sys::fs::exists(testPath.c_str())) {
  238. libPath = testPath;
  239. found = true;
  240. break;
  241. }
  242. }
  243. if (!found)
  244. return false;
  245. llvm::sys::path::append(libPath, "um");
  246. switch (getArch()) {
  247. case llvm::Triple::x86:
  248. llvm::sys::path::append(libPath, "x86");
  249. break;
  250. case llvm::Triple::x86_64:
  251. llvm::sys::path::append(libPath, "x64");
  252. break;
  253. case llvm::Triple::arm:
  254. llvm::sys::path::append(libPath, "arm");
  255. break;
  256. default:
  257. return false;
  258. }
  259. }
  260. path = libPath.str();
  261. return true;
  262. }
  263. // Get the location to use for Visual Studio binaries. The location priority
  264. // is: %VCINSTALLDIR% > %PATH% > newest copy of Visual Studio installed on
  265. // system (as reported by the registry).
  266. bool MSVCToolChain::getVisualStudioBinariesFolder(const char *clangProgramPath,
  267. std::string &path) const {
  268. path.clear();
  269. SmallString<128> BinDir;
  270. // First check the environment variables that vsvars32.bat sets.
  271. llvm::Optional<std::string> VcInstallDir =
  272. llvm::sys::Process::GetEnv("VCINSTALLDIR");
  273. if (VcInstallDir.hasValue()) {
  274. BinDir = VcInstallDir.getValue();
  275. llvm::sys::path::append(BinDir, "bin");
  276. } else {
  277. // Next walk the PATH, trying to find a cl.exe in the path. If we find one,
  278. // use that. However, make sure it's not clang's cl.exe.
  279. llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
  280. if (OptPath.hasValue()) {
  281. const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
  282. SmallVector<StringRef, 8> PathSegments;
  283. llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
  284. for (StringRef PathSegment : PathSegments) {
  285. if (PathSegment.empty())
  286. continue;
  287. SmallString<128> FilePath(PathSegment);
  288. llvm::sys::path::append(FilePath, "cl.exe");
  289. if (llvm::sys::fs::can_execute(FilePath.c_str()) &&
  290. !llvm::sys::fs::equivalent(FilePath.c_str(), clangProgramPath)) {
  291. // If we found it on the PATH, use it exactly as is with no
  292. // modifications.
  293. path = PathSegment;
  294. return true;
  295. }
  296. }
  297. }
  298. std::string installDir;
  299. // With no VCINSTALLDIR and nothing on the PATH, if we can't find it in the
  300. // registry then we have no choice but to fail.
  301. if (!getVisualStudioInstallDir(installDir))
  302. return false;
  303. // Regardless of what binary we're ultimately trying to find, we make sure
  304. // that this is a Visual Studio directory by checking for cl.exe. We use
  305. // cl.exe instead of other binaries like link.exe because programs such as
  306. // GnuWin32 also have a utility called link.exe, so cl.exe is the least
  307. // ambiguous.
  308. BinDir = installDir;
  309. llvm::sys::path::append(BinDir, "VC", "bin");
  310. SmallString<128> ClPath(BinDir);
  311. llvm::sys::path::append(ClPath, "cl.exe");
  312. if (!llvm::sys::fs::can_execute(ClPath.c_str()))
  313. return false;
  314. }
  315. if (BinDir.empty())
  316. return false;
  317. switch (getArch()) {
  318. case llvm::Triple::x86:
  319. break;
  320. case llvm::Triple::x86_64:
  321. llvm::sys::path::append(BinDir, "amd64");
  322. break;
  323. case llvm::Triple::arm:
  324. llvm::sys::path::append(BinDir, "arm");
  325. break;
  326. default:
  327. // Whatever this is, Visual Studio doesn't have a toolchain for it.
  328. return false;
  329. }
  330. path = BinDir.str();
  331. return true;
  332. }
  333. // Get Visual Studio installation directory.
  334. bool MSVCToolChain::getVisualStudioInstallDir(std::string &path) const {
  335. // First check the environment variables that vsvars32.bat sets.
  336. const char *vcinstalldir = getenv("VCINSTALLDIR");
  337. if (vcinstalldir) {
  338. path = vcinstalldir;
  339. path = path.substr(0, path.find("\\VC"));
  340. return true;
  341. }
  342. std::string vsIDEInstallDir;
  343. std::string vsExpressIDEInstallDir;
  344. // Then try the windows registry.
  345. bool hasVCDir =
  346. getSystemRegistryString("SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
  347. "InstallDir", vsIDEInstallDir, nullptr);
  348. if (hasVCDir && !vsIDEInstallDir.empty()) {
  349. path = vsIDEInstallDir.substr(0, vsIDEInstallDir.find("\\Common7\\IDE"));
  350. return true;
  351. }
  352. bool hasVCExpressDir =
  353. getSystemRegistryString("SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
  354. "InstallDir", vsExpressIDEInstallDir, nullptr);
  355. if (hasVCExpressDir && !vsExpressIDEInstallDir.empty()) {
  356. path = vsExpressIDEInstallDir.substr(
  357. 0, vsIDEInstallDir.find("\\Common7\\IDE"));
  358. return true;
  359. }
  360. // Try the environment.
  361. const char *vs120comntools = getenv("VS120COMNTOOLS");
  362. const char *vs100comntools = getenv("VS100COMNTOOLS");
  363. const char *vs90comntools = getenv("VS90COMNTOOLS");
  364. const char *vs80comntools = getenv("VS80COMNTOOLS");
  365. const char *vscomntools = nullptr;
  366. // Find any version we can
  367. if (vs120comntools)
  368. vscomntools = vs120comntools;
  369. else if (vs100comntools)
  370. vscomntools = vs100comntools;
  371. else if (vs90comntools)
  372. vscomntools = vs90comntools;
  373. else if (vs80comntools)
  374. vscomntools = vs80comntools;
  375. if (vscomntools && *vscomntools) {
  376. const char *p = strstr(vscomntools, "\\Common7\\Tools");
  377. path = p ? std::string(vscomntools, p) : vscomntools;
  378. return true;
  379. }
  380. return false;
  381. }
  382. void MSVCToolChain::AddSystemIncludeWithSubfolder(const ArgList &DriverArgs,
  383. ArgStringList &CC1Args,
  384. const std::string &folder,
  385. const char *subfolder) const {
  386. llvm::SmallString<128> path(folder);
  387. llvm::sys::path::append(path, subfolder);
  388. addSystemInclude(DriverArgs, CC1Args, path);
  389. }
  390. void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  391. ArgStringList &CC1Args) const {
  392. if (DriverArgs.hasArg(options::OPT_nostdinc))
  393. return;
  394. if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
  395. SmallString<128> P(getDriver().ResourceDir);
  396. llvm::sys::path::append(P, "include");
  397. addSystemInclude(DriverArgs, CC1Args, P);
  398. }
  399. if (DriverArgs.hasArg(options::OPT_nostdlibinc))
  400. return;
  401. // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
  402. if (const char *cl_include_dir = getenv("INCLUDE")) {
  403. SmallVector<StringRef, 8> Dirs;
  404. StringRef(cl_include_dir)
  405. .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  406. for (StringRef Dir : Dirs)
  407. addSystemInclude(DriverArgs, CC1Args, Dir);
  408. if (!Dirs.empty())
  409. return;
  410. }
  411. std::string VSDir;
  412. // When built with access to the proper Windows APIs, try to actually find
  413. // the correct include paths first.
  414. if (getVisualStudioInstallDir(VSDir)) {
  415. AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, VSDir, "VC\\include");
  416. std::string WindowsSDKDir;
  417. int major, minor;
  418. if (getWindowsSDKDir(WindowsSDKDir, major, minor)) {
  419. if (major >= 8) {
  420. AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
  421. "include\\shared");
  422. AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
  423. "include\\um");
  424. AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
  425. "include\\winrt");
  426. } else {
  427. AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
  428. "include");
  429. }
  430. } else {
  431. addSystemInclude(DriverArgs, CC1Args, VSDir);
  432. }
  433. return;
  434. }
  435. // As a fallback, select default install paths.
  436. // FIXME: Don't guess drives and paths like this on Windows.
  437. const StringRef Paths[] = {
  438. "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
  439. "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
  440. "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
  441. "C:/Program Files/Microsoft Visual Studio 8/VC/include",
  442. "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
  443. };
  444. addSystemIncludes(DriverArgs, CC1Args, Paths);
  445. }
  446. void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  447. ArgStringList &CC1Args) const {
  448. // FIXME: There should probably be logic here to find libc++ on Windows.
  449. }
  450. std::string
  451. MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
  452. types::ID InputType) const {
  453. std::string TripleStr =
  454. ToolChain::ComputeEffectiveClangTriple(Args, InputType);
  455. llvm::Triple Triple(TripleStr);
  456. VersionTuple MSVT =
  457. tools::visualstudio::getMSVCVersion(/*D=*/nullptr, Triple, Args,
  458. /*IsWindowsMSVC=*/true);
  459. if (MSVT.empty())
  460. return TripleStr;
  461. MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
  462. MSVT.getSubminor().getValueOr(0));
  463. if (Triple.getEnvironment() == llvm::Triple::MSVC) {
  464. StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
  465. if (ObjFmt.empty())
  466. Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
  467. else
  468. Triple.setEnvironmentName(
  469. (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
  470. }
  471. return Triple.getTriple();
  472. }
  473. SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
  474. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  475. Res |= SanitizerKind::Address;
  476. return Res;
  477. }