ios.dart 21.7 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 show xcode;
14
import '../../macos/xcode.dart';
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
    final AOTSnapshotter snapshotter = AOTSnapshotter(
36 37
      fileSystem: environment.fileSystem,
      logger: environment.logger,
38
      xcode: globals.xcode!,
39 40
      artifacts: environment.artifacts,
      processManager: environment.processManager,
41
    );
42
    final String buildOutputPath = environment.buildDir.path;
43 44
    final String? environmentBuildMode = environment.defines[kBuildMode];
    if (environmentBuildMode == null) {
45 46
      throw MissingDefineException(kBuildMode, 'aot_assembly');
    }
47 48
    final String? environmentTargetPlatform = environment.defines[kTargetPlatform];
    if (environmentTargetPlatform== null) {
49 50
      throw MissingDefineException(kTargetPlatform, 'aot_assembly');
    }
51 52
    final String? sdkRoot = environment.defines[kSdkRoot];
    if (sdkRoot == null) {
53 54 55
      throw MissingDefineException(kSdkRoot, 'aot_assembly');
    }

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

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

80 81 82
    // If we're building multiple iOS archs the binaries need to be lipo'd
    // together.
    final List<Future<int>> pending = <Future<int>>[];
83 84 85 86 87 88 89 90 91 92 93 94
    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}');
      }
95
      pending.add(snapshotter.build(
96 97 98
        platform: targetPlatform,
        buildMode: buildMode,
        mainPath: environment.buildDir.childFile('app.dill').path,
99 100
        outputPath: environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(darwinArch)),
        darwinArch: darwinArch,
101
        sdkRoot: sdkRoot,
102
        bitcode: bitcode,
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
    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>[
116
      'lipo',
117
      ...darwinArchs.map((DarwinArch iosArch) =>
118
          environment.fileSystem.path.join(buildOutputPath, getNameForDarwinArch(iosArch), 'App.framework', 'App')),
119 120 121 122 123 124
      '-create',
      '-output',
      resultPath,
    ]);
    if (result.exitCode != 0) {
      throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }
  }
}

/// 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'),
140
    Source.hostArtifact(HostArtifact.engineDartBinary),
141
    Source.artifact(Artifact.skyEnginePath),
142
    // TODO(zanderso): cannot reference gen_snapshot with artifacts since
143 144 145 146 147 148
    // 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,
    // ),
149 150 151 152
  ];

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

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

  @override
  List<Source> get outputs => const <Source>[
xster's avatar
xster committed
188
    Source.pattern('{OUTPUT_DIR}/App.framework/App'),
189 190 191 192
  ];

  @override
  List<Target> get dependencies => const <Target>[
193
    ProfileUnpackIOS(),
194 195 196
    KernelSnapshot(),
  ];
}
xster's avatar
xster committed
197

198
/// Create a trivial App.framework file for debug iOS builds.
199 200
class DebugUniversalFramework extends Target {
  const DebugUniversalFramework();
201 202 203 204 205 206

  @override
  String get name => 'debug_universal_framework';

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

  @override
  Future<void> build(Environment environment) async {
223 224
    final String? sdkRoot = environment.defines[kSdkRoot];
    if (sdkRoot == null) {
225 226 227
      throw MissingDefineException(kSdkRoot, name);
    }

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

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

    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');
    }
293
    _thinFramework(environment, frameworkBinaryPath, archs);
294 295
    _bitcodeStripFramework(environment, frameworkBinaryPath);
    _signFramework(environment, frameworkBinaryPath, buildMode);
296 297
  }

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

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

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

    final ProcessResult verifyResult = environment.processManager.runSync(<String>[
      'lipo',
336
      frameworkBinaryPath,
337 338 339 340 341
      '-verify_arch',
      ...archList
    ]);

    if (verifyResult.exitCode != 0) {
342
      throw Exception('Binary $frameworkBinaryPath does not contain $archs. Running lipo -info:\n$lipoInfo');
343 344 345 346
    }

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

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

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

  /// Destructively strip bitcode from the framework, if needed.
