visual_studio.dart 20 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:meta/meta.dart';
6
import 'package:process/process.dart';
7

8
import '../base/common.dart';
9
import '../base/file_system.dart';
10
import '../base/io.dart';
11
import '../base/logger.dart';
12
import '../base/platform.dart';
13
import '../base/process.dart';
14
import '../base/version.dart';
15 16 17 18
import '../convert.dart';

/// Encapsulates information about the installed copy of Visual Studio, if any.
class VisualStudio {
19
  VisualStudio({
20 21 22 23
    required FileSystem fileSystem,
    required ProcessManager processManager,
    required Platform platform,
    required Logger logger,
24 25
  }) : _platform = platform,
       _fileSystem = fileSystem,
26 27
       _processUtils = ProcessUtils(processManager: processManager, logger: logger),
       _logger = logger;
28 29 30 31

  final FileSystem _fileSystem;
  final Platform _platform;
  final ProcessUtils _processUtils;
32 33 34 35
  final Logger _logger;

  /// Matches the description property from the vswhere.exe JSON output.
  final RegExp _vswhereDescriptionProperty = RegExp(r'\s*"description"\s*:\s*".*"\s*,?');
36

37
  /// True if Visual Studio installation was found.
38 39 40 41
  ///
  /// Versions older than 2017 Update 2 won't be detected, so error messages to
  /// users should take into account that [false] may mean that the user may
  /// have an old version rather than no installation at all.
42
  bool get isInstalled => _bestVisualStudioDetails != null;
43

44
  bool get isAtLeastMinimumVersion {
45
    final int? installedMajorVersion = _majorVersion;
46 47 48
    return installedMajorVersion != null && installedMajorVersion >= _minimumSupportedVersion;
  }

49 50
  /// True if there is a version of Visual Studio with all the components
  /// necessary to build the project.
51
  bool get hasNecessaryComponents => _bestVisualStudioDetails?.isUsable ?? false;
52 53 54

  /// The name of the Visual Studio install.
  ///
55 56
  /// For instance: "Visual Studio Community 2019". This should only be used for
  /// display purposes.
57
  String? get displayName => _bestVisualStudioDetails?.displayName;
58 59 60

  /// The user-friendly version number of the Visual Studio install.
  ///
61 62
  /// For instance: "15.4.0". This should only be used for display purposes.
  /// Logic based off the installation's version should use the `fullVersion`.
63
  String? get displayVersion => _bestVisualStudioDetails?.catalogDisplayVersion;
64 65

  /// The directory where Visual Studio is installed.
66
  String? get installLocation => _bestVisualStudioDetails?.installationPath;
67 68 69 70

  /// The full version of the Visual Studio install.
  ///
  /// For instance: "15.4.27004.2002".
71
  String? get fullVersion => _bestVisualStudioDetails?.fullVersion;
72

73 74 75 76
  // Properties that determine the status of the installation. There might be
  // Visual Studio versions that don't include them, so default to a "valid" value to
  // avoid false negatives.

77 78 79 80
  /// True if there is a complete installation of Visual Studio.
  ///
  /// False if installation is not found.
  bool get isComplete {
81
    if (_bestVisualStudioDetails == null) {
82 83
      return false;
    }
84
    return _bestVisualStudioDetails!.isComplete ?? true;
85
  }
86 87

  /// True if Visual Studio is launchable.
88 89 90
  ///
  /// False if installation is not found.
  bool get isLaunchable {
91
    if (_bestVisualStudioDetails == null) {
92 93
      return false;
    }
94
    return _bestVisualStudioDetails!.isLaunchable ?? true;
95
  }
96

97 98
  /// True if the Visual Studio installation is a pre-release version.
  bool get isPrerelease => _bestVisualStudioDetails?.isPrerelease ?? false;
99 100

