ios.dart 17.3 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:meta/meta.dart';

7 8
import '../../artifacts.dart';
import '../../base/build.dart';
xster's avatar
xster committed
9
import '../../base/common.dart';
10 11
import '../../base/file_system.dart';
import '../../base/io.dart';
xster's avatar
xster committed
12
import '../../base/process.dart';
13
import '../../build_info.dart';
14
import '../../globals.dart' as globals hide fs, logger, processManager, artifacts;
15
import '../../project.dart';
16
import '../build_system.dart';
17
import '../depfile.dart';
18
import '../exceptions.dart';
19
import 'assets.dart';
20
import 'common.dart';
21
import 'icon_tree_shaker.dart';
22

23 24 25
/// Supports compiling a dart kernel file to an assembly file.
///
/// If more than one iOS arch is provided, then this rule will
26
/// produce a universal binary.
27 28 29
abstract class AotAssemblyBase extends Target {
  const AotAssemblyBase();

30 31 32
  @override
  String get analyticsName => 'ios_aot';

33
  @override
34
  Future<void> build(Environment environment) async {
35 36
    final AOTSnapshotter snapshotter = AOTSnapshotter(
      reportTimings: false,
37 38
      fileSystem: environment.fileSystem,
      logger: environment.logger,
39
      xcode: globals.xcode,
40 41
      artifacts: environment.artifacts,
      processManager: environment.processManager,
42
    );
43
    final String buildOutputPath = environment.buildDir.path;
44 45 46 47 48 49
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'aot_assembly');
    }
    if (environment.defines[kTargetPlatform] == null) {
      throw MissingDefineException(kTargetPlatform, 'aot_assembly');
    }
50
    final List<String> extraGenSnapshotOptions = decodeDartDefines(environment.defines, kExtraGenSnapshotOptions);
51 52 53
    final bool bitcode = environment.defines[kBitcodeFlag] == 'true';
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);
54
    final String splitDebugInfo = environment.defines[kSplitDebugInfo];
55
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
56
    final List<DarwinArch> darwinArchs = environment.defines[kIosArchs]
57 58 59 60
      ?.split(' ')
      ?.map(getIOSArchForName)
      ?.toList()
      ?? <DarwinArch>[DarwinArch.arm64];
61
    if (targetPlatform != TargetPlatform.ios) {
62 63
      throw Exception('aot_assembly is only supported for iOS applications.');
    }
64
    if (darwinArchs.contains(DarwinArch.x86_64)) {
65 66
      throw Exception(
        'release/profile builds are only supported for physical devices. '
67
        'attempted to build for $darwinArchs.'
68
      );
69
    }
70
    final String codeSizeDirectory = environment.defines[kCodeSizeDirectory];
71

72 73 74
    // If we're building multiple iOS archs the binaries need to be lipo'd
    // together.
    final List<Future<int>> pending = <Future<int>>[];
75 76 77 78 79 80 81 82 83 84 85 86
    for (final DarwinArch darwinArch in darwinArchs) {
      final List<String> archExtraGenSnapshotOptions = List<String>.of(extraGenSnapshotOptions);
      if (codeSizeDirectory != null) {
        final File codeSizeFile = environment.fileSystem
          .directory(codeSizeDirectory)
          .childFile('snapshot.${getNameForDarwinArch(darwinArch)}.json');
        final File precompilerTraceFile = environment.fileSystem
          .directory(codeSizeDirectory)
          .childFile('trace.${getNameForDarwinArch(darwinArch)}.json');
        archExtraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}');
        archExtraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}');
      }
87
      pending.add(snapshotter.build(
88 89 90
        platform: targetPlatform,
        buildMode: buildMode,
        mainPath: environment.buildDir.childFile('app.dill').path,
91 92
        outputPath: environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(darwinArch)),
        darwinArch: darwinArch,
93
        sdkRoot: environment.defines[kSdkRoot],
94
        bitcode: bitcode,
95
        quiet: true,
96
        splitDebugInfo: splitDebugInfo,
97
        dartObfuscation: dartObfuscation,
98
        extraGenSnapshotOptions: archExtraGenSnapshotOptions,
99 100 101 102 103 104
      ));
    }
    final List<int> results = await Future.wait(pending);
    if (results.any((int result) => result != 0)) {
      throw Exception('AOT snapshotter exited with code ${results.join()}');
    }
