common.dart 15.2 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
// @dart = 2.8

7 8
import 'package:package_config/package_config.dart';

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

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

/// 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';

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

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

38 39 40 41 42 43 44 45 46 47
/// 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';

48
/// Whether the build should run gen_snapshot as a split aot build for deferred
49
/// components.
50
const String kDeferredComponents = 'DeferredComponents';
51

52 53 54
/// Whether to strip source code information out of release builds and where to save it.
const String kSplitDebugInfo = 'SplitDebugInfo';

55 56
/// Alternative scheme for file URIs.
///
57
/// May be used along with [kFileSystemRoots] to support a multi-root
58 59 60 61 62 63 64 65
/// filesystem.
const String kFileSystemScheme = 'FileSystemScheme';

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

66 67 68 69 70 71 72 73
/// 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';

74 75 76
/// Path to the SDK root to be used as the isysroot.
const String kSdkRoot = 'SdkRoot';

77 78 79
/// Whether to enable Dart obfuscation and where to save the symbol map.
const String kDartObfuscation = 'DartObfuscation';

80 81 82
/// An output directory where one or more code-size measurements may be written.
const String kCodeSizeDirectory = 'CodeSizeDirectory';

83 84 85 86 87 88
/// SHA identifier of the Apple developer code signing identity.
///
/// Same as EXPANDED_CODE_SIGN_IDENTITY Xcode build setting.
/// Also discoverable via `security find-identity -p codesigning`.
const String kCodesignIdentity = 'CodesignIdentity';

89
/// Copies the pre-built flutter bundle.
90 91 92 93 94 95 96 97 98 99 100 101
// 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'),
102
    ...IconTreeShaker.inputs,
103 104 105 106 107 108 109
  ];

  @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'),
110 111 112 113 114
  ];

  @override
  List<String> get depfiles => <String>[
    'flutter_assets.d'
115 116 117 118 119 120 121 122 123 124 125 126
  ];

  @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) {
127 128
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
129 130
      environment.buildDir.childFile('app.dill')
          .copySync(environment.outputDir.childFile('kernel_blob.bin').path);
131
      environment.fileSystem.file(vmSnapshotData)
132
          .copySync(environment.outputDir.childFile('vm_snapshot_data').path);
133
      environment.fileSystem.file(isolateSnapshotData)
134 135
          .copySync(environment.outputDir.childFile('isolate_snapshot_data').path);
    }
136 137 138 139
    final Depfile assetDepfile = await copyAssets(
      environment,
      environment.outputDir,
      targetPlatform: TargetPlatform.android,
140
      buildMode: buildMode,
141
    );
142
    final DepfileService depfileService = DepfileService(
143 144
      fileSystem: environment.fileSystem,
      logger: environment.logger,
145 146 147 148 149
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
150 151 152 153 154 155 156 157
  }

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

158
/// Copies the pre-built flutter bundle for release mode.
159 160 161 162 163 164 165
class ReleaseCopyFlutterBundle extends CopyFlutterBundle {
  const ReleaseCopyFlutterBundle();

  @override
  String get name => 'release_flutter_bundle';

  @override
166
  List<Source> get inputs => const <Source>[];
167 168

  @override
169 170 171 172 173
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => const <String>[
    'flutter_assets.d',
174 175 176 177 178 179
  ];

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

180
/// Generate a snapshot of the dart code used in the program.
181 182 183
///
/// 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
184
/// the file which causes unnecessary rebuilds, so instead a subset of the contents
185
/// are used an input instead.
186 187 188 189 190 191 192 193
class KernelSnapshot extends Target {
  const KernelSnapshot();

  @override
  String get name => 'kernel_snapshot';

  @override
  List<Source> get inputs => const <Source>[
194
    Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
195
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
196 197 198 199 200 201
    Source.artifact(Artifact.platformKernelDill),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.frontendServerSnapshotForEngineDartSdk),
  ];

  @override
202 203 204 205 206
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => <String>[
    'kernel_snapshot.d',
207 208 209
  ];

  @override
210 211 212
  List<Target> get dependencies => const <Target>[
    GenerateLocalizationsTarget(),
  ];
213 214

  @override
215
  Future<void> build(Environment environment) async {
216 217 218 219 220
    final KernelCompiler compiler = KernelCompiler(
      fileSystem: environment.fileSystem,
      logger: environment.logger,
      processManager: environment.processManager,
      artifacts: environment.artifacts,
221 222
      fileSystemRoots: <String>[],
      fileSystemScheme: null,
223 224 225 226
    );
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'kernel_snapshot');
    }
227 228 229
    if (environment.defines[kTargetPlatform] == null) {
      throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
    }
230
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
231
    final String targetFile = environment.defines[kTargetFile] ?? environment.fileSystem.path.join('lib', 'main.dart');
232 233 234
    final File packagesFile = environment.projectDir
      .childDirectory('.dart_tool')
      .childFile('package_config.json');
235
    final String targetFileAbsolute = environment.fileSystem.file(targetFile).absolute.path;
236 237
    // everything besides 'false' is considered to be enabled.
    final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false';
238 239
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);

240
    // This configuration is all optional.
241
    final List<String> extraFrontEndOptions = decodeCommaSeparated(environment.defines, kExtraFrontEndOptions);
242 243 244
    final List<String> fileSystemRoots = environment.defines[kFileSystemRoots]?.split(',');
    final String fileSystemScheme = environment.defines[kFileSystemScheme];

