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

import '../../artifacts.dart';
6
import '../../base/build.dart';
7
import '../../base/deferred_component.dart';
8 9
import '../../base/file_system.dart';
import '../../build_info.dart';
10
import '../../globals.dart' as globals show xcode;
11
import '../../project.dart';
12 13 14 15
import '../build_system.dart';
import '../depfile.dart';
import '../exceptions.dart';
import 'assets.dart';
16
import 'common.dart';
17
import 'icon_tree_shaker.dart';
18
import 'shader_compiler.dart';
19 20 21 22 23 24 25 26 27 28 29 30 31

/// Prepares the asset bundle in the format expected by flutter.gradle.
///
/// The vm_snapshot_data, isolate_snapshot_data, and kernel_blob.bin are
/// expected to be in the root output directory.
///
/// All assets and manifests are included from flutter_assets/**.
abstract class AndroidAssetBundle extends Target {
  const AndroidAssetBundle();

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{BUILD_DIR}/app.dill'),
32
    ...IconTreeShaker.inputs,
33 34 35
  ];

  @override
36 37 38
  List<Source> get outputs => const <Source>[];

  @override
39
  List<String> get depfiles => <String>[
40
    'flutter_assets.d',
41 42 43 44
  ];

  @override
  Future<void> build(Environment environment) async {
45 46
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
47 48
      throw MissingDefineException(kBuildMode, name);
    }
49
    final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
50 51 52 53 54 55
    final Directory outputDirectory = environment.outputDir
      .childDirectory('flutter_assets')
      ..createSync(recursive: true);

    // Only copy the prebuilt runtimes and kernel blob in debug mode.
    if (buildMode == BuildMode.debug) {
56 57
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
58 59
      environment.buildDir.childFile('app.dill')
          .copySync(outputDirectory.childFile('kernel_blob.bin').path);
60
      environment.fileSystem.file(vmSnapshotData)
61
          .copySync(outputDirectory.childFile('vm_snapshot_data').path);
62
      environment.fileSystem.file(isolateSnapshotData)
63 64
          .copySync(outputDirectory.childFile('isolate_snapshot_data').path);
    }
65 66 67 68
    final Depfile assetDepfile = await copyAssets(
      environment,
      outputDirectory,
      targetPlatform: TargetPlatform.android,
69
      buildMode: buildMode,
70
      shaderTarget: ShaderTarget.impellerAndroid,
71
    );
72
    environment.depFileService.writeToFile(
73 74 75
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  }

  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];
}

/// An implementation of [AndroidAssetBundle] that includes dependencies on vm
/// and isolate data.
class DebugAndroidApplication extends AndroidAssetBundle {
  const DebugAndroidApplication();

  @override
  String get name => 'debug_android_application';

  @override
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
    const Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
  ];

  @override
  List<Source> get outputs => <Source>[
    ...super.outputs,
102 103 104
    const Source.pattern('{OUTPUT_DIR}/flutter_assets/vm_snapshot_data'),
    const Source.pattern('{OUTPUT_DIR}/flutter_assets/isolate_snapshot_data'),
    const Source.pattern('{OUTPUT_DIR}/flutter_assets/kernel_blob.bin'),
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  ];
}

/// An implementation of [AndroidAssetBundle] that only includes assets.
class AotAndroidAssetBundle extends AndroidAssetBundle {
  const AotAndroidAssetBundle();

  @override
  String get name => 'aot_android_asset_bundle';
}

/// Build a profile android application's Dart artifacts.
class ProfileAndroidApplication extends CopyFlutterAotBundle {
  const ProfileAndroidApplication();

  @override
  String get name => 'profile_android_application';

  @override
  List<Target> get dependencies => const <Target>[
125
    AotElfProfile(TargetPlatform.android_arm),
126 127 128 129 130 131 132 133 134 135 136 137 138
    AotAndroidAssetBundle(),
  ];
}

/// Build a release android application's Dart artifacts.
class ReleaseAndroidApplication extends CopyFlutterAotBundle {
  const ReleaseAndroidApplication();

