build_aot.dart 16.4 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import '../android/android_sdk.dart';
8
import '../artifacts.dart';
9
import '../base/build.dart';
10
import '../base/common.dart';
11
import '../base/file_system.dart';
12
import '../base/logger.dart';
13
import '../base/process.dart';
14
import '../base/process_manager.dart';
15
import '../base/utils.dart';
16
import '../build_info.dart';
17
import '../compile.dart';
18
import '../dart/package_map.dart';
19
import '../globals.dart';
20
import '../resident_runner.dart';
21
import '../runner/flutter_command.dart';
22
import 'build.dart';
23 24 25

// Files generated by the ahead-of-time snapshot builder.
const List<String> kAotSnapshotFiles = const <String>[
26
  'vm_snapshot_data', 'vm_snapshot_instr', 'isolate_snapshot_data', 'isolate_snapshot_instr',
27 28
];

29
class BuildAotCommand extends BuildSubCommand {
30
  BuildAotCommand({bool verboseHelp: false}) {
31 32 33
    usesTargetOption();
    addBuildModeFlags();
    usesPubOption();
34
    argParser
35
      ..addOption('output-dir', defaultsTo: getAotBuildDirectory())
36 37 38
      ..addOption('target-platform',
        defaultsTo: 'android-arm',
        allowed: <String>['android-arm', 'ios']
39
      )
40
      ..addFlag('interpreter')
41
      ..addFlag('quiet', defaultsTo: false)
42
      ..addFlag('preview-dart-2', negatable: false, hide: !verboseHelp)
43 44 45 46 47 48 49 50 51
      ..addOption(FlutterOptions.kExtraFrontEndOptions,
        allowMultiple: true,
        splitCommas: true,
        hide: true,
      )
      ..addOption(FlutterOptions.kExtraGenSnapshotOptions,
        allowMultiple: true,
        splitCommas: true,
        hide: true,
52 53 54
      )
      ..addFlag('prefer-shared-library', negatable: false,
          help: 'Whether to prefer compiling to a *.so file (android only).');
55 56 57 58 59 60
  }

  @override
  final String name = 'aot';

  @override
61
  final String description = "Build an ahead-of-time compiled snapshot of your app's Dart code.";
62 63

  @override
64
  Future<Null> runCommand() async {
65
    await super.runCommand();
66 67
    final String targetPlatform = argResults['target-platform'];
    final TargetPlatform platform = getTargetPlatformForName(targetPlatform);
68 69
    if (platform == null)
      throwToolExit('Unknown platform: $targetPlatform');
70

71
    final String typeName = artifacts.getEngineType(platform, getBuildMode());
72 73 74 75 76
    Status status;
    if (!argResults['quiet']) {
      status = logger.startProgress('Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
          expectSlowOperation: true);
    }
77
    final String outputPath = await buildAotSnapshot(
78
      findMainDartFile(targetFile),
79
      platform,
80
      getBuildMode(),
81
      outputPath: argResults['output-dir'],
82 83
      interpreter: argResults['interpreter'],
      previewDart2: argResults['preview-dart-2'],
84 85
      extraFrontEndOptions: argResults[FlutterOptions.kExtraFrontEndOptions],
      extraGenSnapshotOptions: argResults[FlutterOptions.kExtraGenSnapshotOptions],
86
      preferSharedLibrary: argResults['prefer-shared-library'],
87
    );
88
    status?.stop();
89

90
    if (outputPath == null)
91
      throwToolExit(null);
92

93 94 95 96 97 98
    final String builtMessage = 'Built to $outputPath${fs.path.separator}.';
    if (argResults['quiet']) {
      printTrace(builtMessage);
    } else {
      printStatus(builtMessage);
    }
99 100 101
  }
}

Adam Barth's avatar
Adam Barth committed
102
String _getPackagePath(PackageMap packageMap, String package) {
103
  return fs.path.dirname(packageMap.map[package].toFilePath());
104 105
}

