devices.dart 19.4 KB
Newer Older
1 2 3 4 5
// Copyright 2016 The Chromium 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';
6
import 'dart:convert';
7

8 9
import 'package:meta/meta.dart';

10
import '../application_package.dart';
11
import '../base/file_system.dart';
12
import '../base/io.dart';
13
import '../base/logger.dart';
14
import '../base/platform.dart';
15
import '../base/process.dart';
16
import '../base/process_manager.dart';
17
import '../build_info.dart';
18 19
import '../device.dart';
import '../globals.dart';
20
import '../protocol_discovery.dart';
21
import 'code_signing.dart';
22
import 'ios_workflow.dart';
23 24
import 'mac.dart';

25
const String _kIdeviceinstallerInstructions =
26 27
    'To work with iOS devices, please install ideviceinstaller. To install, run:\n'
    'brew install ideviceinstaller.';
28

29
const Duration kPortForwardTimeout = Duration(seconds: 10);
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
class IOSDeploy {
  const IOSDeploy();

  /// Installs and runs the specified app bundle using ios-deploy, then returns
  /// the exit code.
  Future<int> runApp({
    @required String deviceId,
    @required String bundlePath,
    @required List<String> launchArguments,
  }) async {
    final List<String> launchCommand = <String>[
      '/usr/bin/env',
      'ios-deploy',
      '--id',
      deviceId,
      '--bundle',
      bundlePath,
      '--no-wifi',
      '--justlaunch',
    ];
    if (launchArguments.isNotEmpty) {
      launchCommand.add('--args');
      launchCommand.add('${launchArguments.join(" ")}');
    }

    // Push /usr/bin to the front of PATH to pick up default system python, package 'six'.
    //
    // ios-deploy transitively depends on LLDB.framework, which invokes a
    // Python script that uses package 'six'. LLDB.framework relies on the
    // python at the front of the path, which may not include package 'six'.
    // Ensure that we pick up the system install of python, which does include
    // it.
63
    final Map<String, String> iosDeployEnv = Map<String, String>.from(platform.environment);
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
    iosDeployEnv['PATH'] = '/usr/bin:${iosDeployEnv['PATH']}';

    return await runCommandAndStreamOutput(
      launchCommand,
      mapFunction: _monitorInstallationFailure,
      trace: true,
      environment: iosDeployEnv,
    );
  }

  // Maps stdout line stream. Must return original line.
  String _monitorInstallationFailure(String stdout) {
    // Installation issues.
    if (stdout.contains('Error 0xe8008015') || stdout.contains('Error 0xe8000067')) {
      printError(noProvisioningProfileInstruction, emphasis: true);

    // Launch issues.
    } else if (stdout.contains('e80000e2')) {
      printError('''
═══════════════════════════════════════════════════════════════════════════════════
Your device is locked. Unlock your device first before running.
═══════════════════════════════════════════════════════════════════════════════════''',
      emphasis: true);
    } else if (stdout.contains('Error 0xe8000022')) {
      printError('''
═══════════════════════════════════════════════════════════════════════════════════
Error launching app. Try launching from within Xcode via:
    open ios/Runner.xcworkspace

Your Xcode version may be too old for your iOS version.
═══════════════════════════════════════════════════════════════════════════════════''',
      emphasis: true);
    }

    return stdout;
  }
}

102
class IOSDevices extends PollingDeviceDiscovery {
103
  IOSDevices() : super('iOS devices');
104

105
  @override
106
  bool get supportsPlatform => platform.isMacOS;
107

108
  @override
109
  bool get canListAnything => iosWorkflow.canListDevices;
110

111
  @override
112
  Future<List<Device>> pollingGetDevices() => IOSDevice.getAttachedDevices();
113 114 115
}

class IOSDevice extends Device {
116
  IOSDevice(String id, { this.name, String sdkVersion }) : _sdkVersion = sdkVersion, super(id) {
117
    _installerPath = _checkForCommand('ideviceinstaller');
118
    _iproxyPath = _checkForCommand('iproxy');
119 120 121
  }

  String _installerPath;
122
  String _iproxyPath;
123

124 125
  final String _sdkVersion;

126 127 128
  @override
  bool get supportsHotMode => true;

129
  @override
130 131
  final String name;

132
  Map<ApplicationPackage, _IOSDeviceLogReader> _logReaders;
133

134 135
  _IOSDevicePortForwarder _portForwarder;

136
  @override
137
  Future<bool> get isLocalEmulator async => false;
138

139
  @override
140 141
  bool get supportsStartPaused => false;

142
  static Future<List<IOSDevice>> getAttachedDevices() async {
143
    if (!iMobileDevice.isInstalled)
144 145
      return <IOSDevice>[];

146
    final List<IOSDevice> devices = <IOSDevice>[];
147 148 149 150 151 152 153
    for (String id in (await iMobileDevice.getAvailableDeviceIDs()).split('\n')) {
      id = id.trim();
      if (id.isEmpty)
        continue;

      final String deviceName = await iMobileDevice.getInfoForDevice(id, 'DeviceName');
      final String sdkVersion = await iMobileDevice.getInfoForDevice(id, 'ProductVersion');
154
      devices.add(IOSDevice(id, name: deviceName, sdkVersion: sdkVersion));
155 156 157 158 159 160
    }
    return devices;
  }

