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