ios.dart 14.5 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 '../../artifacts.dart';
import '../../base/build.dart';
xster's avatar
xster committed
7
import '../../base/common.dart';
8 9
import '../../base/file_system.dart';
import '../../base/io.dart';
xster's avatar
xster committed
10
import '../../base/process.dart';
11
import '../../build_info.dart';
12
import '../../globals.dart' as globals;
xster's avatar
xster committed
13
import '../../macos/xcode.dart';
14
import '../../project.dart';
15
import '../build_system.dart';
16
import '../depfile.dart';
17
import '../exceptions.dart';
18
import 'assets.dart';
19
import 'dart.dart';
20
import 'icon_tree_shaker.dart';
21

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

  @override
30
  Future<void> build(Environment environment) async {
31
    final AOTSnapshotter snapshotter = AOTSnapshotter(reportTimings: false);
32
    final String buildOutputPath = environment.buildDir.path;
33 34 35 36 37 38 39 40 41
    if (environment.defines[kBuildMode] == null) {
      throw MissingDefineException(kBuildMode, 'aot_assembly');
    }
    if (environment.defines[kTargetPlatform] == null) {
      throw MissingDefineException(kTargetPlatform, 'aot_assembly');
    }
    final bool bitcode = environment.defines[kBitcodeFlag] == 'true';
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
    final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);
42
    final String splitDebugInfo = environment.defines[kSplitDebugInfo];
43
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
44 45 46 47 48
    final List<DarwinArch> iosArchs = environment.defines[kIosArchs]
      ?.split(' ')
      ?.map(getIOSArchForName)
      ?.toList()
      ?? <DarwinArch>[DarwinArch.arm64];
49 50 51 52
    if (targetPlatform != TargetPlatform.ios) {
      throw Exception('aot_assembly is only supported for iOS applications');
    }

53 54 55 56 57
    // If we're building multiple iOS archs the binaries need to be lipo'd
    // together.
    final List<Future<int>> pending = <Future<int>>[];
    for (final DarwinArch iosArch in iosArchs) {
      pending.add(snapshotter.build(
58 59 60 61
        platform: targetPlatform,
        buildMode: buildMode,
        mainPath: environment.buildDir.childFile('app.dill').path,
        packagesPath: environment.projectDir.childFile('.packages').path,
62 63
        outputPath: globals.fs.path.join(buildOutputPath, getNameForDarwinArch(iosArch)),
        darwinArch: iosArch,
64
        bitcode: bitcode,
65
        quiet: true,
66
        splitDebugInfo: splitDebugInfo,
67
        dartObfuscation: dartObfuscation,
68 69 70 71 72 73
      ));
    }
    final List<int> results = await Future.wait(pending);
    if (results.any((int result) => result != 0)) {
      throw Exception('AOT snapshotter exited with code ${results.join()}');
    }
74
    final String resultPath = globals.fs.path.join(environment.buildDir.path, 'App.framework', 'App');
75 76 77 78 79 80 81 82 83 84 85
    globals.fs.directory(resultPath).parent.createSync(recursive: true);
    final ProcessResult result = await globals.processManager.run(<String>[
      'lipo',
      ...iosArchs.map((DarwinArch iosArch) =>
          globals.fs.path.join(buildOutputPath, getNameForDarwinArch(iosArch), 'App.framework', 'App')),
      '-create',
      '-output',
      resultPath,
    ]);
    if (result.exitCode != 0) {
      throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    }
  }
}

/// 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.pattern('{PROJECT_DIR}/.packages'),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.skyEnginePath),
104 105 106 107 108 109 110
    // 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,
    // ),
111 112 113 114
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
115
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
  ];

  @override
  List<Target> get dependencies => const <Target>[
    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.pattern('{PROJECT_DIR}/.packages'),
    Source.artifact(Artifact.engineDartBinary),
    Source.artifact(Artifact.skyEnginePath),
139 140 141 142 143 144 145
    // 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,
    // ),
146 147 148 149
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
150
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
151 152 153 154 155 156 157
  ];

  @override
  List<Target> get dependencies => const <Target>[
    KernelSnapshot(),
  ];
}
xster's avatar
xster committed
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
/// Create a trivial App.framework file for debug iOS builds.
class DebugUniveralFramework extends Target {
  const DebugUniveralFramework();

  @override
  String get name => 'debug_universal_framework';