  static String _checkForCommand(
    String command, [
161
    String macInstructions = _kIdeviceinstallerInstructions
162
  ]) {
163 164 165
    try {
      command = runCheckedSync(<String>['which', command]).trim();
    } catch (e) {
166
      if (platform.isMacOS) {
167 168 169
        printError('$command not found. $macInstructions');
      } else {
        printError('Cannot control iOS devices or simulators. $command is not available on your platform.');
170
      }
171 172 173
      return null;
    }
    return command;
174 175 176
  }

  @override
177
  Future<bool> isAppInstalled(ApplicationPackage app) async {
178
    try {
179
      final RunResult apps = await runCheckedAsync(<String>[_installerPath, '--list-apps']);
180
      if (RegExp(app.id, multiLine: true).hasMatch(apps.stdout)) {
181 182
        return true;
      }
183 184 185 186 187 188
    } catch (e) {
      return false;
    }
    return false;
  }

189
  @override
190
  Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
191

192
  @override
193
  Future<bool> installApp(ApplicationPackage app) async {
194 195
    final IOSApp iosApp = app;
    final Directory bundle = fs.directory(iosApp.deviceBundlePath);
196
    if (!bundle.existsSync()) {
197
      printError('Could not find application bundle at ${bundle.path}; have you run "flutter build ios"?');
198 199 200 201
      return false;
    }

    try {
202
      await runCheckedAsync(<String>[_installerPath, '-i', iosApp.deviceBundlePath]);
203 204 205 206 207
      return true;
    } catch (e) {
      return false;
    }
  }
208 209