106
/// Build an AOT snapshot. Return null (and log to `printError`) if the method
107
/// fails.
108
Future<String> buildAotSnapshot(
109
  String mainPath,
110
  TargetPlatform platform,
111
  BuildMode buildMode, {
112
  String outputPath,
113 114
  bool interpreter: false,
  bool previewDart2: false,
115 116
  List<String> extraFrontEndOptions,
  List<String> extraGenSnapshotOptions,
117
  bool preferSharedLibrary: false,
118
}) async {
119
  outputPath ??= getAotBuildDirectory();
120 121 122 123 124 125
  try {
    return _buildAotSnapshot(
      mainPath,
      platform,
      buildMode,
      outputPath: outputPath,
126 127
      interpreter: interpreter,
      previewDart2: previewDart2,
128 129
      extraFrontEndOptions: extraFrontEndOptions,
      extraGenSnapshotOptions: extraGenSnapshotOptions,
130
      preferSharedLibrary: preferSharedLibrary,
131 132 133 134 135 136 137 138
    );
  } on String catch (error) {
    // Catch the String exceptions thrown from the `runCheckedSync` methods below.
    printError(error);
    return null;
  }
}

139
// TODO(cbracken): split AOT and Assembly AOT snapshotting logic and migrate to Snapshotter class.
140
Future<String> _buildAotSnapshot(
141 142 143
  String mainPath,
  TargetPlatform platform,
  BuildMode buildMode, {
144
  String outputPath,
145 146
  bool interpreter: false,
  bool previewDart2: false,
147 148
  List<String> extraFrontEndOptions,
  List<String> extraGenSnapshotOptions,
149
  bool preferSharedLibrary: false,
150
}) async {
151
  outputPath ??= getAotBuildDirectory();
152
  if (!isAotBuildMode(buildMode) && !interpreter) {
153
    printError('${toTitleCase(getModeName(buildMode))} mode does not support AOT compilation.');
154 155 156
    return null;
  }

157 158 159 160 161
  if (platform != TargetPlatform.android_arm && platform != TargetPlatform.ios) {
    printError('${getNameForTargetPlatform(platform)} does not support AOT compilation.');
    return null;
  }

162
  final String genSnapshot = artifacts.getArtifactPath(Artifact.genSnapshot, platform, buildMode);
163

164
  final Directory outputDir = fs.directory(outputPath);
165
  outputDir.createSync(recursive: true);
166 167 168 169
  final String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');
  final String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');
  final String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');
  final String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');
170
  final String dependencies = fs.path.join(outputDir.path, 'snapshot.d');
171 172 173 174 175 176 177 178 179 180
  final String assembly = fs.path.join(outputDir.path, 'snapshot_assembly.S');
  final String assemblyO = fs.path.join(outputDir.path, 'snapshot_assembly.o');
  final String assemblySo = fs.path.join(outputDir.path, 'app.so');
  final bool compileToSharedLibrary =
      preferSharedLibrary && androidSdk.ndkCompiler != null;

  if (preferSharedLibrary && !compileToSharedLibrary) {
    printStatus(
        'Could not find NDK compiler. Not building in shared library mode');
  }
181

182 183 184 185 186
  final String vmEntryPoints = artifacts.getArtifactPath(
    Artifact.dartVmEntryPointsTxt,
    platform,
    buildMode,
  );
187
  final String ioEntryPoints = artifacts.getArtifactPath(Artifact.dartIoEntriesTxt, platform, buildMode);
188

189 190
  final PackageMap packageMap = new PackageMap(PackageMap.globalPackagesPath);
  final String packageMapError = packageMap.checkValid();
191 192
  if (packageMapError != null) {
    printError(packageMapError);
193 194 195
    return null;
  }

Adam Barth's avatar
Adam Barth committed
196 197
  final String skyEnginePkg = _getPackagePath(packageMap, 'sky_engine');
  final String uiPath = fs.path.join(skyEnginePkg, 'lib', 'ui', 'ui.dart');
198
  final String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
199

200
  final List<String> inputPaths = <String>[
201
    vmEntryPoints,
202
    ioEntryPoints,
203 204
    uiPath,
    vmServicePath,
205
    mainPath,
206
  ];
207

208 209
  final Set<String> outputPaths = new Set<String>();

210 211 212 213 214 215 216
  // These paths are used only on iOS.
  String snapshotDartIOS;

  switch (platform) {
    case TargetPlatform.android_arm:
    case TargetPlatform.android_x64:
    case TargetPlatform.android_x86:
217 218 219 220 221 222 223 224
      if (compileToSharedLibrary) {
        outputPaths.add(assemblySo);
      } else {
        outputPaths.addAll(<String>[
          vmSnapshotData,
          isolateSnapshotData,
        ]);
      }
225 226
      break;
    case TargetPlatform.ios:
227
      snapshotDartIOS = artifacts.getArtifactPath(Artifact.snapshotDart, platform, buildMode);
228
      inputPaths.add(snapshotDartIOS);
229 230 231
      break;
    case TargetPlatform.darwin_x64:
    case TargetPlatform.linux_x64:
232
    case TargetPlatform.windows_x64:
233
    case TargetPlatform.fuchsia:
234 235 236
      assert(false);
  }

237 238 239
  final Iterable<String> missingInputs = inputPaths.where((String p) => !fs.isFileSync(p));
  if (missingInputs.isNotEmpty) {
    printError('Missing input files: $missingInputs');
240 241
    return null;
  }
242 243 244 245
  if (!processManager.canRun(genSnapshot)) {
    printError('Cannot locate the genSnapshot executable');
    return null;
  }
246

247
  final List<String> genSnapshotCmd = <String>[
248
    genSnapshot,
249
    '--await_is_keyword',
250 251
    '--vm_snapshot_data=$vmSnapshotData',
    '--isolate_snapshot_data=$isolateSnapshotData',
252
    '--packages=${packageMap.packagesPath}',
253
    '--url_mapping=dart:ui,$uiPath',
254
    '--url_mapping=dart:vmservice_io,$vmServicePath',
255
    '--print_snapshot_sizes',
256
    '--dependencies=$dependencies',
257
    '--causal_async_stacks',
258 259
  ];

260
  if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty)