105 106 107
    final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App');
    environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);
    final ProcessResult result = await environment.processManager.run(<String>[
108
      'lipo',
109
      ...darwinArchs.map((DarwinArch iosArch) =>
110
          environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(iosArch), 'App.framework', 'App')),
111 112 113 114 115 116
      '-create',
      '-output',
      resultPath,
    ]);
    if (result.exitCode != 0) {
      throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    }
  }
}

/// Generate an assembly target from a dart kernel file in release mode.
class AotAssemblyRelease extends AotAssemblyBase {
  const AotAssemblyRelease();

  @override
  String get name => 'aot_assembly_release';

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
    Source.pattern('{BUILD_DIR}/app.dill'),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.skyEnginePath),
134 135 136 137 138 139 140
    // TODO(jonahwilliams): cannot reference gen_snapshot with artifacts since
    // it resolves to a file (ios/gen_snapshot) that never exists. This was
    // split into gen_snapshot_arm64 and gen_snapshot_armv7.
    // Source.artifact(Artifact.genSnapshot,
    //   platform: TargetPlatform.ios,
    //   mode: BuildMode.release,
    // ),
141 142 143 144
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
145
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
146 147 148 149
  ];

  @override
  List<Target> get dependencies => const <Target>[
150
    ReleaseUnpackIOS(),
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    KernelSnapshot(),
  ];
}


/// Generate an assembly target from a dart kernel file in profile mode.
class AotAssemblyProfile extends AotAssemblyBase {
  const AotAssemblyProfile();

  @override
  String get name => 'aot_assembly_profile';

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
    Source.pattern('{BUILD_DIR}/app.dill'),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.skyEnginePath),
169 170 171 172 173 174 175
    // TODO(jonahwilliams): cannot reference gen_snapshot with artifacts since
    // it resolves to a file (ios/gen_snapshot) that never exists. This was
    // split into gen_snapshot_arm64 and gen_snapshot_armv7.
    // Source.artifact(Artifact.genSnapshot,
    //   platform: TargetPlatform.ios,
    //   mode: BuildMode.profile,
    // ),
176 177 178 179
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
180
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
181 182 183 184
  ];

  @override
  List<Target> get dependencies => const <Target>[
185
    ProfileUnpackIOS(),
186 187 188
    KernelSnapshot(),
  ];
}
xster's avatar
xster committed
189

190
/// Create a trivial App.framework file for debug iOS builds.
191 192
class DebugUniversalFramework extends Target {
  const DebugUniversalFramework();
193 194 195 196 197 198

  @override
  String get name => 'debug_universal_framework';

  @override
  List<Target> get dependencies => const <Target>[
199
    DebugUnpackIOS(),
200 201 202 203 204 205 206 207 208 209
    KernelSnapshot(),
  ];

  @override
  List<Source> get inputs => const <Source>[
     Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
  ];

  @override
  List<Source> get outputs => const <Source>[
210
    Source.pattern('{BUILD_DIR}/App.framework/App'),
211 212 213 214 215
  ];

  @override
  Future<void> build(Environment environment) async {
    // Generate a trivial App.framework.
216
    final Set<String> iosArchNames = environment.defines[kIosArchs]
217
      ?.split(' ')
218 219
      ?.toSet();
    final File output = environment.buildDir
220 221
      .childDirectory('App.framework')
      .childFile('App');
222 223 224 225 226
    environment.buildDir.createSync(recursive: true);
    final RunResult createFrameworkResult = await createStubAppFramework(
      output,
      environment.defines[kSdkRoot],
      iosArchNames,
227
    );
228
    if (createFrameworkResult.exitCode != 0) {
229 230 231 232 233
      throw Exception('Failed to create App.framework.');
    }
  }
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
/// Copy the iOS framework to the correct copy dir by invoking 'rsync'.
///
/// This class is abstract to share logic between the three concrete
/// implementations. The shelling out is done to avoid complications with
/// preserving special files (e.g., symbolic links) in the framework structure.
abstract class UnpackIOS extends Target {
  const UnpackIOS();

