common.dart 15.1 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
import '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/file_system.dart';
10
import '../../base/io.dart';
11 12
import '../../build_info.dart';
import '../../compile.dart';
13
import '../../dart/package_map.dart';
14
import '../../globals.dart' as globals show xcode;
15
import '../build_system.dart';
16
import '../depfile.dart';
17
import '../exceptions.dart';
18
import 'assets.dart';
19
import 'dart_plugin_registrant.dart';
20
import 'icon_tree_shaker.dart';
21
import 'localizations.dart';
22
import 'shader_compiler.dart';
23

24
/// Copies the pre-built flutter bundle.
25 26 27 28 29 30 31 32 33 34 35 36
// 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'),
37
    ...IconTreeShaker.inputs,
38
    ...ShaderCompiler.inputs,
39 40 41 42 43 44 45
  ];

  @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'),
46 47 48 49
  ];

  @override
  List<String> get depfiles => <String>[
50
    'flutter_assets.d',
51 52 53 54
  ];

  @override
  Future<void> build(Environment environment) async {
55 56
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
57 58
      throw MissingDefineException(kBuildMode, 'copy_flutter_bundle');
    }
59
    final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
60 61 62 63
    environment.outputDir.createSync(recursive: true);

    // Only copy the prebuilt runtimes and kernel blob in debug mode.
    if (buildMode == BuildMode.debug) {
64 65
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
66 67
      environment.buildDir.childFile('app.dill')
          .copySync(environment.outputDir.childFile('kernel_blob.bin').path);
68
      environment.fileSystem.file(vmSnapshotData)
69
          .copySync(environment.outputDir.childFile('vm_snapshot_data').path);
70
      environment.fileSystem.file(isolateSnapshotData)
71 72
          .copySync(environment.outputDir.childFile('isolate_snapshot_data').path);
    }
73 74 75 76
    final Depfile assetDepfile = await copyAssets(
      environment,
      environment.outputDir,
      targetPlatform: TargetPlatform.android,
77
      buildMode: buildMode,
78
      shaderTarget: ShaderTarget.sksl,
79
    );
80
    environment.depFileService.writeToFile(
81 82 83
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
84 85 86 87 88 89 90 91
  }

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

92
/// Copies the pre-built flutter bundle for release mode.
93 94 95 96 97 98 99
class ReleaseCopyFlutterBundle extends CopyFlutterBundle {
  const ReleaseCopyFlutterBundle();

  @override
  String get name => 'release_flutter_bundle';

  @override
100
  List<Source> get inputs => const <Source>[];
101 102

  @override
103 104 105 106 107
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => const <String>[
    'flutter_assets.d',
108 109 110 111 112 113
  ];

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

114
/// Generate a snapshot of the dart code used in the program.
115
///
116
/// This target depends on the `.dart_tool/package_config.json` file
117
/// even though it is not listed as an input. Pub inserts a timestamp into
118
/// the file which causes unnecessary rebuilds, so instead a subset of the contents
119
/// are used an input instead.
120 121 122 123 124 125 126 127
class KernelSnapshot extends Target {
  const KernelSnapshot();

  @override
  String get name => 'kernel_snapshot';

  @override
  List<Source> get inputs => const <Source>[
128
    Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
129
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
130
    Source.artifact(Artifact.platformKernelDill),
131
    Source.artifact(Artifact.engineDartBinary),
132 133 134 135
    Source.artifact(Artifact.frontendServerSnapshotForEngineDartSdk),
  ];

  @override
136 137 138 139 140
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => <String>[
    'kernel_snapshot.d',
141 142 143
  ];

  @override
144 145
  List<Target> get dependencies => const <Target>[
    GenerateLocalizationsTarget(),
146
    DartPluginRegistrantTarget(),
147
  ];
148 149

