diff --git a/packages/flutter_tools/lib/executable.dart b/packages/flutter_tools/lib/executable.dart index 0938e64977..1ebf5c1ee8 100644 --- a/packages/flutter_tools/lib/executable.dart +++ b/packages/flutter_tools/lib/executable.dart @@ -52,6 +52,7 @@ import 'src/isolated/mustache_template.dart'; import 'src/isolated/native_assets/native_assets.dart'; import 'src/isolated/native_assets/test/native_assets.dart'; import 'src/isolated/resident_web_runner.dart'; +import 'src/native_assets.dart'; import 'src/pre_run_validator.dart'; import 'src/project_validator.dart'; import 'src/resident_runner.dart'; @@ -141,6 +142,7 @@ Future main(List args) async { // runner.run calls "terminal.applyFeatureFlags()" }, PreRunValidator: () => PreRunValidator(fileSystem: globals.fs), + TestCompilerNativeAssetsBuilder: () => const TestCompilerNativeAssetsBuilderImpl(), }, shutdownHooks: globals.shutdownHooks, ); @@ -249,7 +251,7 @@ List generateCommands({ TestCommand( verboseHelp: verboseHelp, verbose: verbose, - nativeAssetsBuilder: const TestCompilerNativeAssetsBuilderImpl(), + nativeAssetsBuilder: globals.nativeAssetsBuilder, ), UpgradeCommand(verboseHelp: verboseHelp), SymbolizeCommand( diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index bea9751361..8db5cb5b59 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -592,6 +592,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { shardIndex: shardIndex, totalShards: totalShards, testTimeRecorder: testTimeRecorder, + nativeAssetsBuilder: nativeAssetsBuilder, ); } else { result = await testRunner.runTests( diff --git a/packages/flutter_tools/lib/src/context_runner.dart b/packages/flutter_tools/lib/src/context_runner.dart index 92b1856034..b485e5658d 100644 --- a/packages/flutter_tools/lib/src/context_runner.dart +++ b/packages/flutter_tools/lib/src/context_runner.dart @@ -214,6 +214,7 @@ Future runInContext( fuchsiaSdk: globals.fuchsiaSdk!, operatingSystemUtils: globals.os, customDevicesConfig: globals.customDevicesConfig, + nativeAssetsBuilder: globals.nativeAssetsBuilder, ), DevtoolsLauncher: () => DevtoolsServerLauncher( processManager: globals.processManager, diff --git a/packages/flutter_tools/lib/src/flutter_device_manager.dart b/packages/flutter_tools/lib/src/flutter_device_manager.dart index 3b9558e53d..650eea6aaf 100644 --- a/packages/flutter_tools/lib/src/flutter_device_manager.dart +++ b/packages/flutter_tools/lib/src/flutter_device_manager.dart @@ -27,11 +27,11 @@ import 'macos/macos_device.dart'; import 'macos/macos_ipad_device.dart'; import 'macos/macos_workflow.dart'; import 'macos/xcdevice.dart'; +import 'native_assets.dart'; import 'preview_device.dart'; import 'tester/flutter_tester.dart'; import 'version.dart'; import 'web/web_device.dart'; - import 'windows/windows_device.dart'; import 'windows/windows_workflow.dart'; @@ -57,6 +57,7 @@ class FlutterDeviceManager extends DeviceManager { required OperatingSystemUtils operatingSystemUtils, required WindowsWorkflow windowsWorkflow, required CustomDevicesConfig customDevicesConfig, + required TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : deviceDiscoverers = [ AndroidDevices( logger: logger, @@ -88,6 +89,7 @@ class FlutterDeviceManager extends DeviceManager { processManager: processManager, logger: logger, artifacts: artifacts, + nativeAssetsBuilder: nativeAssetsBuilder, ), MacOSDevices( processManager: processManager, diff --git a/packages/flutter_tools/lib/src/globals.dart b/packages/flutter_tools/lib/src/globals.dart index 7dd00897d6..bc392db3cf 100644 --- a/packages/flutter_tools/lib/src/globals.dart +++ b/packages/flutter_tools/lib/src/globals.dart @@ -41,6 +41,7 @@ import 'macos/cocoapods.dart'; import 'macos/cocoapods_validator.dart'; import 'macos/xcdevice.dart'; import 'macos/xcode.dart'; +import 'native_assets.dart'; import 'persistent_tool_state.dart'; import 'pre_run_validator.dart'; import 'project.dart'; @@ -305,3 +306,5 @@ NonNullSafeBuilds get nonNullSafeBuilds => context.get() ?? N /// A value of [null] indicates that no installation of java could be found on /// the host machine. Java? get java => context.get(); + +TestCompilerNativeAssetsBuilder? get nativeAssetsBuilder => context.get(); diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart index 69440cf47b..a0505cd9f5 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart @@ -9,7 +9,6 @@ import 'package:native_assets_cli/native_assets_cli_internal.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart'; import '../../../globals.dart' as globals; - import '../macos/native_assets_host.dart'; import '../native_assets.dart'; @@ -232,8 +231,10 @@ final KernelAssetPath kernelAssetPath; /// For `flutter run -release` a multi-architecture solution is needed. So, /// `lipo` is used to combine all target architectures into a single file. /// -/// The install name is set so that it matches what the place it will -/// be bundled in the final app. +/// The install name is set so that it matches with the place it will +/// be bundled in the final app. Install names that are referenced in dependent +/// libraries are updated to match the new install name, so that the referenced +/// library can be found by the dynamic linker. /// /// Code signing is also done here, so that it doesn't have to be done in /// in xcode_backend.dart. @@ -247,11 +248,15 @@ Future _copyNativeAssetsIOS( if (assetTargetLocations.isNotEmpty) { globals.logger .printTrace('Copying native assets to ${buildUri.toFilePath()}.'); + + final Map oldToNewInstallNames = {}; + final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; + for (final MapEntry> assetMapping in assetTargetLocations.entries) { final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final AssetImpl source in assetMapping.value) source.file! + final List sources = [ + for (final AssetImpl source in assetMapping.value) fileSystem.file(source.file) ]; final Uri targetUri = buildUri.resolveUri(target); final File dylibFile = fileSystem.file(targetUri); @@ -260,12 +265,25 @@ Future _copyNativeAssetsIOS( await frameworkDir.create(recursive: true); } await lipoDylibs(dylibFile, sources); - await setInstallNameDylib(dylibFile); + + final String dylibFileName = dylibFile.basename; + final String newInstallName = '@rpath/$dylibFileName.framework/$dylibFileName'; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; + } + dylibs.add((dylibFile, newInstallName, frameworkDir)); + // TODO(knopp): Wire the value once there is a way to configure that in the hook. // https://github.com/dart-lang/native/issues/1133 await createInfoPlist(targetUri.pathSegments.last, frameworkDir, minimumIOSVersion: '12.0'); + } + + for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); await codesignDylib(codesignIdentity, buildMode, frameworkDir); } + globals.logger.printTrace('Copying native assets done.'); } } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart index 6af1306f3b..ae70ca89ef 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart @@ -274,8 +274,10 @@ KernelAsset _targetLocationMacOS( /// For `flutter run -release` a multi-architecture solution is needed. So, /// `lipo` is used to combine all target architectures into a single file. /// -/// The install name is set so that it matches what the place it will -/// be bundled in the final app. +/// The install name is set so that it matches with the place it will +/// be bundled in the final app. Install names that are referenced in dependent +/// libraries are updated to match the new install name, so that the referenced +/// library can be found the dynamic linker. /// /// Code signing is also done here, so that it doesn't have to be done in /// in macos_assemble.sh. @@ -290,11 +292,15 @@ Future _copyNativeAssetsMacOS( globals.logger.printTrace( 'Copying native assets to ${buildUri.toFilePath()}.', ); + + final Map oldToNewInstallNames = {}; + final List<(File, String, Directory)> dylibs = <(File, String, Directory)>[]; + for (final MapEntry> assetMapping in assetTargetLocations.entries) { final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final AssetImpl source in assetMapping.value) source.file!, + final List sources = [ + for (final AssetImpl source in assetMapping.value) fileSystem.file(source.file), ]; final Uri targetUri = buildUri.resolveUri(target); final String name = targetUri.pathSegments.last; @@ -332,8 +338,20 @@ Future _copyNativeAssetsMacOS( versionsDir.childDirectory('Current').childFile(name).path, from: dylibLink.parent.path, )); - await setInstallNameDylib(dylibFile); + + final String dylibFileName = dylibFile.basename; + final String newInstallName = '@rpath/$dylibFileName.framework/$dylibFileName'; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; + } + dylibs.add((dylibFile, newInstallName, frameworkDir)); + await createInfoPlist(name, resourcesDir); + } + + for (final (File dylibFile, String newInstallName, Directory frameworkDir) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); // Do not code-sign the libraries here with identity. Code-signing // for bundled dylibs is done in `macos_assemble.sh embed` because the // "Flutter Assemble" target does not have access to the signing identity. @@ -341,6 +359,7 @@ Future _copyNativeAssetsMacOS( await codesignDylib(codesignIdentity, buildMode, frameworkDir); } } + globals.logger.printTrace('Copying native assets done.'); } } @@ -350,7 +369,10 @@ Future _copyNativeAssetsMacOS( /// For `flutter run -release` a multi-architecture solution is needed. So, /// `lipo` is used to combine all target architectures into a single file. /// -/// In contrast to [_copyNativeAssetsMacOS], it does not set the install name. +/// The install names are set to the absolute paths from which the +/// flutter_tester executable with load them. Install names that are +/// referenced in dependent libraries are updated to match the new install name, +/// so that the referenced library can be found the dynamic linker. /// /// Code signing is also done here. Future _copyNativeAssetsMacOSFlutterTester( @@ -364,11 +386,15 @@ Future _copyNativeAssetsMacOSFlutterTester( globals.logger.printTrace( 'Copying native assets to ${buildUri.toFilePath()}.', ); + + final Map oldToNewInstallNames = {}; + final List<(File, String)> dylibs = <(File, String)>[]; + for (final MapEntry> assetMapping in assetTargetLocations.entries) { final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri; - final List sources = [ - for (final AssetImpl source in assetMapping.value) source.file!, + final List sources = [ + for (final AssetImpl source in assetMapping.value) fileSystem.file(source.file), ]; final Uri targetUri = buildUri.resolveUri(target); final File dylibFile = fileSystem.file(targetUri); @@ -377,8 +403,19 @@ Future _copyNativeAssetsMacOSFlutterTester( await targetParent.create(recursive: true); } await lipoDylibs(dylibFile, sources); + final String newInstallName = dylibFile.path; + final Set oldInstallNames = await getInstallNamesDylib(dylibFile); + for (final String oldInstallName in oldInstallNames) { + oldToNewInstallNames[oldInstallName] = newInstallName; + } + dylibs.add((dylibFile, newInstallName)); + } + + for (final (File dylibFile, String newInstallName) in dylibs) { + await setInstallNamesDylib(dylibFile, newInstallName, oldToNewInstallNames); await codesignDylib(codesignIdentity, buildMode, dylibFile); } + globals.logger.printTrace('Copying native assets done.'); } } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart index dcc3a76508..4ce136c74d 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart @@ -4,6 +4,7 @@ // Shared logic between iOS and macOS implementations of native assets. +import 'package:native_assets_cli/native_assets_cli.dart' show Architecture; import 'package:native_assets_cli/native_assets_cli_internal.dart'; import '../../../base/common.dart'; @@ -64,14 +65,14 @@ Future createInfoPlist( /// The dylibs must have different architectures. E.g. a dylib targeting /// arm64 ios simulator cannot be combined with a dylib targeting arm64 /// ios device or macos arm64. -Future lipoDylibs(File target, List sources) async { +Future lipoDylibs(File target, List sources) async { final ProcessResult lipoResult = await globals.processManager.run( [ 'lipo', '-create', '-output', target.path, - for (final Uri source in sources) source.toFilePath(), + for (final File source in sources) source.path, ], ); if (lipoResult.exitCode != 0) { @@ -81,29 +82,68 @@ Future lipoDylibs(File target, List sources) async { globals.logger.printTrace(lipoResult.stderr as String); } -/// Sets the install name in a dylib with a Mach-O format. +/// Sets the install names in a dylib with a Mach-O format. /// /// On macOS and iOS, opening a dylib at runtime fails if the path inside the /// dylib itself does not correspond to the path that the file is at. Therefore, /// native assets copied into their final location also need their install name /// updated with the `install_name_tool`. -Future setInstallNameDylib(File dylibFile) async { - final String fileName = dylibFile.basename; - final ProcessResult installNameResult = await globals.processManager.run( +/// +/// [oldToNewInstallNames] is a map from old to new install names, that should +/// be applied to the dependencies of the dylib. Entries in this map for +/// dependencies that are not present in the dylib are ignored. The install +/// name of a dependencies needs to be updated if the location of the dependency +/// has changed. +Future setInstallNamesDylib( + File dylibFile, + String newInstallName, + Map oldToNewInstallNames, +) async { + final ProcessResult setInstallNamesResult = await globals.processManager.run( [ 'install_name_tool', '-id', - '@rpath/$fileName.framework/$fileName', + newInstallName, + for (final MapEntry entry in oldToNewInstallNames.entries) + ...['-change', entry.key, entry.value], + dylibFile.path, + ], + ); + if (setInstallNamesResult.exitCode != 0) { + throwToolExit( + 'Failed to change install names in $dylibFile:\n' + 'id -> $newInstallName\n' + 'dependencies -> $newInstallName\n' + '${setInstallNamesResult.stderr}', + ); + } +} + +Future> getInstallNamesDylib(File dylibFile) async { + final ProcessResult installNameResult = await globals.processManager.run( + [ + 'otool', + '-D', dylibFile.path, ], ); if (installNameResult.exitCode != 0) { throwToolExit( - 'Failed to change the install name of $dylibFile:\n${installNameResult.stderr}', + 'Failed to get the install name of $dylibFile:\n${installNameResult.stderr}', ); } + + return { + for (final List architectureSection + in parseOtoolArchitectureSections(installNameResult.stdout as String).values) + // For each architecture, a separate install name is reported, which are + // not necessarily the same. + architectureSection.single, + }; } + + Future codesignDylib( String? codesignIdentity, BuildMode buildMode, @@ -206,3 +246,53 @@ Uri frameworkUri(String fileName, Set alreadyTakenNames) { alreadyTakenNames.add(fileName); return Uri(path: '$fileName.framework/$fileName'); } + +Map> parseOtoolArchitectureSections(String output) { + // The output of `otool -D`, for example, looks like below. For each + // architecture, there is a separate section. + // + // /build/native_assets/ios/buz.framework/buz (architecture x86_64): + // @rpath/libbuz.dylib + // /build/native_assets/ios/buz.framework/buz (architecture arm64): + // @rpath/libbuz.dylib + // + // Some versions of `otool` don't print the architecture name if the + // binary only has one architecture: + // + // /build/native_assets/ios/buz.framework/buz: + // @rpath/libbuz.dylib + + const Map outputArchitectures = { + 'arm': Architecture.arm, + 'arm64': Architecture.arm64, + 'x86_64': Architecture.x64, + }; + final RegExp architectureHeaderPattern = RegExp(r'^[^(]+( \(architecture (.+)\))?:$'); + final Iterator lines = output.trim().split('\n').iterator; + Architecture? currentArchitecture; + final Map> architectureSections = + >{}; + + while (lines.moveNext()) { + final String line = lines.current; + final Match? architectureHeader = architectureHeaderPattern.firstMatch(line); + if (architectureHeader != null) { + if (architectureSections.containsKey(null)) { + throwToolExit('Expected a single architecture section in otool output: $output'); + } + final String? architectureString = architectureHeader.group(2); + if (architectureString != null) { + currentArchitecture = outputArchitectures[architectureString]; + if (currentArchitecture == null) { + throwToolExit('Unknown architecture in otool output: $architectureString'); + } + } + architectureSections[currentArchitecture] = []; + continue; + } else { + architectureSections[currentArchitecture]!.add(line.trim()); + } + } + + return architectureSections; +} diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart index 41bb77ecce..0dee80b7f1 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart @@ -405,7 +405,7 @@ void ensureNoLinkModeStatic(List nativeAssets) { /// This should be the same for different archs, debug/release, etc. /// It should work for all macOS. -Uri nativeAssetsBuildUri(Uri projectUri, OSImpl os) { +Uri nativeAssetsBuildUri(Uri projectUri, OS os) { final String buildDir = build_info.getBuildDirectory(); return projectUri.resolve('$buildDir/native_assets/$os/'); } diff --git a/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart b/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart index 82bba5b9c7..d62ca7c76c 100644 --- a/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart +++ b/packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart @@ -4,6 +4,8 @@ // Logic for native assets shared between all host OSes. +import 'package:native_assets_cli/native_assets_cli.dart'; + import '../../../base/os.dart'; import '../../../base/platform.dart'; import '../../../build_info.dart'; @@ -22,6 +24,10 @@ class TestCompilerNativeAssetsBuilderImpl @override Future build(BuildInfo buildInfo) => testCompilerBuildNativeAssets(buildInfo); + + @override + String windowsBuildDirectory(FlutterProject project) => + nativeAssetsBuildUri(project.directory.uri, OS.windows).toFilePath(); } Future testCompilerBuildNativeAssets(BuildInfo buildInfo) async { diff --git a/packages/flutter_tools/lib/src/native_assets.dart b/packages/flutter_tools/lib/src/native_assets.dart index 97fbd75232..41f4773b6a 100644 --- a/packages/flutter_tools/lib/src/native_assets.dart +++ b/packages/flutter_tools/lib/src/native_assets.dart @@ -3,9 +3,18 @@ // found in the LICENSE file. import 'build_info.dart'; +import 'project.dart'; /// An interface to enable overriding native assets build logic in other /// build systems. abstract class TestCompilerNativeAssetsBuilder { Future build(BuildInfo buildInfo); + + /// Returns the Windows native assets build directory. + /// + /// By prepending the PATH environment variable for the flutter tester with the + /// return value of this function, DLLs in the native assets build directory can + /// be found by the dynamic linker. This is necessary to support native asset + /// libraries that dynamically link to other libraries. + String windowsBuildDirectory(FlutterProject project); } diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 3cd32358cc..82967b30ca 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -455,6 +455,7 @@ class FlutterPlatform extends PlatformPlugin { icudtlPath: icudtlPath, compileExpression: _compileExpressionService, fontConfigManager: _fontConfigManager, + nativeAssetsBuilder: nativeAssetsBuilder, ); } diff --git a/packages/flutter_tools/lib/src/test/flutter_tester_device.dart b/packages/flutter_tools/lib/src/test/flutter_tester_device.dart index 1cb717e60b..0e9b9b3175 100644 --- a/packages/flutter_tools/lib/src/test/flutter_tester_device.dart +++ b/packages/flutter_tools/lib/src/test/flutter_tester_device.dart @@ -18,10 +18,10 @@ import '../base/platform.dart'; import '../convert.dart'; import '../device.dart'; import '../globals.dart' as globals; +import '../native_assets.dart'; import '../project.dart'; import '../resident_runner.dart'; import '../vmservice.dart'; - import 'font_config_manager.dart'; import 'test_device.dart'; @@ -43,6 +43,7 @@ class FlutterTesterTestDevice extends TestDevice { required this.icudtlPath, required this.compileExpression, required this.fontConfigManager, + required this.nativeAssetsBuilder, }) : assert(!debuggingOptions.startPaused || enableVmService), _gotProcessVmServiceUri = enableVmService ? Completer() : (Completer()..complete()); @@ -63,6 +64,7 @@ class FlutterTesterTestDevice extends TestDevice { final String? icudtlPath; final CompileExpression? compileExpression; final FontConfigManager fontConfigManager; + final TestCompilerNativeAssetsBuilder? nativeAssetsBuilder; late final DartDevelopmentService _ddsLauncher = DartDevelopmentService(logger: logger); final Completer _gotProcessVmServiceUri; @@ -146,6 +148,8 @@ class FlutterTesterTestDevice extends TestDevice { 'FLUTTER_TEST_IMPELLER': 'true', if (testAssetDirectory != null) 'UNIT_TEST_ASSETS': testAssetDirectory!, + if (platform.isWindows && nativeAssetsBuilder != null && flutterProject != null) + 'PATH': '${nativeAssetsBuilder!.windowsBuildDirectory(flutterProject!)};${platform.environment['PATH']}', }; logger.printTrace('test $id: Starting flutter_tester process with command=$command, environment=$environment'); diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index 7bbadbb918..54613922fe 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart @@ -825,6 +825,8 @@ class SpawnPlugin extends PlatformPlugin { 'APP_NAME': flutterProject.manifest.appName, if (testAssetDirectory != null) 'UNIT_TEST_ASSETS': testAssetDirectory, + if (nativeAssetsBuilder != null && globals.platform.isWindows) + 'PATH': '${nativeAssetsBuilder.windowsBuildDirectory(flutterProject)};${globals.platform.environment['PATH']}', }; globals.logger.printTrace('Starting flutter_tester process with command=$command, environment=$environment'); diff --git a/packages/flutter_tools/lib/src/tester/flutter_tester.dart b/packages/flutter_tools/lib/src/tester/flutter_tester.dart index 40d83e79ab..651ab11885 100644 --- a/packages/flutter_tools/lib/src/tester/flutter_tester.dart +++ b/packages/flutter_tools/lib/src/tester/flutter_tester.dart @@ -18,6 +18,8 @@ import '../desktop_device.dart'; import '../devfs.dart'; import '../device.dart'; import '../device_port_forwarder.dart'; +import '../globals.dart' as globals; +import '../native_assets.dart'; import '../project.dart'; import '../protocol_discovery.dart'; import '../version.dart'; @@ -49,11 +51,13 @@ class FlutterTesterDevice extends Device { required super.logger, required FileSystem fileSystem, required Artifacts artifacts, + TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : _processManager = processManager, _flutterVersion = flutterVersion, _logger = logger, _fileSystem = fileSystem, - _artifacts = artifacts, + _artifacts = artifacts, + _nativeAssetsBuilder = nativeAssetsBuilder, super( platformType: null, category: null, @@ -65,6 +69,7 @@ class FlutterTesterDevice extends Device { final Logger _logger; final FileSystem _fileSystem; final Artifacts _artifacts; + final TestCompilerNativeAssetsBuilder? _nativeAssetsBuilder; Process? _process; final DevicePortForwarder _portForwarder = const NoOpDevicePortForwarder(); @@ -151,7 +156,9 @@ class FlutterTesterDevice extends Device { ); // Build assets and perform initial compilation. + final FlutterProject project = FlutterProject.current(); await BundleBuilder().build( + project: project, buildInfo: buildInfo, mainPath: mainPath, applicationKernelFilePath: applicationKernelFilePath, @@ -182,6 +189,8 @@ class FlutterTesterDevice extends Device { _process = await _processManager.start(command, environment: { 'FLUTTER_TEST': 'true', + if (globals.platform.isWindows && _nativeAssetsBuilder != null) + 'PATH': '${_nativeAssetsBuilder.windowsBuildDirectory(project)};${globals.platform.environment['PATH']}', }, ); if (!debuggingOptions.debuggingEnabled) { @@ -256,13 +265,15 @@ class FlutterTesterDevices extends PollingDeviceDiscovery { required ProcessManager processManager, required Logger logger, required FlutterVersion flutterVersion, + TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) : _testerDevice = FlutterTesterDevice( kTesterDeviceId, fileSystem: fileSystem, artifacts: artifacts, processManager: processManager, logger: logger, - flutterVersion: flutterVersion, + flutterVersion: flutterVersion, + nativeAssetsBuilder: nativeAssetsBuilder, ), super('Flutter tester'); diff --git a/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart b/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart index 7a52bf22af..2639e38816 100644 --- a/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart +++ b/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart @@ -12,6 +12,8 @@ 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/device.dart'; +import 'package:flutter_tools/src/native_assets.dart'; +import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/test/flutter_tester_device.dart'; import 'package:flutter_tools/src/test/font_config_manager.dart'; import 'package:flutter_tools/src/vmservice.dart'; @@ -41,6 +43,7 @@ void main() { List dartEntrypointArgs = const [], bool enableVmService = false, bool enableImpeller = false, + FlutterProject? flutterProject , }) => TestFlutterTesterDevice( platform: platform, @@ -49,6 +52,7 @@ void main() { enableVmService: enableVmService, dartEntrypointArgs: dartEntrypointArgs, enableImpeller: enableImpeller, + flutterProject: flutterProject, ); testUsingContext('Missing dir error caught for FontConfigManger.dispose', () async { @@ -95,6 +99,47 @@ void main() { ProcessManager: () => processManager, }); + testUsingContext('The PATH environment variable contains native assets build dir on Windows', () async { + platform = FakePlatform( + environment: {'PATH': r'C:\existing\path'}, + operatingSystem: 'windows', + ); + processManager = FakeProcessManager.list([]); + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + device = createDevice( + enableImpeller: true, + flutterProject: project, + ); + processManager.addCommand(FakeCommand(command: const [ + '/', + '--disable-vm-service', + '--ipv6', + '--enable-checked-mode', + '--verify-entry-points', + '--enable-impeller', + '--enable-dart-profiling', + '--non-interactive', + '--use-test-fonts', + '--disable-asset-fonts', + '--packages=.dart_tool/package_config.json', + 'example.dill', + ], environment: { + 'FLUTTER_TEST': 'true', + 'FONTCONFIG_FILE': device.fontConfigManager.fontConfigFile.path, + 'SERVER_PORT': '0', + 'APP_NAME': '', + 'FLUTTER_TEST_IMPELLER': 'true', + 'PATH': '${device.nativeAssetsBuilder!.windowsBuildDirectory(project)};${platform.environment['PATH']}', + })); + + await device.start('example.dill'); + + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + group('The FLUTTER_TEST environment variable is passed to the test process', () { setUp(() { processManager = FakeProcessManager.list([]); @@ -260,6 +305,7 @@ class TestFlutterTesterDevice extends FlutterTesterTestDevice { required super.enableVmService, required List dartEntrypointArgs, required bool enableImpeller, + super.flutterProject, }) : super( id: 999, shellPath: '/', @@ -278,10 +324,10 @@ class TestFlutterTesterDevice extends FlutterTesterTestDevice { machine: false, host: InternetAddress.loopbackIPv6, testAssetDirectory: null, - flutterProject: null, icudtlPath: null, compileExpression: null, fontConfigManager: FontConfigManager(), + nativeAssetsBuilder: FakeNativeAssetsBuilder(), ); @override @@ -306,3 +352,9 @@ class FakeHttpServer extends Fake implements HttpServer { @override int get port => 0; } + +class FakeNativeAssetsBuilder extends Fake implements TestCompilerNativeAssetsBuilder { + @override + String windowsBuildDirectory(FlutterProject project) => + r'C:\native_assets\path'; +} diff --git a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart index 243eeb323d..c8210fe7a9 100644 --- a/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/build_system/targets/native_assets_test.dart @@ -122,7 +122,61 @@ void main() { 'NativeAssets with an asset', overrides: { FileSystem: () => fileSystem, - ProcessManager: () => FakeProcessManager.any(), + ProcessManager: () => FakeProcessManager.list( + [ + // Create the framework dylib. + const FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + '/build/native_assets/ios/foo.framework/foo', + 'foo.framework/foo', + ], + ), + // Lookup the original install names of the dylib. + // There can be different install names for different architectures. + FakeCommand( + command: const [ + 'otool', + '-D', + '/build/native_assets/ios/foo.framework/foo', + ], + stdout: [ + '/build/native_assets/ios/foo.framework/foo (architecture x86_64):', + '@rpath/libfoo.dylib', + '/build/native_assets/ios/foo.framework/foo (architecture arm64):', + '@rpath/libfoo.dylib', + ].join('\n'), + ), + // Change the instal name of the binary itself and of its dependencies. + // We pass the old to new install name mappings of all native assets dylibs, + // even for the dylib that is being updated, since the `-change` option + // is ignored if the dylib does not depend on the target dylib. + const FakeCommand( + command: [ + 'install_name_tool', + '-id', + '@rpath/foo.framework/foo', + '-change', + '@rpath/libfoo.dylib', + '@rpath/foo.framework/foo', + '/build/native_assets/ios/foo.framework/foo', + ], + ), + // Only after all changes to the dylib have been made do we sign it. + const FakeCommand( + command: [ + 'codesign', + '--force', + '--sign', + '-', + '--timestamp=none', + '/build/native_assets/ios/foo.framework', + ], + ), + ], + ), FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }, () async { diff --git a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart index 2123abaeb2..21bd6e6944 100644 --- a/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/ios/native_assets_test.dart @@ -222,43 +222,109 @@ void main() { BuildMode.debug, BuildMode.release, ]) { - testUsingContext('build with assets $buildMode', - overrides: { - FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), - ProcessManager: () => FakeProcessManager.list( - [ - const FakeCommand( - command: [ - 'lipo', - '-create', - '-output', - '/build/native_assets/ios/bar.framework/bar', - 'arm64/libbar.dylib', - 'x64/libbar.dylib', - ], - ), - const FakeCommand( - command: [ - 'install_name_tool', - '-id', - '@rpath/bar.framework/bar', - '/build/native_assets/ios/bar.framework/bar' - ], - ), - FakeCommand( - command: [ - 'codesign', - '--force', - '--sign', - '-', - if (buildMode == BuildMode.debug) - '--timestamp=none', - '/build/native_assets/ios/bar.framework', - ], - ), - ], - ), - }, () async { + testUsingContext('build with assets $buildMode', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.list( + [ + const FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + '/build/native_assets/ios/bar.framework/bar', + 'arm64/libbar.dylib', + 'x64/libbar.dylib', + ], + ), + FakeCommand( + command: const [ + 'otool', + '-D', + '/build/native_assets/ios/bar.framework/bar', + ], + stdout: [ + '/build/native_assets/ios/bar.framework/bar (architecture x86_64):', + '@rpath/libbar.dylib', + '/build/native_assets/ios/bar.framework/bar (architecture arm64):', + '@rpath/libbar.dylib', + ].join('\n'), + ), + const FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + '/build/native_assets/ios/buz.framework/buz', + 'arm64/libbuz.dylib', + 'x64/libbuz.dylib', + ], + ), + FakeCommand( + command: const [ + 'otool', + '-D', + '/build/native_assets/ios/buz.framework/buz', + ], + stdout: [ + '/build/native_assets/ios/buz.framework/buz (architecture x86_64):', + '@rpath/libbuz.dylib', + '/build/native_assets/ios/buz.framework/buz (architecture arm64):', + '@rpath/libbuz.dylib', + ].join('\n'), + ), + const FakeCommand( + command: [ + 'install_name_tool', + '-id', + '@rpath/bar.framework/bar', + '-change', + '@rpath/libbar.dylib', + '@rpath/bar.framework/bar', + '-change', + '@rpath/libbuz.dylib', + '@rpath/buz.framework/buz', + '/build/native_assets/ios/bar.framework/bar', + ], + ), + FakeCommand( + command: [ + 'codesign', + '--force', + '--sign', + '-', + if (buildMode == BuildMode.debug) + '--timestamp=none', + '/build/native_assets/ios/bar.framework', + ], + ), + const FakeCommand( + command: [ + 'install_name_tool', + '-id', + '@rpath/buz.framework/buz', + '-change', + '@rpath/libbar.dylib', + '@rpath/bar.framework/bar', + '-change', + '@rpath/libbuz.dylib', + '@rpath/buz.framework/buz', + '/build/native_assets/ios/buz.framework/buz', + ], + ), + FakeCommand( + command: [ + 'codesign', + '--force', + '--sign', + '-', + if (buildMode == BuildMode.debug) + '--timestamp=none', + '/build/native_assets/ios/buz.framework', + ], + ), + ], + ), + }, () async { if (const LocalPlatform().isWindows) { return; // Backslashes in commands, but we will never run these commands on Windows. } @@ -273,16 +339,23 @@ void main() { ], onBuild: (native_assets_cli.Target target) => FakeNativeAssetsBuilderResult( - assets: [ - NativeCodeAssetImpl( - id: 'package:bar/bar.dart', - linkMode: DynamicLoadingBundledImpl(), - os: target.os, - architecture: target.architecture, - file: Uri.file('${target.architecture}/libbar.dylib'), + assets: [ + NativeCodeAssetImpl( + id: 'package:bar/bar.dart', + linkMode: DynamicLoadingBundledImpl(), + os: target.os, + architecture: target.architecture, + file: Uri.file('${target.architecture}/libbar.dylib'), + ), + NativeCodeAssetImpl( + id: 'package:buz/buz.dart', + linkMode: DynamicLoadingBundledImpl(), + os: target.os, + architecture: target.architecture, + file: Uri.file('${target.architecture}/libbuz.dylib'), + ), + ], ), - ], - ), ); await buildNativeAssetsIOS( darwinArchs: [DarwinArch.arm64, DarwinArch.x86_64], diff --git a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart index 7608db06de..765e21cca0 100644 --- a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter_tools/src/isolated/native_assets/macos/native_assets_host.dart'; +import 'package:native_assets_cli/native_assets_cli.dart'; import '../../../src/common.dart'; @@ -65,4 +66,83 @@ void main() { equals(Uri.file('atoolongfilenameforaframework2.framework/atoolongfilenameforaframework2')), ); }); + + group('parseOtoolArchitectureSections', () { + test('single architecture', () { + expect( + parseOtoolArchitectureSections( +''' +/build/native_assets/ios/buz.framework/buz (architecture x86_64): +@rpath/libfoo.dylib +''' + ), + >{ + Architecture.x64: ['@rpath/libfoo.dylib'], + }, + ); + }); + + test('single architecture but not specified', () { + expect( + parseOtoolArchitectureSections( +''' +/build/native_assets/ios/buz.framework/buz: +@rpath/libfoo.dylib +''' + ), + >{ + null: ['@rpath/libfoo.dylib'], + }, + ); + }); + + test('multiple architectures', () { + expect( + parseOtoolArchitectureSections( +''' +/build/native_assets/ios/buz.framework/buz (architecture x86_64): +@rpath/libfoo.dylib +/build/native_assets/ios/buz.framework/buz (architecture arm64): +@rpath/libbar.dylib +''' + ), + >{ + Architecture.x64: ['@rpath/libfoo.dylib'], + Architecture.arm64: ['@rpath/libbar.dylib'], + }, + ); + }); + + test('multiple lines in section', () { + expect( + parseOtoolArchitectureSections( +''' +/build/native_assets/ios/buz.framework/buz (architecture x86_64): +@rpath/libfoo.dylib +@rpath/libbar.dylib +''' + ), + >{ + Architecture.x64: [ + '@rpath/libfoo.dylib', + '@rpath/libbar.dylib', + ], + }, + ); + }); + + test('trim each line in section', () { + expect( + parseOtoolArchitectureSections( +''' +/build/native_assets/ios/buz.framework/buz (architecture x86_64): + @rpath/libfoo.dylib +''' + ), + >{ + Architecture.x64: ['@rpath/libfoo.dylib'], + }, + ); + }); + }); } diff --git a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart index accfcd463c..39ba493310 100644 --- a/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart +++ b/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_test.dart @@ -256,16 +256,23 @@ void main() { if (flutterTester) { testName += ' flutter tester'; } - final String dylibPath; - final String signPath; + final String dylibPathBar; + final String signPathBar; + final String dylibPathBuz; + final String signPathBuz; + if (flutterTester) { // Just the dylib. - dylibPath = '/build/native_assets/macos/libbar.dylib'; - signPath = '/build/native_assets/macos/libbar.dylib'; + dylibPathBar = '/build/native_assets/macos/libbar.dylib'; + signPathBar = '/build/native_assets/macos/libbar.dylib'; + dylibPathBuz = '/build/native_assets/macos/libbuz.dylib'; + signPathBuz = '/build/native_assets/macos/libbuz.dylib'; } else { // Packaged in framework. - dylibPath = '/build/native_assets/macos/bar.framework/Versions/A/bar'; - signPath = '/build/native_assets/macos/bar.framework'; + dylibPathBar = '/build/native_assets/macos/bar.framework/Versions/A/bar'; + signPathBar = '/build/native_assets/macos/bar.framework'; + dylibPathBuz = '/build/native_assets/macos/buz.framework/Versions/A/buz'; + signPathBuz = '/build/native_assets/macos/buz.framework'; } for (final BuildMode buildMode in [ BuildMode.debug, @@ -275,35 +282,179 @@ void main() { FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.list( [ - FakeCommand( - command: [ - 'lipo', - '-create', - '-output', - dylibPath, - 'arm64/libbar.dylib', - 'x64/libbar.dylib', - ], - ), - if (!flutterTester) + if (flutterTester) ...[ + FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + dylibPathBar, + 'arm64/libbar.dylib', + 'x64/libbar.dylib', + ], + ), + FakeCommand( + command: [ + 'otool', + '-D', + dylibPathBar, + ], + stdout: [ + '$dylibPathBar (architecture x86_64):', + '@rpath/libbar.dylib', + '$dylibPathBar (architecture arm64):', + '@rpath/libbar.dylib', + ].join('\n'), + ), + FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + dylibPathBuz, + 'arm64/libbuz.dylib', + 'x64/libbuz.dylib', + ], + ), + FakeCommand( + command: [ + 'otool', + '-D', + dylibPathBuz, + ], + stdout: [ + '$dylibPathBuz (architecture x86_64):', + '@rpath/libbuz.dylib', + '$dylibPathBuz (architecture arm64):', + '@rpath/libbuz.dylib', + ].join('\n'), + ), + FakeCommand( + command: [ + 'install_name_tool', + '-id', + dylibPathBar, + '-change', + '@rpath/libbar.dylib', + dylibPathBar, + '-change', + '@rpath/libbuz.dylib', + dylibPathBuz, + dylibPathBar, + ], + ), + FakeCommand( + command: [ + 'codesign', + '--force', + '--sign', + '-', + if (buildMode == BuildMode.debug) + '--timestamp=none', + signPathBar, + ], + ), + FakeCommand( + command: [ + 'install_name_tool', + '-id', + dylibPathBuz, + '-change', + '@rpath/libbar.dylib', + dylibPathBar, + '-change', + '@rpath/libbuz.dylib', + signPathBuz, + signPathBuz, + ], + ), + FakeCommand( + command: [ + 'codesign', + '--force', + '--sign', + '-', + if (buildMode == BuildMode.debug) + '--timestamp=none', + signPathBuz, + ], + ), + ] else ...[ + FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + dylibPathBar, + 'arm64/libbar.dylib', + 'x64/libbar.dylib', + ], + ), + FakeCommand( + command: [ + 'otool', + '-D', + dylibPathBar, + ], + stdout: [ + '$dylibPathBar (architecture x86_64):', + '@rpath/libbar.dylib', + '$dylibPathBar (architecture arm64):', + '@rpath/libbar.dylib', + ].join('\n'), + ), + FakeCommand( + command: [ + 'lipo', + '-create', + '-output', + dylibPathBuz, + 'arm64/libbuz.dylib', + 'x64/libbuz.dylib', + ], + ), + FakeCommand( + command: [ + 'otool', + '-D', + dylibPathBuz, + ], + stdout: [ + '$dylibPathBuz (architecture x86_64):', + '@rpath/libbuz.dylib', + '$dylibPathBuz (architecture arm64):', + '@rpath/libbuz.dylib', + ].join('\n'), + ), FakeCommand( command: [ 'install_name_tool', '-id', '@rpath/bar.framework/bar', - dylibPath, + '-change', + '@rpath/libbar.dylib', + '@rpath/bar.framework/bar', + '-change', + '@rpath/libbuz.dylib', + '@rpath/buz.framework/buz', + dylibPathBar, ], ), - FakeCommand( - command: [ - 'codesign', - '--force', - '--sign', - '-', - if (buildMode == BuildMode.debug) '--timestamp=none', - signPath, - ], - ), + FakeCommand( + command: [ + 'install_name_tool', + '-id', + '@rpath/buz.framework/buz', + '-change', + '@rpath/libbar.dylib', + '@rpath/bar.framework/bar', + '-change', + '@rpath/libbuz.dylib', + '@rpath/buz.framework/buz', + dylibPathBuz, + ], + ), + ], ], ), }, () async { @@ -319,16 +470,23 @@ void main() { ], onBuild: (native_assets_cli.Target target) => FakeNativeAssetsBuilderResult( - assets: [ - NativeCodeAssetImpl( - id: 'package:bar/bar.dart', - linkMode: DynamicLoadingBundledImpl(), - os: target.os, - architecture: target.architecture, - file: Uri.file('${target.architecture}/libbar.dylib'), + assets: [ + NativeCodeAssetImpl( + id: 'package:bar/bar.dart', + linkMode: DynamicLoadingBundledImpl(), + os: target.os, + architecture: target.architecture, + file: Uri.file('${target.architecture}/libbar.dylib'), + ), + NativeCodeAssetImpl( + id: 'package:buz/buz.dart', + linkMode: DynamicLoadingBundledImpl(), + os: target.os, + architecture: target.architecture, + file: Uri.file('${target.architecture}/libbuz.dylib'), + ), + ], ), - ], - ), ); final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsMacOS( darwinArchs: [DarwinArch.arm64, DarwinArch.x86_64], @@ -361,6 +519,18 @@ void main() { '- bar.framework/bar', ]), ); + expect( + await fileSystem.file(nativeAssetsYaml).readAsString(), + stringContainsInOrder([ + 'package:buz/buz.dart', + if (flutterTester) + // Tests run on host system, so the have the full path on the system. + '- ${projectUri.resolve('build/native_assets/macos/libbuz.dylib').toFilePath()}' + else + // Apps are a bundle with the dylibs on their dlopen path. + '- buz.framework/buz', + ]), + ); // Multi arch. expect(buildRunner.buildInvocations, 2); expect( diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index e8cb1050b6..e8f7b567f1 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -570,7 +570,8 @@ Future createTestProject(String packageName, Directory tempDirectory) await pinDependencies( packageDirectory.childDirectory('example').childFile('pubspec.yaml')); - await addLinkHookDepedendency(packageDirectory); + await addLinkHookDependency(packageDirectory); + await addDynamicallyLinkedNativeLibrary(packageDirectory); final ProcessResult result2 = await processManager.run( [ @@ -640,7 +641,7 @@ void main(List args) async { return packageDirectory; } -Future addLinkHookDepedendency(Directory packageDirectory) async { +Future addLinkHookDependency(Directory packageDirectory) async { final Directory flutterDirectory = fileSystem.currentDirectory.parent.parent; final Directory linkHookDirectory = flutterDirectory .childDirectory('dev') @@ -686,6 +687,108 @@ import '${packageName}_bindings_generated.dart' as bindings; await dartFile.writeAsString(dartFileNew2); } +/// Adds a native library to be built by the builder and dynamically link it to +/// the main library. +Future addDynamicallyLinkedNativeLibrary(Directory packageDirectory) async { + // Add linked library source files. + final Directory srcDirectory = packageDirectory.childDirectory('src'); + final File linkedLibraryHeaderFile = srcDirectory.childFile('add.h'); + await linkedLibraryHeaderFile.writeAsString(''' +#include + +#if _WIN32 +#define FFI_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FFI_PLUGIN_EXPORT +#endif + +FFI_PLUGIN_EXPORT intptr_t add(intptr_t a, intptr_t b); +''' + ); + final File linkedLibrarySourceFile = srcDirectory.childFile('add.c'); + await linkedLibrarySourceFile.writeAsString(''' +#include "add.h" + +FFI_PLUGIN_EXPORT intptr_t add(intptr_t a, intptr_t b) { + return a + b; +} +'''); + + // Update main library to include call to linked library. + final File mainLibrarySourceFile = srcDirectory.childFile('$packageName.c'); + String mainLibrarySource = await mainLibrarySourceFile.readAsString(); + mainLibrarySource = mainLibrarySource.replaceFirst( + '#include "$packageName.h"', +''' +#include "$packageName.h" +#include "add.h" +''', + ); + mainLibrarySource = mainLibrarySource.replaceAll('a + b', 'add(a, b)'); + await mainLibrarySourceFile.writeAsString(mainLibrarySource); + + // Update builder to build the native library and link it into the main library. + const String builderSource = r''' +import 'package:native_toolchain_c/native_toolchain_c.dart'; +import 'package:logging/logging.dart'; +import 'package:native_assets_cli/native_assets_cli.dart'; + +void main(List args) async { + await build(args, (config, output) async { + final packageName = config.packageName; + + final builders = [ + CBuilder.library( + name: 'add', + assetName: 'add', + sources: ['src/add.c'], + ), + CBuilder.library( + name: packageName, + assetName: '${packageName}_bindings_generated.dart', + sources: ['src/$packageName.c'], + flags: config.dynamicLinkingFlags('add'), + ), + ]; + + final logger = Logger('') + ..level = Level.ALL + ..onRecord.listen((record) => print(record.message)); + + for (final builder in builders) { + await builder.run( + config: config, + output: output, + logger: logger, + ); + } + }); +} + +extension on BuildConfig { + List dynamicLinkingFlags(String libraryName) => switch (targetOS) { + OS.macOS || OS.iOS => [ + '-L${outputDirectory.toFilePath()}', + '-l$libraryName', + ], + OS.linux || OS.android => [ + '-Wl,-rpath=\$ORIGIN/.', + '-L${outputDirectory.toFilePath()}', + '-l$libraryName', + ], + OS.windows => [ + outputDirectory.resolve('$libraryName.lib').toFilePath() + ], + _ => throw UnimplementedError('Unsupported OS: $targetOS'), + }; +} +'''; + + final Directory hookDirectory = packageDirectory.childDirectory('hook'); + final File builderFile = hookDirectory.childFile('build.dart'); + await builderFile.writeAsString(builderSource); +} + Future pinDependencies(File pubspecFile) async { expect(pubspecFile, exists); final String oldPubspec = await pubspecFile.readAsString();