261
    printTrace('Extra front-end options: $extraFrontEndOptions');
262 263

  if ((extraGenSnapshotOptions != null) && extraGenSnapshotOptions.isNotEmpty) {
264
    printTrace('Extra gen-snapshot options: $extraGenSnapshotOptions');
265 266 267
    genSnapshotCmd.addAll(extraGenSnapshotOptions);
  }

268
  if (!interpreter) {
269 270
    genSnapshotCmd.add('--embedder_entry_points_manifest=$vmEntryPoints');
    genSnapshotCmd.add('--embedder_entry_points_manifest=$ioEntryPoints');
271 272
  }

273 274 275 276 277 278 279 280 281 282
  // iOS symbols used to load snapshot data in the engine.
  const String kVmSnapshotData = 'kDartVmSnapshotData';
  const String kIsolateSnapshotData = 'kDartIsolateSnapshotData';

  // iOS snapshot generated files, compiled object files.
  final String kVmSnapshotDataC = fs.path.join(outputDir.path, '$kVmSnapshotData.c');
  final String kIsolateSnapshotDataC = fs.path.join(outputDir.path, '$kIsolateSnapshotData.c');
  final String kVmSnapshotDataO = fs.path.join(outputDir.path, '$kVmSnapshotData.o');
  final String kIsolateSnapshotDataO = fs.path.join(outputDir.path, '$kIsolateSnapshotData.o');

