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

5 6
import 'package:package_config/package_config.dart';

7 8 9 10 11
import '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/file_system.dart';
import '../../build_info.dart';
import '../../compile.dart';
12
import '../../dart/package_map.dart';
13
import '../../globals.dart' as globals hide fs, processManager, artifacts, logger;
14
import '../build_system.dart';
15
import '../depfile.dart';
16
import '../exceptions.dart';
17
import 'assets.dart';
18
import 'icon_tree_shaker.dart';
19
import 'localizations.dart';
20 21

/// The define to pass a [BuildMode].
22
const String kBuildMode = 'BuildMode';
23 24 25 26 27 28 29

/// The define to pass whether we compile 64-bit android-arm code.
const String kTargetPlatform = 'TargetPlatform';

/// The define to control what target file is used.
const String kTargetFile = 'TargetFile';

30 31 32
/// The define to control whether the AOT snapshot is built with bitcode.
const String kBitcodeFlag = 'EnableBitcode';

33 34 35
/// Whether to enable or disable track widget creation.
const String kTrackWidgetCreation = 'TrackWidgetCreation';

36 37 38 39 40 41 42 43 44 45
/// Additional configuration passed to the dart front end.
///
/// This is expected to be a comma separated list of strings.
const String kExtraFrontEndOptions = 'ExtraFrontEndOptions';

/// Additional configuration passed to gen_snapshot.
///
/// This is expected to be a comma separated list of strings.
const String kExtraGenSnapshotOptions = 'ExtraGenSnapshotOptions';

46 47 48
/// Whether to strip source code information out of release builds and where to save it.
const String kSplitDebugInfo = 'SplitDebugInfo';

49 50
/// Alternative scheme for file URIs.
///
51
/// May be used along with [kFileSystemRoots] to support a multi-root
52 53 54 55 56 57 58 59
/// filesystem.
const String kFileSystemScheme = 'FileSystemScheme';

/// Additional filesystem roots.
///
/// If provided, must be used along with [kFileSystemScheme].
const String kFileSystemRoots = 'FileSystemRoots';

60 61 62 63 64 65 66 67
/// The define to control what iOS architectures are built for.
///
/// This is expected to be a comma-separated list of architectures. If not
/// provided, defaults to arm64.
///
/// The other supported value is armv7, the 32-bit iOS architecture.
const String kIosArchs = 'IosArchs';

68 69 70
/// Whether to enable Dart obfuscation and where to save the symbol map.
const String kDartObfuscation = 'DartObfuscation';

71 72 73
/// An output directory where one or more code-size measurements may be written.
const String kCodeSizeDirectory = 'CodeSizeDirectory';

74
/// Copies the pre-built flutter bundle.
75 76 77 78 79 80 81 82 83 84 85 86
// This is a one-off rule for implementing build bundle in terms of assemble.
class CopyFlutterBundle extends Target {
  const CopyFlutterBundle();

  @override
  String get name => 'copy_flutter_bundle';

  @override
  List<Source> get inputs => const <Source>[
    Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
    Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
    Source.pattern('{BUILD_DIR}/app.dill'),
87
    ...IconTreeShaker.inputs,
88 89 90 91 92 93 94
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/vm_snapshot_data'),
    Source.pattern('{OUTPUT_DIR}/isolate_snapshot_data'),
    Source.pattern('{OUTPUT_DIR}/kernel_blob.bin'),
95 96 97 98 99
  ];

  @override
  List<String> get depfiles => <String>[
    'flutter_assets.d'
100 101 102 103 104 105 106 107 108 109 110 111
  ];

  @override
  Future<void> build(Environment environment) async {
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'copy_flutter_bundle');
    }
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    environment.outputDir.createSync(recursive: true);

    // Only copy the prebuilt runtimes and kernel blob in debug mode.
    if (buildMode == BuildMode.debug) {
112 113
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
114 115
      environment.buildDir.childFile('app.dill')
          .copySync(environment.outputDir.childFile('kernel_blob.bin').path);
116
      environment.fileSystem.file(vmSnapshotData)
117
          .copySync(environment.outputDir.childFile('vm_snapshot_data').path);
118
      environment.fileSystem.file(isolateSnapshotData)
119 120
          .copySync(environment.outputDir.childFile('isolate_snapshot_data').path);
    }
121 122 123 124 125
    final Depfile assetDepfile = await copyAssets(
      environment,
      environment.outputDir,
      targetPlatform: TargetPlatform.android,
    );
126
    final DepfileService depfileService = DepfileService(
127 128
      fileSystem: environment.fileSystem,
      logger: environment.logger,
129 130 131 132 133
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
134 135 136 137 138 139 140 141
  }

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