  /// True if a reboot is required to complete the Visual Studio installation.
101
  bool get isRebootRequired => _bestVisualStudioDetails?.isRebootRequired ?? false;
102

103 104 105
  /// The name of the recommended Visual Studio installer workload.
  String get workloadDescription => 'Desktop development with C++';

106 107 108
  /// Returns the highest installed Windows 10 SDK version, or null if none is
  /// found.
  ///
109
  /// For instance: 10.0.18362.0.
110 111
  String? getWindows10SDKVersion() {
    final String? sdkLocation = _getWindows10SdkLocation();
112 113 114 115 116 117 118 119
    if (sdkLocation == null) {
      return null;
    }
    final Directory sdkIncludeDirectory = _fileSystem.directory(sdkLocation).childDirectory('Include');
    if (!sdkIncludeDirectory.existsSync()) {
      return null;
    }
    // The directories in this folder are named by the SDK version.
120
    Version? highestVersion;
121 122 123 124
    for (final FileSystemEntity versionEntry in sdkIncludeDirectory.listSync()) {
      if (versionEntry.basename.startsWith('10.')) {
        // Version only handles 3 components; strip off the '10.' to leave three
        // components, since they all start with that.
125 126
        final Version? version = Version.parse(versionEntry.basename.substring(3));
        if (highestVersion == null || (version != null && version > highestVersion)) {
127 128 129 130 131 132 133 134 135 136
          highestVersion = version;
        }
      }
    }
    if (highestVersion == null) {
      return null;
    }
    return '10.$highestVersion';
  }

137 138
  /// The names of the components within the workload that must be installed.
  ///
139 140 141 142 143 144 145
  /// The descriptions of some components differ from version to version. When
  /// a supported version is present, the descriptions used will be for that
  /// version.
  List<String> necessaryComponentDescriptions() {
    return _requiredComponents().values.toList();
  }

146
  /// The consumer-facing version name of the minimum supported version.
147 148 149 150
  ///
  /// E.g., for Visual Studio 2019 this returns "2019" rather than "16".
  String get minimumVersionDescription {
    return '2019';
151 152
  }

153
  /// The path to CMake, or null if no Visual Studio installation has
154
  /// the components necessary to build.
155
  String? get cmakePath {
156 157
    final VswhereDetails? details = _bestVisualStudioDetails;
    if (details == null || !details.isUsable || details.installationPath == null) {
158 159
      return null;
    }
160

161
    return _fileSystem.path.joinAll(<String>[
162
      details.installationPath!,
163 164 165 166 167 168 169 170 171
      'Common7',
      'IDE',
      'CommonExtensions',
      'Microsoft',
      'CMake',
      'CMake',
      'bin',
      'cmake.exe',
    ]);
172 173
  }

174 175 176 177 178 179 180 181 182 183 184 185 186
  /// The generator string to pass to CMake to select this Visual Studio
  /// version.
  String? get cmakeGenerator {
    // From https://cmake.org/cmake/help/v3.22/manual/cmake-generators.7.html#visual-studio-generators
    switch (_majorVersion) {
      case 17:
        return 'Visual Studio 17 2022';
      case 16:
      default:
        return 'Visual Studio 16 2019';
    }
  }

187
  /// The major version of the Visual Studio install, as an integer.
188
  int? get _majorVersion => fullVersion != null ? int.tryParse(fullVersion!.split('.')[0]) : null;
189

190 191 192 193 194 195
  /// The path to vswhere.exe.
  ///
  /// vswhere should be installed for VS 2017 Update 2 and later; if it's not
  /// present then there isn't a new enough installation of VS. This path is
  /// not user-controllable, unlike the install location of Visual Studio
  /// itself.
196 197 198 199 200 201 202 203 204 205 206 207
  String get _vswherePath {
    const String programFilesEnv = 'PROGRAMFILES(X86)';
    if (!_platform.environment.containsKey(programFilesEnv)) {
      throwToolExit('%$programFilesEnv% environment variable not found.');
    }
    return _fileSystem.path.join(
      _platform.environment[programFilesEnv]!,
      'Microsoft Visual Studio',
      'Installer',
      'vswhere.exe',
    );
  }
208

209 210
  /// Workload ID for use with vswhere requirements.
  ///
211
  /// Workload ID is different between Visual Studio IDE and Build Tools.
212
  /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
213 214
  static const List<String> _requiredWorkloads = <String>[
    'Microsoft.VisualStudio.Workload.NativeDesktop',
215
    'Microsoft.VisualStudio.Workload.VCTools',
216
  ];
217

218
  /// Components for use with vswhere requirements.
219 220 221
  ///
  /// Maps from component IDs to description in the installer UI.
  /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
222
  Map<String, String> _requiredComponents([int? majorVersion]) {
223 224
    // The description of the C++ toolchain required by the template. The
    // component name is significantly different in different versions.
225
    // When a new major version of VS is supported, its toolchain description
226 227 228 229 230 231 232 233
    // should be added below. It should also be made the default, so that when
    // there is no installation, the message shows the string that will be
    // relevant for the most likely fresh install case).
    String cppToolchainDescription;
    switch (majorVersion ?? _majorVersion) {
      case 16:
      default:
        cppToolchainDescription = 'MSVC v142 - VS 2019 C++ x64/x86 build tools';
234
    }
235 236 237 238 239
    // The 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' ID is assigned to the latest
    // release of the toolchain, and there can be minor updates within a given version of
    // Visual Studio. Since it changes over time, listing a precise version would become
    // wrong after each VC++ toolchain update, so just instruct people to install the
    // latest version.
240
    cppToolchainDescription += '\n   - If there are multiple build tool versions available, install the latest';
241 242
    // Things which are required by the workload (e.g., MSBuild) don't need to
    // be included here.
243 244 245
    return <String, String>{
      // The C++ toolchain required by the template.
      'Microsoft.VisualStudio.Component.VC.Tools.x86.x64': cppToolchainDescription,
246 247
      // CMake
      'Microsoft.VisualStudio.Component.VC.CMake.Project': 'C++ CMake tools for Windows',
248 249 250
    };
  }

251 252 253
  /// The minimum supported major version.
  static const int _minimumSupportedVersion = 16;  // '16' is VS 2019.

254
  /// vswhere argument to specify the minimum version.
255 256 257 258 259
  static const String _vswhereMinVersionArgument = '-version';

