Native assets support for Windows (#134203)

Support for FFI calls with `@Native external` functions through Native assets on Windows. This enables bundling native code without any build-system boilerplate code.

For more info see:

* https://github.com/flutter/flutter/issues/129757

### Implementation details for Windows.

Mainly follows the design of https://github.com/flutter/flutter/pull/134031.

Specifically for Windows in this PR is the logic for finding the compiler `cl.exe` and environment variables that contain the paths to the Windows headers `vcvars.bat` based on `vswhere.exe`.
This commit is contained in:
Daco Harkes
2023-09-27 14:22:58 +02:00
committed by GitHub
parent 3e7c388e91
commit ff4a0f676f
20 changed files with 1187 additions and 322 deletions

View File

@@ -49,7 +49,7 @@ class FakeNativeAssetsBuildRunner implements NativeAssetsBuildRunner {
Future<native_assets_builder.DryRunResult> dryRun({
required bool includeParentEnvironment,
required LinkModePreference linkModePreference,
required OS targetOs,
required OS targetOS,
required Uri workingDirectory,
}) async {
dryRunInvocations++;

View File

@@ -142,6 +142,13 @@ void main() {
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Dry running native assets for ios.',
'Dry running native assets for ios done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/ios/native_assets.yaml'),
@@ -259,13 +266,20 @@ void main() {
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
target: native_assets_cli.Target.iOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Building native assets for [ios_arm64] debug.',
'Building native assets for [ios_arm64] done.',
]),
);
expect(
environment.buildDir.childFile('native_assets.yaml'),
exists,

View File

@@ -180,6 +180,13 @@ void main() {
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Dry running native assets for linux.',
'Dry running native assets for linux done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/linux/native_assets.yaml'),
@@ -222,6 +229,7 @@ void main() {
await packageConfig.parent.create();
await packageConfig.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsLinux(
targetPlatform: TargetPlatform.linux_x64,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
@@ -257,16 +265,14 @@ void main() {
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
if (const LocalPlatform().isWindows) {
return; // Backslashes in commands, but we will never run these commands on Windows.
}
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
final File packageConfig = environment.projectDir.childDirectory('.dart_tool').childFile('package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final File dylibAfterCompiling = fileSystem.file('libbar.so');
// The mock doesn't create the file, so create it here.
await dylibAfterCompiling.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsLinux(
targetPlatform: TargetPlatform.linux_x64,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
@@ -287,6 +293,13 @@ void main() {
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Building native assets for linux_x64 debug.',
'Building native assets for linux_x64 done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/linux/native_assets.yaml'),
@@ -297,7 +310,7 @@ void main() {
'package:bar/bar.dart',
if (flutterTester)
// Tests run on host system, so the have the full path on the system.
'- ${projectUri.resolve('/build/native_assets/linux/libbar.so').toFilePath()}'
'- ${projectUri.resolve('build/native_assets/linux/libbar.so').toFilePath()}'
else
// Apps are a bundle with the dylibs on their dlopen path.
'- libbar.so',
@@ -365,7 +378,6 @@ void main() {
FileSystem: () => fileSystem,
}, () async {
if (!const LocalPlatform().isLinux) {
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
return;
}

View File

@@ -161,6 +161,13 @@ void main() {
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Dry running native assets for macos.',
'Dry running native assets for macos done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/macos/native_assets.yaml'),
@@ -291,6 +298,13 @@ void main() {
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Building native assets for [macos_arm64] debug.',
'Building native assets for [macos_arm64] done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/macos/native_assets.yaml'),
@@ -301,7 +315,7 @@ void main() {
'package:bar/bar.dart',
if (flutterTester)
// Tests run on host system, so the have the full path on the system.
'- ${projectUri.resolve('/build/native_assets/macos/bar.dylib').toFilePath()}'
'- ${projectUri.resolve('build/native_assets/macos/bar.dylib').toFilePath()}'
else
// Apps are a bundle with the dylibs on their dlopen path.
'- bar.dylib',
@@ -370,7 +384,6 @@ InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault
),
}, () async {
if (!const LocalPlatform().isMacOS) {
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
return;
}

View File

@@ -230,9 +230,9 @@ install(DIRECTORY "${NATIVE_ASSETS_DIR}"
expect(testLogger.statusText, isEmpty);
});
// TODO(dacoharkes): Add test for Windows when adding Windows support. https://github.com/flutter/flutter/issues/129757
testWithoutContext('is migrated to copy native assets', () {
managedCmakeFile.writeAsStringSync(r'''
for (final String os in <String>['linux', 'windows']) {
testWithoutContext('is migrated to copy native assets', () {
managedCmakeFile.writeAsStringSync(r'''
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
@@ -249,38 +249,40 @@ install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
''');
final CmakeNativeAssetsMigration cmakeProjectMigration = CmakeNativeAssetsMigration(
mockCmakeProject,
'linux',
testLogger,
);
cmakeProjectMigration.migrate();
final CmakeNativeAssetsMigration cmakeProjectMigration = CmakeNativeAssetsMigration(
mockCmakeProject,
os,
testLogger,
);
cmakeProjectMigration.migrate();
expect(managedCmakeFile.readAsStringSync(), r'''
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
expect(managedCmakeFile.readAsStringSync(), '''
foreach(bundled_library \${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "\${bundled_library}"
DESTINATION "\${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
set(NATIVE_ASSETS_DIR "\${PROJECT_BUILD_DIR}native_assets/$os/")
install(DIRECTORY "\${NATIVE_ASSETS_DIR}"
DESTINATION "\${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
file(REMOVE_RECURSE \\"\${INSTALL_BUNDLE_DATA_DIR}/\${FLUTTER_ASSET_DIR_NAME}\\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
install(DIRECTORY "\${PROJECT_BUILD_DIR}/\${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "\${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
''');
expect(testLogger.statusText, contains('CMake missing install() NATIVE_ASSETS_DIR command, updating.'));
});
expect(testLogger.statusText,
contains('CMake missing install() NATIVE_ASSETS_DIR command, updating.'));
});
}
});
});
}

View File

@@ -0,0 +1,439 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/dart/package_map.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/native_assets.dart';
import 'package:flutter_tools/src/windows/native_assets.dart';
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode, Target;
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import 'package:package_config/package_config_types.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../fake_native_assets_build_runner.dart';
void main() {
late FakeProcessManager processManager;
late Environment environment;
late Artifacts artifacts;
late FileSystem fileSystem;
late BufferLogger logger;
late Uri projectUri;
setUp(() {
processManager = FakeProcessManager.empty();
logger = BufferLogger.test();
artifacts = Artifacts.test();
fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows);
environment = Environment.test(
fileSystem.currentDirectory,
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
environment.buildDir.createSync(recursive: true);
projectUri = environment.projectDir.uri;
});
testUsingContext('dry run with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
expect(
await dryRunNativeAssetsWindows(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
),
null,
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('build with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await buildNativeAssetsWindows(
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run for multiple OSes with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await dryRunNativeAssetsMultipeOSes(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[
TargetPlatform.windows_x64,
],
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => dryRunNativeAssetsWindows(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('dry run with assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final Uri? nativeAssetsYaml = await dryRunNativeAssetsWindows(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.windowsX64,
path: AssetAbsolutePath(Uri.file('bar.dll')),
),
],
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Dry running native assets for windows.',
'Dry running native assets for windows done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/windows/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
contains('package:bar/bar.dart'),
);
});
testUsingContext('build with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => buildNativeAssetsWindows(
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('build no assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsWindows(
targetPlatform: TargetPlatform.windows_x64,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/windows/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
isNot(contains('package:bar/bar.dart')),
);
expect(
environment.projectDir.childDirectory('build').childDirectory('native_assets').childDirectory('windows'),
exists,
);
});
for (final bool flutterTester in <bool>[false, true]) {
String testName = '';
if (flutterTester) {
testName += ' flutter tester';
}
testUsingContext('build with assets$testName', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childDirectory('.dart_tool').childFile('package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final File dylibAfterCompiling = fileSystem.file('bar.dll');
// The mock doesn't create the file, so create it here.
await dylibAfterCompiling.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsWindows(
targetPlatform: TargetPlatform.windows_x64,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
flutterTester: flutterTester,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
buildResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.windowsX64,
path: AssetAbsolutePath(dylibAfterCompiling.uri),
),
],
),
),
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Building native assets for windows_x64 debug.',
'Building native assets for windows_x64 done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/windows/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
stringContainsInOrder(<String>[
'package:bar/bar.dart',
if (flutterTester)
// Tests run on host system, so the have the full path on the system.
'- ${projectUri.resolve('build/native_assets/windows/bar.dll').toFilePath()}'
else
// Apps are a bundle with the dylibs on their dlopen path.
'- bar.dll',
]),
);
});
}
testUsingContext('static libs not supported', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => dryRunNativeAssetsWindows(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.static,
target: native_assets_cli.Target.windowsX64,
path: AssetAbsolutePath(Uri.file(OS.windows.staticlibFileName('bar'))),
),
],
),
),
),
throwsToolExit(
message: 'Native asset(s) package:bar/bar.dart have their link mode set to '
'static, but this is not yet supported. '
'For more info see https://github.com/dart-lang/sdk/issues/49418.',
),
);
});
// This logic is mocked in the other tests to avoid having test order
// randomization causing issues with what processes are invoked.
// Exercise the parsing of the process output in this separate test.
testUsingContext('NativeAssetsBuildRunnerImpl.cCompilerConfig', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: <Pattern>[
RegExp(r'(.*)vswhere.exe'),
'-format',
'json',
'-products',
'*',
'-utf8',
'-latest',
'-version',
'16',
'-requires',
'Microsoft.VisualStudio.Workload.NativeDesktop',
'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
'Microsoft.VisualStudio.Component.VC.CMake.Project',
],
stdout: r'''
[
{
"instanceId": "491ec752",
"installDate": "2023-04-21T08:17:11Z",
"installationName": "VisualStudio/17.5.4+33530.505",
"installationPath": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community",
"installationVersion": "17.5.33530.505",
"productId": "Microsoft.VisualStudio.Product.Community",
"productPath": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe",
"state": 4294967295,
"isComplete": true,
"isLaunchable": true,
"isPrerelease": false,
"isRebootRequired": false,
"displayName": "Visual Studio Community 2022",
"description": "Powerful IDE, free for students, open-source contributors, and individuals",
"channelId": "VisualStudio.17.Release",
"channelUri": "https://aka.ms/vs/17/release/channel",
"enginePath": "C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\resources\\app\\ServiceHub\\Services\\Microsoft.VisualStudio.Setup.Service",
"installedChannelId": "VisualStudio.17.Release",
"installedChannelUri": "https://aka.ms/vs/17/release/channel",
"releaseNotes": "https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.5#17.5.4",
"thirdPartyNotices": "https://go.microsoft.com/fwlink/?LinkId=661288",
"updateDate": "2023-04-21T08:17:11.2249473Z",
"catalog": {
"buildBranch": "d17.5",
"buildVersion": "17.5.33530.505",
"id": "VisualStudio/17.5.4+33530.505",
"localBuild": "build-lab",
"manifestName": "VisualStudio",
"manifestType": "installer",
"productDisplayVersion": "17.5.4",
"productLine": "Dev17",
"productLineVersion": "2022",
"productMilestone": "RTW",
"productMilestoneIsPreRelease": "False",
"productName": "Visual Studio",
"productPatchVersion": "4",
"productPreReleaseMilestoneSuffix": "1.0",
"productSemanticVersion": "17.5.4+33530.505",
"requiredEngineVersion": "3.5.2150.18781"
},
"properties": {
"campaignId": "2060:abb99c5d1ecc4013acf2e1814b10b690",
"channelManifestId": "VisualStudio.17.Release/17.5.4+33530.505",
"nickname": "",
"setupEngineFilePath": "C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\setup.exe"
}
}
]
''', // Newline at the end of the string.
)
],
),
FileSystem: () => fileSystem,
}, () async {
if (!const LocalPlatform().isWindows) {
return;
}
final Directory msvcBinDir =
fileSystem.directory(r'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.35.32215\bin\Hostx64\x64');
await msvcBinDir.create(recursive: true);
final File packagesFile = fileSystem
.directory(projectUri)
.childDirectory('.dart_tool')
.childFile('package_config.json');
await packagesFile.parent.create();
await packagesFile.create();
final PackageConfig packageConfig = await loadPackageConfigWithLogging(
packagesFile,
logger: environment.logger,
);
final NativeAssetsBuildRunner runner = NativeAssetsBuildRunnerImpl(
projectUri,
packageConfig,
fileSystem,
logger,
);
final CCompilerConfig result = await runner.cCompilerConfig;
expect(result.cc?.toFilePath(), msvcBinDir.childFile('cl.exe').uri.toFilePath());
expect(result.ar?.toFilePath(), msvcBinDir.childFile('lib.exe').uri.toFilePath());
expect(result.ld?.toFilePath(), msvcBinDir.childFile('link.exe').uri.toFilePath());
expect(result.envScript, isNotNull);
expect(result.envScriptArgs, isNotNull);
});
}