142
/// Copies the pre-built flutter bundle for release mode.
143 144 145 146 147 148 149
class ReleaseCopyFlutterBundle extends CopyFlutterBundle {
  const ReleaseCopyFlutterBundle();

  @override
  String get name => 'release_flutter_bundle';

  @override
150
  List<Source> get inputs => const <Source>[];
151 152

  @override
153 154 155 156 157
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => const <String>[
    'flutter_assets.d',
158 159 160 161 162 163
  ];

  @override
  List<Target> get dependencies => const <Target>[];
}

164
/// Generate a snapshot of the dart code used in the program.
165 166 167 168 169
///
/// Note that this target depends on the `.dart_tool/package_config.json` file
/// even though it is not listed as an input. Pub inserts a timestamp into
/// the file which causes unecessary rebuilds, so instead a subset of the contents
/// are used an input instead.
170 171 172 173 174 175 176 177
class KernelSnapshot extends Target {
  const KernelSnapshot();

  @override
  String get name => 'kernel_snapshot';

  @override
  List<Source> get inputs => const <Source>[
178
    Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
179
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
180 181 182 183 184 185
    Source.artifact(Artifact.platformKernelDill),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.frontendServerSnapshotForEngineDartSdk),
  ];

  @override
186 187 188 189 190
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => <String>[
    'kernel_snapshot.d',
191 192 193
  ];

  @override
194 195 196
  List<Target> get dependencies => const <Target>[
    GenerateLocalizationsTarget(),
  ];
197 198

  @override
199
  Future<void> build(Environment environment) async {
200 201 202 203 204
    final KernelCompiler compiler = KernelCompiler(
      fileSystem: environment.fileSystem,
      logger: environment.logger,
      processManager: environment.processManager,
      artifacts: environment.artifacts,
205 206
      fileSystemRoots: <String>[],
      fileSystemScheme: null,
207 208 209 210
    );
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'kernel_snapshot');
    }
211 212 213
    if (environment.defines[kTargetPlatform] == null) {
      throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
    }
214
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
215
    final String targetFile = environment.defines[kTargetFile] ?? environment.fileSystem.path.join('lib', 'main.dart');
216 217 218
    final File packagesFile = environment.projectDir
      .childDirectory('.dart_tool')
      .childFile('package_config.json');
219
    final String targetFileAbsolute = environment.fileSystem.file(targetFile).absolute.path;
220 221
    // everything besides 'false' is considered to be enabled.
    final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false';
222 223
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);

224
    // This configuration is all optional.
225
    final List<String> extraFrontEndOptions = decodeDartDefines(environment.defines, kExtraFrontEndOptions);
226 227 228
    final List<String> fileSystemRoots = environment.defines[kFileSystemRoots]?.split(',');
    final String fileSystemScheme = environment.defines[kFileSystemScheme];

229 230 231 232 233
    TargetModel targetModel = TargetModel.flutter;
    if (targetPlatform == TargetPlatform.fuchsia_x64 ||
        targetPlatform == TargetPlatform.fuchsia_arm64) {
      targetModel = TargetModel.flutterRunner;
    }
234 235 236 237 238
    // Force linking of the platform for desktop embedder targets since these
    // do not correctly load the core snapshots in debug mode.
    // See https://github.com/flutter/flutter/issues/44724
    bool forceLinkPlatform;
    switch (targetPlatform) {
239 240 241
      case TargetPlatform.darwin_x64:
      case TargetPlatform.windows_x64:
      case TargetPlatform.linux_x64:
242 243 244 245 246
        forceLinkPlatform = true;
        break;
      default:
        forceLinkPlatform = false;
    }
247

248
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
249
      packagesFile,
250
      logger: environment.logger,
251 252
    );

253
    final CompilerOutput output = await compiler.compile(
254
      sdkRoot: environment.artifacts.getArtifactPath(
255 256 257 258
        Artifact.flutterPatchedSdkPath,
        platform: targetPlatform,
        mode: buildMode,
      ),
259
      aot: buildMode.isPrecompiled,
260
      buildMode: buildMode,
261
      trackWidgetCreation: trackWidgetCreation && buildMode == BuildMode.debug,
262
      targetModel: targetModel,
263
      outputFilePath: environment.buildDir.childFile('app.dill').path,
264
      packagesPath: packagesFile.path,
265
      linkPlatformKernelIn: forceLinkPlatform || buildMode.isPrecompiled,
266
      mainPath: targetFileAbsolute,
267
      depFilePath: environment.buildDir.childFile('kernel_snapshot.d').path,
268 269 270
      extraFrontEndOptions: extraFrontEndOptions,
      fileSystemRoots: fileSystemRoots,
      fileSystemScheme: fileSystemScheme,
271
      dartDefines: decodeDartDefines(environment.defines, kDartDefines),
272
      packageConfig: packageConfig,
273
    );