283 284 285 286
  switch (platform) {
    case TargetPlatform.android_arm:
    case TargetPlatform.android_x64:
    case TargetPlatform.android_x86:
287 288 289 290 291 292 293 294 295 296 297
      if (compileToSharedLibrary) {
        genSnapshotCmd.add('--snapshot_kind=app-aot-assembly');
        genSnapshotCmd.add('--assembly=$assembly');
        outputPaths.add(assemblySo);
      } else {
        genSnapshotCmd.addAll(<String>[
          '--snapshot_kind=app-aot-blobs',
          '--vm_snapshot_instructions=$vmSnapshotInstructions',
          '--isolate_snapshot_instructions=$isolateSnapshotInstructions',
        ]);
      }
298
      genSnapshotCmd.addAll(<String>[
299
        '--no-sim-use-hardfp',  // Android uses the softfloat ABI.
300
        '--no-use-integer-division',  // Not supported by the Pixel in 32-bit mode.
301 302 303
      ]);
      break;
    case TargetPlatform.ios:
304 305 306
      if (interpreter) {
        genSnapshotCmd.add('--snapshot_kind=core');
        genSnapshotCmd.add(snapshotDartIOS);
307 308 309 310
        outputPaths.addAll(<String>[
          kVmSnapshotDataO,
          kIsolateSnapshotDataO,
        ]);
311 312 313
      } else {
        genSnapshotCmd.add('--snapshot_kind=app-aot-assembly');
        genSnapshotCmd.add('--assembly=$assembly');
314
        outputPaths.add(assemblyO);
315
      }
316 317 318
      break;
    case TargetPlatform.darwin_x64:
    case TargetPlatform.linux_x64:
319
    case TargetPlatform.windows_x64:
320
    case TargetPlatform.fuchsia:
321 322 323
      assert(false);
  }

324
  if (buildMode != BuildMode.release) {
325
    genSnapshotCmd.addAll(<String>[
326 327 328 329 330
      '--no-checked',
      '--conditional_directives',
    ]);
  }

331 332 333 334
  if (previewDart2) {
    mainPath = await compile(
      sdkRoot: artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath),
      mainPath: mainPath,
335
      extraFrontEndOptions: extraFrontEndOptions,
336
      linkPlatformKernelIn : true,
337 338 339
    );
  }

340 341
  genSnapshotCmd.add(mainPath);

342
  final SnapshotType snapshotType = new SnapshotType(platform, buildMode);
343 344
  final File fingerprintFile = fs.file('$dependencies.fingerprint');
  final List<File> fingerprintFiles = <File>[fingerprintFile, fs.file(dependencies)]
345 346
      ..addAll(inputPaths.map(fs.file))
      ..addAll(outputPaths.map(fs.file));
347
  if (fingerprintFiles.every((File file) => file.existsSync())) {
348
    try {
349 350
      final String json = await fingerprintFile.readAsString();
      final Fingerprint oldFingerprint = new Fingerprint.fromJson(json);
351 352 353
      final Set<String> snapshotInputPaths = await readDepfile(dependencies)
        ..add(mainPath)
        ..addAll(outputPaths);
354 355 356
      final Fingerprint newFingerprint = Snapshotter.createFingerprint(snapshotType, mainPath, snapshotInputPaths);
      if (oldFingerprint == newFingerprint) {
        printStatus('Skipping AOT snapshot build. Fingerprint match.');
357 358
        return outputPath;
      }
359
    } catch (e) {
360
      // Log exception and continue, this step is a performance improvement only.
361
      printTrace('Rebuilding snapshot due to fingerprint check error: $e');
362 363 364
    }
  }

365
  final RunResult results = await runAsync(genSnapshotCmd);
366
  if (results.exitCode != 0) {
367 368
    printError('Dart snapshot generator failed with exit code ${results.exitCode}');
    printError(results.toString());
369 370
    return null;
  }
371

372 373 374 375
  // Write path to gen_snapshot, since snapshots have to be re-generated when we roll
  // the Dart SDK.
  await outputDir.childFile('gen_snapshot.d').writeAsString('snapshot.d: $genSnapshot\n');

376
  // On iOS, we use Xcode to compile the snapshot into a dynamic library that the