  @override
  String get name => 'release_android_application';

  @override
  List<Target> get dependencies => const <Target>[
139
    AotElfRelease(TargetPlatform.android_arm),
140 141 142
    AotAndroidAssetBundle(),
  ];
}
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

/// Generate an ELF binary from a dart kernel file in release mode.
///
/// This rule implementation outputs the generated so to a unique location
/// based on the Android ABI. This allows concurrent invocations of gen_snapshot
/// to run simultaneously.
///
/// The name of an instance of this rule would be 'android_aot_profile_android-x64'
/// and is relied upon by flutter.gradle to match the correct rule.
///
/// It will produce an 'app.so` in the build directory under a folder named with
/// the matching Android ABI.
class AndroidAot extends AotElfBase {
  /// Create an [AndroidAot] implementation for a given [targetPlatform] and [buildMode].
  const AndroidAot(this.targetPlatform, this.buildMode);

  /// The name of the produced Android ABI.
  String get _androidAbiName {
161
    return getAndroidArchForName(getNameForTargetPlatform(targetPlatform)).archName;
162 163 164
  }

  @override
165
  String get name => 'android_aot_${buildMode.cliName}_'
166 167 168 169 170 171 172
    '${getNameForTargetPlatform(targetPlatform)}';

  /// The specific Android ABI we are building for.
  final TargetPlatform targetPlatform;

  /// The selected build mode.
  ///
173
  /// Build mode is restricted to [BuildMode.profile] or [BuildMode.release] for AOT builds.
174 175 176 177
  final BuildMode buildMode;

  @override
  List<Source> get inputs => <Source>[
178
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/android.dart'),
179
    const Source.pattern('{BUILD_DIR}/app.dill'),
180
    const Source.artifact(Artifact.engineDartBinary),
181 182 183 184 185 186 187 188 189 190 191 192
    const Source.artifact(Artifact.skyEnginePath),
    Source.artifact(Artifact.genSnapshot,
      mode: buildMode,
      platform: targetPlatform,
     ),
  ];

  @override
  List<Source> get outputs => <Source>[
    Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'),
  ];

193 194 195 196 197
  @override
  List<String> get depfiles => <String>[
    'flutter_$name.d',
  ];

198 199 200 201 202 203 204
  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];

  @override
  Future<void> build(Environment environment) async {
205
    final AOTSnapshotter snapshotter = AOTSnapshotter(
206 207
      fileSystem: environment.fileSystem,
      logger: environment.logger,
208
      xcode: globals.xcode!,
209 210
      processManager: environment.processManager,
      artifacts: environment.artifacts,
211
    );
212
    final Directory output = environment.buildDir.childDirectory(_androidAbiName);
213 214
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
215 216 217 218 219
      throw MissingDefineException(kBuildMode, 'aot_elf');
    }
    if (!output.existsSync()) {
      output.createSync(recursive: true);
    }
220
    final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
221
    final List<File> outputs = <File>[]; // outputs for the depfile
222
    final String manifestPath = '${output.path}${environment.platform.pathSeparator}manifest.json';
223 224 225 226
    if (environment.defines[kDeferredComponents] == 'true') {
      extraGenSnapshotOptions.add('--loading_unit_manifest=$manifestPath');
      outputs.add(environment.fileSystem.file(manifestPath));
    }
227
    final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
228
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
229
    final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
230 231 232 233 234 235 236 237 238 239 240 241

    if (codeSizeDirectory != null) {
      final File codeSizeFile = environment.fileSystem
        .directory(codeSizeDirectory)
        .childFile('snapshot.$_androidAbiName.json');
      final File precompilerTraceFile = environment.fileSystem
        .directory(codeSizeDirectory)
        .childFile('trace.$_androidAbiName.json');
      extraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}');
      extraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}');
    }

242
    final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