  @override
  List<Source> get inputs => <Source>[
        const Source.pattern(
            '{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
        Source.artifact(
          Artifact.flutterFramework,
          platform: TargetPlatform.ios,
          mode: buildMode,
        ),
      ];

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

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

  @visibleForOverriding
  BuildMode get buildMode;

  @override
  Future<void> build(Environment environment) async {
    final String basePath = environment.artifacts.getArtifactPath(
      Artifact.flutterFramework,
      platform: TargetPlatform.ios,
      mode: buildMode,
    );

    final ProcessResult result = environment.processManager.runSync(<String>[
      'rsync',
      '-av',
      '--delete',
      '--filter',
      '- .DS_Store/',
      basePath,
      environment.outputDir.path,
    ]);
    if (result.exitCode != 0) {
      throw Exception(
        'Failed to copy framework (exit ${result.exitCode}:\n'
        '${result.stdout}\n---\n${result.stderr}',
      );
    }
  }
}

/// Unpack the release prebuilt engine framework.
class ReleaseUnpackIOS extends UnpackIOS {
  const ReleaseUnpackIOS();

  @override
  String get name => 'release_unpack_ios';

  @override
  BuildMode get buildMode => BuildMode.release;
}

/// Unpack the profile prebuilt engine framework.
class ProfileUnpackIOS extends UnpackIOS {
  const ProfileUnpackIOS();

  @override
  String get name => 'profile_unpack_ios';

  @override
  BuildMode get buildMode => BuildMode.profile;
}

/// Unpack the debug prebuilt engine framework.
class DebugUnpackIOS extends UnpackIOS {
  const DebugUnpackIOS();

  @override
  String get name => 'debug_unpack_ios';

  @override
  BuildMode get buildMode => BuildMode.debug;
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
/// The base class for all iOS bundle targets.
///
/// This is responsible for setting up the basic App.framework structure, including:
/// * Copying the app.dill/kernel_blob.bin from the build directory to assets (debug)
/// * Copying the precompiled isolate/vm data from the engine (debug)
/// * Copying the flutter assets to App.framework/flutter_assets
/// * Copying either the stub or real App assembly file to App.framework/App
abstract class IosAssetBundle extends Target {
  const IosAssetBundle();

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

  @override
  List<Source> get inputs => const <Source>[
340
    Source.pattern('{BUILD_DIR}/App.framework/App'),
341
    Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
342
    ...IconTreeShaker.inputs,
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
    Source.pattern('{OUTPUT_DIR}/App.framework/Info.plist')
  ];

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

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

    // Only copy the prebuilt runtimes and kernel blob in debug mode.
    if (buildMode == BuildMode.debug) {
      // Copy the App.framework to the output directory.
370 371 372
      environment.buildDir
        .childDirectory('App.framework')
        .childFile('App')
373 374
        .copySync(frameworkDirectory.childFile('App').path);

375 376
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
377 378
      environment.buildDir.childFile('app.dill')
          .copySync(assetDirectory.childFile('kernel_blob.bin').path);
379
      environment.fileSystem.file(vmSnapshotData)
380
          .copySync(assetDirectory.childFile('vm_snapshot_data').path);
381
      environment.fileSystem.file(isolateSnapshotData)
382 383 384 385 386 387 388
          .copySync(assetDirectory.childFile('isolate_snapshot_data').path);
    } else {
      environment.buildDir.childDirectory('App.framework').childFile('App')
        .copySync(frameworkDirectory.childFile('App').path);
    }

