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