243 244 245 246 247
    final int snapshotExitCode = await snapshotter.build(
      platform: targetPlatform,
      buildMode: buildMode,
      mainPath: environment.buildDir.childFile('app.dill').path,
      outputPath: output.path,
248
      extraGenSnapshotOptions: extraGenSnapshotOptions,
249
      splitDebugInfo: splitDebugInfo,
250
      dartObfuscation: dartObfuscation,
251 252 253 254
    );
    if (snapshotExitCode != 0) {
      throw Exception('AOT snapshotter exited with code $snapshotExitCode');
    }
255 256 257 258 259 260 261
    if (environment.defines[kDeferredComponents] == 'true') {
      // Parse the manifest for .so paths
      final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(environment.fileSystem.file(manifestPath), environment.logger);
      for (final LoadingUnit unit in loadingUnits) {
        outputs.add(environment.fileSystem.file(unit.path));
      }
    }
262
    environment.depFileService.writeToFile(
263 264 265 266
      Depfile(<File>[], outputs),
      environment.buildDir.childFile('flutter_$name.d'),
      writeEmpty: true,
    );
267 268 269 270
  }
}

// AndroidAot instances used by the bundle rules below.
271 272 273 274 275 276
const AndroidAot androidArmProfile = AndroidAot(TargetPlatform.android_arm,  BuildMode.profile);
const AndroidAot androidArm64Profile = AndroidAot(TargetPlatform.android_arm64, BuildMode.profile);
const AndroidAot androidx64Profile = AndroidAot(TargetPlatform.android_x64, BuildMode.profile);
const AndroidAot androidArmRelease = AndroidAot(TargetPlatform.android_arm,  BuildMode.release);
const AndroidAot androidArm64Release = AndroidAot(TargetPlatform.android_arm64, BuildMode.release);
const AndroidAot androidx64Release = AndroidAot(TargetPlatform.android_x64, BuildMode.release);
277

278
/// A rule paired with [AndroidAot] that copies the produced so file and manifest.json (if present) into the output directory.
279 280 281 282 283 284 285 286 287
class AndroidAotBundle extends Target {
  /// Create an [AndroidAotBundle] implementation for a given [targetPlatform] and [buildMode].
  const AndroidAotBundle(this.dependency);

  /// The [AndroidAot] instance this bundle rule depends on.
  final AndroidAot dependency;

  /// The name of the produced Android ABI.
  String get _androidAbiName {
288
    return getAndroidArchForName(getNameForTargetPlatform(dependency.targetPlatform)).archName;
289 290 291
  }

  @override
292
  String get name => 'android_aot_bundle_${dependency.buildMode.cliName}_'
293 294
    '${getNameForTargetPlatform(dependency.targetPlatform)}';

295 296 297 298 299 300 301
  TargetPlatform get targetPlatform => dependency.targetPlatform;

  /// The selected build mode.
  ///
  /// This is restricted to [BuildMode.profile] or [BuildMode.release].
  BuildMode get buildMode => dependency.buildMode;

302 303
  @override
  List<Source> get inputs => <Source>[
304
    Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'),
305 306 307 308 309 310 311 312
  ];

  // flutter.gradle has been updated to correctly consume it.
  @override
  List<Source> get outputs => <Source>[
    Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'),
  ];

313 314 315 316 317
  @override
  List<String> get depfiles => <String>[
    'flutter_$name.d',
  ];

318 319 320 321 322 323 324 325
  @override
  List<Target> get dependencies => <Target>[
    dependency,
    const AotAndroidAssetBundle(),
  ];