    // Copy the assets.
389 390 391 392 393
    final Depfile assetDepfile = await copyAssets(
      environment,
      assetDirectory,
      targetPlatform: TargetPlatform.ios,
    );
394
    final DepfileService depfileService = DepfileService(
395 396
      fileSystem: environment.fileSystem,
      logger: environment.logger,
397 398 399 400 401
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443


    // Copy the plist from either the project or module.
    // TODO(jonahwilliams): add plist to inputs
    final FlutterProject flutterProject = FlutterProject.fromDirectory(environment.projectDir);
    final Directory plistRoot = flutterProject.isModule
      ? flutterProject.ios.ephemeralDirectory
      : environment.projectDir.childDirectory('ios');
    plistRoot
      .childDirectory('Flutter')
      .childFile('AppFrameworkInfo.plist')
      .copySync(environment.outputDir
      .childDirectory('App.framework')
      .childFile('Info.plist').path);
  }
}

/// Build a debug iOS application bundle.
class DebugIosApplicationBundle extends IosAssetBundle {
  const DebugIosApplicationBundle();

  @override
  String get name => 'debug_ios_bundle_flutter_assets';

  @override
  List<Source> get inputs => <Source>[
    const Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
    const Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
    const Source.pattern('{BUILD_DIR}/app.dill'),
    ...super.inputs,
  ];

  @override
  List<Source> get outputs => <Source>[
    const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/vm_snapshot_data'),
    const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/isolate_snapshot_data'),
    const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/kernel_blob.bin'),
    ...super.outputs,
  ];

  @override
  List<Target> get dependencies => <Target>[
444
    const DebugUniversalFramework(),
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    ...super.dependencies,
  ];
}

/// Build a profile iOS application bundle.
class ProfileIosApplicationBundle extends IosAssetBundle {
  const ProfileIosApplicationBundle();

  @override
  String get name => 'profile_ios_bundle_flutter_assets';

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

/// Build a release iOS application bundle.
class ReleaseIosApplicationBundle extends IosAssetBundle {
  const ReleaseIosApplicationBundle();

  @override
  String get name => 'release_ios_bundle_flutter_assets';

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

xster's avatar
xster committed
475 476 477 478 479
/// Create an App.framework for debug iOS targets.
///
/// This framework needs to exist for the Xcode project to link/bundle,
/// but it isn't actually executed. To generate something valid, we compile a trivial
/// constant.
480 481
Future<RunResult> createStubAppFramework(File outputFile, String sdkRoot,
    Set<String> iosArchNames) async {
xster's avatar
xster committed
482 483
  try {
    outputFile.createSync(recursive: true);
484 485
  } on Exception catch (e) {
    throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
486 487
  }

488 489
  final Directory tempDir = outputFile.fileSystem.systemTempDirectory
    .createTempSync('flutter_tools_stub_source.');
xster's avatar
xster committed
490 491 492 493 494 495
  try {
    final File stubSource = tempDir.childFile('debug_app.cc')
      ..writeAsStringSync(r'''
  static const int Moo = 88;
  ''');

496
    return await globals.xcode.clang(<String>[
xster's avatar
xster committed
497 498
      '-x',
      'c',
499
      for (String arch in iosArchNames) ...<String>['-arch', arch],
xster's avatar
xster committed
500 501
      stubSource.path,
      '-dynamiclib',
502
      '-fembed-bitcode-marker',
503 504
      // Keep version in sync with AOTSnapshotter flag
      '-miphoneos-version-min=8.0',
xster's avatar
xster committed
505 506 507
      '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
      '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
      '-install_name', '@rpath/App.framework/App',
508
      '-isysroot', sdkRoot,
xster's avatar
xster committed
509 510 511 512 513
      '-o', outputFile.path,
    ]);
  } finally {
    try {
      tempDir.deleteSync(recursive: true);
514
    } on FileSystemException {
xster's avatar
xster committed
515
      // Best effort. Sometimes we can't delete things from system temp.
516 517
    } on Exception catch (e) {
      throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
518 519 520
    }
  }
}