File size: 60,638 Bytes
a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b b0336a8 a4ff84b | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 | // 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:vm_service/vm_service.dart' as vm_service;
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/utils.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../convert.dart';
import '../device.dart';
import '../device_port_forwarder.dart';
import '../device_vm_service_discovery_for_attach.dart';
import '../globals.dart' as globals;
import '../macos/xcdevice.dart';
import '../mdns_discovery.dart';
import '../project.dart';
import '../protocol_discovery.dart';
import '../vmservice.dart';
import 'application_package.dart';
import 'core_devices.dart';
import 'ios_deploy.dart';
import 'ios_workflow.dart';
import 'iproxy.dart';
import 'mac.dart';
import 'xcode_build_settings.dart';
import 'xcode_debug.dart';
import 'xcodeproj.dart';
const String kJITCrashFailureMessage =
'Crash occurred when compiling unknown function in unoptimized JIT mode in unknown pass';
@visibleForTesting
String jITCrashFailureInstructions(String deviceVersion) => '''
════════════════════════════════════════════════════════════════════════════════
A change to iOS has caused a temporary break in Flutter's debug mode on
physical devices.
See https://github.com/flutter/flutter/issues/163984 for details.
In the meantime, we recommend these temporary workarounds:
* When developing with a physical device, use one running iOS 18.3 or lower.
* Use a simulator for development rather than a physical device.
* If you must use a device updated to $deviceVersion, use Flutter's release or
profile mode via --release or --profile flags.
════════════════════════════════════════════════════════════════════════════════''';
class IOSDevices extends PollingDeviceDiscovery {
IOSDevices({
required Platform platform,
required this.xcdevice,
required IOSWorkflow iosWorkflow,
required Logger logger,
}) : _platform = platform,
_iosWorkflow = iosWorkflow,
_logger = logger,
super('iOS devices');
final Platform _platform;
final IOSWorkflow _iosWorkflow;
final Logger _logger;
@visibleForTesting
final XCDevice xcdevice;
@override
bool get supportsPlatform => _platform.isMacOS;
@override
bool get canListAnything => _iosWorkflow.canListDevices;
@override
bool get requiresExtendedWirelessDeviceDiscovery => true;
StreamSubscription<XCDeviceEventNotification>? _observedDeviceEventsSubscription;
/// Cache for all devices found by `xcdevice list`, including not connected
/// devices. Used to minimize the need to call `xcdevice list`.
///
/// Separate from `deviceNotifier` since `deviceNotifier` should only contain
/// connected devices.
final Map<String, IOSDevice> _cachedPolledDevices = <String, IOSDevice>{};
/// Maps device id to a map of the device's observed connections. When the
/// mapped connection is `true`, that means that observed events indicated
/// the device is connected via that particular interface.
///
/// The device id must be missing from the map or both interfaces must be
/// false for the device to be considered disconnected.
///
/// Example:
/// {
/// device-id: {
/// usb: false,
/// wifi: false,
/// },
/// }
final Map<String, Map<XCDeviceEventInterface, bool>> _observedConnectionsByDeviceId =
<String, Map<XCDeviceEventInterface, bool>>{};
@override
Future<void> startPolling() async {
if (!_platform.isMacOS) {
throw UnsupportedError('Control of iOS devices or simulators only supported on macOS.');
}
if (!xcdevice.isInstalled) {
return;
}
// Start by populating all currently attached devices.
_updateCachedDevices(await pollingGetDevices());
_updateNotifierFromCache();
// cancel any outstanding subscriptions.
await _observedDeviceEventsSubscription?.cancel();
_observedDeviceEventsSubscription = xcdevice.observedDeviceEvents()?.listen(
onDeviceEvent,
onError: (Object error, StackTrace stack) {
_logger.printTrace('Process exception running xcdevice observe:\n$error\n$stack');
},
onDone: () {
// If xcdevice is killed or otherwise dies, polling will be stopped.
// No retry is attempted and the polling client will have to restart polling
// (restart the IDE). Avoid hammering on a process that is
// continuously failing.
_logger.printTrace('xcdevice observe stopped');
},
cancelOnError: true,
);
}
@visibleForTesting
Future<void> onDeviceEvent(XCDeviceEventNotification event) async {
final ItemListNotifier<Device> notifier = deviceNotifier;
Device? knownDevice;
for (final Device device in notifier.items) {
if (device.id == event.deviceIdentifier) {
knownDevice = device;
}
}
final Map<XCDeviceEventInterface, bool> deviceObservedConnections =
_observedConnectionsByDeviceId[event.deviceIdentifier] ??
<XCDeviceEventInterface, bool>{
XCDeviceEventInterface.usb: false,
XCDeviceEventInterface.wifi: false,
};
if (event.eventType == XCDeviceEvent.attach) {
// Update device's observed connections.
deviceObservedConnections[event.eventInterface] = true;
_observedConnectionsByDeviceId[event.deviceIdentifier] = deviceObservedConnections;
// If device was not already in notifier, add it.
if (knownDevice == null) {
if (_cachedPolledDevices[event.deviceIdentifier] == null) {
// If device is not found in cache, there's no way to get details
// for an individual attached device, so repopulate them all.
_updateCachedDevices(await pollingGetDevices());
}
_updateNotifierFromCache();
}
} else {
// Update device's observed connections.
deviceObservedConnections[event.eventInterface] = false;
_observedConnectionsByDeviceId[event.deviceIdentifier] = deviceObservedConnections;
// If device is in the notifier and does not have other observed
// connections, remove it.
if (knownDevice != null && !_deviceHasObservedConnection(deviceObservedConnections)) {
notifier.removeItem(knownDevice);
}
}
}
/// Adds or updates devices in cache. Does not remove devices from cache.
void _updateCachedDevices(List<Device> devices) {
for (final Device device in devices) {
if (device is! IOSDevice) {
continue;
}
_cachedPolledDevices[device.id] = device;
}
}
/// Updates notifier with devices found in the cache that are determined
/// to be connected.
void _updateNotifierFromCache() {
final ItemListNotifier<Device> notifier = deviceNotifier;
// Device is connected if it has either an observed usb or wifi connection
// or it has not been observed but was found as connected in the cache.
final List<Device> connectedDevices =
_cachedPolledDevices.values.where((Device device) {
final Map<XCDeviceEventInterface, bool>? deviceObservedConnections =
_observedConnectionsByDeviceId[device.id];
return (deviceObservedConnections != null &&
_deviceHasObservedConnection(deviceObservedConnections)) ||
(deviceObservedConnections == null && device.isConnected);
}).toList();
notifier.updateWithNewList(connectedDevices);
}
bool _deviceHasObservedConnection(Map<XCDeviceEventInterface, bool> deviceObservedConnections) {
return (deviceObservedConnections[XCDeviceEventInterface.usb] ?? false) ||
(deviceObservedConnections[XCDeviceEventInterface.wifi] ?? false);
}
@override
Future<void> stopPolling() async {
await _observedDeviceEventsSubscription?.cancel();
}
@override
Future<List<Device>> pollingGetDevices({Duration? timeout}) async {
if (!_platform.isMacOS) {
throw UnsupportedError('Control of iOS devices or simulators only supported on macOS.');
}
return xcdevice.getAvailableIOSDevices(timeout: timeout);
}
Future<Device?> waitForDeviceToConnect(IOSDevice device, Logger logger) async {
final XCDeviceEventNotification? eventDetails = await xcdevice.waitForDeviceToConnect(
device.id,
);
if (eventDetails != null) {
device.isConnected = true;
device.connectionInterface = eventDetails.eventInterface.connectionInterface;
return device;
}
return null;
}
void cancelWaitForDeviceToConnect() {
xcdevice.cancelWaitForDeviceToConnect();
}
@override
Future<List<String>> getDiagnostics() async {
if (!_platform.isMacOS) {
return const <String>['Control of iOS devices or simulators only supported on macOS.'];
}
return xcdevice.getDiagnostics();
}
@override
List<String> get wellKnownIds => const <String>[];
}
class IOSDevice extends Device {
IOSDevice(
super.id, {
required FileSystem fileSystem,
required this.name,
required this.cpuArchitecture,
required this.connectionInterface,
required this.isConnected,
required this.isPaired,
required this.devModeEnabled,
required this.isCoreDevice,
String? sdkVersion,
required Platform platform,
required IOSDeploy iosDeploy,
required IMobileDevice iMobileDevice,
required IOSCoreDeviceControl coreDeviceControl,
required XcodeDebug xcodeDebug,
required IProxy iProxy,
required super.logger,
}) : _sdkVersion = sdkVersion,
_iosDeploy = iosDeploy,
_iMobileDevice = iMobileDevice,
_coreDeviceControl = coreDeviceControl,
_xcodeDebug = xcodeDebug,
_iproxy = iProxy,
_fileSystem = fileSystem,
_logger = logger,
_platform = platform,
super(category: Category.mobile, platformType: PlatformType.ios, ephemeral: true) {
if (!_platform.isMacOS) {
assert(false, 'Control of iOS devices or simulators only supported on Mac OS.');
return;
}
}
final String? _sdkVersion;
final IOSDeploy _iosDeploy;
final FileSystem _fileSystem;
final Logger _logger;
final Platform _platform;
final IMobileDevice _iMobileDevice;
final IOSCoreDeviceControl _coreDeviceControl;
final XcodeDebug _xcodeDebug;
final IProxy _iproxy;
Version? get sdkVersion {
return Version.parse(_sdkVersion);
}
/// May be 0 if version cannot be parsed.
int get majorSdkVersion {
return sdkVersion?.major ?? 0;
}
@override
final String name;
@override
bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;
final DarwinArch cpuArchitecture;
@override
/// The [connectionInterface] provided from `XCDevice.getAvailableIOSDevices`
/// may not be accurate. Sometimes if it doesn't have a long enough time
/// to connect, wireless devices will have an interface of `usb`/`attached`.
/// This may change after waiting for the device to connect in
/// `waitForDeviceToConnect`.
DeviceConnectionInterface connectionInterface;
@override
bool isConnected;
bool devModeEnabled = false;
/// Device has trusted this computer and paired.
bool isPaired = false;
/// CoreDevice is a device connectivity stack introduced in Xcode 15. Devices
/// with iOS 17 or greater are CoreDevices.
final bool isCoreDevice;
final Map<IOSApp?, DeviceLogReader> _logReaders = <IOSApp?, DeviceLogReader>{};
DevicePortForwarder? _portForwarder;
@visibleForTesting
IOSDeployDebugger? iosDeployDebugger;
@override
Future<bool> get isLocalEmulator async => false;
@override
Future<String?> get emulatorId async => null;
@override
bool get supportsStartPaused => false;
@override
bool get supportsFlavors => true;
@override
Future<bool> isAppInstalled(ApplicationPackage app, {String? userIdentifier}) async {
bool result;
try {
if (isCoreDevice) {
result = await _coreDeviceControl.isAppInstalled(bundleId: app.id, deviceId: id);
} else {
result = await _iosDeploy.isAppInstalled(bundleId: app.id, deviceId: id);
}
} on ProcessException catch (e) {
_logger.printError(e.message);
return false;
}
return result;
}
@override
Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
@override
Future<bool> installApp(covariant IOSApp app, {String? userIdentifier}) async {
final Directory bundle = _fileSystem.directory(app.deviceBundlePath);
if (!bundle.existsSync()) {
_logger.printError(
'Could not find application bundle at ${bundle.path}; have you run "flutter build ios"?',
);
return false;
}
int installationResult;
try {
if (isCoreDevice) {
installationResult =
await _coreDeviceControl.installApp(deviceId: id, bundlePath: bundle.path) ? 0 : 1;
} else {
installationResult = await _iosDeploy.installApp(
deviceId: id,
bundlePath: bundle.path,
appDeltaDirectory: app.appDeltaDirectory,
launchArguments: <String>[],
interfaceType: connectionInterface,
);
}
} on ProcessException catch (e) {
_logger.printError(e.message);
return false;
}
if (installationResult != 0) {
_logger.printError('Could not install ${bundle.path} on $id.');
_logger.printError('Try launching Xcode and selecting "Product > Run" to fix the problem:');
_logger.printError(' open ios/Runner.xcworkspace');
_logger.printError('');
return false;
}
return true;
}
@override
Future<bool> uninstallApp(ApplicationPackage app, {String? userIdentifier}) async {
int uninstallationResult;
try {
if (isCoreDevice) {
uninstallationResult =
await _coreDeviceControl.uninstallApp(deviceId: id, bundleId: app.id) ? 0 : 1;
} else {
uninstallationResult = await _iosDeploy.uninstallApp(deviceId: id, bundleId: app.id);
}
} on ProcessException catch (e) {
_logger.printError(e.message);
return false;
}
if (uninstallationResult != 0) {
_logger.printError('Could not uninstall ${app.id} on $id.');
return false;
}
return true;
}
@override
// 32-bit devices are not supported.
bool isSupported() => cpuArchitecture == DarwinArch.arm64;
@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,
@visibleForTesting Duration? discoveryTimeout,
@visibleForTesting ShutdownHooks? shutdownHooks,
}) async {
String? packageId;
if (isWirelesslyConnected &&
debuggingOptions.debuggingEnabled &&
debuggingOptions.disablePortPublication) {
throwToolExit(
'Cannot start app on wirelessly tethered iOS device. Try running again with the --publish-port flag',
);
}
if (!prebuiltApplication) {
_logger.printTrace('Building ${package.name} for $id');
// Step 1: Build the precompiled/DBC application if necessary.
final XcodeBuildResult buildResult = await buildXcodeProject(
app: package as BuildableIOSApp,
buildInfo: debuggingOptions.buildInfo,
targetOverride: mainPath,
activeArch: cpuArchitecture,
deviceID: id,
disablePortPublication:
debuggingOptions.usingCISystem && debuggingOptions.disablePortPublication,
);
if (!buildResult.success) {
_logger.printError('Could not build the precompiled application for the device.');
await diagnoseXcodeBuildFailure(
buildResult,
analytics: globals.analytics,
fileSystem: globals.fs,
logger: globals.logger,
platform: SupportedPlatform.ios,
project: package.project.parent,
);
_logger.printError('');
return LaunchResult.failed();
}
packageId = buildResult.xcodeBuildExecution?.buildSettings[IosProject.kProductBundleIdKey];
}
packageId ??= package.id;
// Step 2: Check that the application exists at the specified path.
final Directory bundle = _fileSystem.directory(package.deviceBundlePath);
if (!bundle.existsSync()) {
_logger.printError('Could not find the built application bundle at ${bundle.path}.');
return LaunchResult.failed();
}
// Step 3: Attempt to install the application on the device.
final List<String> launchArguments = debuggingOptions.getIOSLaunchArguments(
EnvironmentType.physical,
route,
platformArgs,
interfaceType: connectionInterface,
isCoreDevice: isCoreDevice,
);
Status startAppStatus = _logger.startProgress('Installing and launching...');
try {
ProtocolDiscovery? vmServiceDiscovery;
int installationResult = 1;
if (debuggingOptions.debuggingEnabled) {
_logger.printTrace('Debugging is enabled, connecting to vmService');
vmServiceDiscovery = _setupDebuggerAndVmServiceDiscovery(
package: package,
bundle: bundle,
debuggingOptions: debuggingOptions,
launchArguments: launchArguments,
uninstallFirst: debuggingOptions.uninstallFirst,
);
}
if (isCoreDevice) {
installationResult =
await _startAppOnCoreDevice(
debuggingOptions: debuggingOptions,
package: package,
launchArguments: launchArguments,
mainPath: mainPath,
discoveryTimeout: discoveryTimeout,
shutdownHooks: shutdownHooks ?? globals.shutdownHooks,
)
? 0
: 1;
} else if (iosDeployDebugger == null) {
installationResult = await _iosDeploy.launchApp(
deviceId: id,
bundlePath: bundle.path,
appDeltaDirectory: package.appDeltaDirectory,
launchArguments: launchArguments,
interfaceType: connectionInterface,
uninstallFirst: debuggingOptions.uninstallFirst,
);
} else {
installationResult = await iosDeployDebugger!.launchAndAttach() ? 0 : 1;
}
if (installationResult != 0) {
_printInstallError(bundle);
await dispose();
return LaunchResult.failed();
}
if (!debuggingOptions.debuggingEnabled) {
return LaunchResult.succeeded();
}
_logger.printTrace('Application launched on the device. Waiting for Dart VM Service url.');
final int defaultTimeout;
if (isCoreDevice && debuggingOptions.debuggingEnabled) {
// Core devices with debugging enabled takes longer because this
// includes time to install and launch the app on the device.
defaultTimeout = isWirelesslyConnected ? 75 : 60;
} else if (isWirelesslyConnected) {
defaultTimeout = 45;
} else {
defaultTimeout = 30;
}
final Timer timer = Timer(discoveryTimeout ?? Duration(seconds: defaultTimeout), () {
_logger.printError(
'The Dart VM Service was not discovered after $defaultTimeout seconds. This is taking much longer than expected...',
);
if (isCoreDevice && debuggingOptions.debuggingEnabled) {
_logger.printError(
'Open the Xcode window the project is opened in to ensure the app '
'is running. If the app is not running, try selecting "Product > Run" '
'to fix the problem.',
);
}
// If debugging with a wireless device and the timeout is reached, remind the
// user to allow local network permissions.
if (isWirelesslyConnected) {
_logger.printError(
'\nYour debugging device seems wirelessly connected. '
'Consider plugging it in and trying again.',
);
_logger.printError(
'\nClick "Allow" to the prompt asking if you would like to find and connect devices on your local network. '
'This is required for wireless debugging. If you selected "Don\'t Allow", '
'you can turn it on in Settings > Your App Name > Local Network. '
"If you don't see your app in the Settings, uninstall the app and rerun to see the prompt again.",
);
} else {
iosDeployDebugger?.checkForSymbolsFiles(_fileSystem);
iosDeployDebugger?.pauseDumpBacktraceResume();
}
});
Uri? localUri;
if (isCoreDevice) {
localUri = await _discoverDartVMForCoreDevice(
debuggingOptions: debuggingOptions,
packageId: packageId,
vmServiceDiscovery: vmServiceDiscovery,
package: package,
);
} else if (isWirelesslyConnected) {
// Wait for the Dart VM url to be discovered via logs (from `ios-deploy`)
// in ProtocolDiscovery. Then via mDNS, construct the Dart VM url using
// the device IP as the host by finding Dart VM services matching the
// app bundle id and Dart VM port.
// Wait for Dart VM Service to start up.
final Uri? serviceURL = await vmServiceDiscovery?.uri;
if (serviceURL == null) {
await iosDeployDebugger?.stopAndDumpBacktrace();
await dispose();
return LaunchResult.failed();
}
// If Dart VM Service URL with the device IP is not found within 5 seconds,
// change the status message to prompt users to click Allow. Wait 5 seconds because it
// should only show this message if they have not already approved the permissions.
// MDnsVmServiceDiscovery usually takes less than 5 seconds to find it.
final Timer mDNSLookupTimer = Timer(const Duration(seconds: 5), () {
startAppStatus.stop();
startAppStatus = _logger.startProgress(
'Waiting for approval of local network permissions...',
);
});
// Get Dart VM Service URL with the device IP as the host.
localUri = await MDnsVmServiceDiscovery.instance!.getVMServiceUriForLaunch(
packageId,
this,
usesIpv6: debuggingOptions.ipv6,
deviceVmservicePort: serviceURL.port,
useDeviceIPAsHost: true,
);
mDNSLookupTimer.cancel();
} else {
localUri = await vmServiceDiscovery?.uri;
// If the `ios-deploy` debugger loses connection before it finds the
// Dart Service VM url, try starting the debugger and launching the
// app again.
if (localUri == null &&
debuggingOptions.usingCISystem &&
iosDeployDebugger != null &&
iosDeployDebugger!.lostConnection) {
_logger.printStatus('Lost connection to device. Trying to connect again...');
await dispose();
vmServiceDiscovery = _setupDebuggerAndVmServiceDiscovery(
package: package,
bundle: bundle,
debuggingOptions: debuggingOptions,
launchArguments: launchArguments,
uninstallFirst: false,
skipInstall: true,
);
installationResult = await iosDeployDebugger!.launchAndAttach() ? 0 : 1;
if (installationResult != 0) {
_printInstallError(bundle);
await dispose();
return LaunchResult.failed();
}
localUri = await vmServiceDiscovery.uri;
}
}
timer.cancel();
if (localUri == null) {
await iosDeployDebugger?.stopAndDumpBacktrace();
await dispose();
return LaunchResult.failed();
}
return LaunchResult.succeeded(vmServiceUri: localUri);
} on ProcessException catch (e) {
await iosDeployDebugger?.stopAndDumpBacktrace();
_logger.printError(e.message);
await dispose();
return LaunchResult.failed();
} finally {
startAppStatus.stop();
if (isCoreDevice && debuggingOptions.debuggingEnabled && package is BuildableIOSApp) {
// When debugging via Xcode, after the app launches, reset the Generated
// settings to not include the custom configuration build directory.
// This is to prevent confusion if the project is later ran via Xcode
// rather than the Flutter CLI.
await updateGeneratedXcodeProperties(
project: FlutterProject.current(),
buildInfo: debuggingOptions.buildInfo,
targetOverride: mainPath,
);
}
}
}
void _printInstallError(Directory bundle) {
_logger.printError('Could not run ${bundle.path} on $id.');
_logger.printError('Try launching Xcode and selecting "Product > Run" to fix the problem:');
_logger.printError(' open ios/Runner.xcworkspace');
_logger.printError('');
}
/// Find the Dart VM url using ProtocolDiscovery (logs from `idevicesyslog`)
/// and mDNS simultaneously, using whichever is found first. `idevicesyslog`
/// does not work on wireless devices, so only use mDNS for wireless devices.
/// Wireless devices require using the device IP as the host.
Future<Uri?> _discoverDartVMForCoreDevice({
required String packageId,
required DebuggingOptions debuggingOptions,
ProtocolDiscovery? vmServiceDiscovery,
IOSApp? package,
}) async {
Timer? maxWaitForCI;
final Completer<Uri?> cancelCompleter = Completer<Uri?>();
// When testing in CI, wait a max of 10 minutes for the Dart VM to be found.
// Afterwards, stop the app from running and upload DerivedData Logs to debug
// logs directory. CoreDevices are run through Xcode and launch logs are
// therefore found in DerivedData.
if (debuggingOptions.usingCISystem && debuggingOptions.debugLogsDirectoryPath != null) {
maxWaitForCI = Timer(const Duration(minutes: 10), () async {
_logger.printError('Failed to find Dart VM after 10 minutes.');
await _xcodeDebug.exit();
final String? homePath = _platform.environment['HOME'];
Directory? derivedData;
if (homePath != null) {
derivedData = _fileSystem.directory(
_fileSystem.path.join(homePath, 'Library', 'Developer', 'Xcode', 'DerivedData'),
);
}
if (derivedData != null && derivedData.existsSync()) {
final Directory debugLogsDirectory = _fileSystem.directory(
debuggingOptions.debugLogsDirectoryPath,
);
debugLogsDirectory.createSync(recursive: true);
for (final FileSystemEntity entity in derivedData.listSync()) {
if (entity is! Directory || !entity.childDirectory('Logs').existsSync()) {
continue;
}
final Directory logsToCopy = entity.childDirectory('Logs');
final Directory copyDestination = debugLogsDirectory
.childDirectory('DerivedDataLogs')
.childDirectory(entity.basename)
.childDirectory('Logs');
_logger.printTrace('Copying logs ${logsToCopy.path} to ${copyDestination.path}...');
copyDirectory(logsToCopy, copyDestination);
}
}
cancelCompleter.complete();
});
}
final StreamSubscription<String>? errorListener = await _interceptErrorsFromLogs(
package,
debuggingOptions: debuggingOptions,
);
final bool discoverVMUrlFromLogs = vmServiceDiscovery != null && !isWirelesslyConnected;
// If mDNS fails, don't throw since url may still be findable through vmServiceDiscovery.
final Future<Uri?> vmUrlFromMDns = MDnsVmServiceDiscovery.instance!.getVMServiceUriForLaunch(
packageId,
this,
usesIpv6: debuggingOptions.ipv6,
useDeviceIPAsHost: isWirelesslyConnected,
throwOnMissingLocalNetworkPermissionsError: !discoverVMUrlFromLogs,
);
final List<Future<Uri?>> discoveryOptions = <Future<Uri?>>[
vmUrlFromMDns,
// vmServiceDiscovery uses device logs (`idevicesyslog`), which doesn't work
// on wireless devices.
if (discoverVMUrlFromLogs) vmServiceDiscovery.uri,
];
Uri? localUri = await Future.any(<Future<Uri?>>[...discoveryOptions, cancelCompleter.future]);
// If the first future to return is null, wait for the other to complete
// unless canceled.
if (localUri == null && !cancelCompleter.isCompleted) {
final Future<List<Uri?>> allDiscoveryOptionsComplete = Future.wait(discoveryOptions);
await Future.any(<Future<Object?>>[allDiscoveryOptionsComplete, cancelCompleter.future]);
if (!cancelCompleter.isCompleted) {
// If it wasn't cancelled, that means one of the discovery options completed.
final List<Uri?> vmUrls = await allDiscoveryOptionsComplete;
localUri = vmUrls.where((Uri? vmUrl) => vmUrl != null).firstOrNull;
}
}
maxWaitForCI?.cancel();
await errorListener?.cancel();
return localUri;
}
/// Listen to device logs for crash on iOS 18.4+ due to JIT restriction. If
/// found, give guided error and throw tool exit. Returns null and does not
/// listen if device is less than iOS 18.4.
Future<StreamSubscription<String>?> _interceptErrorsFromLogs(
IOSApp? package, {
required DebuggingOptions debuggingOptions,
}) async {
// Currently only checking for kJITCrashFailureMessage, which only should
// be checked on iOS 18.4+.
if (sdkVersion == null || sdkVersion! < Version(18, 4, null)) {
return null;
}
final DeviceLogReader deviceLogReader = getLogReader(
app: package,
usingCISystem: debuggingOptions.usingCISystem,
);
final Stream<String> logStream = deviceLogReader.logLines;
final String deviceSdkVersion = await sdkNameAndVersion;
final StreamSubscription<String> errorListener = logStream.listen((String line) {
if (line.contains(kJITCrashFailureMessage)) {
throwToolExit(jITCrashFailureInstructions(deviceSdkVersion));
}
});
return errorListener;
}
ProtocolDiscovery _setupDebuggerAndVmServiceDiscovery({
required IOSApp package,
required Directory bundle,
required DebuggingOptions debuggingOptions,
required List<String> launchArguments,
required bool uninstallFirst,
bool skipInstall = false,
}) {
final DeviceLogReader deviceLogReader = getLogReader(
app: package,
usingCISystem: debuggingOptions.usingCISystem,
);
// If the device supports syslog reading, prefer launching the app without
// attaching the debugger to avoid the overhead of the unnecessary extra running process.
if (majorSdkVersion >= IOSDeviceLogReader.minimumUniversalLoggingSdkVersion) {
iosDeployDebugger = _iosDeploy.prepareDebuggerForLaunch(
deviceId: id,
bundlePath: bundle.path,
appDeltaDirectory: package.appDeltaDirectory,
launchArguments: launchArguments,
interfaceType: connectionInterface,
uninstallFirst: uninstallFirst,
skipInstall: skipInstall,
);
if (deviceLogReader is IOSDeviceLogReader) {
deviceLogReader.debuggerStream = iosDeployDebugger;
}
}
// Don't port forward if debugging with a wireless device.
return ProtocolDiscovery.vmService(
deviceLogReader,
portForwarder: isWirelesslyConnected ? null : portForwarder,
hostPort: debuggingOptions.hostVmServicePort,
devicePort: debuggingOptions.deviceVmServicePort,
ipv6: debuggingOptions.ipv6,
logger: _logger,
);
}
/// Starting with Xcode 15 and iOS 17, `ios-deploy` stopped working due to
/// the new CoreDevice connectivity stack. Previously, `ios-deploy` was used
/// to install the app, launch the app, and start `debugserver`.
/// Xcode 15 introduced a new command line tool called `devicectl` that
/// includes much of the functionality supplied by `ios-deploy`. However,
/// `devicectl` lacks the ability to start a `debugserver` and therefore `ptrace`, which are needed
/// for debug mode due to using a JIT Dart VM.
///
/// Therefore, when starting an app on a CoreDevice, use `devicectl` when
/// debugging is not enabled. Otherwise, use Xcode automation.
Future<bool> _startAppOnCoreDevice({
required DebuggingOptions debuggingOptions,
required IOSApp package,
required List<String> launchArguments,
required String? mainPath,
required ShutdownHooks shutdownHooks,
@visibleForTesting Duration? discoveryTimeout,
}) async {
if (!debuggingOptions.debuggingEnabled) {
// Release mode
// Install app to device
final bool installSuccess = await _coreDeviceControl.installApp(
deviceId: id,
bundlePath: package.deviceBundlePath,
);
if (!installSuccess) {
return installSuccess;
}
// Launch app to device
final bool launchSuccess = await _coreDeviceControl.launchApp(
deviceId: id,
bundleId: package.id,
launchArguments: launchArguments,
);
return launchSuccess;
} else {
_logger.printStatus(
'You may be prompted to give access to control Xcode. Flutter uses Xcode '
'to run your app. If access is not allowed, you can change this through '
'your Settings > Privacy & Security > Automation.',
);
final int launchTimeout = isWirelesslyConnected ? 45 : 30;
final Timer timer = Timer(discoveryTimeout ?? Duration(seconds: launchTimeout), () {
_logger.printError(
'Xcode is taking longer than expected to start debugging the app. '
'Ensure the project is opened in Xcode.',
);
});
XcodeDebugProject debugProject;
final FlutterProject flutterProject = FlutterProject.current();
if (package is PrebuiltIOSApp) {
debugProject = await _xcodeDebug.createXcodeProjectWithCustomBundle(
package.deviceBundlePath,
templateRenderer: globals.templateRenderer,
verboseLogging: _logger.isVerbose,
);
} else if (package is BuildableIOSApp) {
// Before installing/launching/debugging with Xcode, update the build
// settings to use a custom configuration build directory so Xcode
// knows where to find the app bundle to launch.
final Directory bundle = _fileSystem.directory(package.deviceBundlePath);
await updateGeneratedXcodeProperties(
project: flutterProject,
buildInfo: debuggingOptions.buildInfo,
targetOverride: mainPath,
configurationBuildDir: bundle.parent.absolute.path,
);
final IosProject project = package.project;
final XcodeProjectInfo? projectInfo = await project.projectInfo();
if (projectInfo == null) {
globals.printError('Xcode project not found.');
return false;
}
if (project.xcodeWorkspace == null) {
globals.printError('Unable to get Xcode workspace.');
return false;
}
final String? scheme = projectInfo.schemeFor(debuggingOptions.buildInfo);
if (scheme == null) {
projectInfo.reportFlavorNotFoundAndExit();
}
_xcodeDebug.ensureXcodeDebuggerLaunchAction(project.xcodeProjectSchemeFile(scheme: scheme));
debugProject = XcodeDebugProject(
scheme: scheme,
xcodeProject: project.xcodeProject,
xcodeWorkspace: project.xcodeWorkspace!,
hostAppProjectName: project.hostAppProjectName,
expectedConfigurationBuildDir: bundle.parent.absolute.path,
verboseLogging: _logger.isVerbose,
);
} else {
// This should not happen. Currently, only PrebuiltIOSApp and
// BuildableIOSApp extend from IOSApp.
_logger.printError('IOSApp type ${package.runtimeType} is not recognized.');
return false;
}
final bool debugSuccess = await _xcodeDebug.debugApp(
project: debugProject,
deviceId: id,
launchArguments: launchArguments,
);
timer.cancel();
// Kill Xcode on shutdown when running from CI
if (debuggingOptions.usingCISystem) {
shutdownHooks.addShutdownHook(() => _xcodeDebug.exit(force: true));
}
return debugSuccess;
}
}
@override
Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async {
// If the debugger is not attached, killing the ios-deploy process won't stop the app.
final IOSDeployDebugger? deployDebugger = iosDeployDebugger;
if (deployDebugger != null && deployDebugger.debuggerAttached) {
return deployDebugger.exit();
}
if (_xcodeDebug.debugStarted) {
return _xcodeDebug.exit();
}
return false;
}
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
@override
Future<String> get sdkNameAndVersion async => 'iOS ${_sdkVersion ?? 'unknown version'}';
@override
DeviceLogReader getLogReader({
covariant IOSApp? app,
bool includePastLogs = false,
bool usingCISystem = false,
}) {
assert(!includePastLogs, 'Past log reading not supported on iOS devices.');
return _logReaders.putIfAbsent(
app,
() => IOSDeviceLogReader.create(
device: this,
app: app,
iMobileDevice: _iMobileDevice,
usingCISystem: usingCISystem,
),
);
}
@visibleForTesting
void setLogReader(IOSApp app, DeviceLogReader logReader) {
_logReaders[app] = logReader;
}
@override
DevicePortForwarder get portForwarder =>
_portForwarder ??= IOSDevicePortForwarder(
logger: _logger,
iproxy: _iproxy,
id: id,
operatingSystemUtils: globals.os,
);
@visibleForTesting
set portForwarder(DevicePortForwarder forwarder) {
_portForwarder = forwarder;
}
@override
void clearLogs() {}
@override
VMServiceDiscoveryForAttach getVMServiceDiscoveryForAttach({
String? appId,
String? fuchsiaModule,
int? filterDevicePort,
int? expectedHostPort,
required bool ipv6,
required Logger logger,
}) {
final bool compatibleWithProtocolDiscovery =
majorSdkVersion < IOSDeviceLogReader.minimumUniversalLoggingSdkVersion &&
!isWirelesslyConnected;
final MdnsVMServiceDiscoveryForAttach mdnsVMServiceDiscoveryForAttach =
MdnsVMServiceDiscoveryForAttach(
device: this,
appId: appId,
deviceVmservicePort: filterDevicePort,
hostVmservicePort: expectedHostPort,
usesIpv6: ipv6,
useDeviceIPAsHost: isWirelesslyConnected,
);
if (compatibleWithProtocolDiscovery) {
return DelegateVMServiceDiscoveryForAttach(<VMServiceDiscoveryForAttach>[
mdnsVMServiceDiscoveryForAttach,
super.getVMServiceDiscoveryForAttach(
appId: appId,
fuchsiaModule: fuchsiaModule,
filterDevicePort: filterDevicePort,
expectedHostPort: expectedHostPort,
ipv6: ipv6,
logger: logger,
),
]);
} else {
return mdnsVMServiceDiscoveryForAttach;
}
}
@override
bool get supportsScreenshot {
if (isCoreDevice) {
// `idevicescreenshot` stopped working with iOS 17 / Xcode 15
// (https://github.com/flutter/flutter/issues/128598).
return false;
}
return _iMobileDevice.isInstalled;
}
@override
Future<void> takeScreenshot(File outputFile) async {
await _iMobileDevice.takeScreenshot(outputFile, id, connectionInterface);
}
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.ios.existsSync();
}
@override
Future<void> dispose() async {
for (final DeviceLogReader logReader in _logReaders.values) {
logReader.dispose();
}
_logReaders.clear();
await _portForwarder?.dispose();
}
}
/// Decodes a vis-encoded syslog string to a UTF-8 representation.
///
/// Apple's syslog logs are encoded in 7-bit form. Input bytes are encoded as follows:
/// 1. 0x00 to 0x19: non-printing range. Some ignored, some encoded as <...>.
/// 2. 0x20 to 0x7f: as-is, with the exception of 0x5c (backslash).
/// 3. 0x5c (backslash): octal representation \134.
/// 4. 0x80 to 0x9f: \M^x (using control-character notation for range 0x00 to 0x40).
/// 5. 0xa0: octal representation \240.
/// 6. 0xa1 to 0xf7: \M-x (where x is the input byte stripped of its high-order bit).
/// 7. 0xf8 to 0xff: unused in 4-byte UTF-8.
///
/// See: [vis(3) manpage](https://www.freebsd.org/cgi/man.cgi?query=vis&sektion=3)
String decodeSyslog(String line) {
// UTF-8 values for \, M, -, ^.
const int kBackslash = 0x5c;
const int kM = 0x4d;
const int kDash = 0x2d;
const int kCaret = 0x5e;
// Mask for the UTF-8 digit range.
const int kNum = 0x30;
// Returns true when `byte` is within the UTF-8 7-bit digit range (0x30 to 0x39).
bool isDigit(int byte) => (byte & 0xf0) == kNum;
// Converts a three-digit ASCII (UTF-8) representation of an octal number `xyz` to an integer.
int decodeOctal(int x, int y, int z) => (x & 0x3) << 6 | (y & 0x7) << 3 | z & 0x7;
try {
final List<int> bytes = utf8.encode(line);
final List<int> out = <int>[];
for (int i = 0; i < bytes.length;) {
if (bytes[i] != kBackslash || i > bytes.length - 4) {
// Unmapped byte: copy as-is.
out.add(bytes[i++]);
} else {
// Mapped byte: decode next 4 bytes.
if (bytes[i + 1] == kM && bytes[i + 2] == kCaret) {
// \M^x form: bytes in range 0x80 to 0x9f.
out.add((bytes[i + 3] & 0x7f) + 0x40);
} else if (bytes[i + 1] == kM && bytes[i + 2] == kDash) {
// \M-x form: bytes in range 0xa0 to 0xf7.
out.add(bytes[i + 3] | 0x80);
} else if (bytes.getRange(i + 1, i + 3).every(isDigit)) {
// \ddd form: octal representation (only used for \134 and \240).
out.add(decodeOctal(bytes[i + 1], bytes[i + 2], bytes[i + 3]));
} else {
// Unknown form: copy as-is.
out.addAll(bytes.getRange(0, 4));
}
i += 4;
}
}
return utf8.decode(out);
} on Exception {
// Unable to decode line: return as-is.
return line;
}
}
class IOSDeviceLogReader extends DeviceLogReader {
IOSDeviceLogReader._(
this._iMobileDevice,
this._majorSdkVersion,
this._deviceId,
this.name,
this._isWirelesslyConnected,
this._isCoreDevice,
String appName,
bool usingCISystem,
) : // Match for lines for the runner in syslog.
//
// iOS 9 format: Runner[297] <Notice>:
// iOS 10 format: Runner(Flutter)[297] <Notice>:
_runnerLineRegex = RegExp(appName + r'(\(Flutter\))?\[[\d]+\] <[A-Za-z]+>: '),
_usingCISystem = usingCISystem;
/// Create a new [IOSDeviceLogReader].
factory IOSDeviceLogReader.create({
required IOSDevice device,
IOSApp? app,
required IMobileDevice iMobileDevice,
bool usingCISystem = false,
}) {
final String appName = app?.name?.replaceAll('.app', '') ?? '';
return IOSDeviceLogReader._(
iMobileDevice,
device.majorSdkVersion,
device.id,
device.displayName,
device.isWirelesslyConnected,
device.isCoreDevice,
appName,
usingCISystem,
);
}
/// Create an [IOSDeviceLogReader] for testing.
factory IOSDeviceLogReader.test({
required IMobileDevice iMobileDevice,
bool useSyslog = true,
bool usingCISystem = false,
int? majorSdkVersion,
bool isWirelesslyConnected = false,
bool isCoreDevice = false,
}) {
final int sdkVersion = majorSdkVersion ?? (useSyslog ? 12 : 13);
return IOSDeviceLogReader._(
iMobileDevice,
sdkVersion,
'1234',
'test',
isWirelesslyConnected,
isCoreDevice,
'Runner',
usingCISystem,
);
}
@override
final String name;
final int _majorSdkVersion;
final String _deviceId;
final bool _isWirelesslyConnected;
final bool _isCoreDevice;
final IMobileDevice _iMobileDevice;
final bool _usingCISystem;
// Matches a syslog line from the runner.
RegExp _runnerLineRegex;
// Similar to above, but allows ~arbitrary components instead of "Runner"
// and "Flutter". The regex tries to strike a balance between not producing
// false positives and not producing false negatives.
final RegExp _anyLineRegex = RegExp(r'\w+(\([^)]*\))?\[\d+\] <[A-Za-z]+>: ');
// Logging from native code/Flutter engine is prefixed by timestamp and process metadata:
// 2020-09-15 19:15:10.931434-0700 Runner[541:226276] Did finish launching.
// 2020-09-15 19:15:10.931434-0700 Runner[541:226276] [Category] Did finish launching.
//
// Logging from the dart code has no prefixing metadata.
final RegExp _debuggerLoggingRegex = RegExp(r'^\S* \S* \S*\[[0-9:]*] (.*)');
@visibleForTesting
late final StreamController<String> linesController = StreamController<String>.broadcast(
onListen: _listenToSysLog,
onCancel: dispose,
);
// Sometimes (race condition?) we try to send a log after the controller has
// been closed. See https://github.com/flutter/flutter/issues/99021 for more
// context.
@visibleForTesting
void addToLinesController(String message, IOSDeviceLogSource source) {
if (!linesController.isClosed) {
if (_excludeLog(message, source)) {
return;
}
linesController.add(message);
}
}
/// Used to track messages prefixed with "flutter:" from the fallback log source.
final List<String> _fallbackStreamFlutterMessages = <String>[];
/// Used to track if a message prefixed with "flutter:" has been received from the primary log.
bool primarySourceFlutterLogReceived = false;
/// There are three potential logging sources: `idevicesyslog`, `ios-deploy`,
/// and Unified Logging (Dart VM). When using more than one of these logging
/// sources at a time, prefer to use the primary source. However, if the
/// primary source is not working, use the fallback.
bool _excludeLog(String message, IOSDeviceLogSource source) {
// If no fallback, don't exclude any logs.
if (logSources.fallbackSource == null) {
return false;
}
// If log is from primary source, don't exclude it unless the fallback was
// quicker and added the message first.
if (source == logSources.primarySource) {
if (!primarySourceFlutterLogReceived && message.startsWith('flutter:')) {
primarySourceFlutterLogReceived = true;
}
// If the message was already added by the fallback, exclude it to
// prevent duplicates.
final bool foundAndRemoved = _fallbackStreamFlutterMessages.remove(message);
if (foundAndRemoved) {
return true;
}
return false;
}
// If a flutter log was received from the primary source, that means it's
// working so don't use any messages from the fallback.
if (primarySourceFlutterLogReceived) {
return true;
}
// When using logs from fallbacks, skip any logs not prefixed with "flutter:".
// This is done because different sources often have different prefixes for
// non-flutter messages, which makes duplicate matching difficult. Also,
// non-flutter messages are not critical for CI tests.
if (!message.startsWith('flutter:')) {
return true;
}
_fallbackStreamFlutterMessages.add(message);
return false;
}
final List<StreamSubscription<void>> _loggingSubscriptions = <StreamSubscription<void>>[];
@override
Stream<String> get logLines => linesController.stream;
FlutterVmService? _connectedVmService;
@override
Future<void> provideVmService(FlutterVmService connectedVmService) async {
await _listenToUnifiedLoggingEvents(connectedVmService);
_connectedVmService = connectedVmService;
}
static const int minimumUniversalLoggingSdkVersion = 13;
/// Determine the primary and fallback source for device logs.
///
/// There are three potential logging sources: `idevicesyslog`, `ios-deploy`,
/// and Unified Logging (Dart VM).
@visibleForTesting
_IOSDeviceLogSources get logSources {
// `ios-deploy` stopped working with iOS 17 / Xcode 15, so use `idevicesyslog` instead.
// However, `idevicesyslog` is sometimes unreliable so use Dart VM as a fallback.
// Also, `idevicesyslog` does not work with iOS 17 wireless devices, so use the
// Dart VM for wireless devices.
if (_isCoreDevice) {
if (_isWirelesslyConnected) {
return _IOSDeviceLogSources(primarySource: IOSDeviceLogSource.unifiedLogging);
}
return _IOSDeviceLogSources(
primarySource: IOSDeviceLogSource.idevicesyslog,
fallbackSource: IOSDeviceLogSource.unifiedLogging,
);
}
// Use `idevicesyslog` for iOS 12 or less.
// Syslog stopped working on iOS 13 (https://github.com/flutter/flutter/issues/41133).
// However, from at least iOS 16, it has began working again. It's unclear
// why it started working again.
if (_majorSdkVersion < minimumUniversalLoggingSdkVersion) {
return _IOSDeviceLogSources(primarySource: IOSDeviceLogSource.idevicesyslog);
}
// Use `idevicesyslog` as a fallback to `ios-deploy` when debugging from
// CI system since sometimes `ios-deploy` does not return the device logs:
// https://github.com/flutter/flutter/issues/121231
if (_usingCISystem && _majorSdkVersion >= 16) {
return _IOSDeviceLogSources(
primarySource: IOSDeviceLogSource.iosDeploy,
fallbackSource: IOSDeviceLogSource.idevicesyslog,
);
}
// Use `ios-deploy` to stream logs from the device when the device is not a
// CoreDevice and has iOS 13 or greater.
// When using `ios-deploy` and the Dart VM, prefer the more complete logs
// from the attached debugger, if available.
if (_connectedVmService != null &&
(_iosDeployDebugger == null || !_iosDeployDebugger!.debuggerAttached)) {
return _IOSDeviceLogSources(
primarySource: IOSDeviceLogSource.unifiedLogging,
fallbackSource: IOSDeviceLogSource.iosDeploy,
);
}
return _IOSDeviceLogSources(
primarySource: IOSDeviceLogSource.iosDeploy,
fallbackSource: IOSDeviceLogSource.unifiedLogging,
);
}
/// Whether `idevicesyslog` is used as either the primary or fallback source for device logs.
@visibleForTesting
bool get useSyslogLogging {
return logSources.primarySource == IOSDeviceLogSource.idevicesyslog ||
logSources.fallbackSource == IOSDeviceLogSource.idevicesyslog;
}
/// Whether the Dart VM is used as either the primary or fallback source for device logs.
///
/// Unified Logging only works after the Dart VM has been connected to.
@visibleForTesting
bool get useUnifiedLogging {
return logSources.primarySource == IOSDeviceLogSource.unifiedLogging ||
logSources.fallbackSource == IOSDeviceLogSource.unifiedLogging;
}
/// Whether `ios-deploy` is used as either the primary or fallback source for device logs.
@visibleForTesting
bool get useIOSDeployLogging {
return logSources.primarySource == IOSDeviceLogSource.iosDeploy ||
logSources.fallbackSource == IOSDeviceLogSource.iosDeploy;
}
/// Listen to Dart VM for logs on iOS 13 or greater.
Future<void> _listenToUnifiedLoggingEvents(FlutterVmService connectedVmService) async {
if (!useUnifiedLogging) {
return;
}
try {
// The VM service will not publish logging events unless the debug stream is being listened to.
// Listen to this stream as a side effect.
unawaited(connectedVmService.service.streamListen('Debug'));
await Future.wait(<Future<void>>[
connectedVmService.service.streamListen(vm_service.EventStreams.kStdout),
connectedVmService.service.streamListen(vm_service.EventStreams.kStderr),
]);
} on vm_service.RPCError {
// Do nothing, since the tool is already subscribed.
}
void logMessage(vm_service.Event event) {
final String message = processVmServiceMessage(event);
if (message.isNotEmpty) {
addToLinesController(message, IOSDeviceLogSource.unifiedLogging);
}
}
_loggingSubscriptions.addAll(<StreamSubscription<void>>[
connectedVmService.service.onStdoutEvent.listen(logMessage),
connectedVmService.service.onStderrEvent.listen(logMessage),
]);
}
/// Log reader will listen to [debugger.logLines] and will detach debugger on dispose.
IOSDeployDebugger? get debuggerStream => _iosDeployDebugger;
/// Send messages from ios-deploy debugger stream to device log reader stream.
set debuggerStream(IOSDeployDebugger? debugger) {
// Logging is gathered from syslog on iOS earlier than 13.
if (!useIOSDeployLogging) {
return;
}
_iosDeployDebugger = debugger;
if (debugger == null) {
return;
}
// Add the debugger logs to the controller created on initialization.
_loggingSubscriptions.add(
debugger.logLines.listen(
(String line) =>
addToLinesController(_debuggerLineHandler(line), IOSDeviceLogSource.iosDeploy),
onError: linesController.addError,
onDone: linesController.close,
cancelOnError: true,
),
);
}
IOSDeployDebugger? _iosDeployDebugger;
// Strip off the logging metadata (leave the category), or just echo the line.
String _debuggerLineHandler(String line) =>
_debuggerLoggingRegex.firstMatch(line)?.group(1) ?? line;
/// Start and listen to idevicesyslog to get device logs for iOS versions
/// prior to 13 or if [useBothLogDeviceReaders] is true.
void _listenToSysLog() {
if (!useSyslogLogging) {
return;
}
_iMobileDevice.startLogger(_deviceId, _isWirelesslyConnected).then<void>((Process process) {
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(_newSyslogLineHandler());
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(_newSyslogLineHandler());
process.exitCode.whenComplete(() {
if (!linesController.hasListener) {
return;
}
// When using both log readers, do not close the stream on exit.
// This is to allow ios-deploy to be the source of authority to close
// the stream.
if (useSyslogLogging && useIOSDeployLogging && debuggerStream != null) {
return;
}
linesController.close();
});
assert(idevicesyslogProcess == null);
idevicesyslogProcess = process;
});
}
@visibleForTesting
Process? idevicesyslogProcess;
// Returns a stateful line handler to properly capture multiline output.
//
// For multiline log messages, any line after the first is logged without
// any specific prefix. To properly capture those, we enter "printing" mode
// after matching a log line from the runner. When in printing mode, we print
// all lines until we find the start of another log message (from any app).
void Function(String line) _newSyslogLineHandler() {
bool printing = false;
return (String line) {
if (printing) {
if (!_anyLineRegex.hasMatch(line)) {
addToLinesController(decodeSyslog(line), IOSDeviceLogSource.idevicesyslog);
return;
}
printing = false;
}
final Match? match = _runnerLineRegex.firstMatch(line);
if (match != null) {
final String logLine = line.substring(match.end);
// Only display the log line after the initial device and executable information.
addToLinesController(decodeSyslog(logLine), IOSDeviceLogSource.idevicesyslog);
printing = true;
}
};
}
@override
void dispose() {
for (final StreamSubscription<void> loggingSubscription in _loggingSubscriptions) {
loggingSubscription.cancel();
}
idevicesyslogProcess?.kill();
_iosDeployDebugger?.detach();
}
}
enum IOSDeviceLogSource {
/// Gets logs from ios-deploy debugger.
iosDeploy,
/// Gets logs from idevicesyslog.
idevicesyslog,
/// Gets logs from the Dart VM Service.
unifiedLogging,
}
class _IOSDeviceLogSources {
_IOSDeviceLogSources({required this.primarySource, this.fallbackSource});
final IOSDeviceLogSource primarySource;
final IOSDeviceLogSource? fallbackSource;
}
/// A [DevicePortForwarder] specialized for iOS usage with iproxy.
class IOSDevicePortForwarder extends DevicePortForwarder {
/// Create a new [IOSDevicePortForwarder].
IOSDevicePortForwarder({
required Logger logger,
required String id,
required IProxy iproxy,
required OperatingSystemUtils operatingSystemUtils,
}) : _logger = logger,
_id = id,
_iproxy = iproxy,
_operatingSystemUtils = operatingSystemUtils;
/// Create a [IOSDevicePortForwarder] for testing.
///
/// This specifies the path to iproxy as 'iproxy` and the dyLdLibEntry as
/// 'DYLD_LIBRARY_PATH: /path/to/libs'.
///
/// The device id may be provided, but otherwise defaults to '1234'.
factory IOSDevicePortForwarder.test({
required ProcessManager processManager,
required Logger logger,
String? id,
required OperatingSystemUtils operatingSystemUtils,
}) {
return IOSDevicePortForwarder(
logger: logger,
iproxy: IProxy.test(logger: logger, processManager: processManager),
id: id ?? '1234',
operatingSystemUtils: operatingSystemUtils,
);
}
final Logger _logger;
final String _id;
final IProxy _iproxy;
final OperatingSystemUtils _operatingSystemUtils;
@override
List<ForwardedPort> forwardedPorts = <ForwardedPort>[];
@visibleForTesting
void addForwardedPorts(List<ForwardedPort> ports) {
ports.forEach(forwardedPorts.add);
}
static const Duration _kiProxyPortForwardTimeout = Duration(seconds: 1);
@override
Future<int> forward(int devicePort, {int? hostPort}) async {
final bool autoselect = hostPort == null || hostPort == 0;
if (autoselect) {
final int freePort = await _operatingSystemUtils.findFreePort();
// Dynamic port range 49152 - 65535.
hostPort = freePort == 0 ? 49152 : freePort;
}
Process? process;
bool connected = false;
while (!connected) {
_logger.printTrace('Attempting to forward device port $devicePort to host port $hostPort');
process = await _iproxy.forward(devicePort, hostPort!, _id);
// TODO(ianh): This is a flaky race condition, https://github.com/libimobiledevice/libimobiledevice/issues/674
connected =
!await process.stdout.isEmpty.timeout(_kiProxyPortForwardTimeout, onTimeout: () => false);
if (!connected) {
process.kill();
if (autoselect) {
hostPort += 1;
if (hostPort > 65535) {
throw Exception('Could not find open port on host.');
}
} else {
throw Exception('Port $hostPort is not available.');
}
}
}
assert(connected);
assert(process != null);
final ForwardedPort forwardedPort = ForwardedPort.withContext(hostPort!, devicePort, process);
_logger.printTrace('Forwarded port $forwardedPort');
forwardedPorts.add(forwardedPort);
return hostPort;
}
@override
Future<void> unforward(ForwardedPort forwardedPort) async {
if (!forwardedPorts.remove(forwardedPort)) {
// Not in list. Nothing to remove.
return;
}
_logger.printTrace('Un-forwarding port $forwardedPort');
forwardedPort.dispose();
}
@override
Future<void> dispose() async {
for (final ForwardedPort forwardedPort in forwardedPorts) {
forwardedPort.dispose();
}
}
}
|