  @override
  Future<void> build(Environment environment) async {
326
    final Directory buildDir = environment.buildDir.childDirectory(_androidAbiName);
327 328 329 330 331
    final Directory outputDirectory = environment.outputDir
      .childDirectory(_androidAbiName);
    if (!outputDirectory.existsSync()) {
      outputDirectory.createSync(recursive: true);
    }
332 333 334 335 336 337 338 339 340 341 342 343
    final File outputLibFile = buildDir.childFile('app.so');
    outputLibFile.copySync(outputDirectory.childFile('app.so').path);

    final List<File> inputs = <File>[];
    final List<File> outputs = <File>[];
    final File manifestFile = buildDir.childFile('manifest.json');
    if (manifestFile.existsSync()) {
      final File destinationFile = outputDirectory.childFile('manifest.json');
      manifestFile.copySync(destinationFile.path);
      inputs.add(manifestFile);
      outputs.add(destinationFile);
    }
344
    environment.depFileService.writeToFile(
345 346 347 348
      Depfile(inputs, outputs),
      environment.buildDir.childFile('flutter_$name.d'),
      writeEmpty: true,
    );
349 350 351 352
  }
}

// AndroidBundleAot instances.
353 354 355 356 357 358 359 360 361 362 363 364
const AndroidAotBundle androidArmProfileBundle = AndroidAotBundle(androidArmProfile);
const AndroidAotBundle androidArm64ProfileBundle = AndroidAotBundle(androidArm64Profile);
const AndroidAotBundle androidx64ProfileBundle = AndroidAotBundle(androidx64Profile);
const AndroidAotBundle androidArmReleaseBundle = AndroidAotBundle(androidArmRelease);
const AndroidAotBundle androidArm64ReleaseBundle = AndroidAotBundle(androidArm64Release);
const AndroidAotBundle androidx64ReleaseBundle = AndroidAotBundle(androidx64Release);

// Rule that copies split aot library files to the intermediate dirs of each deferred component.
class AndroidAotDeferredComponentsBundle extends Target {
  /// Create an [AndroidAotDeferredComponentsBundle] implementation for a given [targetPlatform] and [buildMode].
  ///
  /// If [components] is not provided, it will be read from the pubspec.yaml manifest.
365
  AndroidAotDeferredComponentsBundle(this.dependency, {List<DeferredComponent>? components}) : _components = components;
366 367 368 369

  /// The [AndroidAotBundle] instance this bundle rule depends on.
  final AndroidAotBundle dependency;

370
  List<DeferredComponent>? _components;
371 372 373

  /// The name of the produced Android ABI.
  String get _androidAbiName {
374
    return getAndroidArchForName(getNameForTargetPlatform(dependency.targetPlatform)).archName;
375 376 377
  }

  @override
378
  String get name => 'android_aot_deferred_components_bundle_${dependency.buildMode.cliName}_'
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    '${getNameForTargetPlatform(dependency.targetPlatform)}';

  TargetPlatform get targetPlatform => dependency.targetPlatform;

  @override
  List<Source> get inputs => <Source>[
    // Tracking app.so is enough to invalidate the dynamically named
    // loading unit libs as changes to loading units guarantee
    // changes to app.so as well. This task does not actually
    // copy app.so.
    Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'),
    const Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
  ];

  @override
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => <String>[
    'flutter_$name.d',
  ];

  @override
  List<Target> get dependencies => <Target>[
    dependency,
  ];

  @override
  Future<void> build(Environment environment) async {
    _components ??= FlutterProject.current().manifest.deferredComponents ?? <DeferredComponent>[];
    final List<String> abis = <String>[_androidAbiName];
    final List<LoadingUnit> generatedLoadingUnits = LoadingUnit.parseGeneratedLoadingUnits(environment.outputDir, environment.logger, abis: abis);
411
    for (final DeferredComponent component in _components!) {
412 413
      component.assignLoadingUnits(generatedLoadingUnits);
    }
414
    final Depfile libDepfile = copyDeferredComponentSoFiles(environment, _components!, generatedLoadingUnits, environment.projectDir.childDirectory('build'), abis, dependency.buildMode);
415 416 417 418 419 420

    final File manifestFile = environment.outputDir.childDirectory(_androidAbiName).childFile('manifest.json');
    if (manifestFile.existsSync()) {
      libDepfile.inputs.add(manifestFile);
    }

421
    environment.depFileService.writeToFile(
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
      libDepfile,
      environment.buildDir.childFile('flutter_$name.d'),
      writeEmpty: true,
    );
  }
}