370
  void _bitcodeStripFramework(Environment environment, String frameworkBinaryPath) {
371 372 373 374 375 376 377 378 379 380 381 382 383 384
    if (environment.defines[kBitcodeFlag] == 'true') {
      return;
    }
    final ProcessResult stripResult = environment.processManager.runSync(<String>[
      'xcrun',
      'bitcode_strip',
      frameworkBinaryPath,
      '-m', // leave the bitcode marker.
      '-o',
      frameworkBinaryPath,
    ]);

    if (stripResult.exitCode != 0) {
      throw Exception('Failed to strip bitcode for $frameworkBinaryPath.\n${stripResult.stderr}');
385 386
    }
  }
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
}

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

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

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

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

    // Copy the assets.
490 491 492 493 494
    final Depfile assetDepfile = await copyAssets(
      environment,
      assetDirectory,
      targetPlatform: TargetPlatform.ios,
    );
495
    final DepfileService depfileService = DepfileService(
496 497
      fileSystem: environment.fileSystem,
      logger: environment.logger,
498 499 500 501 502
    );
    depfileService.writeToFile(
      assetDepfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
503 504

    // Copy the plist from either the project or module.
505
    // TODO(zanderso): add plist to inputs
506
    final FlutterProject flutterProject = FlutterProject.fromDirectory(environment.projectDir);
507
    flutterProject.ios.appFrameworkInfoPlist
508 509 510
      .copySync(environment.outputDir
      .childDirectory('App.framework')
      .childFile('Info.plist').path);
511 512

    _signFramework(environment, frameworkBinaryPath, buildMode);
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
  }
}

/// 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>[
541
    const DebugUniversalFramework(),
542 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 571
    ...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
572 573 574 575 576
/// 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.
577
Future<void> _createStubAppFramework(File outputFile, Environment environment,
578
    Set<String>? iosArchNames, String sdkRoot) async {
xster's avatar
xster committed
579 580
  try {
    outputFile.createSync(recursive: true);
581 582
  } on Exception catch (e) {
    throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
583 584
  }

585 586
  final FileSystem fileSystem = environment.fileSystem;
  final Directory tempDir = fileSystem.systemTempDirectory
587
    .createTempSync('flutter_tools_stub_source.');
xster's avatar
xster committed
588 589 590 591 592 593
  try {
    final File stubSource = tempDir.childFile('debug_app.cc')
      ..writeAsStringSync(r'''
  static const int Moo = 88;
  ''');

594
    final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, fileSystem);
595

596
    await globals.xcode!.clang(<String>[
xster's avatar
xster committed
597 598
      '-x',
      'c',
599
      for (String arch in iosArchNames ?? <String>{}) ...<String>['-arch', arch],
xster's avatar
xster committed
600 601
      stubSource.path,
      '-dynamiclib',
602
      '-fembed-bitcode-marker',
603
      // Keep version in sync with AOTSnapshotter flag
604
      if (environmentType == EnvironmentType.physical)
605
        '-miphoneos-version-min=9.0'
606
      else
607
        '-miphonesimulator-version-min=9.0',
xster's avatar
xster committed
608 609 610
      '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
      '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
      '-install_name', '@rpath/App.framework/App',
611
      '-isysroot', sdkRoot,
xster's avatar
xster committed
612 613 614 615 616
      '-o', outputFile.path,
    ]);
  } finally {
    try {
      tempDir.deleteSync(recursive: true);
617
    } on FileSystemException {
xster's avatar
xster committed
618
      // Best effort. Sometimes we can't delete things from system temp.
619 620
    } on Exception catch (e) {
      throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
xster's avatar
xster committed
621 622
    }
  }
623 624 625 626 627

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

void _signFramework(Environment environment, String binaryPath, BuildMode buildMode) {
628
  String? codesignIdentity = environment.defines[kCodesignIdentity];
629
  if (codesignIdentity == null || codesignIdentity.isEmpty) {
630
    codesignIdentity = '-';
631
  }
632
  final ProcessResult result = environment.processManager.runSync(<String>[
633 634 635 636 637 638 639 640 641 642
    'codesign',
    '--force',
    '--sign',
    codesignIdentity,
    if (buildMode != BuildMode.release) ...<String>[
      // Mimic Xcode's timestamp codesigning behavior on non-release binaries.
      '--timestamp=none',
    ],
    binaryPath,
  ]);
643 644
  if (result.exitCode != 0) {
    throw Exception('Failed to codesign $binaryPath with identity $codesignIdentity.\n${result.stderr}');
645
  }
xster's avatar
xster committed
646
}