  @override
  List<Target> get dependencies => const <Target>[
    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>[
    Source.pattern('{BUILD_DIR}/App')
  ];

  @override
  Future<void> build(Environment environment) async {
    // Generate a trivial App.framework.
    final Set<DarwinArch> iosArchs = environment.defines[kIosArchs]
      ?.split(' ')
      ?.map(getIOSArchForName)
      ?.toSet()
      ?? <DarwinArch>{DarwinArch.arm64};
    final File iphoneFile = environment.buildDir.childFile('iphone_framework');
    final File simulatorFile = environment.buildDir.childFile('simulator_framework');
    final File lipoOutputFile = environment.buildDir.childFile('App');
    final RunResult iphoneResult = await createStubAppFramework(
      iphoneFile,
      SdkType.iPhone,
      // Only include 32bit if it is contained in the active architectures.
      include32Bit: iosArchs.contains(DarwinArch.armv7)
    );
    final RunResult simulatorResult = await createStubAppFramework(
      simulatorFile,
      SdkType.iPhoneSimulator,
    );
    if (iphoneResult.exitCode != 0 || simulatorResult.exitCode != 0) {
      throw Exception('Failed to create App.framework.');
    }
    final List<String> lipoCommand = <String>[
      'xcrun',
      'lipo',
      '-create',
      iphoneFile.path,
      simulatorFile.path,
      '-output',
      lipoOutputFile.path
    ];
    final RunResult lipoResult = await processUtils.run(
      lipoCommand,
    );

    if (lipoResult.exitCode != 0) {
      throw Exception('Failed to create App.framework.');
    }
  }
}

/// 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>[
    Source.pattern('{BUILD_DIR}/App'),
    Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
243
    ...IconTreeShaker.inputs,
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
  ];

  @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.
      environment.buildDir.childFile('App')
        .copySync(frameworkDirectory.childFile('App').path);

      final String vmSnapshotData = globals.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = globals.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
      environment.buildDir.childFile('app.dill')
          .copySync(assetDirectory.childFile('kernel_blob.bin').path);
      globals.fs.file(vmSnapshotData)
          .copySync(assetDirectory.childFile('vm_snapshot_data').path);
      globals.fs.file(isolateSnapshotData)
          .copySync(assetDirectory.childFile('isolate_snapshot_data').path);
    } else {
      environment.buildDir.childDirectory('App.framework').childFile('App')
        .copySync(frameworkDirectory.childFile('App').path);
    }

    // Copy the assets.
    final Depfile assetDepfile = await copyAssets(environment, assetDirectory);
289 290 291 292 293 294 295 296 297
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
      platform: globals.platform,
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 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 370


    // 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>[
    const DebugUniveralFramework(),
    ...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
371 372 373 374 375
/// 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.
376
Future<RunResult> createStubAppFramework(File outputFile, SdkType sdk, { bool include32Bit = true }) async {
xster's avatar
xster committed
377 378
  try {
    outputFile.createSync(recursive: true);
379 380
  } on Exception catch (e) {
    throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
381 382
  }

383
  final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_stub_source.');
xster's avatar
xster committed
384 385 386 387 388 389
  try {
    final File stubSource = tempDir.childFile('debug_app.cc')
      ..writeAsStringSync(r'''
  static const int Moo = 88;
  ''');

390 391 392
    List<String> archFlags;
    if (sdk == SdkType.iPhone) {
      archFlags = <String>[
393 394
        if (include32Bit)
          ...<String>['-arch', getNameForDarwinArch(DarwinArch.armv7)],
395 396 397 398 399 400 401 402 403 404
        '-arch',
        getNameForDarwinArch(DarwinArch.arm64),
      ];
    } else {
      archFlags = <String>[
        '-arch',
        getNameForDarwinArch(DarwinArch.x86_64),
      ];
    }

405
    return await globals.xcode.clang(<String>[
xster's avatar
xster committed
406 407
      '-x',
      'c',
408
      ...archFlags,
xster's avatar
xster committed
409 410
      stubSource.path,
      '-dynamiclib',
411
      '-fembed-bitcode-marker',
xster's avatar
xster committed
412 413 414
      '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
      '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
      '-install_name', '@rpath/App.framework/App',
415
      '-isysroot', await globals.xcode.sdkLocation(sdk),
xster's avatar
xster committed
416 417 418 419 420 421 422
      '-o', outputFile.path,
    ]);
  } finally {
    try {
      tempDir.deleteSync(recursive: true);
    } on FileSystemException catch (_) {
      // Best effort. Sometimes we can't delete things from system temp.
423 424
    } on Exception catch (e) {
      throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
425 426 427
    }
  }
}