  @override
210
  Future<bool> uninstallApp(ApplicationPackage app) async {
211
    try {
212
      await runCheckedAsync(<String>[_installerPath, '-U', app.id]);
213
      return true;
214 215 216 217 218
    } catch (e) {
      return false;
    }
  }

219 220 221
  @override
  bool isSupported() => true;

222
  @override
Devon Carew's avatar
Devon Carew committed
223
  Future<LaunchResult> startApp(
224
    ApplicationPackage package, {
225 226
    String mainPath,
    String route,
Devon Carew's avatar
Devon Carew committed
227
    DebuggingOptions debuggingOptions,
228
    Map<String, dynamic> platformArgs,
229 230 231 232
    bool prebuiltApplication = false,
    bool applicationNeedsRebuild = false,
    bool usesTerminalUi = true,
    bool ipv6 = false,
233
  }) async {
234
    if (!prebuiltApplication) {
235
      // TODO(chinmaygarde): Use mainPath, route.
236
      printTrace('Building ${package.name} for $id');
237 238

      // Step 1: Build the precompiled/DBC application if necessary.
239
      final XcodeBuildResult buildResult = await buildXcodeProject(
240
          app: package,
241
          buildInfo: debuggingOptions.buildInfo,
242
          targetOverride: mainPath,
243 244 245
          buildForDevice: true,
          usesTerminalUi: usesTerminalUi,
      );
246 247
      if (!buildResult.success) {
        printError('Could not build the precompiled application for the device.');
xster's avatar
xster committed
248
        await diagnoseXcodeBuildFailure(buildResult);
249
        printError('');
250
        return LaunchResult.failed();
251
      }
252
    } else {
253
      if (!await installApp(package))
254
        return LaunchResult.failed();
255 256 257
    }

    // Step 2: Check that the application exists at the specified path.
258
    final IOSApp iosApp = package;
259
    final Directory bundle = fs.directory(iosApp.deviceBundlePath);
260
    if (!bundle.existsSync()) {
261
      printError('Could not find the built application bundle at ${bundle.path}.');
262
      return LaunchResult.failed();
263 264 265
    }

    // Step 3: Attempt to install the application on the device.
266
    final List<String> launchArguments = <String>['--enable-dart-profiling'];
267 268

    if (debuggingOptions.startPaused)
269
      launchArguments.add('--start-paused');
270

271
    if (debuggingOptions.useTestFonts)
272
      launchArguments.add('--use-test-fonts');
273

274
    if (debuggingOptions.debuggingEnabled)
275
      launchArguments.add('--enable-checked-mode');
276

277
    if (debuggingOptions.enableSoftwareRendering)
278 279
      launchArguments.add('--enable-software-rendering');

280 281 282
    if (debuggingOptions.skiaDeterministicRendering)
      launchArguments.add('--skia-deterministic-rendering');

283 284 285
    if (debuggingOptions.traceSkia)
      launchArguments.add('--trace-skia');

286 287 288
    if (platformArgs['trace-startup'] ?? false)
      launchArguments.add('--trace-startup');

289
    int installationResult = -1;
290
    Uri localObservatoryUri;
291

292 293
    final Status installStatus = logger.startProgress('Installing and launching...', expectSlowOperation: true);

294
    if (!debuggingOptions.debuggingEnabled) {
295
      // If debugging is not enabled, just launch the application and continue.
296
      printTrace('Debugging is not enabled');
297 298 299 300
      installationResult = await const IOSDeploy().runApp(
        deviceId: id,
        bundlePath: bundle.path,
        launchArguments: launchArguments,
301
      );
302
    } else {
303 304
      // Debugging is enabled, look for the observatory server port post launch.
      printTrace('Debugging is enabled, connecting to observatory');
305

306 307
      // TODO(danrubel): The Android device class does something similar to this code below.
      // The various Device subclasses should be refactored and common code moved into the superclass.
308
      final ProtocolDiscovery observatoryDiscovery = ProtocolDiscovery.observatory(
309
        getLogReader(app: package),
310 311 312 313
        portForwarder: portForwarder,
        hostPort: debuggingOptions.observatoryPort,
        ipv6: ipv6,
      );
314

315
      final Future<Uri> forwardObservatoryUri = observatoryDiscovery.uri;
316

317 318 319 320
      final Future<int> launch = const IOSDeploy().runApp(
        deviceId: id,
        bundlePath: bundle.path,
        launchArguments: launchArguments,
321
      );
322

323
      localObservatoryUri = await launch.then<Uri>((int result) async {
324 325 326
        installationResult = result;

        if (result != 0) {
327
          printTrace('Failed to launch the application on device.');
328
          return null;
329 330
        }

331
        printTrace('Application launched on the device. Waiting for observatory port.');
332
        return await forwardObservatoryUri;
333 334
      }).whenComplete(() {
        observatoryDiscovery.cancel();
335 336
      });
    }
337
    installStatus.stop();
338 339 340

    if (installationResult != 0) {
      printError('Could not install ${bundle.path} on $id.');
341
      printError('Try launching Xcode and selecting "Product > Run" to fix the problem:');
342
      printError('  open ios/Runner.xcworkspace');
343
      printError('');
344
      return LaunchResult.failed();
345 346
    }

347
    return LaunchResult.succeeded(observatoryUri: localObservatoryUri);
348 349
  }

350 351 352 353 354 355 356
  @override
  Future<bool> stopApp(ApplicationPackage app) async {
    // Currently we don't have a way to stop an app running on iOS.
    return false;
  }

  @override
357
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
358

359
  @override
360
  Future<String> get sdkNameAndVersion async => 'iOS $_sdkVersion';
361

362
  @override
363 364
  DeviceLogReader getLogReader({ApplicationPackage app}) {
    _logReaders ??= <ApplicationPackage, _IOSDeviceLogReader>{};
365
    return _logReaders.putIfAbsent(app, () => _IOSDeviceLogReader(this, app));
366 367
  }

368
  @override
369
  DevicePortForwarder get portForwarder => _portForwarder ??= _IOSDevicePortForwarder(this);
370

371
  @override
372 373
  void clearLogs() {
  }
Devon Carew's avatar
Devon Carew committed
374 375

  @override
376
  bool get supportsScreenshot => iMobileDevice.isInstalled;
Devon Carew's avatar
Devon Carew committed
377 378

  @override
379 380 381
  Future<Null> takeScreenshot(File outputFile) async {
    await iMobileDevice.takeScreenshot(outputFile);
  }
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
/// Decodes an 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.
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 {
411
    final List<int> bytes = utf8.encode(line);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    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;
      }
    }
435
    return utf8.decode(out);
436 437 438 439 440 441
  } catch (_) {
    // Unable to decode line: return as-is.
    return line;
  }
}