  /// vswhere argument to allow prerelease versions.
  static const String _vswherePrereleaseArgument = '-prerelease';

260 261 262 263 264 265 266
  /// The registry path for Windows 10 SDK installation details.
  static const String _windows10SdkRegistryPath = r'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0';

  /// The registry key in _windows10SdkRegistryPath for the folder where the
  /// SDKs are installed.
  static const String _windows10SdkRegistryKey = 'InstallationFolder';

267 268
  /// Returns the details of the newest version of Visual Studio.
  ///
269 270
  /// If [validateRequirements] is set, the search will be limited to versions
  /// that have all of the required workloads and components.
271
  VswhereDetails? _visualStudioDetails({
272
      bool validateRequirements = false,
273 274
      List<String>? additionalArguments,
      String? requiredWorkload
275 276 277
    }) {
    final List<String> requirementArguments = validateRequirements
        ? <String>[
278 279 280 281
            if (requiredWorkload != null) ...<String>[
              '-requires',
              requiredWorkload,
            ],
282
            ..._requiredComponents(_minimumSupportedVersion).keys,
283 284
          ]
        : <String>[];
285
    try {
286
      final List<String> defaultArguments = <String>[
287
        '-format', 'json',
288
        '-products', '*',
289 290
        '-utf8',
        '-latest',
291
      ];
292 293 294
      // Ignore replacement characters as vswhere.exe is known to output them.
      // See: https://github.com/flutter/flutter/issues/102451
      const Encoding encoding = Utf8Codec(reportErrors: false);
295
      final RunResult whereResult = _processUtils.runSync(<String>[
296 297 298
        _vswherePath,
        ...defaultArguments,
        ...?additionalArguments,
299
        ...requirementArguments,
300
      ], encoding: encoding);
301
      if (whereResult.exitCode == 0) {
302 303
        final List<Map<String, dynamic>>? installations = _tryDecodeVswhereJson(whereResult.stdout);
        if (installations != null && installations.isNotEmpty) {
304
          return VswhereDetails.fromJson(validateRequirements, installations[0]);
305 306
        }
      }
307 308
    } on ArgumentError {
      // Thrown if vswhere doesn't exist; ignore and return null below.
309 310 311 312 313 314
    } on ProcessException {
      // Ignored, return null below.
    }
    return null;
  }

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  List<Map<String, dynamic>>? _tryDecodeVswhereJson(String vswhereJson) {
    List<dynamic>? result;
    FormatException? originalError;
    try {
      // Some versions of vswhere.exe are known to encode their output incorrectly,
      // resulting in invalid JSON in the 'description' property when interpreted
      // as UTF-8. First, try to decode without any pre-processing.
      try {
        result = json.decode(vswhereJson) as List<dynamic>;
      } on FormatException catch (error) {
        // If that fails, remove the 'description' property and try again.
        // See: https://github.com/flutter/flutter/issues/106601
        vswhereJson = vswhereJson.replaceFirst(_vswhereDescriptionProperty, '');

        _logger.printTrace('Failed to decode vswhere.exe JSON output. $error'
          'Retrying after removing the unused description property:\n$vswhereJson');

        originalError = error;
        result = json.decode(vswhereJson) as List<dynamic>;
      }
    } on FormatException {
      // Removing the description property didn't help.
      // Report the original decoding error on the unprocessed JSON.
      _logger.printWarning('Warning: Unexpected vswhere.exe JSON output. $originalError'
        'To see the full JSON, run flutter doctor -vv.');
      return null;
    }

    return result.cast<Map<String, dynamic>>();
  }

346
  /// Returns the details of the best available version of Visual Studio.
347
  ///
348 349 350 351 352 353 354
  /// If there's a version that has all the required components, that
  /// will be returned, otherwise returns the latest installed version regardless
  /// of components and version, or null if no such installation is found.
  late final VswhereDetails?  _bestVisualStudioDetails = () {
    // First, attempt to find the latest version of Visual Studio that satifies
    // both the minimum supported version and the required workloads.
    // Check in the order of stable VS, stable BT, pre-release VS, pre-release BT.
355 356 357 358
    final List<String> minimumVersionArguments = <String>[
      _vswhereMinVersionArgument,
      _minimumSupportedVersion.toString(),
    ];
359 360
    for (final bool checkForPrerelease in <bool>[false, true]) {
      for (final String requiredWorkload in _requiredWorkloads) {
361
        final VswhereDetails? result = _visualStudioDetails(
362 363 364 365 366
          validateRequirements: true,
          additionalArguments: checkForPrerelease
              ? <String>[...minimumVersionArguments, _vswherePrereleaseArgument]
              : minimumVersionArguments,
          requiredWorkload: requiredWorkload);
367

368 369 370
          if (result != null) {
            return result;
          }
371 372
      }
    }
373

374 375 376
    // An installation that satifies requirements could not be found.
    // Fallback to the latest Visual Studio installation.
    return _visualStudioDetails(
377
        additionalArguments: <String>[_vswherePrereleaseArgument, '-all']);
378
  }();
379 380 381

