You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

find-visualstudio.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. 'use strict'
  2. const log = require('npmlog')
  3. const execFile = require('child_process').execFile
  4. const fs = require('fs')
  5. const path = require('path').win32
  6. const logWithPrefix = require('./util').logWithPrefix
  7. const regSearchKeys = require('./util').regSearchKeys
  8. function findVisualStudio (nodeSemver, configMsvsVersion, callback) {
  9. const finder = new VisualStudioFinder(nodeSemver, configMsvsVersion,
  10. callback)
  11. finder.findVisualStudio()
  12. }
  13. function VisualStudioFinder (nodeSemver, configMsvsVersion, callback) {
  14. this.nodeSemver = nodeSemver
  15. this.configMsvsVersion = configMsvsVersion
  16. this.callback = callback
  17. this.errorLog = []
  18. this.validVersions = []
  19. }
  20. VisualStudioFinder.prototype = {
  21. log: logWithPrefix(log, 'find VS'),
  22. regSearchKeys: regSearchKeys,
  23. // Logs a message at verbose level, but also saves it to be displayed later
  24. // at error level if an error occurs. This should help diagnose the problem.
  25. addLog: function addLog (message) {
  26. this.log.verbose(message)
  27. this.errorLog.push(message)
  28. },
  29. findVisualStudio: function findVisualStudio () {
  30. this.configVersionYear = null
  31. this.configPath = null
  32. if (this.configMsvsVersion) {
  33. this.addLog('msvs_version was set from command line or npm config')
  34. if (this.configMsvsVersion.match(/^\d{4}$/)) {
  35. this.configVersionYear = parseInt(this.configMsvsVersion, 10)
  36. this.addLog(
  37. `- looking for Visual Studio version ${this.configVersionYear}`)
  38. } else {
  39. this.configPath = path.resolve(this.configMsvsVersion)
  40. this.addLog(
  41. `- looking for Visual Studio installed in "${this.configPath}"`)
  42. }
  43. } else {
  44. this.addLog('msvs_version not set from command line or npm config')
  45. }
  46. if (process.env.VCINSTALLDIR) {
  47. this.envVcInstallDir =
  48. path.resolve(process.env.VCINSTALLDIR, '..')
  49. this.addLog('running in VS Command Prompt, installation path is:\n' +
  50. `"${this.envVcInstallDir}"\n- will only use this version`)
  51. } else {
  52. this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
  53. }
  54. this.findVisualStudio2017OrNewer((info) => {
  55. if (info) {
  56. return this.succeed(info)
  57. }
  58. this.findVisualStudio2015((info) => {
  59. if (info) {
  60. return this.succeed(info)
  61. }
  62. this.findVisualStudio2013((info) => {
  63. if (info) {
  64. return this.succeed(info)
  65. }
  66. this.fail()
  67. })
  68. })
  69. })
  70. },
  71. succeed: function succeed (info) {
  72. this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
  73. `\n"${info.path}"` +
  74. '\nrun with --verbose for detailed information')
  75. process.nextTick(this.callback.bind(null, null, info))
  76. },
  77. fail: function fail () {
  78. if (this.configMsvsVersion && this.envVcInstallDir) {
  79. this.errorLog.push(
  80. 'msvs_version does not match this VS Command Prompt or the',
  81. 'installation cannot be used.')
  82. } else if (this.configMsvsVersion) {
  83. // If msvs_version was specified but finding VS failed, print what would
  84. // have been accepted
  85. this.errorLog.push('')
  86. if (this.validVersions) {
  87. this.errorLog.push('valid versions for msvs_version:')
  88. this.validVersions.forEach((version) => {
  89. this.errorLog.push(`- "${version}"`)
  90. })
  91. } else {
  92. this.errorLog.push('no valid versions for msvs_version were found')
  93. }
  94. }
  95. const errorLog = this.errorLog.join('\n')
  96. // For Windows 80 col console, use up to the column before the one marked
  97. // with X (total 79 chars including logger prefix, 62 chars usable here):
  98. // X
  99. const infoLog = [
  100. '**************************************************************',
  101. 'You need to install the latest version of Visual Studio',
  102. 'including the "Desktop development with C++" workload.',
  103. 'For more information consult the documentation at:',
  104. 'https://github.com/nodejs/node-gyp#on-windows',
  105. '**************************************************************'
  106. ].join('\n')
  107. this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
  108. process.nextTick(this.callback.bind(null, new Error(
  109. 'Could not find any Visual Studio installation to use')))
  110. },
  111. // Invoke the PowerShell script to get information about Visual Studio 2017
  112. // or newer installations
  113. findVisualStudio2017OrNewer: function findVisualStudio2017OrNewer (cb) {
  114. var ps = path.join(process.env.SystemRoot, 'System32',
  115. 'WindowsPowerShell', 'v1.0', 'powershell.exe')
  116. var csFile = path.join(__dirname, 'Find-VisualStudio.cs')
  117. var psArgs = [
  118. '-ExecutionPolicy',
  119. 'Unrestricted',
  120. '-NoProfile',
  121. '-Command',
  122. '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
  123. ]
  124. this.log.silly('Running', ps, psArgs)
  125. var child = execFile(ps, psArgs, { encoding: 'utf8' },
  126. (err, stdout, stderr) => {
  127. this.parseData(err, stdout, stderr, cb)
  128. })
  129. child.stdin.end()
  130. },
  131. // Parse the output of the PowerShell script and look for an installation
  132. // of Visual Studio 2017 or newer to use
  133. parseData: function parseData (err, stdout, stderr, cb) {
  134. this.log.silly('PS stderr = %j', stderr)
  135. const failPowershell = () => {
  136. this.addLog(
  137. 'could not use PowerShell to find Visual Studio 2017 or newer, try re-running with \'--loglevel silly\' for more details')
  138. cb(null)
  139. }
  140. if (err) {
  141. this.log.silly('PS err = %j', err && (err.stack || err))
  142. return failPowershell()
  143. }
  144. var vsInfo
  145. try {
  146. vsInfo = JSON.parse(stdout)
  147. } catch (e) {
  148. this.log.silly('PS stdout = %j', stdout)
  149. this.log.silly(e)
  150. return failPowershell()
  151. }
  152. if (!Array.isArray(vsInfo)) {
  153. this.log.silly('PS stdout = %j', stdout)
  154. return failPowershell()
  155. }
  156. vsInfo = vsInfo.map((info) => {
  157. this.log.silly(`processing installation: "${info.path}"`)
  158. info.path = path.resolve(info.path)
  159. var ret = this.getVersionInfo(info)
  160. ret.path = info.path
  161. ret.msBuild = this.getMSBuild(info, ret.versionYear)
  162. ret.toolset = this.getToolset(info, ret.versionYear)
  163. ret.sdk = this.getSDK(info)
  164. return ret
  165. })
  166. this.log.silly('vsInfo:', vsInfo)
  167. // Remove future versions or errors parsing version number
  168. vsInfo = vsInfo.filter((info) => {
  169. if (info.versionYear) {
  170. return true
  171. }
  172. this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
  173. return false
  174. })
  175. // Sort to place newer versions first
  176. vsInfo.sort((a, b) => b.versionYear - a.versionYear)
  177. for (var i = 0; i < vsInfo.length; ++i) {
  178. const info = vsInfo[i]
  179. this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
  180. `at:\n"${info.path}"`)
  181. if (info.msBuild) {
  182. this.addLog('- found "Visual Studio C++ core features"')
  183. } else {
  184. this.addLog('- "Visual Studio C++ core features" missing')
  185. continue
  186. }
  187. if (info.toolset) {
  188. this.addLog(`- found VC++ toolset: ${info.toolset}`)
  189. } else {
  190. this.addLog('- missing any VC++ toolset')
  191. continue
  192. }
  193. if (info.sdk) {
  194. this.addLog(`- found Windows SDK: ${info.sdk}`)
  195. } else {
  196. this.addLog('- missing any Windows SDK')
  197. continue
  198. }
  199. if (!this.checkConfigVersion(info.versionYear, info.path)) {
  200. continue
  201. }
  202. return cb(info)
  203. }
  204. this.addLog(
  205. 'could not find a version of Visual Studio 2017 or newer to use')
  206. cb(null)
  207. },
  208. // Helper - process version information
  209. getVersionInfo: function getVersionInfo (info) {
  210. const match = /^(\d+)\.(\d+)\..*/.exec(info.version)
  211. if (!match) {
  212. this.log.silly('- failed to parse version:', info.version)
  213. return {}
  214. }
  215. this.log.silly('- version match = %j', match)
  216. var ret = {
  217. version: info.version,
  218. versionMajor: parseInt(match[1], 10),
  219. versionMinor: parseInt(match[2], 10)
  220. }
  221. if (ret.versionMajor === 15) {
  222. ret.versionYear = 2017
  223. return ret
  224. }
  225. if (ret.versionMajor === 16) {
  226. ret.versionYear = 2019
  227. return ret
  228. }
  229. if (ret.versionMajor === 17) {
  230. ret.versionYear = 2022
  231. return ret
  232. }
  233. this.log.silly('- unsupported version:', ret.versionMajor)
  234. return {}
  235. },
  236. msBuildPathExists: function msBuildPathExists (path) {
  237. return fs.existsSync(path)
  238. },
  239. // Helper - process MSBuild information
  240. getMSBuild: function getMSBuild (info, versionYear) {
  241. const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
  242. const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
  243. const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe')
  244. if (info.packages.indexOf(pkg) !== -1) {
  245. this.log.silly('- found VC.MSBuild.Base')
  246. if (versionYear === 2017) {
  247. return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
  248. }
  249. if (versionYear === 2019) {
  250. return msbuildPath
  251. }
  252. }
  253. /**
  254. * Visual Studio 2022 doesn't have the MSBuild package.
  255. * Support for compiling _on_ ARM64 was added in MSVC 14.32.31326,
  256. * so let's leverage it if the user has an ARM64 device.
  257. */
  258. if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
  259. return msbuildPathArm64
  260. } else if (this.msBuildPathExists(msbuildPath)) {
  261. return msbuildPath
  262. }
  263. return null
  264. },
  265. // Helper - process toolset information
  266. getToolset: function getToolset (info, versionYear) {
  267. const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
  268. const express = 'Microsoft.VisualStudio.WDExpress'
  269. if (info.packages.indexOf(pkg) !== -1) {
  270. this.log.silly('- found VC.Tools.x86.x64')
  271. } else if (info.packages.indexOf(express) !== -1) {
  272. this.log.silly('- found Visual Studio Express (looking for toolset)')
  273. } else {
  274. return null
  275. }
  276. if (versionYear === 2017) {
  277. return 'v141'
  278. } else if (versionYear === 2019) {
  279. return 'v142'
  280. } else if (versionYear === 2022) {
  281. return 'v143'
  282. }
  283. this.log.silly('- invalid versionYear:', versionYear)
  284. return null
  285. },
  286. // Helper - process Windows SDK information
  287. getSDK: function getSDK (info) {
  288. const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
  289. const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
  290. const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.'
  291. var Win10or11SDKVer = 0
  292. info.packages.forEach((pkg) => {
  293. if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) {
  294. return
  295. }
  296. const parts = pkg.split('.')
  297. if (parts.length > 5 && parts[5] !== 'Desktop') {
  298. this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg)
  299. return
  300. }
  301. const foundSdkVer = parseInt(parts[4], 10)
  302. if (isNaN(foundSdkVer)) {
  303. // Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
  304. this.log.silly('- failed to parse Win10/11SDK number:', pkg)
  305. return
  306. }
  307. this.log.silly('- found Win10/11SDK:', foundSdkVer)
  308. Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer)
  309. })
  310. if (Win10or11SDKVer !== 0) {
  311. return `10.0.${Win10or11SDKVer}.0`
  312. } else if (info.packages.indexOf(win8SDK) !== -1) {
  313. this.log.silly('- found Win8SDK')
  314. return '8.1'
  315. }
  316. return null
  317. },
  318. // Find an installation of Visual Studio 2015 to use
  319. findVisualStudio2015: function findVisualStudio2015 (cb) {
  320. if (this.nodeSemver.major >= 19) {
  321. this.addLog(
  322. 'not looking for VS2015 as it is only supported up to Node.js 18')
  323. return cb(null)
  324. }
  325. return this.findOldVS({
  326. version: '14.0',
  327. versionMajor: 14,
  328. versionMinor: 0,
  329. versionYear: 2015,
  330. toolset: 'v140'
  331. }, cb)
  332. },
  333. // Find an installation of Visual Studio 2013 to use
  334. findVisualStudio2013: function findVisualStudio2013 (cb) {
  335. if (this.nodeSemver.major >= 9) {
  336. this.addLog(
  337. 'not looking for VS2013 as it is only supported up to Node.js 8')
  338. return cb(null)
  339. }
  340. return this.findOldVS({
  341. version: '12.0',
  342. versionMajor: 12,
  343. versionMinor: 0,
  344. versionYear: 2013,
  345. toolset: 'v120'
  346. }, cb)
  347. },
  348. // Helper - common code for VS2013 and VS2015
  349. findOldVS: function findOldVS (info, cb) {
  350. const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
  351. 'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
  352. const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'
  353. this.addLog(`looking for Visual Studio ${info.versionYear}`)
  354. this.regSearchKeys(regVC7, info.version, [], (err, res) => {
  355. if (err) {
  356. this.addLog('- not found')
  357. return cb(null)
  358. }
  359. const vsPath = path.resolve(res, '..')
  360. this.addLog(`- found in "${vsPath}"`)
  361. const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']
  362. this.regSearchKeys([`${regMSBuild}\\${info.version}`],
  363. 'MSBuildToolsPath', msBuildRegOpts, (err, res) => {
  364. if (err) {
  365. this.addLog(
  366. '- could not find MSBuild in registry for this version')
  367. return cb(null)
  368. }
  369. const msBuild = path.join(res, 'MSBuild.exe')
  370. this.addLog(`- MSBuild in "${msBuild}"`)
  371. if (!this.checkConfigVersion(info.versionYear, vsPath)) {
  372. return cb(null)
  373. }
  374. info.path = vsPath
  375. info.msBuild = msBuild
  376. info.sdk = null
  377. cb(info)
  378. })
  379. })
  380. },
  381. // After finding a usable version of Visual Studio:
  382. // - add it to validVersions to be displayed at the end if a specific
  383. // version was requested and not found;
  384. // - check if this is the version that was requested.
  385. // - check if this matches the Visual Studio Command Prompt
  386. checkConfigVersion: function checkConfigVersion (versionYear, vsPath) {
  387. this.validVersions.push(versionYear)
  388. this.validVersions.push(vsPath)
  389. if (this.configVersionYear && this.configVersionYear !== versionYear) {
  390. this.addLog('- msvs_version does not match this version')
  391. return false
  392. }
  393. if (this.configPath &&
  394. path.relative(this.configPath, vsPath) !== '') {
  395. this.addLog('- msvs_version does not point to this installation')
  396. return false
  397. }
  398. if (this.envVcInstallDir &&
  399. path.relative(this.envVcInstallDir, vsPath) !== '') {
  400. this.addLog('- does not match this Visual Studio Command Prompt')
  401. return false
  402. }
  403. return true
  404. }
  405. }
  406. module.exports = findVisualStudio
  407. module.exports.test = {
  408. VisualStudioFinder: VisualStudioFinder,
  409. findVisualStudio: findVisualStudio
  410. }