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

7 8
import '../../artifacts.dart';
import '../../base/build.dart';
xster's avatar
xster committed
9
import '../../base/common.dart';
10 11 12
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
13
import '../../globals.dart' as globals;
14
import '../../macos/xcode.dart';
15
import '../../project.dart';
16
import '../../reporting/reporting.dart';
17
import '../build_system.dart';
18
import '../depfile.dart';
19
import '../exceptions.dart';
20
import 'assets.dart';
21
import 'common.dart';
22
import 'icon_tree_shaker.dart';
23
import 'shader_compiler.dart';
24

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

32 33 34
  @override
  String get analyticsName => 'ios_aot';

35
  @override
36
  Future<void> build(Environment environment) async {
37
    final AOTSnapshotter snapshotter = AOTSnapshotter(
38 39
      fileSystem: environment.fileSystem,
      logger: environment.logger,
40
      xcode: globals.xcode!,
41 42
      artifacts: environment.artifacts,
      processManager: environment.processManager,
43
    );
44
    final String buildOutputPath = environment.buildDir.path;
45 46
    final String? environmentBuildMode = environment.defines[kBuildMode];
    if (environmentBuildMode == null) {
47 48
      throw MissingDefineException(kBuildMode, 'aot_assembly');
    }
49 50
    final String? environmentTargetPlatform = environment.defines[kTargetPlatform];
    if (environmentTargetPlatform== null) {
51 52
      throw MissingDefineException(kTargetPlatform, 'aot_assembly');
    }
53 54
    final String? sdkRoot = environment.defines[kSdkRoot];
    if (sdkRoot == null) {
55 56 57
      throw MissingDefineException(kSdkRoot, 'aot_assembly');
    }

58
    final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
59 60 61
    final BuildMode buildMode = getBuildModeForName(environmentBuildMode);
    final TargetPlatform targetPlatform = getTargetPlatformForName(environmentTargetPlatform);
    final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
62
    final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
63
    final List<DarwinArch> darwinArchs = environment.defines[kIosArchs]
64
      ?.split(' ')
65 66
      .map(getIOSArchForName)
      .toList()
67
      ?? <DarwinArch>[DarwinArch.arm64];
68
    if (targetPlatform != TargetPlatform.ios) {
69 70
      throw Exception('aot_assembly is only supported for iOS applications.');
    }
71

72
    final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem);
73
    if (environmentType == EnvironmentType.simulator) {
74 75
      throw Exception(
        'release/profile builds are only supported for physical devices. '
76
        'attempted to build for simulator.'
77
      );
78
    }
79
    final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
80

81 82 83
    // If we're building multiple iOS archs the binaries need to be lipo'd
    // together.
    final List<Future<int>> pending = <Future<int>>[];
84 85 86 87 88 89 90 91 92 93 94 95
    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}');
      }
96
      pending.add(snapshotter.build(
97 98 99
        platform: targetPlatform,
        buildMode: buildMode,
        mainPath: environment.buildDir.childFile('app.dill').path,
100 101
        outputPath: environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(darwinArch)),
        darwinArch: darwinArch,
102
        sdkRoot: sdkRoot,
103
        quiet: true,
104
        splitDebugInfo: splitDebugInfo,
105
        dartObfuscation: dartObfuscation,
106
        extraGenSnapshotOptions: archExtraGenSnapshotOptions,
107 108 109 110 111 112
      ));
    }
    final List<int> results = await Future.wait(pending);
    if (results.any((int result) => result != 0)) {
      throw Exception('AOT snapshotter exited with code ${results.join()}');
    }
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

    // Combine the app lib into a fat framework.
    await Lipo.create(
      environment,
      darwinArchs,
      relativePath: 'App.framework/App',
      inputDir: buildOutputPath,
    );

    // And combine the dSYM for each architecture too, if it was created.
    await Lipo.create(
      environment,
      darwinArchs,
      relativePath: 'App.framework.dSYM/Contents/Resources/DWARF/App',
      inputDir: buildOutputPath,
      // Don't fail if the dSYM wasn't created (i.e. during a debug build).
      skipMissingInputs: true,
    );
131 132 133 134 135 136 137 138 139 140 141 142 143 144
  }
}

/// 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'),
145
    Source.artifact(Artifact.engineDartBinary),
146
    Source.artifact(Artifact.skyEnginePath),
147
    // TODO(zanderso): cannot reference gen_snapshot with artifacts since
148 149 150 151 152 153
    // 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,
    // ),