View File

@@ -11,12 +11,16 @@ import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/windows/visual_studio.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
import '../../src/context.dart';
const String programFilesPath = r'C:\Program Files (x86)';
const String visualStudioPath = programFilesPath + r'\Microsoft Visual Studio\2017\Community';
const String cmakePath = visualStudioPath + r'\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe';
const String vswherePath = programFilesPath + r'\Microsoft Visual Studio\Installer\vswhere.exe';
const String clPath = visualStudioPath + r'\VC\Tools\MSVC\14.35.32215\bin\Hostx64\x64\cl.exe';
const String libPath = visualStudioPath + r'\VC\Tools\MSVC\14.35.32215\bin\Hostx64\x64\lib.exe';
const String linkPath = visualStudioPath + r'\VC\Tools\MSVC\14.35.32215\bin\Hostx64\x64\link.exe';
const String vcvarsPath = visualStudioPath + r'\VC\Auxiliary\Build\vcvars64.bat';
final Platform windowsPlatform = FakePlatform(
operatingSystem: 'windows',
@@ -140,6 +144,7 @@ void setMockVswhereResponse(
]) {
fileSystem.file(vswherePath).createSync(recursive: true);
fileSystem.file(cmakePath).createSync(recursive: true);
fileSystem.file(clPath).createSync(recursive: true);
final String finalResponse = responseOverride
?? (response != null ? json.encode(<Map<String, dynamic>>[response]) : '[]');
final List<String> requirementArguments = requiredComponents == null
@@ -300,11 +305,11 @@ void setMockSdkRegResponse(
const String registryKey = r'InstallationFolder';
const String installationPath = r'C:\Program Files (x86)\Windows Kits\10\';
final String stdout = registryPresent
? '''
? '''
$registryPath
$registryKey REG_SZ $installationPath
'''
: '''
: '''
ERROR: The system was unable to find the specified registry key or value.
''';
@@ -776,6 +781,10 @@ void main() {
expect(visualStudio.hasNecessaryComponents, true);
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 16 2019'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
});
testWithoutContext('Everything returns good values when Build Tools is present with all components', () {
@@ -814,6 +823,10 @@ void main() {
expect(visualStudio.hasNecessaryComponents, true);
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 17 2022'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
});
testWithoutContext('Metadata is for compatible version when latest is missing components', () {
@@ -905,8 +918,7 @@ void main() {
});
testWithoutContext('Ignores unicode replacement char in unused properties', () {
final Map<String, dynamic> response = Map<String, dynamic>.of(_defaultResponse)
..['unused'] = 'Bad UTF8 \u{FFFD}';
final Map<String, dynamic> response = Map<String, dynamic>.of(_defaultResponse)..['unused'] = 'Bad UTF8 \u{FFFD}';
setMockCompatibleVisualStudioInstallation(
response,
@@ -919,6 +931,10 @@ void main() {
expect(visualStudio.hasNecessaryComponents, true);
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 16 2019'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
});
testWithoutContext('Throws ToolExit on bad UTF-8 in installationPath', () {
@@ -953,13 +969,16 @@ void main() {
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 16 2019'));
expect(visualStudio.displayName, equals('\u{FFFD}'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
});
testWithoutContext("Ignores bad UTF-8 in catalog's productDisplayVersion", () {
final Map<String, dynamic> catalog = Map<String, dynamic>.of(_defaultResponse['catalog'] as Map<String, dynamic>)
..['productDisplayVersion'] = '\u{FFFD}';
final Map<String, dynamic> response = Map<String, dynamic>.of(_defaultResponse)
..['catalog'] = catalog;
final Map<String, dynamic> response = Map<String, dynamic>.of(_defaultResponse)..['catalog'] = catalog;
setMockCompatibleVisualStudioInstallation(response, fixture.fileSystem, fixture.processManager);
@@ -969,6 +988,10 @@ void main() {
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 16 2019'));
expect(visualStudio.displayVersion, equals('\u{FFFD}'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
});
testWithoutContext('Ignores malformed JSON in description property', () {
@@ -987,101 +1010,109 @@ void main() {
expect(visualStudio.cmakePath, equals(cmakePath));
expect(visualStudio.cmakeGenerator, equals('Visual Studio 16 2019'));
expect(visualStudio.displayVersion, equals('16.2.5'));
expect(visualStudio.clPath, equals(clPath));
expect(visualStudio.libPath, equals(libPath));
expect(visualStudio.linkPath, equals(linkPath));
expect(visualStudio.vcvarsPath, equals(vcvarsPath));
expect(fixture.logger.warningText, isEmpty);
});
});
group(VswhereDetails, () {
test('Accepts empty JSON', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = <String, dynamic>{};
test('Accepts empty JSON', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = <String, dynamic>{};
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json, msvcVersion);
expect(result.installationPath, null);
expect(result.displayName, null);
expect(result.fullVersion, null);
expect(result.isComplete, null);
expect(result.isLaunchable, null);
expect(result.isRebootRequired, null);
expect(result.isPrerelease, null);
expect(result.catalogDisplayVersion, null);
expect(result.isUsable, isTrue);
});
expect(result.installationPath, null);
expect(result.displayName, null);
expect(result.fullVersion, null);
expect(result.isComplete, null);
expect(result.isLaunchable, null);
expect(result.isRebootRequired, null);
expect(result.isPrerelease, null);
expect(result.catalogDisplayVersion, null);
expect(result.isUsable, isTrue);
});
test('Ignores unknown JSON properties', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = <String, dynamic>{
'hello': 'world',
};
test('Ignores unknown JSON properties', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = <String, dynamic>{
'hello': 'world',
};
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json, msvcVersion);
expect(result.installationPath, null);
expect(result.displayName, null);
expect(result.fullVersion, null);
expect(result.isComplete, null);
expect(result.isLaunchable, null);
expect(result.isRebootRequired, null);
expect(result.isPrerelease, null);
expect(result.catalogDisplayVersion, null);
expect(result.isUsable, isTrue);
});
expect(result.installationPath, null);
expect(result.displayName, null);
expect(result.fullVersion, null);
expect(result.isComplete, null);
expect(result.isLaunchable, null);
expect(result.isRebootRequired, null);
expect(result.isPrerelease, null);
expect(result.catalogDisplayVersion, null);
expect(result.isUsable, isTrue);
});
test('Accepts JSON', () {
const bool meetsRequirements = true;
test('Accepts JSON', () {
const bool meetsRequirements = true;
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, _defaultResponse);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, _defaultResponse, msvcVersion);
expect(result.installationPath, visualStudioPath);
expect(result.displayName, 'Visual Studio Community 2019');
expect(result.fullVersion, '16.2.29306.81');
expect(result.isComplete, true);
expect(result.isLaunchable, true);
expect(result.isRebootRequired, false);
expect(result.isPrerelease, false);
expect(result.catalogDisplayVersion, '16.2.5');
expect(result.isUsable, isTrue);
});
expect(result.installationPath, visualStudioPath);
expect(result.displayName, 'Visual Studio Community 2019');
expect(result.fullVersion, '16.2.29306.81');
expect(result.isComplete, true);
expect(result.isLaunchable, true);
expect(result.isRebootRequired, false);
expect(result.isPrerelease, false);
expect(result.catalogDisplayVersion, '16.2.5');
expect(result.isUsable, isTrue);
});
test('Installation that does not satisfy requirements is not usable', () {
const bool meetsRequirements = false;
test('Installation that does not satisfy requirements is not usable', () {
const bool meetsRequirements = false;
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, _defaultResponse);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, _defaultResponse, msvcVersion);
expect(result.isUsable, isFalse);
});
expect(result.isUsable, isFalse);
});
test('Incomplete installation is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)
..['isComplete'] = false;
test('Incomplete installation is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)..['isComplete'] = false;
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json, msvcVersion);
expect(result.isUsable, isFalse);
});
expect(result.isUsable, isFalse);
});
test('Unlaunchable installation is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)
..['isLaunchable'] = false;
test('Unlaunchable installation is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)..['isLaunchable'] = false;
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json, msvcVersion);
expect(result.isUsable, isFalse);
});
expect(result.isUsable, isFalse);
});
test('Installation that requires reboot is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)
..['isRebootRequired'] = true;
test('Installation that requires reboot is not usable', () {
const bool meetsRequirements = true;
final Map<String, dynamic> json = Map<String, dynamic>.of(_defaultResponse)..['isRebootRequired'] = true;
const String msvcVersion = '';
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json);
final VswhereDetails result = VswhereDetails.fromJson(meetsRequirements, json, msvcVersion);
expect(result.isUsable, isFalse);
});
expect(result.isUsable, isFalse);
});
});
}