274
    if (output == null || output.errorCount != 0) {
275
      throw Exception();
276
    }
277
  }
278
}
279

280 281 282 283
/// Supports compiling a dart kernel file to an ELF binary.
abstract class AotElfBase extends Target {
  const AotElfBase();

284 285 286
  @override
  String get analyticsName => 'android_aot';

287
  @override
288
  Future<void> build(Environment environment) async {
289 290
    final AOTSnapshotter snapshotter = AOTSnapshotter(
      reportTimings: false,
291 292
      fileSystem: environment.fileSystem,
      logger: environment.logger,
293
      xcode: globals.xcode,
294 295
      processManager: environment.processManager,
      artifacts: environment.artifacts,
296
    );
297 298 299 300 301 302 303
    final String outputPath = environment.buildDir.path;
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'aot_elf');
    }
    if (environment.defines[kTargetPlatform] == null) {
      throw MissingDefineException(kTargetPlatform, 'aot_elf');
    }
304
    final List<String> extraGenSnapshotOptions = decodeDartDefines(environment.defines, kExtraGenSnapshotOptions);
305 306
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);
307 308
    final String splitDebugInfo = environment.defines[kSplitDebugInfo];
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
309 310 311 312 313 314 315 316 317 318 319 320 321
    final String codeSizeDirectory = environment.defines[kCodeSizeDirectory];

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

322 323 324
    final int snapshotExitCode = await snapshotter.build(
      platform: targetPlatform,
      buildMode: buildMode,
325
      mainPath: environment.buildDir.childFile('app.dill').path,
326 327
      packagesPath: environment.projectDir.childFile('.packages').path,
      outputPath: outputPath,
328
      bitcode: false,
329
      extraGenSnapshotOptions: extraGenSnapshotOptions,
330 331
      splitDebugInfo: splitDebugInfo,
      dartObfuscation: dartObfuscation,
332 333 334 335 336 337 338 339
    );
    if (snapshotExitCode != 0) {
      throw Exception('AOT snapshotter exited with code $snapshotExitCode');
    }
  }
}

/// Generate an ELF binary from a dart kernel file in profile mode.
340
class AotElfProfile extends AotElfBase {
341
  const AotElfProfile(this.targetPlatform);
342 343 344 345 346

  @override
  String get name => 'aot_elf_profile';

  @override
347
  List<Source> get inputs => <Source>[
348
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
349 350 351
    const Source.pattern('{BUILD_DIR}/app.dill'),
    const Source.artifact(Artifact.engineDartBinary),
    const Source.artifact(Artifact.skyEnginePath),
352
    Source.artifact(Artifact.genSnapshot,
353
      platform: targetPlatform,
354 355
      mode: BuildMode.profile,
    ),
356 357 358 359
  ];

  @override
  List<Source> get outputs => const <Source>[
360
    Source.pattern('{BUILD_DIR}/app.so'),
361 362 363 364 365 366
  ];

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

368
  final TargetPlatform targetPlatform;
369
}
370 371

/// Generate an ELF binary from a dart kernel file in release mode.
372
class AotElfRelease extends AotElfBase {
373
  const AotElfRelease(this.targetPlatform);
374 375 376 377 378

  @override
  String get name => 'aot_elf_release';

  @override
379
  List<Source> get inputs => <Source>[
380
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
381 382 383
    const Source.pattern('{BUILD_DIR}/app.dill'),
    const Source.artifact(Artifact.engineDartBinary),
    const Source.artifact(Artifact.skyEnginePath),
384
    Source.artifact(Artifact.genSnapshot,
385
      platform: targetPlatform,
386 387
      mode: BuildMode.release,
    ),
388
  ];
389

390 391 392 393
  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/app.so'),
  ];
394

395 396 397 398
  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];
399

400
  final TargetPlatform targetPlatform;
401
}
402

403
/// Copies the pre-built flutter aot bundle.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
// This is a one-off rule for implementing build aot in terms of assemble.
abstract class CopyFlutterAotBundle extends Target {
  const CopyFlutterAotBundle();

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

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

  @override
  Future<void> build(Environment environment) async {
    final File outputFile = environment.outputDir.childFile('app.so');
    if (!outputFile.parent.existsSync()) {
      outputFile.parent.createSync(recursive: true);
    }
    environment.buildDir.childFile('app.so').copySync(outputFile.path);
  }
}