154 155 156 157
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
158
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
159 160 161 162
  ];

  @override
  List<Target> get dependencies => const <Target>[
163
    ReleaseUnpackIOS(),
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    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'),
180
    Source.artifact(Artifact.engineDartBinary),
181
    Source.artifact(Artifact.skyEnginePath),
182
    // TODO(zanderso): cannot reference gen_snapshot with artifacts since
183 184 185 186 187 188
    // 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,
    // ),
189 190 191 192
  ];

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
193
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
194 195 196 197
  ];

  @override
  List<Target> get dependencies => const <Target>[
198
    ProfileUnpackIOS(),
199 200 201
    KernelSnapshot(),
  ];
}
xster's avatar
xster committed
202

203
/// Create a trivial App.framework file for debug iOS builds.
204 205
class DebugUniversalFramework extends Target {
  const DebugUniversalFramework();
206 207 208 209 210 211

  @override
  String get name => 'debug_universal_framework';

  @override
  List<Target> get dependencies => const <Target>[
212
    DebugUnpackIOS(),
213 214 215 216 217 218 219 220 221 222
    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>[
223
    Source.pattern('{BUILD_DIR}/App.framework/App'),
224 225 226 227
  ];

  @override
  Future<void> build(Environment environment) async {
228 229
    final String? sdkRoot = environment.defines[kSdkRoot];
    if (sdkRoot == null) {
230 231 232
      throw MissingDefineException(kSdkRoot, name);
    }

233
    // Generate a trivial App.framework.
234
    final Set<String>? iosArchNames = environment.defines[kIosArchs]?.split(' ').toSet();
235
    final File output = environment.buildDir
236 237
      .childDirectory('App.framework')
      .childFile('App');
238
    environment.buildDir.createSync(recursive: true);
239
    await _createStubAppFramework(
240
      output,
241
      environment,
242
      iosArchNames,
243
      sdkRoot,
244 245 246 247
    );
  }
}

248 249 250 251 252 253 254 255 256 257 258 259 260
/// 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(
261
          Artifact.flutterXcframework,
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
          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 {
280 281
    final String? sdkRoot = environment.defines[kSdkRoot];
    if (sdkRoot == null) {
282 283
      throw MissingDefineException(kSdkRoot, name);
    }
284 285
    final String? archs = environment.defines[kIosArchs];
    if (archs == null) {
286 287
      throw MissingDefineException(kIosArchs, name);
    }
288
    _copyFramework(environment, sdkRoot);
289 290 291 292 293 294

    final File frameworkBinary = environment.outputDir.childDirectory('Flutter.framework').childFile('Flutter');
    final String frameworkBinaryPath = frameworkBinary.path;
    if (!frameworkBinary.existsSync()) {
      throw Exception('Binary $frameworkBinaryPath does not exist, cannot thin');
    }
295
    _thinFramework(environment, frameworkBinaryPath, archs);
296 297 298
    if (buildMode == BuildMode.release) {
      _bitcodeStripFramework(environment, frameworkBinaryPath);
    }
299
    _signFramework(environment, frameworkBinaryPath, buildMode);
300 301
  }

302 303
  void _copyFramework(Environment environment, String sdkRoot) {
    final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem);
304 305 306 307
    final String basePath = environment.artifacts.getArtifactPath(
      Artifact.flutterFramework,
      platform: TargetPlatform.ios,
      mode: buildMode,
308
      environmentType: environmentType,
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    );

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

  /// Destructively thin Flutter.framework to include only the specified architectures.
329
  void _thinFramework(Environment environment, String frameworkBinaryPath, String archs) {
330 331 332 333
    final List<String> archList = archs.split(' ').toList();
    final ProcessResult infoResult = environment.processManager.runSync(<String>[
      'lipo',
      '-info',
334
      frameworkBinaryPath,
335 336 337 338 339
    ]);
    final String lipoInfo = infoResult.stdout as String;

    final ProcessResult verifyResult = environment.processManager.runSync(<String>[
      'lipo',
340
      frameworkBinaryPath,
341
      '-verify_arch',
342
      ...archList,
343 344 345
    ]);

    if (verifyResult.exitCode != 0) {
346
      throw Exception('Binary $frameworkBinaryPath does not contain $archs. Running lipo -info:\n$lipoInfo');
347 348 349 350
    }

    // Skip thinning for non-fat executables.
    if (lipoInfo.startsWith('Non-fat file:')) {
351
      environment.logger.printTrace('Skipping lipo for non-fat file $frameworkBinaryPath');
352 353 354 355 356 357 358
      return;
    }

    // Thin in-place.
    final ProcessResult extractResult = environment.processManager.runSync(<String>[
      'lipo',
      '-output',
359
      frameworkBinaryPath,
360 361 362 363 364
      for (final String arch in archList)
        ...<String>[
          '-extract',
          arch,
        ],
365
      ...<String>[frameworkBinaryPath],
366 367 368
    ]);

    if (extractResult.exitCode != 0) {
369 370 371 372
      throw Exception('Failed to extract $archs for $frameworkBinaryPath.\n${extractResult.stderr}\nRunning lipo -info:\n$lipoInfo');
    }
  }

373 374
  /// Destructively strip bitcode from the framework. This can be removed
  /// when the framework is no longer built with bitcode.
375
  void _bitcodeStripFramework(Environment environment, String frameworkBinaryPath) {
376 377 378 379
    final ProcessResult stripResult = environment.processManager.runSync(<String>[
      'xcrun',
      'bitcode_strip',
      frameworkBinaryPath,
380
      '-r', // Delete the bitcode segment.
381 382 383 384 385 386
      '-o',
      frameworkBinaryPath,
    ]);

    if (stripResult.exitCode != 0) {
      throw Exception('Failed to strip bitcode for $frameworkBinaryPath.\n${stripResult.stderr}');
387 388
    }
  }
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
}

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

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
/// 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>[
441
    Source.pattern('{BUILD_DIR}/App.framework/App'),