442
class _IOSDeviceLogReader extends DeviceLogReader {
443
  _IOSDeviceLogReader(this.device, ApplicationPackage app) {
444
    _linesController = StreamController<String>.broadcast(
445 446 447 448 449 450 451
      onListen: _start,
      onCancel: _stop
    );

    // Match for lines for the runner in syslog.
    //
    // iOS 9 format:  Runner[297] <Notice>:
452
    // iOS 10 format: Runner(Flutter)[297] <Notice>:
453
    final String appName = app == null ? '' : app.name.replaceAll('.app', '');
454
    _runnerLineRegex = RegExp(appName + r'(\(Flutter\))?\[[\d]+\] <[A-Za-z]+>: ');
455 456 457
    // 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.
458
    _anyLineRegex = RegExp(r'\w+(\([^)]*\))?\[\d+\] <[A-Za-z]+>: ');
Devon Carew's avatar
Devon Carew committed
459
  }
460 461 462

  final IOSDevice device;

463 464 465 466 467
  // Matches a syslog line from the runner.
  RegExp _runnerLineRegex;
  // Matches a syslog line from any app.
  RegExp _anyLineRegex;

Devon Carew's avatar
Devon Carew committed
468
  StreamController<String> _linesController;
469
  Process _process;
470

471
  @override
Devon Carew's avatar
Devon Carew committed
472
  Stream<String> get logLines => _linesController.stream;
473

474
  @override
475 476
  String get name => device.name;

Devon Carew's avatar
Devon Carew committed
477
  void _start() {
478
    iMobileDevice.startLogger().then<Null>((Process process) {
Devon Carew's avatar
Devon Carew committed
479
      _process = process;
480 481
      _process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newLineHandler());
      _process.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newLineHandler());
482
      _process.exitCode.whenComplete(() {
Devon Carew's avatar
Devon Carew committed
483 484 485 486
        if (_linesController.hasListener)
          _linesController.close();
      });
    });
487 488
  }

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
  // Returns a stateful line handler to properly capture multi-line output.
  //
  // For multi-line 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).
  Function _newLineHandler() {
    bool printing = false;

    return (String line) {
      if (printing) {
        if (!_anyLineRegex.hasMatch(line)) {
          _linesController.add(decodeSyslog(line));
          return;
        }
504

505 506 507 508 509 510 511 512 513 514 515 516 517
        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.
        _linesController.add(decodeSyslog(logLine));

        printing = true;
      }
    };
518 519
  }

Devon Carew's avatar
Devon Carew committed
520 521
  void _stop() {
    _process?.kill();
522 523
  }
}
524 525

class _IOSDevicePortForwarder extends DevicePortForwarder {
526
  _IOSDevicePortForwarder(this.device) : _forwardedPorts = <ForwardedPort>[];
527 528 529

  final IOSDevice device;

530 531
  final List<ForwardedPort> _forwardedPorts;

532
  @override
533
  List<ForwardedPort> get forwardedPorts => _forwardedPorts;
534

535
  static const Duration _kiProxyPortForwardTimeout = Duration(seconds: 1);
536

537
  @override
538
  Future<int> forward(int devicePort, {int hostPort}) async {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    final bool autoselect = hostPort == null || hostPort == 0;
    if (autoselect)
      hostPort = 1024;

    Process process;

    bool connected = false;
    while (!connected) {
      printTrace('attempting to forward device port $devicePort to host port $hostPort');
      // Usage: iproxy LOCAL_TCP_PORT DEVICE_TCP_PORT UDID
      process = await runCommand(<String>[
        device._iproxyPath,
        hostPort.toString(),
        devicePort.toString(),
        device.id,
      ]);
      // TODO(ianh): This is a flakey race condition, https://github.com/libimobiledevice/libimobiledevice/issues/674
      connected = !await process.stdout.isEmpty.timeout(_kiProxyPortForwardTimeout, onTimeout: () => false);
      if (!connected) {
        if (autoselect) {
          hostPort += 1;
          if (hostPort > 65535)
561
            throw Exception('Could not find open port on host.');
562
        } else {
563
          throw Exception('Port $hostPort is not available.');
564 565
        }
      }
566
    }
567 568
    assert(connected);
    assert(process != null);
569

570
    final ForwardedPort forwardedPort = ForwardedPort.withContext(
571 572
      hostPort, devicePort, process,
    );
573
    printTrace('Forwarded port $forwardedPort');
574
    _forwardedPorts.add(forwardedPort);
575
    return hostPort;
576 577
  }

578
  @override
Ian Hickson's avatar
Ian Hickson committed
579
  Future<Null> unforward(ForwardedPort forwardedPort) async {
580 581 582 583 584
    if (!_forwardedPorts.remove(forwardedPort)) {
      // Not in list. Nothing to remove.
      return null;
    }

585
    printTrace('Unforwarding port $forwardedPort');
586

587
    final Process process = forwardedPort.context;
588 589

    if (process != null) {
590
      processManager.killPid(process.pid);
591
    } else {
592
      printError('Forwarded port did not have a valid process');
593 594 595
    }

    return null;
596 597
  }
}