  @override
150
  Future<void> build(Environment environment) async {
151 152 153 154 155
    final KernelCompiler compiler = KernelCompiler(
      fileSystem: environment.fileSystem,
      logger: environment.logger,
      processManager: environment.processManager,
      artifacts: environment.artifacts,
156
      fileSystemRoots: <String>[],
157
    );
158 159
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
160 161
      throw MissingDefineException(kBuildMode, 'kernel_snapshot');
    }
162 163
    final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
    if (targetPlatformEnvironment == null) {
164 165
      throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
    }
166
    final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
167
    final String targetFile = environment.defines[kTargetFile] ?? environment.fileSystem.path.join('lib', 'main.dart');
168 169 170
    final File packagesFile = environment.projectDir
      .childDirectory('.dart_tool')
      .childFile('package_config.json');
171
    final String targetFileAbsolute = environment.fileSystem.file(targetFile).absolute.path;
172 173
    // everything besides 'false' is considered to be enabled.
    final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false';
174
    final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
175

176
    // This configuration is all optional.
177
    final List<String> extraFrontEndOptions = decodeCommaSeparated(environment.defines, kExtraFrontEndOptions);
178 179
    final List<String>? fileSystemRoots = environment.defines[kFileSystemRoots]?.split(',');
    final String? fileSystemScheme = environment.defines[kFileSystemScheme];
180

181 182 183 184 185
    TargetModel targetModel = TargetModel.flutter;
    if (targetPlatform == TargetPlatform.fuchsia_x64 ||
        targetPlatform == TargetPlatform.fuchsia_arm64) {
      targetModel = TargetModel.flutterRunner;
    }
186 187 188
    // 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
189
    final bool forceLinkPlatform;
190
    switch (targetPlatform) {
191
      case TargetPlatform.darwin:
192 193
      case TargetPlatform.windows_x64:
      case TargetPlatform.linux_x64:
194
        forceLinkPlatform = true;
195 196 197 198 199 200 201 202 203 204 205
      case TargetPlatform.android:
      case TargetPlatform.android_arm:
      case TargetPlatform.android_arm64:
      case TargetPlatform.android_x64:
      case TargetPlatform.android_x86:
      case TargetPlatform.fuchsia_arm64:
      case TargetPlatform.fuchsia_x64:
      case TargetPlatform.ios:
      case TargetPlatform.linux_arm64:
      case TargetPlatform.tester:
      case TargetPlatform.web_javascript:
206 207
        forceLinkPlatform = false;
    }
208

209
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
210
      packagesFile,
211
      logger: environment.logger,
212 213
    );

214
    final CompilerOutput? output = await compiler.compile(
215
      sdkRoot: environment.artifacts.getArtifactPath(
216 217 218 219
        Artifact.flutterPatchedSdkPath,
        platform: targetPlatform,
        mode: buildMode,
      ),
220
      aot: buildMode.isPrecompiled,
221
      buildMode: buildMode,
222
      trackWidgetCreation: trackWidgetCreation && buildMode != BuildMode.release,
223
      targetModel: targetModel,
224
      outputFilePath: environment.buildDir.childFile('app.dill').path,
225 226
      initializeFromDill: buildMode.isPrecompiled ? null :
          environment.buildDir.childFile('app.dill').path,
227
      packagesPath: packagesFile.path,
228
      linkPlatformKernelIn: forceLinkPlatform || buildMode.isPrecompiled,
229
      mainPath: targetFileAbsolute,
230
      depFilePath: environment.buildDir.childFile('kernel_snapshot.d').path,
231 232 233
      extraFrontEndOptions: extraFrontEndOptions,
      fileSystemRoots: fileSystemRoots,
      fileSystemScheme: fileSystemScheme,
234
      dartDefines: decodeDartDefines(environment.defines, kDartDefines),
235
      packageConfig: packageConfig,
236 237
      buildDir: environment.buildDir,
      checkDartPluginRegistry: environment.generateDartPluginRegistry,
238
    );
239
    if (output == null || output.errorCount != 0) {
240
      throw Exception();
241
    }
242
  }
243
}
244