442
    Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
443
    ...IconTreeShaker.inputs,
444
    ...ShaderCompiler.inputs,
445 446 447 448 449
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
450
    Source.pattern('{OUTPUT_DIR}/App.framework/Info.plist'),
451 452 453 454 455 456 457 458 459
  ];

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

  @override
  Future<void> build(Environment environment) async {
460 461
    final String? environmentBuildMode = environment.defines[kBuildMode];
    if (environmentBuildMode == null) {
462 463
      throw MissingDefineException(kBuildMode, name);
    }
464
    final BuildMode buildMode = getBuildModeForName(environmentBuildMode);
465
    final Directory frameworkDirectory = environment.outputDir.childDirectory('App.framework');
466
    final String frameworkBinaryPath = frameworkDirectory.childFile('App').path;
467 468 469 470 471 472 473
    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.
474 475 476
      environment.buildDir
        .childDirectory('App.framework')
        .childFile('App')
477
        .copySync(frameworkBinaryPath);
478

479 480
      final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
      final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
481 482
      environment.buildDir.childFile('app.dill')
          .copySync(assetDirectory.childFile('kernel_blob.bin').path);
483
      environment.fileSystem.file(vmSnapshotData)
484
          .copySync(assetDirectory.childFile('vm_snapshot_data').path);
485
      environment.fileSystem.file(isolateSnapshotData)
486 487 488
          .copySync(assetDirectory.childFile('isolate_snapshot_data').path);
    } else {
      environment.buildDir.childDirectory('App.framework').childFile('App')
489
        .copySync(frameworkBinaryPath);
490 491
    }

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    // Copy the dSYM
    if (environment.buildDir.childDirectory('App.framework.dSYM').existsSync()) {
      final File dsymOutputBinary = environment
        .outputDir
        .childDirectory('App.framework.dSYM')
        .childDirectory('Contents')
        .childDirectory('Resources')
        .childDirectory('DWARF')
        .childFile('App');
      dsymOutputBinary.parent.createSync(recursive: true);
      environment
        .buildDir
        .childDirectory('App.framework.dSYM')
        .childDirectory('Contents')
        .childDirectory('Resources')
        .childDirectory('DWARF')
        .childFile('App')
        .copySync(dsymOutputBinary.path);
    }

512 513
    final FlutterProject flutterProject = FlutterProject.fromDirectory(environment.projectDir);

514
    // Copy the assets.
515 516 517 518
    final Depfile assetDepfile = await copyAssets(
      environment,
      assetDirectory,
      targetPlatform: TargetPlatform.ios,
519 520 521
      // Always specify an impeller shader target so that we support runtime toggling and
      // the --enable-impeller debug flag.
      shaderTarget: ShaderTarget.impelleriOS,
522 523 524 525
      additionalInputs: <File>[
        flutterProject.ios.infoPlist,
        flutterProject.ios.appFrameworkInfoPlist,
      ],
526
    );
527
    final DepfileService depfileService = DepfileService(
528 529
      fileSystem: environment.fileSystem,
      logger: environment.logger,
530 531 532 533 534
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
535 536

    // Copy the plist from either the project or module.
537
    flutterProject.ios.appFrameworkInfoPlist
538 539 540
      .copySync(environment.outputDir
      .childDirectory('App.framework')
      .childFile('Info.plist').path);
541 542

    _signFramework(environment, frameworkBinaryPath, buildMode);
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
  }
}

/// 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>[
571
    const DebugUniversalFramework(),
572 573 574 575
    ...super.dependencies,
  ];
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
/// IosAssetBundle with debug symbols, used for Profile and Release builds.
abstract class _IosAssetBundleWithDSYM extends IosAssetBundle {
  const _IosAssetBundleWithDSYM();

  @override
  List<Source> get inputs => <Source>[
    ...super.inputs,
    const Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
  ];

