Repository navigation
Expand file tree
/
Copy pathmac.dart
More file actions
1638 lines (1509 loc) · 60.4 KB
/
Copy pathmac.dart
File metadata and controls
1638 lines (1509 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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
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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
541
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter 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';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../artifacts.dart';
import '../base/bot_detector.dart';
import '../base/config.dart';
import '../base/file_system.dart';
import '../base/fingerprint.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/project_migrator.dart';
import '../base/template.dart';
import '../base/utils.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../cache.dart';
import '../context/tool_context.dart';
import '../darwin/darwin.dart';
import '../device.dart';
import '../features.dart';
import '../flutter_manifest.dart';
import '../macos/cocoapod_utils.dart';
import '../macos/cocoapods.dart';
import '../macos/darwin_dependency_management.dart';
import '../macos/swift_package_manager.dart';
import '../macos/xcode.dart';
import '../migrations/lldb_init_migration.dart';
import '../migrations/swift_package_manager_gitignore_migration.dart';
import '../migrations/swift_package_manager_integration_migration.dart';
import '../migrations/uiscene_migration.dart';
import '../migrations/xcode_project_object_version_migration.dart';
import '../migrations/xcode_script_build_phase_migration.dart';
import '../migrations/xcode_thin_binary_build_phase_input_paths_migration.dart';
import '../plugins.dart';
import '../project.dart';
import '../reporting/crash_reporting.dart';
import 'application_package.dart';
import 'code_signing.dart';
import 'migrations/host_app_info_plist_migration.dart';
import 'migrations/ios_deployment_target_migration.dart';
import 'migrations/metal_api_validation_migration.dart';
import 'migrations/project_base_configuration_migration.dart';
import 'migrations/project_build_location_migration.dart';
import 'migrations/remove_bitcode_migration.dart';
import 'migrations/remove_framework_link_and_embedding_migration.dart';
import 'migrations/uiapplicationmain_deprecation_migration.dart';
import 'migrations/xcode_build_system_migration.dart';
import 'plist_parser.dart';
import 'xcode_build_settings.dart';
import 'xcodeproj.dart';
import 'xcresult.dart';
const kConcurrentRunFailureMessage1 = 'database is locked';
const kConcurrentRunFailureMessage2 = 'there are two concurrent builds running';
/// User message when missing platform required to use Xcode.
///
/// Starting with Xcode 15, the simulator is no longer downloaded with Xcode
/// and must be downloaded and installed separately.
@visibleForTesting
String missingPlatformInstructions(String simulatorVersion) =>
'''
════════════════════════════════════════════════════════════════════════════════
$simulatorVersion is not installed. To download and install the platform, open
Xcode, select Xcode > Settings > Components, and click the GET button for the
required platform.
For more information, please visit:
https://developer.apple.com/documentation/xcode/installing-additional-simulator-runtimes
════════════════════════════════════════════════════════════════════════════════''';
class IMobileDevice {
IMobileDevice({
required this._artifacts,
required Cache cache,
required ProcessManager processManager,
required Logger logger,
}) : _dyLdLibEntry = cache.dyLdLibEntry,
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
/// Create an [IMobileDevice] for testing.
factory IMobileDevice.test({required ProcessManager processManager}) {
return IMobileDevice(
// ignore: invalid_use_of_visible_for_testing_member
artifacts: Artifacts.test(),
cache: Cache.test(processManager: processManager),
processManager: processManager,
logger: BufferLogger.test(),
);
}
final Artifacts _artifacts;
final MapEntry<String, String> _dyLdLibEntry;
final ProcessUtils _processUtils;
String get _idevicesyslogPath => _artifacts.getHostArtifact(HostArtifact.idevicesyslog).path;
/// Starts `idevicesyslog` and returns the running process.
Future<Process> startLogger(String deviceID, bool isWirelesslyConnected) {
return _processUtils.start(<String>[
_idevicesyslogPath,
'-u',
deviceID,
if (isWirelesslyConnected) '--network',
], environment: Map<String, String>.fromEntries(<MapEntry<String, String>>[_dyLdLibEntry]));
}
}
Future<XcodeBuildResult> buildXcodeProject({
required Analytics analytics,
required BuildableIOSApp app,
required BuildInfo buildInfo,
required CocoaPods cocoaPods,
required FeatureFlags featureFlags,
required PlistParser plistParser,
required TemplateRenderer templateRenderer,
required ToolContext toolContext,
required Xcode xcode,
required XcodeProjectInterpreter xcodeProjectInterpreter,
String? targetOverride,
EnvironmentType environmentType = EnvironmentType.physical,
CpuArch? activeArch,
bool codesign = true,
String? deviceID,
bool configOnly = false,
XcodeBuildAction buildAction = XcodeBuildAction.build,
bool disablePortPublication = false,
bool verboseLogging = false,
}) async {
final ToolContext(
:Artifacts artifacts,
:BotDetector botDetector,
:Config config,
:FileSystem fs,
:Logger logger,
:OperatingSystemUtils os,
:Platform platform,
:ProcessUtils processUtils,
) = toolContext;
final bool isVerbose = verboseLogging || logger.isVerbose;
if (!upgradePbxProjWithFlutterAssets(app.project, logger)) {
return XcodeBuildResult(success: false);
}
final FlutterProject project = app.project.parent;
const FlutterDarwinPlatform darwinPlatform = FlutterDarwinPlatform.ios;
final migrators = <ProjectMigrator>[
RemoveFrameworkLinkAndEmbeddingMigration(app.project, logger, analytics),
XcodeBuildSystemMigration(app.project, logger),
ProjectBaseConfigurationMigration(app.project, logger),
ProjectBuildLocationMigration(app.project, logger),
IOSDeploymentTargetMigration(app.project, logger),
XcodeProjectObjectVersionMigration(app.project, logger),
HostAppInfoPlistMigration(app.project, logger),
XcodeScriptBuildPhaseMigration(app.project, logger),
RemoveBitcodeMigration(app.project, logger),
XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, logger),
UIApplicationMainDeprecationMigration(app.project, logger),
SwiftPackageManagerIntegrationMigration(
app.project,
darwinPlatform,
buildInfo,
analytics: analytics,
crashReportSenderFactory: botDetector.isRunningOnBot
? null
: () => CrashReportSender(
platform: platform,
logger: logger,
operatingSystemUtils: os,
analytics: analytics,
),
plistParser: plistParser,
toolContext: toolContext,
xcodeProjectInterpreter: xcodeProjectInterpreter,
),
SwiftPackageManagerGitignoreMigration(project, logger),
MetalAPIValidationMigrator.ios(app.project, logger),
LLDBInitMigration(
app.project,
buildInfo,
logger,
deviceID: deviceID,
fileSystem: fs,
environmentType: environmentType,
),
UISceneMigration(
app.project,
logger,
isMigrationFeatureEnabled: featureFlags.isUISceneMigrationEnabled,
plistParser: plistParser,
),
];
final migration = ProjectMigration(migrators);
await migration.run();
if (!_checkXcodeVersion(
logger: logger,
platform: platform,
xcode: xcode,
xcodeProjectInterpreter: xcodeProjectInterpreter,
)) {
return XcodeBuildResult(success: false);
}
await DarwinDependencyManagement.validatePluginSupport(
platform: darwinPlatform,
xcodeProject: project.ios,
plugins: await project.ios.getPlugins(),
fileSystem: fs,
logger: logger,
cocoapods: cocoaPods,
analytics: analytics,
featureFlags: featureFlags,
);
await removeExtendedAttributesForProject(
xcodeProject: app.project,
toolContext: toolContext,
xcodeProjectInterpreter: xcodeProjectInterpreter,
);
final XcodeProjectInfo? projectInfo = await app.project.projectInfo();
if (projectInfo == null) {
logger.printError('Xcode project not found.');
return XcodeBuildResult(success: false);
}
final String? scheme = projectInfo.schemeFor(buildInfo);
if (scheme == null) {
projectInfo.reportFlavorNotFoundAndExit();
}
final String? configuration = projectInfo.buildConfigurationFor(buildInfo, scheme);
if (configuration == null) {
logger.printError('');
logger.printError(
'The Xcode project defines build configurations: ${projectInfo.buildConfigurations.join(', ')}',
);
logger.printError(
'Flutter expects a build configuration named ${XcodeProjectInfo.expectedBuildConfigurationFor(buildInfo, scheme)} or similar.',
);
logger.printError('Open Xcode to fix the problem:');
logger.printError(' open ios/Runner.xcworkspace');
logger.printError('1. Click on "Runner" in the project navigator.');
logger.printError('2. Ensure the Runner PROJECT is selected, not the Runner TARGET.');
if (buildInfo.isDebug) {
logger.printError('3. Click the Editor->Add Configuration->Duplicate "Debug" Configuration.');
} else {
logger.printError(
'3. Click the Editor->Add Configuration->Duplicate "Release" Configuration.',
);
}
logger.printError('');
logger.printError(
' If this option is disabled, it is likely you have the target selected instead',
);
logger.printError(' of the project; see:');
logger.printError(
' https://stackoverflow.com/questions/19842746/adding-a-build-configuration-in-xcode',
);
logger.printError('');
logger.printError(' If you have created a completely custom set of build configurations,');
logger.printError(' you can set the FLUTTER_BUILD_MODE=${buildInfo.modeName.toLowerCase()}');
logger.printError(' in the .xcconfig file for that configuration and run from Xcode.');
logger.printError('');
logger.printError(
'4. If you are not using completely custom build configurations, name the newly created configuration ${buildInfo.modeName}.',
);
return XcodeBuildResult(success: false);
} else if (buildInfo.flavor != null &&
!configuration.toLowerCase().contains(buildInfo.flavor!.toLowerCase())) {
final String expectedConfiguration = XcodeProjectInfo.expectedBuildConfigurationFor(
buildInfo,
scheme,
);
logger.printWarning(
'Unable to find "$expectedConfiguration" build configuration for flavor "${buildInfo.flavor}".\n'
'Using "$configuration" configuration instead.\n'
' To optionally support custom build settings for this flavor, consider adding the "$expectedConfiguration" build configuration to your Xcode project.\n'
' Visit https://docs.flutter.dev/deployment/flavors-ios for instructions.',
);
}
final FlutterManifest manifest = app.project.parent.manifest;
final String? buildName = parsedBuildName(
manifest: manifest,
logger: logger,
buildInfo: buildInfo,
);
final bool buildNameIsMissing = buildName == null || buildName.isEmpty;
if (buildNameIsMissing) {
logger.printStatus('Warning: Missing build name (CFBundleShortVersionString).');
}
final String? buildNumber = parsedBuildNumber(
manifest: manifest,
logger: logger,
buildInfo: buildInfo,
);
final bool buildNumberIsMissing = buildNumber == null || buildNumber.isEmpty;
if (buildNumberIsMissing) {
logger.printStatus('Warning: Missing build number (CFBundleVersion).');
}
if (buildNameIsMissing || buildNumberIsMissing) {
logger.printError(
'Action Required: You must set a build name and number in the pubspec.yaml '
'file version field before submitting to the App Store.',
);
}
final String buildDirectoryPath = getIosBuildDirectory(config: config, fileSystem: fs);
final Map<String, String> buildSettings =
await app.project.buildSettingsForBuildInfo(
buildInfo,
environmentType: environmentType,
deviceId: deviceID,
) ??
<String, String>{};
if (buildSettings.isEmpty) {
// xcodebuild should have printed possible error messages already, as when
// it fails, it returns an empty build settings Map.
logger.printError(
'No Xcode build settings have been found. Please check possible errors above.',
);
return XcodeBuildResult(success: false);
}
final String? targetBuildDirPath = buildSettings['TARGET_BUILD_DIR'];
final Directory? targetBuildDir = targetBuildDirPath != null
? fs.directory(targetBuildDirPath)
: null;
final bool incrementalBuild = targetBuildDir != null && targetBuildDir.existsSync();
final List<String> xcodebuildCommandArgs = await xcode.fetchDependenciesAndGenerateXcodebuildArgs(
app.project,
fs.directory(buildDirectoryPath),
skipPackageValidation: false,
);
final buildCommands = <String>[...xcodebuildCommandArgs, '-configuration', configuration];
// Check the public headers before checking Xcode version so headers fingerprinter is created
// regardless of Xcode version.
final bool headersChanged = publicHeadersChanged(
environmentType: environmentType,
mode: buildInfo.mode,
buildDirectory: buildDirectoryPath,
artifacts: artifacts,
fileSystem: fs,
logger: logger,
);
final Version? xcodeVersion = xcode.currentVersion;
if (headersChanged &&
incrementalBuild &&
(xcodeVersion != null && xcodeVersion >= Version(26, 0, 0))) {
// Xcode 26 changed the way headers are pre-compiled and will throw an error if the headers
// have changed since the last time they were compiled. To avoid this error, clean before
// building if headers have changed.
targetBuildDir.deleteSync(recursive: true);
buildCommands.addAll(<String>['clean', 'build']);
}
Map<String, String>? autoSigningConfigs;
if (codesign && environmentType == EnvironmentType.physical) {
autoSigningConfigs = await getCodeSigningIdentityDevelopmentTeamBuildSetting(
buildSettings: buildSettings,
plistParser: plistParser,
toolContext: toolContext,
);
}
await updateGeneratedXcodeProperties(
project: project,
targetOverride: targetOverride,
buildInfo: buildInfo,
toolContext: toolContext,
printWarnings: true,
);
if (app.project.usesSwiftPackageManager) {
final String? iosDeploymentTarget = buildSettings['IPHONEOS_DEPLOYMENT_TARGET'];
if (iosDeploymentTarget != null) {
SwiftPackageManager.updateMinimumDeployment(
platform: darwinPlatform,
project: project.ios,
deploymentTarget: iosDeploymentTarget,
);
}
}
await processPodsIfNeeded(
project.ios,
buildDirectoryPath,
buildInfo.mode,
cocoaPods: cocoaPods,
featureFlags: featureFlags,
templateRenderer: templateRenderer,
toolContext: toolContext,
);
if (configOnly) {
return XcodeBuildResult(success: true);
}
if (isVerbose) {
// An environment variable to be passed to xcode_backend.sh determining
// whether to echo back executed commands.
buildCommands.add('VERBOSE_SCRIPT_LOGGING=YES');
} else {
// This will print warnings and errors only.
buildCommands.add('-quiet');
}
if (autoSigningConfigs != null) {
for (final MapEntry(:String key, :String value) in autoSigningConfigs.entries) {
buildCommands.add('$key=$value');
}
}
if (codesign) {
buildCommands.add('-allowProvisioningUpdates');
buildCommands.add('-allowProvisioningDeviceRegistration');
}
final Directory? workspacePath = app.project.xcodeWorkspace;
if (workspacePath != null) {
buildCommands.addAll(<String>['-workspace', workspacePath.basename]);
} else {
buildCommands.addAll(<String>['-project', app.project.xcodeProject.basename]);
}
buildCommands.addAll(<String>[
'-scheme',
scheme,
if (buildAction !=
XcodeBuildAction.archive) // dSYM files aren't copied to the archive if BUILD_DIR is set.
'BUILD_DIR=${fs.path.absolute(buildDirectoryPath)}',
]);
// Check if the project contains a watchOS companion app.
final bool hasWatchCompanion = await app.project.containsWatchCompanion(
projectInfo: projectInfo,
buildInfo: buildInfo,
deviceId: deviceID,
);
if (hasWatchCompanion) {
// The -sdk argument has to be omitted if a watchOS companion app exists.
// Otherwise the build will fail as WatchKit dependencies cannot be build using the iOS SDK.
logger.printStatus('Watch companion app found.');
if (environmentType == EnvironmentType.simulator && (deviceID == null || deviceID == '')) {
logger.printError('No simulator device ID has been set.');
logger.printError('A device ID is required to build an app with a watchOS companion app.');
logger.printError('Please run "flutter devices" to get a list of available device IDs');
logger.printError('and specify one using the -d, --device-id flag.');
return XcodeBuildResult(success: false);
}
} else {
if (environmentType == EnvironmentType.physical) {
buildCommands.addAll(<String>['-sdk', XcodeSdk.IPhoneOS.platformName]);
} else {
buildCommands.addAll(<String>['-sdk', XcodeSdk.IPhoneSimulator.platformName]);
}
}
buildCommands.add('-destination');
if (deviceID != null) {
buildCommands.add('id=$deviceID');
} else if (environmentType == EnvironmentType.physical) {
buildCommands.add(XcodeSdk.IPhoneOS.genericPlatform);
} else {
buildCommands.add(XcodeSdk.IPhoneSimulator.genericPlatform);
}
if (activeArch != null) {
// Setting ARCHS to $activeArchName will break the build if a watchOS companion app exists,
// as it cannot be build for the architecture of the Flutter app.
if (!hasWatchCompanion) {
// ONLY_ACTIVE_ARCH specifies whether the product includes only code for
// the native architecture.
final onlyActiveArch = activeArch == os.hostPlatform.cpuArch;
buildCommands.add('ONLY_ACTIVE_ARCH=${onlyActiveArch ? 'YES' : 'NO'}');
buildCommands.add('ARCHS=${activeArch.darwinArchName}');
}
}
if (!codesign) {
buildCommands.addAll(<String>[
'CODE_SIGNING_ALLOWED=NO',
'CODE_SIGNING_REQUIRED=NO',
'CODE_SIGNING_IDENTITY=""',
]);
}
Status? buildSubStatus;
Status? initialBuildStatus;
File? scriptOutputPipeFile;
RunResult? buildResult;
XCResult? xcResult;
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_ios_build_temp_dir');
try {
if (logger.hasTerminal) {
scriptOutputPipeFile = tempDir.childFile('pipe_to_stdout');
os.makePipe(scriptOutputPipeFile.path);
Future<void> listenToScriptOutputLine() async {
final List<String> lines = await scriptOutputPipeFile!.readAsLines();
var inWarningBlock = false;
var inNoteBlock = false;
for (final line in lines) {
if (line == 'done' || line == 'all done') {
buildSubStatus?.stop();
buildSubStatus = null;
if (line == 'all done') {
return;
}
} else {
if (!isVerbose) {
if (line.contains('error:')) {
logger.printError(line);
} else if (line.contains('warning:')) {
logger.printWarning(line);
inWarningBlock = true;
} else if (inNoteBlock) {
logger.printWarning(line);
inNoteBlock = false;
} else if (inWarningBlock) {
if (line.startsWith(RegExp(r'\s+?note[:]'))) {
// Xcode doesn't echo this, so we don't.
inNoteBlock = true;
}
inWarningBlock = false;
}
continue;
}
initialBuildStatus?.cancel();
initialBuildStatus = null;
buildSubStatus = logger.startProgress(
line,
progressIndicatorPadding: kDefaultStatusPadding - 7,
);
}
}
await listenToScriptOutputLine();
}
// Trigger the start of the pipe -> stdout loop. Ignore exceptions.
unawaited(listenToScriptOutputLine());
buildCommands.add('SCRIPT_OUTPUT_STREAM_FILE=${scriptOutputPipeFile.absolute.path}');
}
final Directory resultBundleDirectory = tempDir.childDirectory(_kResultBundlePath);
buildCommands.addAll(<String>[
'-resultBundlePath',
resultBundleDirectory.absolute.path,
'-resultBundleVersion',
_kResultBundleVersion,
]);
// Adds a setting which xcode_backend.dart will use to skip adding Bonjour
// service settings to the Info.plist.
if (disablePortPublication) {
buildCommands.add('DISABLE_PORT_PUBLICATION=YES');
}
// Don't log analytics for downstream Flutter commands.
// e.g. `flutter build bundle`.
buildCommands.add('FLUTTER_SUPPRESS_ANALYTICS=true');
buildCommands.add('COMPILER_INDEX_STORE_ENABLE=NO');
buildCommands.addAll(environmentVariablesAsXcodeBuildSettings(platform));
if (buildAction == XcodeBuildAction.archive) {
buildCommands.addAll(<String>[
'-archivePath',
fs.path.absolute(app.archiveBundlePath),
'archive',
]);
}
final sw = Stopwatch()..start();
initialBuildStatus = logger.startProgress('Running Xcode build...');
buildResult = await _runBuildWithRetries(
buildCommands,
app,
resultBundleDirectory,
logger: logger,
processUtils: processUtils,
);
// Notifies listener that no more output is coming.
scriptOutputPipeFile?.writeAsStringSync('all done');
buildSubStatus?.stop();
buildSubStatus = null;
initialBuildStatus?.cancel();
initialBuildStatus = null;
logger.printStatus(
'Xcode ${xcodeBuildActionToString(buildAction)} done.'.padRight(kDefaultStatusPadding + 1) +
getElapsedAsSeconds(sw.elapsed).padLeft(5),
);
final Duration elapsedDuration = sw.elapsed;
analytics.send(
Event.timing(
workflow: xcodeBuildActionToString(buildAction),
variableName: 'xcode-ios',
elapsedMilliseconds: elapsedDuration.inMilliseconds,
),
);
if (tempDir.existsSync()) {
// Display additional warning and error message from xcresult bundle.
final Directory resultBundle = tempDir.childDirectory(_kResultBundlePath);
if (!resultBundle.existsSync()) {
logger.printTrace(
'The xcresult bundle are not generated. Displaying xcresult is disabled.',
);
} else {
// Discard unwanted errors. See: https://github.com/flutter/flutter/issues/95354
final warningDiscarder = XCResultIssueDiscarder(typeMatcher: XCResultIssueType.warning);
final dartBuildErrorDiscarder = XCResultIssueDiscarder(
messageMatcher: RegExp(r'Command PhaseScriptExecution failed with a nonzero exit code'),
);
final xcResultGenerator = XCResultGenerator(
resultPath: resultBundle.absolute.path,
xcode: xcode,
processUtils: processUtils,
);
xcResult = await xcResultGenerator.generate(
issueDiscarders: <XCResultIssueDiscarder>[warningDiscarder, dartBuildErrorDiscarder],
);
}
}
} finally {
tempDir.deleteSync(recursive: true);
}
if (buildResult != null && buildResult.exitCode != 0) {
logger.printStatus('Failed to build iOS app');
return XcodeBuildResult(
success: false,
stdout: buildResult.stdout,
stderr: buildResult.stderr,
xcodeBuildExecution: XcodeBuildExecution(
buildCommands: buildCommands,
appDirectory: app.project.hostAppRoot.path,
environmentType: environmentType,
buildSettings: buildSettings,
),
xcResult: xcResult,
);
} else {
String? outputDir;
if (buildAction == XcodeBuildAction.build) {
// If the app contains a watch companion target, the sdk argument of xcodebuild has to be omitted.
// For some reason this leads to TARGET_BUILD_DIR always ending in 'iphoneos' even though the
// actual directory will end with 'iphonesimulator' for simulator builds.
// The value of TARGET_BUILD_DIR is adjusted to accommodate for this effect.
String? targetBuildDir = buildSettings['TARGET_BUILD_DIR'];
if (targetBuildDir == null) {
logger.printError('Xcode build is missing expected TARGET_BUILD_DIR build setting.');
return XcodeBuildResult(success: false);
}
if (hasWatchCompanion && environmentType == EnvironmentType.simulator) {
logger.printTrace('Replacing iphoneos with iphonesimulator in TARGET_BUILD_DIR.');
targetBuildDir = targetBuildDir.replaceFirst(
XcodeSdk.IPhoneOS.platformName,
XcodeSdk.IPhoneSimulator.platformName,
);
}
await ensureTargetBuildDirAttribute(
targetBuildDir,
logger: logger,
processUtils: processUtils,
);
final String? appBundle = buildSettings['WRAPPER_NAME'];
final String expectedOutputDirectory = fs.path.join(targetBuildDir, appBundle);
if (fs.directory(expectedOutputDirectory).existsSync()) {
// Copy app folder to a place where other tools can find it without knowing
// the BuildInfo.
outputDir = targetBuildDir.replaceFirst('/$configuration-', '/');
fs.directory(outputDir).createSync(recursive: true);
// rsync instead of copy to maintain timestamps to support incremental
// app install deltas. Use --delete to remove incompatible artifacts
// (for example, kernel binary files produced from previous run).
await processUtils.run(<String>[
'rsync',
'-8', // Avoid mangling filenames with encodings that do not match the current locale.
'-av',
'--delete',
expectedOutputDirectory,
outputDir,
], throwOnError: true);
outputDir = fs.path.join(outputDir, appBundle);
} else {
logger.printError(
'Build succeeded but the expected app at $expectedOutputDirectory not found',
);
}
} else {
outputDir = fs.path.absolute(app.archiveBundleOutputPath);
if (!fs.isDirectorySync(outputDir)) {
logger.printError('Archive succeeded but the expected xcarchive at $outputDir not found');
}
}
return XcodeBuildResult(
success: true,
output: outputDir,
xcodeBuildExecution: XcodeBuildExecution(
buildCommands: buildCommands,
appDirectory: app.project.hostAppRoot.path,
environmentType: environmentType,
buildSettings: buildSettings,
),
xcResult: xcResult,
);
}
}
/// Ensure the TARGET_BUILD_DIR has the `com.apple.xcode.CreatedByBuildSystem` extended attribute.
/// When using SwiftPM, this attribute is missing. This is required for `xcodebuild clean`.
Future<void> ensureTargetBuildDirAttribute(
String targetBuildDirPath, {
required Logger logger,
required ProcessUtils processUtils,
}) async {
final RunResult result = await processUtils.run(<String>[
'xattr',
'-w',
'com.apple.xcode.CreatedByBuildSystem',
'true',
targetBuildDirPath,
]);
if (result.exitCode != 0) {
logger.printTrace(
'Failed to add xattr com.apple.xcode.CreatedByBuildSystem to $targetBuildDirPath.\n'
'Exit code: ${result.exitCode}\n'
'Stdout: ${result.stdout}\n'
'Stderr: ${result.stderr}',
);
}
}
/// Check if the Flutter framework's public headers have changed since last built.
bool publicHeadersChanged({
required BuildMode mode,
required EnvironmentType environmentType,
required String buildDirectory,
required Artifacts? artifacts,
required FileSystem fileSystem,
required Logger logger,
}) {
final String? basePath = artifacts?.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: mode,
environmentType: environmentType,
);
if (basePath == null) {
return false;
}
final Directory headersDirectory = fileSystem.directory(
fileSystem.path.join(basePath, 'Headers'),
);
if (!headersDirectory.existsSync()) {
return false;
}
final List<String> files = headersDirectory
.listSync()
.map<String>((FileSystemEntity header) => header.path)
.toList();
final String fingerprintPath = fileSystem.path.join(
buildDirectory,
'framework_public_headers.fingerprint',
);
final fingerprinter = Fingerprinter(
fingerprintPath: fingerprintPath,
paths: files,
fileSystem: fileSystem,
logger: logger,
);
final bool headersChanged = !fingerprinter.doesFingerprintMatch();
if (headersChanged) {
fingerprinter.writeFingerprint();
}
return headersChanged;
}
/// Remove extended attributes from all files in the Flutter project, except the Swift package
/// cache in the build directory.
///
/// The Swift package cache is skipped because it makes the command very slow and are not expected to
/// need to have the attributes removed. See https://github.com/flutter/flutter/issues/183662.
///
/// Attributes must be removed from the entire project rather than just the iOS directory due to
/// user reporting images in the root of their project also need to have the attributes removed.
/// See https://github.com/flutter/flutter/pull/81435.
Future<void> removeExtendedAttributesForProject({
required XcodeBasedProject xcodeProject,
required ToolContext toolContext,
required XcodeProjectInterpreter xcodeProjectInterpreter,
}) async {
final ToolContext(
:Config config,
fs: FileSystem fileSystem,
:Logger logger,
:ProcessUtils processUtils,
) = toolContext;
final Directory projectDirectory = xcodeProject.parent.directory;
final futures = <Future<void>>[];
// Remove for all files from the project (except the build directory).
final Directory buildDir = fileSystem.directory(getBuildDirectory(config, fileSystem));
if (projectDirectory.existsSync()) {
for (final FileSystemEntity entity in projectDirectory.listSync()) {
if (fileSystem.path.equals(entity.absolute.path, buildDir.absolute.path)) {
continue;
}
futures.add(removeExtendedAttributes(entity, processUtils, logger));
}
}
// Remove for all files from the iOS build directory (except the Swift package cache).
// We don't remove from other directories in the build directory since they should be unrelated
// to the iOS build.
final Directory iosBuildDir = fileSystem.directory(
getIosBuildDirectory(config: config, fileSystem: fileSystem),
);
final String swiftPackageCachePath = xcodeProjectInterpreter.swiftPackageCachePath(iosBuildDir);
if (iosBuildDir.existsSync()) {
for (final FileSystemEntity entity in iosBuildDir.listSync()) {
if (fileSystem.path.equals(entity.absolute.path, swiftPackageCachePath)) {
continue;
}
futures.add(removeExtendedAttributes(entity, processUtils, logger));
}
}
await Future.wait(futures);
}
/// Extended attributes can cause code signing errors. Remove them.
///
/// Attributes like `com.apple.FinderInfo` and `com.apple.provenance` are added
/// by Finder, cloud storage services (OneDrive, iCloud, Dropbox), or when files
/// are downloaded. These must be removed before code signing.
///
/// See: https://developer.apple.com/library/archive/qa/qa1940/_index.html
/// See: https://github.com/flutter/flutter/issues/180351
Future<void> removeExtendedAttributes(
FileSystemEntity projectDirectory,
ProcessUtils processUtils,
Logger logger,
) async {
// Remove specific extended attributes that cause code signing failures.
// We remove com.apple.FinderInfo and com.apple.provenance, but preserve
// com.apple.xcode.CreatedByBuildSystem which Xcode uses to manage build directories.
const attributesToRemove = <String>{'com.apple.FinderInfo', 'com.apple.provenance'};
for (final attribute in attributesToRemove) {
final bool success = await processUtils.exitsHappy(<String>[
'xattr',
'-r',
'-d',
attribute,
projectDirectory.path,
]);
// Ignore all errors, for example if directory is missing or attribute doesn't exist.
if (!success) {
logger.printTrace('Failed to remove $attribute from ${projectDirectory.path}');
}
}
}
Future<RunResult?> _runBuildWithRetries(
List<String> buildCommands,
BuildableIOSApp app,
Directory resultBundleDirectory, {
required Logger logger,
required ProcessUtils processUtils,
}) async {
var buildRetryDelaySeconds = 1;
var remainingTries = 8;
RunResult? buildResult;
while (remainingTries > 0) {
if (resultBundleDirectory.existsSync()) {
resultBundleDirectory.deleteSync(recursive: true);
}
remainingTries--;
buildRetryDelaySeconds *= 2;
buildResult = await processUtils.run(
buildCommands,
workingDirectory: app.project.hostAppRoot.path,
allowReentrantFlutter: true,
);
// If the result is anything other than a concurrent build failure, exit
// the loop after the first build.
if (!_isXcodeConcurrentBuildFailure(buildResult)) {
break;
}
if (remainingTries > 0) {
logger.printStatus(
'Xcode build failed due to concurrent builds, '
'will retry in $buildRetryDelaySeconds seconds.',
);
await Future<void>.delayed(Duration(seconds: buildRetryDelaySeconds));
} else {
logger.printStatus(
'Xcode build failed too many times due to concurrent builds, '
'giving up.',
);
break;
}
}
return buildResult;
}
bool _isXcodeConcurrentBuildFailure(RunResult result) {
return result.exitCode != 0 &&
result.stdout.contains(kConcurrentRunFailureMessage1) &&
result.stdout.contains(kConcurrentRunFailureMessage2);
}
Future<void> diagnoseXcodeBuildFailure(
XcodeBuildResult result, {
required Analytics analytics,
required Logger logger,
required FileSystem fileSystem,
required FlutterDarwinPlatform platform,
required ProcessUtils processUtils,
required FlutterProject project,
required Xcode? xcode,
Device? device,
}) async {
final XcodeBuildExecution? xcodeBuildExecution = result.xcodeBuildExecution;
if (xcodeBuildExecution != null &&
xcodeBuildExecution.environmentType == EnvironmentType.physical &&
(result.stdout?.toUpperCase().contains('BITCODE') ?? false)) {
const label = 'xcode-bitcode-failure';
const buildType = 'ios';
final command = xcodeBuildExecution.buildCommands.toString();
final settings = xcodeBuildExecution.buildSettings.toString();
analytics.send(
Event.flutterBuildInfo(
label: label,
buildType: buildType,
command: command,
settings: settings,
),
);
}
// Handle errors.
final bool issueDetected = await _handleIssues(
result,
xcodeBuildExecution,
project: project,
platform: platform,
processUtils: processUtils,
logger: logger,
fileSystem: fileSystem,
analytics: analytics,
xcode: xcode,
device: device,
);
if (!issueDetected && xcodeBuildExecution != null) {
// Fallback to use stdout to detect and print issues.
_parseIssueInStdout(xcodeBuildExecution, logger, result);
}
}
/// `xcodebuild <buildaction>` parameter (see `man xcodebuild` for details).
///
/// `clean`, `test`, `analyze`, and `install` are not supported.
enum XcodeBuildAction { build, archive }
String xcodeBuildActionToString(XcodeBuildAction action) {
return switch (action) {
XcodeBuildAction.build => 'build',
XcodeBuildAction.archive => 'archive',
};