245 246 247 248
/// Supports compiling a dart kernel file to an ELF binary.
abstract class AotElfBase extends Target {
  const AotElfBase();

249 250 251
  @override
  String get analyticsName => 'android_aot';

252
  @override
253
  Future<void> build(Environment environment) async {
254
    final AOTSnapshotter snapshotter = AOTSnapshotter(
255 256
      fileSystem: environment.fileSystem,
      logger: environment.logger,
257
      xcode: globals.xcode!,
258 259
      processManager: environment.processManager,
      artifacts: environment.artifacts,
260
    );
261
    final String outputPath = environment.buildDir.path;
262 263
    final String? buildModeEnvironment = environment.defines[kBuildMode];
    if (buildModeEnvironment == null) {
264 265
      throw MissingDefineException(kBuildMode, 'aot_elf');
    }
266 267
    final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
    if (targetPlatformEnvironment == null) {
268 269
      throw MissingDefineException(kTargetPlatform, 'aot_elf');
    }
270
    final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
271
    final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
272 273
    final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
    final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
274
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
275
    final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
276 277 278 279 280 281 282 283 284 285 286 287

    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}');
    }

288 289 290
    final int snapshotExitCode = await snapshotter.build(
      platform: targetPlatform,
      buildMode: buildMode,
291
      mainPath: environment.buildDir.childFile('app.dill').path,
292
      outputPath: outputPath,
293
      extraGenSnapshotOptions: extraGenSnapshotOptions,
294 295
      splitDebugInfo: splitDebugInfo,
      dartObfuscation: dartObfuscation,
296 297 298 299 300 301 302 303
    );
    if (snapshotExitCode != 0) {
      throw Exception('AOT snapshotter exited with code $snapshotExitCode');
    }
  }
}

/// Generate an ELF binary from a dart kernel file in profile mode.
304
class AotElfProfile extends AotElfBase {
305
  const AotElfProfile(this.targetPlatform);
306 307 308 309 310

  @override
  String get name => 'aot_elf_profile';

  @override
311
  List<Source> get inputs => <Source>[
312
    const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
313
    const Source.pattern('{BUILD_DIR}/app.dill'),
314
    const Source.artifact(Artifact.engineDartBinary),
315
    const Source.artifact(Artifact.skyEnginePath),
316
    Source.artifact(Artifact.genSnapshot,
317
      platform: targetPlatform,
318 319
      mode: BuildMode.profile,
    ),
320 321 322 323
  ];

  @override
  List<Source> get outputs => const <Source>[
324
    Source.pattern('{BUILD_DIR}/app.so'),
325 326 327 328 329 330
  ];

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

332
  final TargetPlatform targetPlatform;
333
}
334 335

/// Generate an ELF binary from a dart kernel file in release mode.
336
class AotElfRelease extends AotElfBase {
337
  const AotElfRelease(this.targetPlatform);
338 339 340 341 342

  @override
  String get name => 'aot_elf_release';

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

354 355 356 357
  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/app.so'),
  ];
358

359 360 361 362
  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];
363

364
  final TargetPlatform targetPlatform;
365
}
366

367
/// Copies the pre-built flutter aot bundle.
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
// 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);
  }
}
391 392

/// Lipo CLI tool wrapper shared by iOS and macOS builds.
393
abstract final class Lipo {
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  /// Create a "fat" binary by combining multiple architecture-specific ones.
  /// `skipMissingInputs` can be changed to `true` to first check whether
  /// the expected input paths exist and ignore the command if they don't.
  /// Otherwise, `lipo` would fail if the given paths didn't exist.
  static Future<void> create(
    Environment environment,
    List<DarwinArch> darwinArchs, {
    required String relativePath,
    required String inputDir,
    bool skipMissingInputs = false,
  }) async {

    final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, relativePath);
    environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);

    Iterable<String> inputPaths = darwinArchs.map(
410
      (DarwinArch iosArch) => environment.fileSystem.path.join(inputDir, iosArch.name, relativePath)
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    );
    if (skipMissingInputs) {
      inputPaths = inputPaths.where(environment.fileSystem.isFileSync);
      if (inputPaths.isEmpty) {
        return;
      }
    }

    final List<String> lipoArgs = <String>[
      'lipo',
      ...inputPaths,
      '-create',
      '-output',
      resultPath,
    ];

    final ProcessResult result = await environment.processManager.run(lipoArgs);
    if (result.exitCode != 0) {
      throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
    }
  }
}