  /// Returns the installation location of the Windows 10 SDKs, or null if the
  /// registry doesn't contain that information.
382
  String? _getWindows10SdkLocation() {
383 384 385 386 387 388 389 390 391 392
    try {
      final RunResult result = _processUtils.runSync(<String>[
        'reg',
        'query',
        _windows10SdkRegistryPath,
        '/v',
        _windows10SdkRegistryKey,
      ]);
      if (result.exitCode == 0) {
        final RegExp pattern = RegExp(r'InstallationFolder\s+REG_SZ\s+(.+)');
393
        final RegExpMatch? match = pattern.firstMatch(result.stdout);
394
        if (match != null) {
395
          return match.group(1)!.trim();
396 397
        }
      }
398 399
    } on ArgumentError {
      // Thrown if reg somehow doesn't exist; ignore and return null below.
400 401 402 403 404 405 406 407 408 409
    } on ProcessException {
      // Ignored, return null below.
    }
    return null;
  }

  /// Returns the highest-numbered SDK version in [dir], which should be the
  /// Windows 10 SDK installation directory.
  ///
  /// Returns null if no Windows 10 SDKs are found.
410
  String? findHighestVersionInSdkDirectory(Directory dir) {
411 412 413 414 415
    // This contains subfolders that are named by the SDK version.
    final Directory includeDir = dir.childDirectory('Includes');
    if (!includeDir.existsSync()) {
      return null;
    }
416
    Version? highestVersion;
417 418 419 420 421 422
    for (final FileSystemEntity versionEntry in includeDir.listSync()) {
      if (!versionEntry.basename.startsWith('10.')) {
        continue;
      }
      // Version only handles 3 components; strip off the '10.' to leave three
      // components, since they all start with that.
423 424
      final Version? version = Version.parse(versionEntry.basename.substring(3));
      if (highestVersion == null || (version != null && version > highestVersion)) {
425 426 427 428 429 430
        highestVersion = version;
      }
    }
    // Re-add the leading '10.' that was removed for comparison.
    return highestVersion == null ? null : '10.$highestVersion';
  }
431
}
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