245 246 247 248 249
    TargetModel targetModel = TargetModel.flutter;
    if (targetPlatform == TargetPlatform.fuchsia_x64 ||
        targetPlatform == TargetPlatform.fuchsia_arm64) {
      targetModel = TargetModel.flutterRunner;
    }
250 251 252 253 254
    // 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) {
255 256 257
      case TargetPlatform.darwin_x64:
      case TargetPlatform.windows_x64:
      case TargetPlatform.linux_x64:
258 259 260 261 262
        forceLinkPlatform = true;
        break;
      default:
        forceLinkPlatform = false;
    }
263

264
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
265
      packagesFile,
266
      logger: environment.logger,
267 268
    );

269
    final CompilerOutput output = await compiler.compile(
270
      sdkRoot: environment.artifacts.getArtifactPath(
271 272 273 274
        Artifact.flutterPatchedSdkPath,
        platform: targetPlatform,
        mode: buildMode,
      ),
275
      aot: buildMode.isPrecompiled,
276
      buildMode: buildMode,
277
      trackWidgetCreation: trackWidgetCreation && buildMode == BuildMode.debug,
278
      targetModel: targetModel,
279
      outputFilePath: environment.buildDir.childFile('app.dill').path,
280
      packagesPath: packagesFile.path,
281
      linkPlatformKernelIn: forceLinkPlatform || buildMode.isPrecompiled,
282
      mainPath: targetFileAbsolute,
283
      depFilePath: environment.buildDir.childFile('kernel_snapshot.d').path,
284 285 286
      extraFrontEndOptions: extraFrontEndOptions,
      fileSystemRoots: fileSystemRoots,
      fileSystemScheme: fileSystemScheme,
287
      dartDefines: decodeDartDefines(environment.defines, kDartDefines),
288
      packageConfig: packageConfig,
289
    );
290
    if (output == null || output.errorCount != 0) {
291
      throw Exception();
292
    }
293
  }
294
}
295

296 297 298 299
/// Supports compiling a dart kernel file to an ELF binary.
abstract class AotElfBase extends Target {
  const AotElfBase();

300 301 302
  @override
  String get analyticsName => 'android_aot';

303
  @override
304
  Future<void> build(Environment environment) async {
305 306
    final AOTSnapshotter snapshotter = AOTSnapshotter(
      reportTimings: false,
307 308
      fileSystem: environment.fileSystem,
      logger: environment.logger,
309
      xcode: globals.xcode,
310 311
      processManager: environment.processManager,
      artifacts: environment.artifacts,
312
    );
313 314 315 316 317 318 319
    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');
    }
320
    final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
321 322
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);
323 324
    final String splitDebugInfo = environment.defines[kSplitDebugInfo];
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
325 326 327 328 329 330 331 332 333 334 335 336 337
    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}');
    }

338 339 340
    final int snapshotExitCode = await snapshotter.build(
      platform: targetPlatform,
      buildMode: buildMode,
341
      mainPath: environment.buildDir.childFile('app.dill').path,
342
      outputPath: outputPath,
343
      bitcode: false,
344
      extraGenSnapshotOptions: extraGenSnapshotOptions,
345 346
      splitDebugInfo: splitDebugInfo,
      dartObfuscation: dartObfuscation,
347 348 349 350 351 352 353 354
    );
    if (snapshotExitCode != 0) {
      throw Exception('AOT snapshotter exited with code $snapshotExitCode');
    }
  }
}

/// Generate an ELF binary from a dart kernel file in profile mode.
355
class AotElfProfile extends AotElfBase {
356
  const AotElfProfile(this.targetPlatform);
357 358 359 360 361

  @override
  String get name => 'aot_elf_profile';

  @override
362
  List<Source> get inputs => <Source>[
363
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
364 365 366
    const Source.pattern('{BUILD_DIR}/app.dill'),
    const Source.artifact(Artifact.engineDartBinary),
    const Source.artifact(Artifact.skyEnginePath),
367
    Source.artifact(Artifact.genSnapshot,
368
      platform: targetPlatform,
369 370
      mode: BuildMode.profile,
    ),
371 372 373 374
  ];

  @override
  List<Source> get outputs => const <Source>[
375
    Source.pattern('{BUILD_DIR}/app.so'),
376 377 378 379 380 381
  ];

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

383
  final TargetPlatform targetPlatform;
384
}
385 386

/// Generate an ELF binary from a dart kernel file in release mode.
387
class AotElfRelease extends AotElfBase {
388
  const AotElfRelease(this.targetPlatform);
389 390 391 392 393

  @override
  String get name => 'aot_elf_release';

  @override
394
  List<Source> get inputs => <Source>[
395
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
396 397 398
    const Source.pattern('{BUILD_DIR}/app.dill'),
    const Source.artifact(Artifact.engineDartBinary),
    const Source.artifact(Artifact.skyEnginePath),
399
    Source.artifact(Artifact.genSnapshot,
400
      platform: targetPlatform,
401 402
      mode: BuildMode.release,
    ),
403
  ];
404

405 406 407 408
  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/app.so'),
  ];
409

410 411 412 413
  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];
414

415
  final TargetPlatform targetPlatform;
416
}
417

418
/// Copies the pre-built flutter aot bundle.
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
// 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);
  }
}