find-visualstudio.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. 'use strict'
  2. const log = require('./log')
  3. const { existsSync } = require('fs')
  4. const { win32: path } = require('path')
  5. const { regSearchKeys, execFile } = require('./util')
  6. class VisualStudioFinder {
  7. static findVisualStudio = (...args) => new VisualStudioFinder(...args).findVisualStudio()
  8. log = log.withPrefix('find VS')
  9. regSearchKeys = regSearchKeys
  10. constructor (nodeSemver, configMsvsVersion) {
  11. this.nodeSemver = nodeSemver
  12. this.configMsvsVersion = configMsvsVersion
  13. this.errorLog = []
  14. this.validVersions = []
  15. }
  16. // Logs a message at verbose level, but also saves it to be displayed later
  17. // at error level if an error occurs. This should help diagnose the problem.
  18. addLog (message) {
  19. this.log.verbose(message)
  20. this.errorLog.push(message)
  21. }
  22. async findVisualStudio () {
  23. this.configVersionYear = null
  24. this.configPath = null
  25. if (this.configMsvsVersion) {
  26. this.addLog('msvs_version was set from command line or npm config')
  27. if (this.configMsvsVersion.match(/^\d{4}$/)) {
  28. this.configVersionYear = parseInt(this.configMsvsVersion, 10)
  29. this.addLog(
  30. `- looking for Visual Studio version ${this.configVersionYear}`)
  31. } else {
  32. this.configPath = path.resolve(this.configMsvsVersion)
  33. this.addLog(
  34. `- looking for Visual Studio installed in "${this.configPath}"`)
  35. }
  36. } else {
  37. this.addLog('msvs_version not set from command line or npm config')
  38. }
  39. if (process.env.VCINSTALLDIR) {
  40. this.envVcInstallDir =
  41. path.resolve(process.env.VCINSTALLDIR, '..')
  42. this.addLog('running in VS Command Prompt, installation path is:\n' +
  43. `"${this.envVcInstallDir}"\n- will only use this version`)
  44. } else {
  45. this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
  46. }
  47. const checks = [
  48. () => this.findVisualStudio2019OrNewerFromSpecifiedLocation(),
  49. () => this.findVisualStudio2019OrNewerUsingSetupModule(),
  50. () => this.findVisualStudio2019OrNewer(),
  51. () => this.findVisualStudio2017FromSpecifiedLocation(),
  52. () => this.findVisualStudio2017UsingSetupModule(),
  53. () => this.findVisualStudio2017(),
  54. () => this.findVisualStudio2015(),
  55. () => this.findVisualStudio2013()
  56. ]
  57. for (const check of checks) {
  58. const info = await check()
  59. if (info) {
  60. return this.succeed(info)
  61. }
  62. }
  63. return this.fail()
  64. }
  65. succeed (info) {
  66. this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
  67. `\n"${info.path}"` +
  68. '\nrun with --verbose for detailed information')
  69. return info
  70. }
  71. fail () {
  72. if (this.configMsvsVersion && this.envVcInstallDir) {
  73. this.errorLog.push(
  74. 'msvs_version does not match this VS Command Prompt or the',
  75. 'installation cannot be used.')
  76. } else if (this.configMsvsVersion) {
  77. // If msvs_version was specified but finding VS failed, print what would
  78. // have been accepted
  79. this.errorLog.push('')
  80. if (this.validVersions) {
  81. this.errorLog.push('valid versions for msvs_version:')
  82. this.validVersions.forEach((version) => {
  83. this.errorLog.push(`- "${version}"`)
  84. })
  85. } else {
  86. this.errorLog.push('no valid versions for msvs_version were found')
  87. }
  88. }
  89. const errorLog = this.errorLog.join('\n')
  90. // For Windows 80 col console, use up to the column before the one marked
  91. // with X (total 79 chars including logger prefix, 62 chars usable here):
  92. // X
  93. const infoLog = [
  94. '**************************************************************',
  95. 'You need to install the latest version of Visual Studio',
  96. 'including the "Desktop development with C++" workload.',
  97. 'For more information consult the documentation at:',
  98. 'https://github.com/nodejs/node-gyp#on-windows',
  99. '**************************************************************'
  100. ].join('\n')
  101. this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
  102. throw new Error('Could not find any Visual Studio installation to use')
  103. }
  104. async findVisualStudio2019OrNewerFromSpecifiedLocation () {
  105. return this.findVSFromSpecifiedLocation([2019, 2022])
  106. }
  107. async findVisualStudio2017FromSpecifiedLocation () {
  108. if (this.nodeSemver.major >= 22) {
  109. this.addLog(
  110. 'not looking for VS2017 as it is only supported up to Node.js 21')
  111. return null
  112. }
  113. return this.findVSFromSpecifiedLocation([2017])
  114. }
  115. async findVSFromSpecifiedLocation (supportedYears) {
  116. if (!this.envVcInstallDir) {
  117. return null
  118. }
  119. const info = {
  120. path: path.resolve(this.envVcInstallDir),
  121. // Assume the version specified by the user is correct.
  122. // Since Visual Studio 2015, the Developer Command Prompt sets the
  123. // VSCMD_VER environment variable which contains the version information
  124. // for Visual Studio.
  125. // https://learn.microsoft.com/en-us/visualstudio/ide/reference/command-prompt-powershell?view=vs-2022
  126. version: process.env.VSCMD_VER,
  127. packages: [
  128. 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
  129. 'Microsoft.VisualStudio.Component.VC.Tools.ARM64',
  130. // Assume MSBuild exists. It will be checked in processing.
  131. 'Microsoft.VisualStudio.VC.MSBuild.Base'
  132. ]
  133. }
  134. // Is there a better way to get SDK information?
  135. const envWindowsSDKVersion = process.env.WindowsSDKVersion
  136. const sdkVersionMatched = envWindowsSDKVersion?.match(/^(\d+)\.(\d+)\.(\d+)\..*/)
  137. if (sdkVersionMatched) {
  138. info.packages.push(`Microsoft.VisualStudio.Component.Windows10SDK.${sdkVersionMatched[3]}.Desktop`)
  139. }
  140. // pass for further processing
  141. return this.processData([info], supportedYears)
  142. }
  143. async findVisualStudio2019OrNewerUsingSetupModule () {
  144. return this.findNewVSUsingSetupModule([2019, 2022])
  145. }
  146. async findVisualStudio2017UsingSetupModule () {
  147. if (this.nodeSemver.major >= 22) {
  148. this.addLog(
  149. 'not looking for VS2017 as it is only supported up to Node.js 21')
  150. return null
  151. }
  152. return this.findNewVSUsingSetupModule([2017])
  153. }
  154. async findNewVSUsingSetupModule (supportedYears) {
  155. const ps = path.join(process.env.SystemRoot, 'System32',
  156. 'WindowsPowerShell', 'v1.0', 'powershell.exe')
  157. const vcInstallDir = this.envVcInstallDir
  158. const checkModuleArgs = [
  159. '-NoProfile',
  160. '-Command',
  161. '&{@(Get-Module -ListAvailable -Name VSSetup).Version.ToString()}'
  162. ]
  163. this.log.silly('Running', ps, checkModuleArgs)
  164. const [cErr] = await this.execFile(ps, checkModuleArgs)
  165. if (cErr) {
  166. this.addLog('VSSetup module doesn\'t seem to exist. You can install it via: "Install-Module VSSetup -Scope CurrentUser"')
  167. this.log.silly('VSSetup error = %j', cErr && (cErr.stack || cErr))
  168. return null
  169. }
  170. const filterArg = vcInstallDir !== undefined ? `| where {$_.InstallationPath -eq '${vcInstallDir}' }` : ''
  171. const psArgs = [
  172. '-NoProfile',
  173. '-Command',
  174. `&{Get-VSSetupInstance ${filterArg} | ConvertTo-Json -Depth 3}`
  175. ]
  176. this.log.silly('Running', ps, psArgs)
  177. const [err, stdout, stderr] = await this.execFile(ps, psArgs)
  178. let parsedData = this.parseData(err, stdout, stderr)
  179. if (parsedData === null) {
  180. return null
  181. }
  182. this.log.silly('Parsed data', parsedData)
  183. if (!Array.isArray(parsedData)) {
  184. // if there are only 1 result, then Powershell will output non-array
  185. parsedData = [parsedData]
  186. }
  187. // normalize output
  188. parsedData = parsedData.map((info) => {
  189. info.path = info.InstallationPath
  190. info.version = `${info.InstallationVersion.Major}.${info.InstallationVersion.Minor}.${info.InstallationVersion.Build}.${info.InstallationVersion.Revision}`
  191. info.packages = info.Packages.map((p) => p.Id)
  192. return info
  193. })
  194. // pass for further processing
  195. return this.processData(parsedData, supportedYears)
  196. }
  197. // Invoke the PowerShell script to get information about Visual Studio 2019
  198. // or newer installations
  199. async findVisualStudio2019OrNewer () {
  200. return this.findNewVS([2019, 2022])
  201. }
  202. // Invoke the PowerShell script to get information about Visual Studio 2017
  203. async findVisualStudio2017 () {
  204. if (this.nodeSemver.major >= 22) {
  205. this.addLog(
  206. 'not looking for VS2017 as it is only supported up to Node.js 21')
  207. return null
  208. }
  209. return this.findNewVS([2017])
  210. }
  211. // Invoke the PowerShell script to get information about Visual Studio 2017
  212. // or newer installations
  213. async findNewVS (supportedYears) {
  214. const ps = path.join(process.env.SystemRoot, 'System32',
  215. 'WindowsPowerShell', 'v1.0', 'powershell.exe')
  216. const csFile = path.join(__dirname, 'Find-VisualStudio.cs')
  217. const psArgs = [
  218. '-ExecutionPolicy',
  219. 'Unrestricted',
  220. '-NoProfile',
  221. '-Command',
  222. '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
  223. ]
  224. this.log.silly('Running', ps, psArgs)
  225. const [err, stdout, stderr] = await this.execFile(ps, psArgs)
  226. const parsedData = this.parseData(err, stdout, stderr, { checkIsArray: true })
  227. if (parsedData === null) {
  228. return null
  229. }
  230. return this.processData(parsedData, supportedYears)
  231. }
  232. // Parse the output of the PowerShell script, make sanity checks
  233. parseData (err, stdout, stderr, sanityCheckOptions) {
  234. const defaultOptions = {
  235. checkIsArray: false
  236. }
  237. // Merging provided options with the default options
  238. const sanityOptions = { ...defaultOptions, ...sanityCheckOptions }
  239. this.log.silly('PS stderr = %j', stderr)
  240. const failPowershell = (failureDetails) => {
  241. this.addLog(
  242. `could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details. \n
  243. Failure details: ${failureDetails}`)
  244. return null
  245. }
  246. if (err) {
  247. this.log.silly('PS err = %j', err && (err.stack || err))
  248. return failPowershell(`${err}`.substring(0, 40))
  249. }
  250. let vsInfo
  251. try {
  252. vsInfo = JSON.parse(stdout)
  253. } catch (e) {
  254. this.log.silly('PS stdout = %j', stdout)
  255. this.log.silly(e)
  256. return failPowershell()
  257. }
  258. if (sanityOptions.checkIsArray && !Array.isArray(vsInfo)) {
  259. this.log.silly('PS stdout = %j', stdout)
  260. return failPowershell('Expected array as output of the PS script')
  261. }
  262. return vsInfo
  263. }
  264. // Process parsed data containing information about VS installations
  265. // Look for the required parts, extract and output them back
  266. processData (vsInfo, supportedYears) {
  267. vsInfo = vsInfo.map((info) => {
  268. this.log.silly(`processing installation: "${info.path}"`)
  269. info.path = path.resolve(info.path)
  270. const ret = this.getVersionInfo(info)
  271. ret.path = info.path
  272. ret.msBuild = this.getMSBuild(info, ret.versionYear)
  273. ret.toolset = this.getToolset(info, ret.versionYear)
  274. ret.sdk = this.getSDK(info)
  275. return ret
  276. })
  277. this.log.silly('vsInfo:', vsInfo)
  278. // Remove future versions or errors parsing version number
  279. // Also remove any unsupported versions
  280. vsInfo = vsInfo.filter((info) => {
  281. if (info.versionYear && supportedYears.indexOf(info.versionYear) !== -1) {
  282. return true
  283. }
  284. this.addLog(`${info.versionYear ? 'unsupported' : 'unknown'} version "${info.version}" found at "${info.path}"`)
  285. return false
  286. })
  287. // Sort to place newer versions first
  288. vsInfo.sort((a, b) => b.versionYear - a.versionYear)
  289. for (let i = 0; i < vsInfo.length; ++i) {
  290. const info = vsInfo[i]
  291. this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
  292. `at:\n"${info.path}"`)
  293. if (info.msBuild) {
  294. this.addLog('- found "Visual Studio C++ core features"')
  295. } else {
  296. this.addLog('- "Visual Studio C++ core features" missing')
  297. continue
  298. }
  299. if (info.toolset) {
  300. this.addLog(`- found VC++ toolset: ${info.toolset}`)
  301. } else {
  302. this.addLog('- missing any VC++ toolset')
  303. continue
  304. }
  305. if (info.sdk) {
  306. this.addLog(`- found Windows SDK: ${info.sdk}`)
  307. } else {
  308. this.addLog('- missing any Windows SDK')
  309. continue
  310. }
  311. if (!this.checkConfigVersion(info.versionYear, info.path)) {
  312. continue
  313. }
  314. return info
  315. }
  316. this.addLog(
  317. 'could not find a version of Visual Studio 2017 or newer to use')
  318. return null
  319. }
  320. // Helper - process version information
  321. getVersionInfo (info) {
  322. const match = /^(\d+)\.(\d+)(?:\..*)?/.exec(info.version)
  323. if (!match) {
  324. this.log.silly('- failed to parse version:', info.version)
  325. return {}
  326. }
  327. this.log.silly('- version match = %j', match)
  328. const ret = {
  329. version: info.version,
  330. versionMajor: parseInt(match[1], 10),
  331. versionMinor: parseInt(match[2], 10)
  332. }
  333. if (ret.versionMajor === 15) {
  334. ret.versionYear = 2017
  335. return ret
  336. }
  337. if (ret.versionMajor === 16) {
  338. ret.versionYear = 2019
  339. return ret
  340. }
  341. if (ret.versionMajor === 17) {
  342. ret.versionYear = 2022
  343. return ret
  344. }
  345. this.log.silly('- unsupported version:', ret.versionMajor)
  346. return {}
  347. }
  348. msBuildPathExists (path) {
  349. return existsSync(path)
  350. }
  351. // Helper - process MSBuild information
  352. getMSBuild (info, versionYear) {
  353. const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
  354. const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
  355. const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe')
  356. if (info.packages.indexOf(pkg) !== -1) {
  357. this.log.silly('- found VC.MSBuild.Base')
  358. if (versionYear === 2017) {
  359. return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
  360. }
  361. if (versionYear === 2019) {
  362. if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
  363. return msbuildPathArm64
  364. } else {
  365. return msbuildPath
  366. }
  367. }
  368. }
  369. /**
  370. * Visual Studio 2022 doesn't have the MSBuild package.
  371. * Support for compiling _on_ ARM64 was added in MSVC 14.32.31326,
  372. * so let's leverage it if the user has an ARM64 device.
  373. */
  374. if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
  375. return msbuildPathArm64
  376. } else if (this.msBuildPathExists(msbuildPath)) {
  377. return msbuildPath
  378. }
  379. return null
  380. }
  381. // Helper - process toolset information
  382. getToolset (info, versionYear) {
  383. const vcToolsArm64 = 'VC.Tools.ARM64'
  384. const pkgArm64 = `Microsoft.VisualStudio.Component.${vcToolsArm64}`
  385. const vcToolsX64 = 'VC.Tools.x86.x64'
  386. const pkgX64 = `Microsoft.VisualStudio.Component.${vcToolsX64}`
  387. const express = 'Microsoft.VisualStudio.WDExpress'
  388. if (process.arch === 'arm64' && info.packages.includes(pkgArm64)) {
  389. this.log.silly(`- found ${vcToolsArm64}`)
  390. } else if (info.packages.includes(pkgX64)) {
  391. if (process.arch === 'arm64') {
  392. this.addLog(`- found ${vcToolsX64} on ARM64 platform. Expect less performance and/or link failure with ARM64 binary.`)
  393. } else {
  394. this.log.silly(`- found ${vcToolsX64}`)
  395. }
  396. } else if (info.packages.includes(express)) {
  397. this.log.silly('- found Visual Studio Express (looking for toolset)')
  398. } else {
  399. return null
  400. }
  401. if (versionYear === 2017) {
  402. return 'v141'
  403. } else if (versionYear === 2019) {
  404. return 'v142'
  405. } else if (versionYear === 2022) {
  406. return 'v143'
  407. }
  408. this.log.silly('- invalid versionYear:', versionYear)
  409. return null
  410. }
  411. // Helper - process Windows SDK information
  412. getSDK (info) {
  413. const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
  414. const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
  415. const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.'
  416. let Win10or11SDKVer = 0
  417. info.packages.forEach((pkg) => {
  418. if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) {
  419. return
  420. }
  421. const parts = pkg.split('.')
  422. if (parts.length > 5 && parts[5] !== 'Desktop') {
  423. this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg)
  424. return
  425. }
  426. const foundSdkVer = parseInt(parts[4], 10)
  427. if (isNaN(foundSdkVer)) {
  428. // Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
  429. this.log.silly('- failed to parse Win10/11SDK number:', pkg)
  430. return
  431. }
  432. this.log.silly('- found Win10/11SDK:', foundSdkVer)
  433. Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer)
  434. })
  435. if (Win10or11SDKVer !== 0) {
  436. return `10.0.${Win10or11SDKVer}.0`
  437. } else if (info.packages.indexOf(win8SDK) !== -1) {
  438. this.log.silly('- found Win8SDK')
  439. return '8.1'
  440. }
  441. return null
  442. }
  443. // Find an installation of Visual Studio 2015 to use
  444. async findVisualStudio2015 () {
  445. if (this.nodeSemver.major >= 19) {
  446. this.addLog(
  447. 'not looking for VS2015 as it is only supported up to Node.js 18')
  448. return null
  449. }
  450. return this.findOldVS({
  451. version: '14.0',
  452. versionMajor: 14,
  453. versionMinor: 0,
  454. versionYear: 2015,
  455. toolset: 'v140'
  456. })
  457. }
  458. // Find an installation of Visual Studio 2013 to use
  459. async findVisualStudio2013 () {
  460. if (this.nodeSemver.major >= 9) {
  461. this.addLog(
  462. 'not looking for VS2013 as it is only supported up to Node.js 8')
  463. return null
  464. }
  465. return this.findOldVS({
  466. version: '12.0',
  467. versionMajor: 12,
  468. versionMinor: 0,
  469. versionYear: 2013,
  470. toolset: 'v120'
  471. })
  472. }
  473. // Helper - common code for VS2013 and VS2015
  474. async findOldVS (info) {
  475. const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
  476. 'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
  477. const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'
  478. this.addLog(`looking for Visual Studio ${info.versionYear}`)
  479. try {
  480. let res = await this.regSearchKeys(regVC7, info.version, [])
  481. const vsPath = path.resolve(res, '..')
  482. this.addLog(`- found in "${vsPath}"`)
  483. const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']
  484. try {
  485. res = await this.regSearchKeys([`${regMSBuild}\\${info.version}`], 'MSBuildToolsPath', msBuildRegOpts)
  486. } catch (err) {
  487. this.addLog('- could not find MSBuild in registry for this version')
  488. return null
  489. }
  490. const msBuild = path.join(res, 'MSBuild.exe')
  491. this.addLog(`- MSBuild in "${msBuild}"`)
  492. if (!this.checkConfigVersion(info.versionYear, vsPath)) {
  493. return null
  494. }
  495. info.path = vsPath
  496. info.msBuild = msBuild
  497. info.sdk = null
  498. return info
  499. } catch (err) {
  500. this.addLog('- not found')
  501. return null
  502. }
  503. }
  504. // After finding a usable version of Visual Studio:
  505. // - add it to validVersions to be displayed at the end if a specific
  506. // version was requested and not found;
  507. // - check if this is the version that was requested.
  508. // - check if this matches the Visual Studio Command Prompt
  509. checkConfigVersion (versionYear, vsPath) {
  510. this.validVersions.push(versionYear)
  511. this.validVersions.push(vsPath)
  512. if (this.configVersionYear && this.configVersionYear !== versionYear) {
  513. this.addLog('- msvs_version does not match this version')
  514. return false
  515. }
  516. if (this.configPath &&
  517. path.relative(this.configPath, vsPath) !== '') {
  518. this.addLog('- msvs_version does not point to this installation')
  519. return false
  520. }
  521. if (this.envVcInstallDir &&
  522. path.relative(this.envVcInstallDir, vsPath) !== '') {
  523. this.addLog('- does not match this Visual Studio Command Prompt')
  524. return false
  525. }
  526. return true
  527. }
  528. async execFile (exec, args) {
  529. return await execFile(exec, args, { encoding: 'utf8' })
  530. }
  531. }
  532. module.exports = VisualStudioFinder