Target androidArmProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmProfileBundle);
Target androidArm64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ProfileBundle);
Target androidx64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ProfileBundle);
Target androidArmReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmReleaseBundle);
Target androidArm64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ReleaseBundle);
Target androidx64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ReleaseBundle);

/// A set of all target names that build deferred component apps.
Set<String> deferredComponentsTargets = <String>{
  androidArmProfileDeferredComponentsBundle.name,
  androidArm64ProfileDeferredComponentsBundle.name,
  androidx64ProfileDeferredComponentsBundle.name,
  androidArmReleaseDeferredComponentsBundle.name,
  androidArm64ReleaseDeferredComponentsBundle.name,
  androidx64ReleaseDeferredComponentsBundle.name,
};
445 446 447 448 449 450 451 452

/// Utility method to copy and rename the required .so shared libs from the build output
/// to the correct component intermediate directory.
///
/// The [DeferredComponent]s passed to this method must have had loading units assigned.
/// Assigned components are components that have determined which loading units contains
/// the dart libraries it has via the DeferredComponent.assignLoadingUnits method.
Depfile copyDeferredComponentSoFiles(
453 454 455 456 457 458 459
  Environment env,
  List<DeferredComponent> components,
  List<LoadingUnit> loadingUnits,
  Directory buildDir, // generally `<projectDir>/build`
  List<String> abis,
  BuildMode buildMode,
) {
460 461 462 463 464 465
  final List<File> inputs = <File>[];
  final List<File> outputs = <File>[];
  final Set<int> usedLoadingUnits = <int>{};
  // Copy all .so files for loading units that are paired with a deferred component.
  for (final String abi in abis) {
    for (final DeferredComponent component in components) {
466 467 468
      final Set<LoadingUnit>? loadingUnits = component.loadingUnits;
      if (loadingUnits == null || !component.assigned) {
        env.logger.printError('Deferred component require loading units to be assigned.');
469 470
        return Depfile(inputs, outputs);
      }
471
      for (final LoadingUnit unit in loadingUnits) {
472
        // ensure the abi for the unit is one of the abis we build for.
473 474
        final List<String>? splitPath = unit.path?.split(env.fileSystem.path.separator);
        if (splitPath == null || splitPath[splitPath.length - 2] != abi) {
475 476 477 478 479 480 481 482
          continue;
        }
        usedLoadingUnits.add(unit.id);
        // the deferred_libs directory is added as a source set for the component.
        final File destination = buildDir
            .childDirectory(component.name)
            .childDirectory('intermediates')
            .childDirectory('flutter')
483
            .childDirectory(buildMode.cliName)
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
            .childDirectory('deferred_libs')
            .childDirectory(abi)
            .childFile('libapp.so-${unit.id}.part.so');
        if (!destination.existsSync()) {
          destination.createSync(recursive: true);
        }
        final File source = env.fileSystem.file(unit.path);
        source.copySync(destination.path);
        inputs.add(source);
        outputs.add(destination);
      }
    }
  }
  // Copy unused loading units, which are included in the base module.
  for (final String abi in abis) {
    for (final LoadingUnit unit in loadingUnits) {
      if (usedLoadingUnits.contains(unit.id)) {
        continue;
      }
        // ensure the abi for the unit is one of the abis we build for.
504 505
      final List<String>? splitPath = unit.path?.split(env.fileSystem.path.separator);
      if (splitPath == null || splitPath[splitPath.length - 2] != abi) {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        continue;
      }
      final File destination = env.outputDir
          .childDirectory(abi)
          // Omit 'lib' prefix here as it is added by the gradle task that adds 'lib' to 'app.so'.
          .childFile('app.so-${unit.id}.part.so');
      if (!destination.existsSync()) {
          destination.createSync(recursive: true);
        }
      final File source = env.fileSystem.file(unit.path);
      source.copySync(destination.path);
      inputs.add(source);
      outputs.add(destination);
    }
  }
  return Depfile(inputs, outputs);
}