377 378
  // end-developer can link into their app.
  if (platform == TargetPlatform.ios) {
379
    printStatus('Building App.framework...');
380

381
    final List<String> commonBuildOptions = <String>['-arch', 'arm64', '-miphoneos-version-min=8.0'];
382

Ryan Macnak's avatar
Ryan Macnak committed
383
    if (interpreter) {
384 385
      await runCheckedAsync(<String>['mv', vmSnapshotData, fs.path.join(outputDir.path, kVmSnapshotData)]);
      await runCheckedAsync(<String>['mv', isolateSnapshotData, fs.path.join(outputDir.path, kIsolateSnapshotData)]);
386

387
      await runCheckedAsync(<String>[
388
        'xxd', '--include', kVmSnapshotData, fs.path.basename(kVmSnapshotDataC)
Ryan Macnak's avatar
Ryan Macnak committed
389
      ], workingDirectory: outputDir.path);
390
      await runCheckedAsync(<String>[
391
        'xxd', '--include', kIsolateSnapshotData, fs.path.basename(kIsolateSnapshotDataC)
Ryan Macnak's avatar
Ryan Macnak committed
392
      ], workingDirectory: outputDir.path);
393

394
      await runCheckedAsync(<String>['xcrun', 'cc']
Ryan Macnak's avatar
Ryan Macnak committed
395
        ..addAll(commonBuildOptions)
396
        ..addAll(<String>['-c', kVmSnapshotDataC, '-o', kVmSnapshotDataO]));
397
      await runCheckedAsync(<String>['xcrun', 'cc']
Ryan Macnak's avatar
Ryan Macnak committed
398
        ..addAll(commonBuildOptions)
399
        ..addAll(<String>['-c', kIsolateSnapshotDataC, '-o', kIsolateSnapshotDataO]));
Ryan Macnak's avatar
Ryan Macnak committed
400
    } else {
401
      await runCheckedAsync(<String>['xcrun', 'cc']
402 403
        ..addAll(commonBuildOptions)
        ..addAll(<String>['-c', assembly, '-o', assemblyO]));
Ryan Macnak's avatar
Ryan Macnak committed
404
    }
405

406 407 408
    final String frameworkDir = fs.path.join(outputDir.path, 'App.framework');
    fs.directory(frameworkDir).createSync(recursive: true);
    final String appLib = fs.path.join(frameworkDir, 'App');
409
    final List<String> linkCommand = <String>['xcrun', 'clang']
410 411 412 413 414
      ..addAll(commonBuildOptions)
      ..addAll(<String>[
        '-dynamiclib',
        '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
        '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
415 416
        '-install_name', '@rpath/App.framework/App',
        '-o', appLib,
417
    ]);
Ryan Macnak's avatar
Ryan Macnak committed
418
    if (interpreter) {
419 420
      linkCommand.add(kVmSnapshotDataO);
      linkCommand.add(kIsolateSnapshotDataO);
Ryan Macnak's avatar
Ryan Macnak committed
421
    } else {
422
      linkCommand.add(assemblyO);
Ryan Macnak's avatar
Ryan Macnak committed
423
    }
424
    await runCheckedAsync(linkCommand);
425 426 427 428 429 430 431 432 433 434 435 436 437
  } else {
    if (compileToSharedLibrary) {
      // A word of warning: Instead of compiling via two steps, to a .o file and
      // then to a .so file we use only one command.  When using two commands
      // gcc will end up putting a .eh_frame and a .debug_frame into the shared
      // library.  Without stripping .debug_frame afterwards, unwinding tools
      // based upon libunwind use just one and ignore the contents of the other
      // (which causes it to not look into the other section and therefore not
      // find the correct unwinding information).
      await runCheckedAsync(<String>[androidSdk.ndkCompiler]
          ..addAll(androidSdk.ndkCompilerArgs)
          ..addAll(<String>[ '-shared', '-nostdlib', '-o', assemblySo, assembly ]));
    }
438 439
  }

440
  // Compute and record build fingerprint.
441 442 443 444
  try {
    final Set<String> snapshotInputPaths = await readDepfile(dependencies)
      ..add(mainPath)
      ..addAll(outputPaths);
445 446
    final Fingerprint fingerprint = Snapshotter.createFingerprint(snapshotType, mainPath, snapshotInputPaths);
    await fingerprintFile.writeAsString(fingerprint.toJson());
447 448
  } catch (e, s) {
    // Log exception and continue, this step is a performance improvement only.
449
    printStatus('Error during AOT snapshot fingerprinting: $e\n$s');
450 451
  }

452 453
  return outputPath;
}