Repository navigation
Expand file tree
/
Copy pathsimulators.dart
More file actions
1209 lines (1060 loc) · 37.7 KB
/
Copy pathsimulators.dart
File metadata and controls
1209 lines (1060 loc) · 37.7 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 'dart:math' as math;
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../application_package.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/template.dart';
import '../base/utils.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../context/tool_context.dart';
import '../convert.dart';
import '../darwin/darwin.dart';
import '../devfs.dart';
import '../device.dart';
import '../device_port_forwarder.dart';
import '../device_vm_service_discovery_for_attach.dart';
import '../macos/cocoapods.dart';
import '../macos/xcode.dart';
import '../mdns_discovery.dart';
import '../project.dart';
import '../protocol_discovery.dart';
import '../vmservice.dart';
import 'application_package.dart';
import 'devices.dart';
import 'ios_workflow.dart';
import 'mac.dart';
import 'plist_parser.dart';
import 'xcodeproj.dart';
const iosSimulatorId = 'apple_ios_simulator';
class IOSSimulators extends PollingDeviceDiscovery {
IOSSimulators({
required this._iosSimulatorUtils,
required this._iosWorkflow,
required this._platform,
}) : super('iOS simulators');
final IOSSimulatorUtils _iosSimulatorUtils;
final IOSWorkflow _iosWorkflow;
final Platform _platform;
@override
bool get supportsPlatform => _platform.isMacOS;
@override
bool get canListAnything => _iosWorkflow.canListDevices;
@override
Future<List<Device>> pollingGetDevices({
Duration? timeout,
bool forWirelessDiscovery = false,
}) async => _iosSimulatorUtils.getAttachedDevices();
@override
List<String> get wellKnownIds => const <String>[];
}
class IOSSimulatorUtils {
IOSSimulatorUtils({
required this._analytics,
required this._cocoaPods,
required this._plistParser,
required this._templateRenderer,
required this._toolContext,
required this._xcode,
required this._xcodeProjectInterpreter,
MDnsVmServiceDiscovery? mdnsVmServiceDiscovery,
}) {
final ToolContext(:Logger logger, :Platform platform, :ProcessManager processManager) =
_toolContext;
_mdnsVmServiceDiscovery =
mdnsVmServiceDiscovery ??
MDnsVmServiceDiscovery(analytics: _analytics, logger: logger, platform: platform);
_simControl = SimControl(logger: logger, processManager: processManager, xcode: _xcode);
}
late final MDnsVmServiceDiscovery _mdnsVmServiceDiscovery;
late final SimControl _simControl;
final Xcode _xcode;
final XcodeProjectInterpreter _xcodeProjectInterpreter;
final Analytics _analytics;
final CocoaPods _cocoaPods;
final PlistParser _plistParser;
final TemplateRenderer _templateRenderer;
final ToolContext _toolContext;
Future<List<IOSSimulator>> getAttachedDevices() async {
if (!_xcode.isInstalledAndMeetsVersionCheck || !_xcode.isSimctlInstalled) {
return <IOSSimulator>[];
}
final ToolContext(:Logger logger, :OperatingSystemUtils os) = _toolContext;
final CpuArch cpuArch = os.hostPlatform.cpuArch;
final List<BootedSimDevice> connected = await _simControl.getConnectedDevices();
return connected
.map<IOSSimulator?>((BootedSimDevice device) {
final BootedSimDevice(:String? udid, :String? name) = device;
if (udid == null) {
logger.printTrace('Could not parse simulator udid');
return null;
}
if (name == null) {
logger.printTrace('Could not parse simulator name');
return null;
}
return IOSSimulator(
udid,
analytics: _analytics,
cocoaPods: _cocoaPods,
cpuArch: cpuArch,
mdnsVmServiceDiscovery: _mdnsVmServiceDiscovery,
name: name,
plistParser: _plistParser,
simControl: _simControl,
simulatorCategory: device.category,
templateRenderer: _templateRenderer,
toolContext: _toolContext,
xcode: _xcode,
xcodeProjectInterpreter: _xcodeProjectInterpreter,
);
})
.whereType<IOSSimulator>()
.toList();
}
Future<List<IOSSimulatorRuntime>> getAvailableIOSRuntimes() async {
if (!_xcode.isInstalledAndMeetsVersionCheck || !_xcode.isSimctlInstalled) {
return <IOSSimulatorRuntime>[];
}
return _simControl.listAvailableIOSRuntimes();
}
}
/// A wrapper around the `simctl` command line tool.
class SimControl {
SimControl({required Logger logger, required ProcessManager processManager, required this._xcode})
: _logger = logger,
_processUtils = ProcessUtils(processManager: processManager, logger: logger);
final Logger _logger;
final ProcessUtils _processUtils;
final Xcode _xcode;
/// Runs `simctl list --json` and returns the JSON of
/// the corresponding section.
Future<Map<String, Object?>> _listBootedDevices() async {
// Sample output from `simctl list available booted --json`:
//
// {
// "devices" : {
// "com.apple.CoreSimulator.SimRuntime.iOS-14-0" : [
// {
// "lastBootedAt" : "2022-07-26T01:46:23Z",
// "dataPath" : "\/Users\/magder\/Library\/Developer\/CoreSimulator\/Devices\/9EC90A99-6924-472D-8CDD-4D8234AB4779\/data",
// "dataPathSize" : 1620578304,
// "logPath" : "\/Users\/magder\/Library\/Logs\/CoreSimulator\/9EC90A99-6924-472D-8CDD-4D8234AB4779",
// "udid" : "9EC90A99-6924-472D-8CDD-4D8234AB4779",
// "isAvailable" : true,
// "logPathSize" : 9740288,
// "deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-11",
// "state" : "Booted",
// "name" : "iPhone 11"
// }
// ],
// "com.apple.CoreSimulator.SimRuntime.iOS-13-0" : [
//
// ],
// "com.apple.CoreSimulator.SimRuntime.iOS-12-4" : [
//
// ],
// "com.apple.CoreSimulator.SimRuntime.iOS-16-0" : [
//
// ]
// }
// }
final command = <String>[
..._xcode.xcrunCommand(),
'simctl',
'list',
'devices',
'booted',
'iOS',
'--json',
];
_logger.printTrace(command.join(' '));
final RunResult results;
try {
results = await _processUtils.run(command);
} on Exception catch (exception) {
_logger.printError('Error executing simctl:\n$exception');
return <String, Map<String, Object?>>{};
}
if (results.exitCode != 0) {
_logger.printError('Error executing simctl: ${results.exitCode}\n${results.stderr}');
return <String, Map<String, Object?>>{};
}
try {
final Object? decodeResult = (json.decode(results.stdout) as Map<String, Object?>)['devices'];
if (decodeResult is Map<String, Object?>) {
return decodeResult;
}
_logger.printError('simctl returned unexpected JSON response: ${results.stdout}');
return <String, Object>{};
} on FormatException {
// We failed to parse the simctl output, or it returned junk.
// One known message is "Install Started" isn't valid JSON but is
// returned sometimes.
_logger.printError('simctl returned non-JSON response: ${results.stdout}');
return <String, Object>{};
}
}
/// Returns all the connected simulator devices.
Future<List<BootedSimDevice>> getConnectedDevices() async {
if (!_xcode.isSimctlInstalled) {
_logger.printTrace('Skipping iOS simulator discovery because simctl is not available.');
return <BootedSimDevice>[];
}
final Map<String, Object?> devicesSection = await _listBootedDevices();
return <BootedSimDevice>[
for (final String deviceCategory in devicesSection.keys)
if (devicesSection[deviceCategory] case final List<Object?> devicesData)
for (final Object? data in devicesData.map<Map<String, Object?>?>(castStringKeyedMap))
if (data is Map<String, Object?>) BootedSimDevice(deviceCategory, data),
];
}
Future<bool> isInstalled(String deviceId, String appId) {
return _processUtils.exitsHappy(<String>[
..._xcode.xcrunCommand(),
'simctl',
'get_app_container',
deviceId,
appId,
]);
}
Future<RunResult> install(String deviceId, String appPath) async {
RunResult result;
try {
result = await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'install',
deviceId,
appPath,
], throwOnError: true);
} on ProcessException catch (exception) {
throwToolExit(
'Unable to install $appPath on $deviceId. This is sometimes caused by a malformed plist file:\n$exception',
);
}
return result;
}
Future<RunResult> uninstall(String deviceId, String appId) async {
RunResult result;
try {
result = await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'uninstall',
deviceId,
appId,
], throwOnError: true);
} on ProcessException catch (exception) {
throwToolExit('Unable to uninstall $appId from $deviceId:\n$exception');
}
return result;
}
Future<RunResult> launch(
String deviceId,
String appIdentifier, [
List<String>? launchArgs,
]) async {
RunResult result;
try {
result = await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'launch',
deviceId,
appIdentifier,
...?launchArgs,
], throwOnError: true);
} on ProcessException catch (exception) {
throwToolExit('Unable to launch $appIdentifier on $deviceId:\n$exception');
}
return result;
}
Future<RunResult> stopApp(String deviceId, String appIdentifier) async {
RunResult result;
try {
result = await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'terminate',
deviceId,
appIdentifier,
], throwOnError: true);
} on ProcessException catch (exception) {
throwToolExit('Unable to terminate $appIdentifier on $deviceId:\n$exception');
}
return result;
}
Future<void> takeScreenshot(String deviceId, String outputPath) async {
try {
await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'io',
deviceId,
'screenshot',
outputPath,
], throwOnError: true);
} on ProcessException catch (exception) {
_logger.printError('Unable to take screenshot of $deviceId:\n$exception');
}
}
/// Runs `simctl list runtimes available iOS --json` and returns all available iOS simulator runtimes.
Future<List<IOSSimulatorRuntime>> listAvailableIOSRuntimes() async {
final runtimes = <IOSSimulatorRuntime>[];
final RunResult results = await _processUtils.run(<String>[
..._xcode.xcrunCommand(),
'simctl',
'list',
'runtimes',
'available',
'iOS',
'--json',
]);
if (results.exitCode != 0) {
_logger.printError('Error executing simctl: ${results.exitCode}\n${results.stderr}');
return runtimes;
}
try {
final Object? decodeResult =
(json.decode(results.stdout) as Map<String, Object?>)['runtimes'];
if (decodeResult is List<Object?>) {
for (final Object? runtimeData in decodeResult) {
if (runtimeData is Map<String, Object?>) {
runtimes.add(IOSSimulatorRuntime.fromJson(runtimeData));
}
}
}
return runtimes;
} on FormatException {
// We failed to parse the simctl output, or it returned junk.
// One known message is "Install Started" isn't valid JSON but is
// returned sometimes.
_logger.printError('simctl returned non-JSON response: ${results.stdout}');
return runtimes;
}
}
}
class BootedSimDevice {
BootedSimDevice(this.category, this.data);
final String category;
final Map<String, Object?> data;
String? get name => data['name']?.toString();
String? get udid => data['udid']?.toString();
}
class IOSSimulator extends Device {
IOSSimulator(
super.id, {
required this._analytics,
required this._cocoaPods,
required this._cpuArch,
required this._mdnsVmServiceDiscovery,
required this.name,
required this._plistParser,
required this._simControl,
required this.simulatorCategory,
required this._templateRenderer,
required ToolContext super.toolContext,
required this._xcode,
required this._xcodeProjectInterpreter,
}) : super(
category: Category.mobile,
ephemeral: true,
logger: toolContext.logger,
platformType: PlatformType.ios,
);
@override
final String name;
final String simulatorCategory;
final MDnsVmServiceDiscovery _mdnsVmServiceDiscovery;
final SimControl _simControl;
final CpuArch _cpuArch;
final Analytics _analytics;
final CocoaPods _cocoaPods;
final PlistParser _plistParser;
final TemplateRenderer _templateRenderer;
final Xcode _xcode;
final XcodeProjectInterpreter _xcodeProjectInterpreter;
@override
DevFSWriter createDevFSWriter(ApplicationPackage? app, String? userIdentifier) {
return LocalDevFSWriter(fileSystem: toolContext.fs);
}
@override
Future<bool> get isLocalEmulator async => true;
@override
Future<String> get emulatorId async => iosSimulatorId;
@override
bool get supportsHotReload => true;
@override
bool get supportsHotRestart => true;
@override
bool get supportsFlavors => true;
@override
Future<bool> get supportsHardwareRendering async => false;
@override
bool supportsRuntimeMode(BuildMode buildMode) => buildMode == BuildMode.debug;
@override
Future<CpuArch> get cpuArch async => _cpuArch;
final _logReaders = <IOSApp?, _IOSSimulatorLogReader>{};
_IOSSimulatorDevicePortForwarder? _portForwarder;
@override
Future<bool> isAppInstalled(ApplicationPackage app, {String? userIdentifier}) {
return _simControl.isInstalled(id, app.id);
}
@override
Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
@override
Future<bool> installApp(covariant IOSApp app, {String? userIdentifier}) async {
try {
await _simControl.install(id, app.simulatorBundlePath);
return true;
} on Exception {
return false;
}
}
@override
Future<bool> uninstallApp(ApplicationPackage app, {String? userIdentifier}) async {
try {
await _simControl.uninstall(id, app.id);
return true;
} on Exception {
return false;
}
}
@override
Future<bool> isSupported() async {
if (!toolContext.platform.isMacOS) {
_supportMessage = 'iOS devices require a Mac host machine.';
return false;
}
// Check if the device is part of a blocked category.
// We do not yet support WatchOS or tvOS devices.
final blocklist = RegExp(r'Apple (TV|Watch)', caseSensitive: false);
if (blocklist.hasMatch(name)) {
_supportMessage = 'Flutter does not support Apple TV or Apple Watch.';
return false;
}
return true;
}
String? _supportMessage;
@override
Future<String> supportMessage() async {
if (await isSupported()) {
return 'Supported';
}
return _supportMessage ?? 'Unknown';
}
@override
Future<LaunchResult> startApp(
IOSApp package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object?>{},
bool prebuiltApplication = false,
String? userIdentifier,
}) async {
final ToolContext(:FileSystem fs, :Logger logger) = toolContext;
if (!prebuiltApplication && package is BuildableIOSApp) {
logger.printTrace('Building ${package.name} for $id.');
try {
await _setupUpdatedApplicationBundle(package, debuggingOptions.buildInfo, mainPath);
} on ToolExit catch (e) {
logger.printError('${e.message}');
return LaunchResult.failed();
}
} else {
if (!await installApp(package)) {
return LaunchResult.failed();
}
}
// Prepare launch arguments.
final List<String> launchArguments = debuggingOptions.getIOSLaunchArguments(
EnvironmentType.simulator,
route,
platformArgs,
);
ProtocolDiscovery? vmServiceDiscovery;
if (debuggingOptions.debuggingEnabled) {
final _IOSSimulatorLogReader logReader = getLogReader(app: package);
vmServiceDiscovery = ProtocolDiscovery.vmService(
logReader,
ipv6: debuggingOptions.ipv6,
hostPort: debuggingOptions.hostVmServicePort,
devicePort: debuggingOptions.deviceVmServicePort,
logger: logger,
);
// Launch the app only after the log stream is ready; otherwise the
// Dart VM Service URL it logs on startup can be missed.
const warningDelay = Duration(seconds: 30);
final timer = Timer(warningDelay, () {
logger.printError(
'The iOS simulator log stream did not start after ${warningDelay.inSeconds} seconds. '
'This is taking much longer than expected...',
);
});
await logReader._ready.future;
timer.cancel();
}
// Launch the updated application in the simulator.
try {
// Use the built application's Info.plist to get the bundle identifier,
// which should always yield the correct value and does not require
// parsing the xcodeproj or configuration files.
// See https://github.com/flutter/flutter/issues/31037 for more information.
final String plistPath = fs.path.join(package.simulatorBundlePath, 'Info.plist');
final String? bundleIdentifier = _plistParser.getValueFromFile<String>(
plistPath,
PlistParser.kCFBundleIdentifierKey,
);
if (bundleIdentifier == null) {
logger.printError(
'Invalid prebuilt iOS app. Info.plist does not contain bundle identifier',
);
return LaunchResult.failed();
}
await _simControl.launch(id, bundleIdentifier, launchArguments);
} on Exception catch (error) {
logger.printError('$error');
return LaunchResult.failed();
}
if (!debuggingOptions.debuggingEnabled) {
return LaunchResult.succeeded();
}
// Wait for the service protocol port here. This will complete once the
// device has printed "Dart VM Service is listening on..."
logger.printTrace('Waiting for VM Service port to be available...');
try {
final Uri? deviceUri = await vmServiceDiscovery?.uri;
if (deviceUri != null) {
return LaunchResult.succeeded(vmServiceUri: deviceUri);
}
logger.printError(
'Error waiting for a debug connection: '
'The log reader failed unexpectedly',
);
} on Exception catch (error) {
logger.printError('Error waiting for a debug connection: $error');
} finally {
await vmServiceDiscovery?.cancel();
}
return LaunchResult.failed();
}
Future<void> _setupUpdatedApplicationBundle(
BuildableIOSApp app,
BuildInfo buildInfo,
String? mainPath,
) async {
final ToolContext(:FileSystem fs, :Logger logger, :ProcessUtils processUtils) = toolContext;
// Step 1: Build the Xcode project.
// The build mode for the simulator is always debug.
assert(buildInfo.isDebug);
final XcodeBuildResult buildResult = await buildXcodeProject(
analytics: _analytics,
app: app,
buildInfo: buildInfo,
plistParser: _plistParser,
templateRenderer: _templateRenderer,
toolContext: toolContext,
xcodeProjectInterpreter: _xcodeProjectInterpreter,
targetOverride: mainPath,
environmentType: EnvironmentType.simulator,
deviceID: id,
cocoaPods: _cocoaPods,
xcode: _xcode,
);
if (!buildResult.success) {
await diagnoseXcodeBuildFailure(
buildResult,
analytics: _analytics,
fileSystem: fs,
logger: logger,
platform: FlutterDarwinPlatform.ios,
processUtils: processUtils,
project: app.project.parent,
xcode: _xcode,
device: this,
);
throwToolExit('Could not build the application for the simulator.');
}
// Step 2: Assert that the Xcode project was successfully built.
final Directory bundle = fs.directory(app.simulatorBundlePath);
final bool bundleExists = bundle.existsSync();
if (!bundleExists) {
throwToolExit('Could not find the built application bundle at ${bundle.path}.');
}
// Step 3: Install the updated bundle to the simulator.
await _simControl.install(id, fs.path.absolute(bundle.path));
}
@override
Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async {
if (app == null) {
return false;
}
return (await _simControl.stopApp(id, app.id)).exitCode == 0;
}
String get logFilePath {
final ToolContext(:FileSystem fs, :FileSystemUtils fileSystemUtils, :Platform platform) =
toolContext;
final String? logPath = platform.environment['IOS_SIMULATOR_LOG_FILE_PATH'];
return logPath != null
? logPath.replaceAll('%{id}', id)
: fs.path.join(
fileSystemUtils.homeDirPath!,
'Library',
'Logs',
'CoreSimulator',
id,
'system.log',
);
}
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
@override
Future<String> get sdkNameAndVersion async => simulatorCategory;
final _iosSdkRegExp = RegExp(r'iOS( |-)(\d+)');
Future<int> get sdkMajorVersion async {
final Match? sdkMatch = _iosSdkRegExp.firstMatch(await sdkNameAndVersion);
return int.parse(sdkMatch?.group(2) ?? '11');
}
@override
_IOSSimulatorLogReader getLogReader({covariant IOSApp? app, bool includePastLogs = false}) {
assert(!includePastLogs, 'Past log reading not supported on iOS simulators.');
return _logReaders.putIfAbsent(
app,
() => _IOSSimulatorLogReader(this, app, logger: toolContext.logger),
);
}
@override
DevicePortForwarder get portForwarder =>
_portForwarder ??= _IOSSimulatorDevicePortForwarder(this);
@override
void clearLogs() {
final File logFile = toolContext.fs.file(logFilePath);
if (logFile.existsSync()) {
final RandomAccessFile randomFile = logFile.openSync(mode: FileMode.write);
randomFile.truncateSync(0);
randomFile.closeSync();
}
}
Future<void> ensureLogsExists() async {
if (await sdkMajorVersion < 11) {
final File logFile = toolContext.fs.file(logFilePath);
if (!logFile.existsSync()) {
logFile.writeAsBytesSync(<int>[]);
}
}
}
@override
VMServiceDiscoveryForAttach getVMServiceDiscoveryForAttach({
String? appId,
String? fuchsiaModule,
int? filterDevicePort,
int? expectedHostPort,
required bool ipv6,
required Logger logger,
}) {
final mdnsVMServiceDiscoveryForAttach = MdnsVMServiceDiscoveryForAttach(
device: this,
appId: appId,
deviceVmservicePort: filterDevicePort,
hostVmservicePort: expectedHostPort,
mdnsVmServiceDiscovery: _mdnsVmServiceDiscovery,
// Do not throw on error since DelegateVMServiceDiscoveryForAttach falls
// back to log-based protocol discovery.
throwOnError: false,
useDeviceIPAsHost: false,
usesIpv6: ipv6,
);
return DelegateVMServiceDiscoveryForAttach(<VMServiceDiscoveryForAttach>[
mdnsVMServiceDiscoveryForAttach,
super.getVMServiceDiscoveryForAttach(
appId: appId,
fuchsiaModule: fuchsiaModule,
filterDevicePort: filterDevicePort,
expectedHostPort: expectedHostPort,
ipv6: ipv6,
logger: logger,
),
]);
}
@override
bool get supportsScreenshot => true;
@override
Future<void> takeScreenshot(File outputFile) {
return _simControl.takeScreenshot(id, outputFile.path);
}
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.ios.existsSync();
}
@override
Future<void> dispose() async {
await Future.wait(<Future<void>>[
for (final DeviceLogReader logReader in _logReaders.values) logReader.dispose(),
]);
await _portForwarder?.dispose();
}
Future<Process> _launchDeviceSystemLogTool() async {
return toolContext.processUtils.start(<String>['tail', '-n', '0', '-F', logFilePath]);
}
Future<Process> _launchDeviceUnifiedLogging(String? appName) async {
// Make NSPredicate concatenation easier to read.
String orP(List<String> clauses) => '(${clauses.join(" OR ")})';
String andP(List<String> clauses) => clauses.join(' AND ');
String notP(String clause) => 'NOT($clause)';
final String predicate = andP(<String>[
'eventType = logEvent',
if (appName != null) 'processImagePath ENDSWITH "$appName"',
// Either from Flutter or Swift (maybe assertion or fatal error) or from the app itself.
orP(<String>[
'senderImagePath ENDSWITH "/Flutter"',
'senderImagePath ENDSWITH "/libswiftCore.dylib"',
'processImageUUID == senderImageUUID',
'eventMessage CONTAINS "UIScene life cycle is required"',
'eventMessage CONTAINS "`UIScene` lifecycle will soon be required"',
'eventMessage CONTAINS "This process does not adopt UIScene lifecycle."',
]),
// Filter out some messages that clearly aren't related to Flutter.
notP('eventMessage CONTAINS ": could not find icon for representation -> com.apple."'),
notP('eventMessage BEGINSWITH "assertion failed: "'),
notP('eventMessage CONTAINS " libxpc.dylib "'),
]);
return toolContext.processUtils.start(<String>[
..._xcode.xcrunCommand(),
'simctl',
'spawn',
id,
'log',
'stream',
'--style',
'json',
'--predicate',
predicate,
]);
}
Future<Process?> _launchSystemLogTool() async {
// Versions of iOS prior to 11 tail the simulator syslog file.
if (await sdkMajorVersion < 11) {
return toolContext.processUtils.start(<String>[
'tail',
'-n',
'0',
'-F',
'/private/var/log/system.log',
]);
}
// For iOS 11 and later, all relevant detail is in the device log.
return null;
}
}
class IOSSimulatorRuntime {
IOSSimulatorRuntime._({
this.bundlePath,
this.buildVersion,
this.platform,
this.runtimeRoot,
this.identifier,
this.version,
this.isInternal,
this.isAvailable,
this.name,
});
// Example:
// {
// "bundlePath" : "\/Library\/Developer\/CoreSimulator\/Volumes\/iOS_21A5277g\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS 17.0.simruntime",
// "buildversion" : "21A5277g",
// "platform" : "iOS",
// "runtimeRoot" : "\/Library\/Developer\/CoreSimulator\/Volumes\/iOS_21A5277g\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS 17.0.simruntime\/Contents\/Resources\/RuntimeRoot",
// "identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-17-0",
// "version" : "17.0",
// "isInternal" : false,
// "isAvailable" : true,
// "name" : "iOS 17.0",
// "supportedDeviceTypes" : [
// {
// "bundlePath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/DeviceTypes\/iPhone 8.simdevicetype",
// "name" : "iPhone 8",
// "identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8",
// "productFamily" : "iPhone"
// }
// ]
// },
factory IOSSimulatorRuntime.fromJson(Map<String, Object?> data) {
return IOSSimulatorRuntime._(
bundlePath: data['bundlePath']?.toString(),
buildVersion: data['buildversion']?.toString(),
platform: data['platform']?.toString(),
runtimeRoot: data['runtimeRoot']?.toString(),
identifier: data['identifier']?.toString(),
version: Version.parse(data['version']?.toString()),
isInternal: data['isInternal'] is bool? ? data['isInternal'] as bool? : null,
isAvailable: data['isAvailable'] is bool? ? data['isAvailable'] as bool? : null,
name: data['name']?.toString(),
);
}
final String? bundlePath;
final String? buildVersion;
final String? platform;
final String? runtimeRoot;
final String? identifier;
final Version? version;
final bool? isInternal;
final bool? isAvailable;
final String? name;
}
/// Launches the device log reader process on the host and parses the syslog.
@visibleForTesting
Future<Process> launchDeviceSystemLogTool(IOSSimulator device) =>
device._launchDeviceSystemLogTool();
/// Launches the device log reader process on the host and parses unified logging.
@visibleForTesting
Future<Process> launchDeviceUnifiedLogging(IOSSimulator device, String? appName) =>
device._launchDeviceUnifiedLogging(appName);
@visibleForTesting
Future<Process?> launchSystemLogTool(IOSSimulator device) => device._launchSystemLogTool();
class _IOSSimulatorLogReader extends SharedIOSDeviceLogReader {
_IOSSimulatorLogReader(this.device, IOSApp? app, {required this._logger})
: _appName = app?.name?.replaceAll('.app', '') {
final uisceneCrashInterceptor = LogInterceptor(
identifier: 'uiscene_crash',
pattern: RegExp(r'UIScene life\s?cycle is required'),
action: (String message) {
throwToolExit(kUISceneMigrationRequiredError);
},
excludeFromStream: false,
);
addLogInterceptor(uisceneCrashInterceptor);
}
final IOSSimulator device;
final Logger _logger;
final String? _appName;
late final _linesController = StreamController<String>.broadcast(
onListen: _start,
onCancel: _stop,
);
/// Completes once the log stream is ready to deliver events, or has exited.
///
/// `log stream` is ready once it prints its first line (a "Filtering the log
/// data using ..." header).
///
/// Recreated on every listen, since each one starts a new `log stream`.
var _ready = Completer<void>();
@override
@visibleForTesting
StreamController<String> get linesController => _linesController;
// We log from two files: the device and the system log.
Process? _deviceProcess;
Process? _systemProcess;
@override
Stream<String> get logLines => _linesController.stream;
@override
String get name => device.name;
Future<void> _start() async {
// Use a local so that a previous process exiting late cannot complete it.
_ready = Completer<void>();
final Completer<void> ready = _ready;
// Unified logging iOS 11 and greater (introduced in iOS 10).
if (await device.sdkMajorVersion >= 11) {
_deviceProcess = await launchDeviceUnifiedLogging(device, _appName);
_deviceProcess?.stdout.transform(utf8LineDecoder).listen((String line) {
if (!ready.isCompleted) {
ready.complete();
}
_onUnifiedLoggingLine(line);
});
_deviceProcess?.stderr.transform(utf8LineDecoder).listen(_onUnifiedLoggingLine);
} else {
// Fall back to syslog parsing.
await device.ensureLogsExists();
_deviceProcess = await launchDeviceSystemLogTool(device);
_deviceProcess?.stdout.transform(utf8LineDecoder).listen(_onSysLogDeviceLine);
_deviceProcess?.stderr.transform(utf8LineDecoder).listen(_onSysLogDeviceLine);
}
// Track system.log crashes.
// ReportCrash[37965]: Saved crash report for FlutterRunner[37941]...
_systemProcess = await launchSystemLogTool(device);