/// The details of a Visual Studio installation according to vswhere.
@visibleForTesting
class VswhereDetails {
  const VswhereDetails({
    required this.meetsRequirements,
    required this.installationPath,
    required this.displayName,
    required this.fullVersion,
    required this.isComplete,
    required this.isLaunchable,
    required this.isRebootRequired,
    required this.isPrerelease,
    required this.catalogDisplayVersion,
  });

  /// Create a `VswhereDetails` from the JSON output of vswhere.exe.
  factory VswhereDetails.fromJson(
    bool meetsRequirements,
    Map<String, dynamic> details
  ) {
    final Map<String, dynamic>? catalog = details['catalog'] as Map<String, dynamic>?;

    return VswhereDetails(
      meetsRequirements: meetsRequirements,
      isComplete: details['isComplete'] as bool?,
      isLaunchable: details['isLaunchable'] as bool?,
      isRebootRequired: details['isRebootRequired'] as bool?,
      isPrerelease: details['isPrerelease'] as bool?,
461 462 463 464 465 466 467 468

      // Below are strings that must be well-formed without replacement characters.
      installationPath: _validateString(details['installationPath'] as String?),
      fullVersion: _validateString(details['installationVersion'] as String?),

      // Below are strings that are used only for display purposes and are allowed to
      // contain replacement characters.
      displayName: details['displayName'] as String?,
469 470 471 472
      catalogDisplayVersion: catalog == null ? null : catalog['productDisplayVersion'] as String?,
    );
  }

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  /// Verify JSON strings from vswhere.exe output are valid.
  ///
  /// The output of vswhere.exe is known to output replacement characters.
  /// Use this to ensure values that must be well-formed are valid. Strings that
  /// are only used for display purposes should skip this check.
  /// See: https://github.com/flutter/flutter/issues/102451
  static String? _validateString(String? value) {
    if (value != null && value.contains('\u{FFFD}')) {
      throwToolExit(
        'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found in string: $value. '
        'The Flutter team would greatly appreciate if you could file a bug explaining '
        'exactly what you were doing when this happened:\n'
        'https://github.com/flutter/flutter/issues/new/choose\n');
    }

    return value;
  }

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  /// Whether the installation satisfies the required workloads and minimum version.
  final bool meetsRequirements;

  /// The root directory of the Visual Studio installation.
  final String? installationPath;

  /// The user-friendly name of the installation.
  final String? displayName;

  /// The complete version.
  final String? fullVersion;

  /// Keys for the status of the installation.
  final bool? isComplete;
  final bool? isLaunchable;
  final bool? isRebootRequired;

  /// The key for a pre-release version.
  final bool? isPrerelease;

  /// The user-friendly version.
  final String? catalogDisplayVersion;

  /// Checks if the Visual Studio installation can be used by Flutter.
  ///
  /// Returns false if the installation has issues the user must resolve.
  /// This may return true even if required information is missing as older
  /// versions of Visual Studio might not include them.
  bool get isUsable {
    if (!meetsRequirements) {
      return false;
    }

    if (!(isComplete ?? true)) {
      return false;
    }

    if (!(isLaunchable ?? true)) {
      return false;
    }

    if (isRebootRequired ?? false) {
      return false;
    }

    return true;
  }
}