  @override
  List<Source> get outputs => <Source>[
    ...super.outputs,
    const Source.pattern('{OUTPUT_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
  ];
}

593
/// Build a profile iOS application bundle.
594
class ProfileIosApplicationBundle extends _IosAssetBundleWithDSYM {
595 596 597 598 599 600 601 602 603 604 605 606
  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.
607
class ReleaseIosApplicationBundle extends _IosAssetBundleWithDSYM {
608 609 610 611 612 613 614 615 616
  const ReleaseIosApplicationBundle();

  @override
  String get name => 'release_ios_bundle_flutter_assets';

  @override
  List<Target> get dependencies => const <Target>[
    AotAssemblyRelease(),
  ];
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

  @override
  Future<void> build(Environment environment) async {
    bool buildSuccess = true;
    try {
      await super.build(environment);
    } catch (_) {  // ignore: avoid_catches_without_on_clauses
      buildSuccess = false;
      rethrow;
    } finally {
      // Send a usage event when the app is being archived.
      // Since assemble is run during a `flutter build`/`run` as well as an out-of-band
      // archive command from Xcode, this is a more accurate count than `flutter build ipa` alone.
      if (environment.defines[kXcodeAction]?.toLowerCase() == 'install') {
        environment.logger.printTrace('Sending archive event if usage enabled.');
        UsageEvent(
          'assemble',
          'ios-archive',
          label: buildSuccess ? 'success' : 'fail',
          flutterUsage: environment.usage,
        ).send();
      }
    }
  }
641 642
}

xster's avatar
xster committed
643 644 645 646 647
/// 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.
648
Future<void> _createStubAppFramework(File outputFile, Environment environment,
649
    Set<String>? iosArchNames, String sdkRoot) async {
xster's avatar
xster committed
650 651
  try {
    outputFile.createSync(recursive: true);
652 653
  } on Exception catch (e) {
    throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
654 655
  }

656 657
  final FileSystem fileSystem = environment.fileSystem;
  final Directory tempDir = fileSystem.systemTempDirectory
658
    .createTempSync('flutter_tools_stub_source.');
xster's avatar
xster committed
659 660 661 662 663 664
  try {
    final File stubSource = tempDir.childFile('debug_app.cc')
      ..writeAsStringSync(r'''
  static const int Moo = 88;
  ''');

665
    final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, fileSystem);
666

667
    await globals.xcode!.clang(<String>[
xster's avatar
xster committed
668 669
      '-x',
      'c',
670
      for (String arch in iosArchNames ?? <String>{}) ...<String>['-arch', arch],
xster's avatar
xster committed
671 672
      stubSource.path,
      '-dynamiclib',
673
      // Keep version in sync with AOTSnapshotter flag
674
      if (environmentType == EnvironmentType.physical)
675
        '-miphoneos-version-min=11.0'
676
      else
677
        '-miphonesimulator-version-min=11.0',
xster's avatar
xster committed
678 679 680
      '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
      '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
      '-install_name', '@rpath/App.framework/App',
681
      '-isysroot', sdkRoot,
xster's avatar
xster committed
682 683 684 685 686
      '-o', outputFile.path,
    ]);
  } finally {
    try {
      tempDir.deleteSync(recursive: true);
687
    } on FileSystemException {
xster's avatar
xster committed
688
      // Best effort. Sometimes we can't delete things from system temp.
689 690
    } on Exception catch (e) {
      throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
691 692
    }
  }
693 694 695 696 697

  _signFramework(environment, outputFile.path, BuildMode.debug);
}

void _signFramework(Environment environment, String binaryPath, BuildMode buildMode) {
698
  String? codesignIdentity = environment.defines[kCodesignIdentity];
699
  if (codesignIdentity == null || codesignIdentity.isEmpty) {
700
    codesignIdentity = '-';
701
  }
702
  final ProcessResult result = environment.processManager.runSync(<String>[
703 704 705 706 707 708 709 710 711 712
    'codesign',
    '--force',
    '--sign',
    codesignIdentity,
    if (buildMode != BuildMode.release) ...<String>[
      // Mimic Xcode's timestamp codesigning behavior on non-release binaries.
      '--timestamp=none',
    ],
    binaryPath,
  ]);
713
  if (result.exitCode != 0) {
714 715 716 717 718 719 720 721 722 723 724
    final String stdout = (result.stdout as String).trim();
    final String stderr = (result.stderr as String).trim();
    final StringBuffer output = StringBuffer();
    output.writeln('Failed to codesign $binaryPath with identity $codesignIdentity.');
    if (stdout.isNotEmpty) {
      output.writeln(stdout);
    }
    if (stderr.isNotEmpty) {
      output.writeln(stderr);
    }
    throw Exception(output.toString());
725
  }
xster's avatar
xster committed
726
}