View File

@@ -58,8 +58,8 @@ const String packageName = 'package_with_native_assets';
const String exampleAppName = '${packageName}_example';
void main() {
if (!platform.isMacOS && !platform.isLinux) {
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
if (!platform.isMacOS && !platform.isLinux && !platform.isWindows) {
// TODO(dacoharkes): Implement Fuchsia. https://github.com/flutter/flutter/issues/129757
return;
}
@@ -146,9 +146,10 @@ void main() {
if (device == 'macos') {
expectDylibIsBundledMacOS(exampleDirectory, buildMode);
}
if (device == 'linux') {
} else if (device == 'linux') {
expectDylibIsBundledLinux(exampleDirectory, buildMode);
} else if (device == 'windows') {
expectDylibIsBundledWindows(exampleDirectory, buildMode);
}
if (device == hostOs) {
expectCCompilerIsConfigured(exampleDirectory);
@@ -205,6 +206,8 @@ void main() {
expectDylibIsBundledIos(exampleDirectory, buildMode);
} else if (buildSubcommand == 'linux') {
expectDylibIsBundledLinux(exampleDirectory, buildMode);
} else if (buildSubcommand == 'windows') {
expectDylibIsBundledWindows(exampleDirectory, buildMode);
}
expectCCompilerIsConfigured(exampleDirectory);
});
@@ -239,11 +242,15 @@ void main() {
'build',
buildSubcommand,
if (buildSubcommand == 'ios') '--no-codesign',
if (buildSubcommand == 'windows') '-v' // Requires verbose mode for error.
],
workingDirectory: exampleDirectory.path,
);
expect(result.exitCode, isNot(0));
expect(result.stderr, contains('link mode set to static, but this is not yet supported'));
expect(
(result.stdout as String) + (result.stderr as String),
contains('link mode set to static, but this is not yet supported'),
);
});
});
}
@@ -301,14 +308,36 @@ void expectDylibIsBundledIos(Directory appDirectory, String buildMode) {
void expectDylibIsBundledLinux(Directory appDirectory, String buildMode) {
// Linux does not support cross compilation, so always only check current architecture.
final String architecture = Architecture.current.dartPlatform;
final Directory appBundle = appDirectory.childDirectory('build/$hostOs/$architecture/$buildMode/bundle/');
final Directory appBundle = appDirectory
.childDirectory('build')
.childDirectory(hostOs)
.childDirectory(architecture)
.childDirectory(buildMode)
.childDirectory('bundle');
expect(appBundle, exists);
final Directory dylibsFolder = appBundle.childDirectory('lib/');
final Directory dylibsFolder = appBundle.childDirectory('lib');
expect(dylibsFolder, exists);
final File dylib = dylibsFolder.childFile(OS.linux.dylibFileName(packageName));
expect(dylib, exists);
}
/// Checks that dylibs are bundled.
///
/// Sample path: build\windows\x64\runner\Debug\my_package_example.exe
void expectDylibIsBundledWindows(Directory appDirectory, String buildMode) {
// Linux does not support cross compilation, so always only check current architecture.
final String architecture = Architecture.current.dartPlatform;
final Directory appBundle = appDirectory
.childDirectory('build')
.childDirectory(hostOs)
.childDirectory(architecture)
.childDirectory('runner')
.childDirectory(buildMode.upperCaseFirst());
expect(appBundle, exists);
final File dylib = appBundle.childFile(OS.windows.dylibFileName(packageName));
expect(dylib, exists);
}
/// For `flutter build` we can't easily test whether running the app works.
/// Check that we have the dylibs in the app.
void expectDylibIsBundledWithFrameworks(Directory appDirectory, String buildMode, String os) {