android_device.dart 20.1 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
import 'dart:io';

9
import '../android/android_sdk.dart';
10
import '../application_package.dart';
11
import '../base/os.dart';
12
import '../base/process.dart';
13
import '../build_info.dart';
14 15
import '../device.dart';
import '../flx.dart' as flx;
16
import '../globals.dart';
17
import '../protocol_discovery.dart';
18
import 'adb.dart';
19
import 'android.dart';
20
import 'android_sdk.dart';
21

22 23
const String _defaultAdbPath = 'adb';

24 25 26 27 28 29
// Path where the FLX bundle will be copied on the device.
const String _deviceBundlePath = '/data/local/tmp/dev.flx';

// Path where the snapshot will be copied on the device.
const String _deviceSnapshotPath = '/data/local/tmp/dev_snapshot.bin';

30 31
class AndroidDevices extends PollingDeviceDiscovery {
  AndroidDevices() : super('AndroidDevices');
32

33
  @override
34
  bool get supportsPlatform => true;
35 36

  @override
37
  List<Device> pollingGetDevices() => getAdbDevices();
38 39
}

40
class AndroidDevice extends Device {
41 42 43 44
  AndroidDevice(
    String id, {
    this.productID,
    this.modelID,
45 46
    this.deviceCodeName
  }) : super(id);
47

48 49 50 51
  final String productID;
  final String modelID;
  final String deviceCodeName;

52
  Map<String, String> _properties;
53
  bool _isLocalEmulator;
54 55 56 57 58
  TargetPlatform _platform;

  String _getProperty(String name) {
    if (_properties == null) {
      _properties = <String, String>{};
59

60 61 62 63
      List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
      printTrace(propCommand.join(' '));
      ProcessResult result = Process.runSync(propCommand.first, propCommand.sublist(1));
      if (result.exitCode == 0) {
64
        RegExp propertyExp = new RegExp(r'\[(.*?)\]: \[(.*?)\]');
65 66 67 68
        for (Match match in propertyExp.allMatches(result.stdout))
          _properties[match.group(1)] = match.group(2);
      } else {
        printError('Error retrieving device properties for $name.');
69 70
      }
    }
71

72 73
    return _properties[name];
  }
74

75
  @override
76 77
  bool get isLocalEmulator {
    if (_isLocalEmulator == null) {
78 79 80 81 82 83 84 85 86
      String characteristics = _getProperty('ro.build.characteristics');
      _isLocalEmulator = characteristics != null && characteristics.contains('emulator');
    }
    return _isLocalEmulator;
  }

  @override
  TargetPlatform get platform {
    if (_platform == null) {
87
      // http://developer.android.com/ndk/guides/abis.html (x86, armeabi-v7a, ...)
88 89 90 91 92 93 94 95 96 97
      switch (_getProperty('ro.product.cpu.abi')) {
        case 'x86_64':
          _platform = TargetPlatform.android_x64;
          break;
        case 'x86':
          _platform = TargetPlatform.android_x86;
          break;
        default:
          _platform = TargetPlatform.android_arm;
          break;
98
      }
99 100
    }

101
    return _platform;
102
  }
103

104
  _AdbLogReader _logReader;
105
  _AndroidDevicePortForwarder _portForwarder;
106

107
  List<String> adbCommandForDevice(List<String> args) {
108
    return <String>[getAdbPath(androidSdk), '-s', id]..addAll(args);
109 110 111 112
  }

  bool _isValidAdbVersion(String adbVersion) {
    // Sample output: 'Android Debug Bridge version 1.0.31'
113
    Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    if (versionFields != null) {
      int majorVersion = int.parse(versionFields[1]);
      int minorVersion = int.parse(versionFields[2]);
      int patchVersion = int.parse(versionFields[3]);
      if (majorVersion > 1) {
        return true;
      }
      if (majorVersion == 1 && minorVersion > 0) {
        return true;
      }
      if (majorVersion == 1 && minorVersion == 0 && patchVersion >= 32) {
        return true;
      }
      return false;
    }
129
    printError(
130 131 132 133
        'Unrecognized adb version string $adbVersion. Skipping version check.');
    return true;
  }

134 135 136 137
  bool _checkForSupportedAdbVersion() {
    if (androidSdk == null)
      return false;

138
    try {
139
      String adbVersion = runCheckedSync(<String>[getAdbPath(androidSdk), 'version']);
140
      if (_isValidAdbVersion(adbVersion))
141
        return true;
142
      printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.32 or later.');
143 144
    } catch (error, trace) {
      printError('Error running ADB: $error', trace);
145
    }
146

147 148 149 150 151 152 153 154 155
    return false;
  }

  bool _checkForSupportedAndroidVersion() {
    try {
      // If the server is automatically restarted, then we get irrelevant
      // output lines like this, which we want to ignore:
      //   adb server is out of date.  killing..
      //   * daemon started successfully *
156
      runCheckedSync(<String>[getAdbPath(androidSdk), 'start-server']);
157 158

      // Sample output: '22'
159
      String sdkVersion = _getProperty('ro.build.version.sdk');
160

161
      int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
162
      if (sdkVersionParsed == null) {
163
        printError('Unexpected response from getprop: "$sdkVersion"');
164 165
        return false;
      }
166

167
      if (sdkVersionParsed < minApiLevel) {
168
        printError(
169 170 171 172
          'The Android version ($sdkVersion) on the target device is too old. Please '
          'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.');
        return false;
      }
173

174 175
      return true;
    } catch (e) {
176
      printError('Unexpected failure from adb: $e');
177
      return false;
178 179 180 181 182 183 184 185
    }
  }

  String _getDeviceSha1Path(ApplicationPackage app) {
    return '/data/local/tmp/sky.${app.id}.sha1';
  }

  String _getDeviceApkSha1(ApplicationPackage app) {
186
    return runCheckedSync(adbCommandForDevice(<String>['shell', 'cat', _getDeviceSha1Path(app)]));
187 188 189
  }

  String _getSourceSha1(ApplicationPackage app) {
Devon Carew's avatar
Devon Carew committed
190 191
    File shaFile = new File('${app.localPath}.sha1');
    return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
192 193
  }

194
  @override
195 196 197 198
  String get name => modelID;

  @override
  bool isAppInstalled(ApplicationPackage app) {
199
    // This call takes 400ms - 600ms.
200 201
    String listOut = runCheckedSync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
    if (!LineSplitter.split(listOut).contains("package:${app.id}"))
202 203 204
      return false;

    // Check the application SHA.
Devon Carew's avatar
Devon Carew committed
205
    return _getDeviceApkSha1(app) == _getSourceSha1(app);
206 207 208 209 210
  }

  @override
  bool installApp(ApplicationPackage app) {
    if (!FileSystemEntity.isFileSync(app.localPath)) {
211
      printError('"${app.localPath}" does not exist.');
212 213 214
      return false;
    }

215 216 217
    if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
      return false;

218 219 220 221 222 223 224 225
    String installOut = runCheckedSync(adbCommandForDevice(<String>['install', '-r', app.localPath]));
    RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
    String failure = failureExp.stringMatch(installOut);
    if (failure != null) {
      printError('Package install error: $failure');
      return false;
    }

226
    runCheckedSync(adbCommandForDevice(<String>['shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app)]));
227 228 229
    return true;
  }

230
  Future<Null> _forwardPort(String service, int devicePort, int port) async {
231
    try {
232
      // Set up port forwarding for observatory.
Devon Carew's avatar
Devon Carew committed
233 234
      port = await portForwarder.forward(devicePort, hostPort: port);
      printStatus('$service listening on http://127.0.0.1:$port');
235
    } catch (e) {
236
      printError('Unable to forward port $port: $e');
237 238 239
    }
  }

Devon Carew's avatar
Devon Carew committed
240
  Future<LaunchResult> startBundle(AndroidApk apk, String bundlePath, {
241 242
    bool traceStartup: false,
    String route,
Devon Carew's avatar
Devon Carew committed
243
    DebuggingOptions options
244
  }) async {
245
    printTrace('$this startBundle');
246 247

    if (!FileSystemEntity.isFileSync(bundlePath)) {
248
      printError('Cannot find $bundlePath');
Devon Carew's avatar
Devon Carew committed
249
      return new LaunchResult.failed();
250 251
    }

252
    runCheckedSync(adbCommandForDevice(<String>['push', bundlePath, _deviceBundlePath]));
253

254 255
    ProtocolDiscovery observatoryDiscovery;
    ProtocolDiscovery diagnosticDiscovery;
256

Devon Carew's avatar
Devon Carew committed
257
    if (options.debuggingEnabled) {
258 259
      observatoryDiscovery = new ProtocolDiscovery(logReader, ProtocolDiscovery.kObservatoryService);
      diagnosticDiscovery = new ProtocolDiscovery(logReader, ProtocolDiscovery.kDiagnosticService);
Devon Carew's avatar
Devon Carew committed
260
    }
261

262
    List<String> cmd = adbCommandForDevice(<String>[
263 264
      'shell', 'am', 'start',
      '-a', 'android.intent.action.RUN',
265
      '-d', _deviceBundlePath,
266
      '-f', '0x20000000',  // FLAG_ACTIVITY_SINGLE_TOP
267
      '--ez', 'enable-background-compilation', 'true',
268 269
    ]);
    if (traceStartup)
270
      cmd.addAll(<String>['--ez', 'trace-startup', 'true']);
271
    if (route != null)
272
      cmd.addAll(<String>['--es', 'route', route]);
Devon Carew's avatar
Devon Carew committed
273
    if (options.debuggingEnabled) {
274
      if (options.buildMode == BuildMode.debug)
Devon Carew's avatar
Devon Carew committed
275 276 277 278
        cmd.addAll(<String>['--ez', 'enable-checked-mode', 'true']);
      if (options.startPaused)
        cmd.addAll(<String>['--ez', 'start-paused', 'true']);
    }
279
    cmd.add(apk.launchActivity);
280 281 282 283
    String result = runCheckedSync(cmd);
    // This invocation returns 0 even when it fails.
    if (result.contains('Error: ')) {
      printError(result.trim());
Devon Carew's avatar
Devon Carew committed
284
      return new LaunchResult.failed();
285
    }
286

Devon Carew's avatar
Devon Carew committed
287 288 289 290 291 292
    if (!options.debuggingEnabled) {
      return new LaunchResult.succeeded();
    } else {
      // Wait for the service protocol port here. This will complete once the
      // device has printed "Observatory is listening on...".
      printTrace('Waiting for observatory port to be available...');
Devon Carew's avatar
Devon Carew committed
293

Devon Carew's avatar
Devon Carew committed
294 295 296 297 298 299 300 301 302 303
      try {
        Future<List<int>> scrapeServicePorts = Future.wait(
          <Future<int>>[observatoryDiscovery.nextPort(), diagnosticDiscovery.nextPort()]
        );
        List<int> devicePorts = await scrapeServicePorts.timeout(new Duration(seconds: 20));
        int observatoryDevicePort = devicePorts[0];
        printTrace('observatory port = $observatoryDevicePort');
        int observatoryLocalPort = await options.findBestObservatoryPort();
        // TODO(devoncarew): Remember the forwarding information (so we can later remove the
        // port forwarding).
304
        await _forwardPort(ProtocolDiscovery.kObservatoryService, observatoryDevicePort, observatoryLocalPort);
Devon Carew's avatar
Devon Carew committed
305 306 307
        int diagnosticDevicePort = devicePorts[1];
        printTrace('diagnostic port = $diagnosticDevicePort');
        int diagnosticLocalPort = await options.findBestDiagnosticPort();
308
        await _forwardPort(ProtocolDiscovery.kDiagnosticService, diagnosticDevicePort, diagnosticLocalPort);
Devon Carew's avatar
Devon Carew committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322
        return new LaunchResult.succeeded(
          observatoryPort: observatoryLocalPort,
          diagnosticPort: diagnosticLocalPort
        );
      } catch (error) {
        if (error is TimeoutException)
          printError('Timed out while waiting for a debug connection.');
        else
          printError('Error waiting for a debug connection: $error');
        return new LaunchResult.failed();
      } finally {
        observatoryDiscovery.cancel();
        diagnosticDiscovery.cancel();
      }
Devon Carew's avatar
Devon Carew committed
323
    }
324 325 326
  }

  @override
Devon Carew's avatar
Devon Carew committed
327
  Future<LaunchResult> startApp(
328 329
    ApplicationPackage package,
    BuildMode mode, {
330 331
    String mainPath,
    String route,
Devon Carew's avatar
Devon Carew committed
332
    DebuggingOptions debuggingOptions,
333
    Map<String, dynamic> platformArgs
334
  }) async {
335
    if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
Devon Carew's avatar
Devon Carew committed
336
      return new LaunchResult.failed();
337

Devon Carew's avatar
Devon Carew committed
338
    String localBundlePath = await flx.buildFlx(
339
      mainPath: mainPath,
340
      precompiledSnapshot: isAotBuildMode(debuggingOptions.buildMode),
341
      includeRobotoFonts: false
342
    );
343 344 345

    if (localBundlePath == null)
      return new LaunchResult.failed();
346 347 348

    printTrace('Starting bundle for $this.');

Devon Carew's avatar
Devon Carew committed
349
    return startBundle(
Devon Carew's avatar
Devon Carew committed
350 351 352 353
      package,
      localBundlePath,
      traceStartup: platformArgs['trace-startup'],
      route: route,
Devon Carew's avatar
Devon Carew committed
354 355
      options: debuggingOptions
    );
356 357
  }

358
  @override
359 360 361
  Future<bool> stopApp(ApplicationPackage app) {
    List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
    return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
362 363
  }

364
  @override
365
  void clearLogs() {
366
    runSync(adbCommandForDevice(<String>['logcat', '-c']));
367 368
  }

369
  @override
370 371 372 373 374
  DeviceLogReader get logReader {
    if (_logReader == null)
      _logReader = new _AdbLogReader(this);
    return _logReader;
  }
375

376
  @override
377 378 379 380 381 382 383
  DevicePortForwarder get portForwarder {
    if (_portForwarder == null)
      _portForwarder = new _AndroidDevicePortForwarder(this);

    return _portForwarder;
  }

384 385
  /// Return the most recent timestamp in the Android log or `null` if there is
  /// no available timestamp. The format can be passed to logcat's -T option.
386
  String get lastLogcatTimestamp {
387
    String output = runCheckedSync(adbCommandForDevice(<String>[
388
      'logcat', '-v', 'time', '-t', '1'
389
    ]));
390 391 392

    RegExp timeRegExp = new RegExp(r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}', multiLine: true);
    Match timeMatch = timeRegExp.firstMatch(output);
393
    return timeMatch?.group(0);
394 395
  }

396
  @override
397 398
  bool isSupported() => true;

399
  Future<bool> refreshSnapshot(String activity, String snapshotPath) async {
400 401 402 403 404 405 406 407 408 409 410 411 412
    if (!FileSystemEntity.isFileSync(snapshotPath)) {
      printError('Cannot find $snapshotPath');
      return false;
    }

    runCheckedSync(adbCommandForDevice(<String>['push', snapshotPath, _deviceSnapshotPath]));

    List<String> cmd = adbCommandForDevice(<String>[
      'shell', 'am', 'start',
      '-a', 'android.intent.action.RUN',
      '-d', _deviceBundlePath,
      '-f', '0x20000000',  // FLAG_ACTIVITY_SINGLE_TOP
      '--es', 'snapshot', _deviceSnapshotPath,
413
      activity,
414
    ]);
415 416 417 418 419 420 421 422

    RegExp errorRegExp = new RegExp(r'^Error: .*$', multiLine: true);
    Match errorMatch = errorRegExp.firstMatch(runCheckedSync(cmd));
    if (errorMatch != null) {
      printError(errorMatch.group(0));
      return false;
    }

423 424
    return true;
  }
Devon Carew's avatar
Devon Carew committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438

  @override
  bool get supportsScreenshot => true;

  @override
  Future<bool> takeScreenshot(File outputFile) {
    const String remotePath = '/data/local/tmp/flutter_screenshot.png';

    runCheckedSync(adbCommandForDevice(<String>['shell', 'screencap', '-p', remotePath]));
    runCheckedSync(adbCommandForDevice(<String>['pull', remotePath, outputFile.path]));
    runCheckedSync(adbCommandForDevice(<String>['shell', 'rm', remotePath]));

    return new Future<bool>.value(true);
  }
439
}
440

441 442 443
// 015d172c98400a03       device usb:340787200X product:nakasi model:Nexus_7 device:grouper
final RegExp _kDeviceRegex = new RegExp(r'^(\S+)\s+(\S+)(.*)');

444 445 446 447
/// Return the list of connected ADB devices.
///
/// [mockAdbOutput] is public for testing.
List<AndroidDevice> getAdbDevices({ String mockAdbOutput }) {
448
  List<AndroidDevice> devices = <AndroidDevice>[];
449 450 451 452 453 454 455 456 457 458
  List<String> output;

  if (mockAdbOutput == null) {
    String adbPath = getAdbPath(androidSdk);
    if (adbPath == null)
      return <AndroidDevice>[];
    output = runSync(<String>[adbPath, 'devices', '-l']).trim().split('\n');
  } else {
    output = mockAdbOutput.trim().split('\n');
  }
459

460 461
  for (String line in output) {
    // Skip lines like: * daemon started successfully *
462 463 464 465 466 467
    if (line.startsWith('* daemon '))
      continue;

    if (line.startsWith('List of devices'))
      continue;

468 469 470
    if (_kDeviceRegex.hasMatch(line)) {
      Match match = _kDeviceRegex.firstMatch(line);

471
      String deviceID = match[1];
472
      String deviceState = match[2];
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
      String rest = match[3];

      Map<String, String> info = <String, String>{};
      if (rest != null && rest.isNotEmpty) {
        rest = rest.trim();
        for (String data in rest.split(' ')) {
          if (data.contains(':')) {
            List<String> fields = data.split(':');
            info[fields[0]] = fields[1];
          }
        }
      }

      if (info['model'] != null)
        info['model'] = cleanAdbDeviceName(info['model']);
488 489 490 491 492 493 494 495 496

      if (deviceState == 'unauthorized') {
        printError(
          'Device $deviceID is not authorized.\n'
          'You might need to check your device for an authorization dialog.'
        );
      } else if (deviceState == 'offline') {
        printError('Device $deviceID is offline.');
      } else {
497 498 499 500 501 502
        devices.add(new AndroidDevice(
          deviceID,
          productID: info['product'],
          modelID: info['model'] ?? deviceID,
          deviceCodeName: info['device']
        ));
503
      }
504
    } else {
505
      printError(
506 507 508 509 510
        'Unexpected failure parsing device information from adb output:\n'
        '$line\n'
        'Please report a bug at https://github.com/flutter/flutter/issues/new');
    }
  }
511

512 513 514
  return devices;
}

515
/// A log reader that logs from `adb logcat`.
Devon Carew's avatar
Devon Carew committed
516
class _AdbLogReader extends DeviceLogReader {
Devon Carew's avatar
Devon Carew committed
517 518 519 520 521 522
  _AdbLogReader(this.device) {
    _linesController = new StreamController<String>.broadcast(
      onListen: _start,
      onCancel: _stop
    );
  }
Devon Carew's avatar
Devon Carew committed
523 524 525

  final AndroidDevice device;

526 527
  bool _lastWasFiltered = false;

Devon Carew's avatar
Devon Carew committed
528
  StreamController<String> _linesController;
529 530
  Process _process;

531
  @override
Devon Carew's avatar
Devon Carew committed
532
  Stream<String> get logLines => _linesController.stream;
533

534
  @override
535
  String get name => device.name;
Devon Carew's avatar
Devon Carew committed
536

Devon Carew's avatar
Devon Carew committed
537
  void _start() {
538
    // Start the adb logcat process.
539
    List<String> args = <String>['logcat', '-v', 'tag'];
540 541 542
    String lastTimestamp = device.lastLogcatTimestamp;
    if (lastTimestamp != null)
      args.addAll(<String>['-T', lastTimestamp]);
Devon Carew's avatar
Devon Carew committed
543 544 545 546 547 548 549 550 551 552
    runCommand(device.adbCommandForDevice(args)).then((Process process) {
      _process = process;
      _process.stdout.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);
      _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()).listen(_onLine);

      _process.exitCode.then((int code) {
        if (_linesController.hasListener)
          _linesController.close();
      });
    });
553 554
  }

555 556 557 558 559 560 561 562 563 564 565
  // 'W/ActivityManager: '
  static final RegExp _logFormat = new RegExp(r'^[VDIWEF]\/[^:]+:\s+');

  static final List<RegExp> _whitelistedTags = <RegExp>[
    new RegExp(r'^[VDIWEF]\/flutter[^:]*:\s+', caseSensitive: false),
    new RegExp(r'^[WEF]\/AndroidRuntime:\s+'),
    new RegExp(r'^[WEF]\/ActivityManager:\s+'),
    new RegExp(r'^[WEF]\/System\.err:\s+'),
    new RegExp(r'^[F]\/[\S^:]+:\s+')
  ];

566
  void _onLine(String line) {
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    if (_logFormat.hasMatch(line)) {
      // Filter out some noisy ActivityManager notifications.
      if (line.startsWith('W/ActivityManager: getRunningAppProcesses'))
        return;

      // Filter on approved names and levels.
      for (RegExp regex in _whitelistedTags) {
        if (regex.hasMatch(line)) {
          _lastWasFiltered = false;
          _linesController.add(line);
          return;
        }
      }

      _lastWasFiltered = true;
    } else {
      // If it doesn't match the log pattern at all, pass it through.
      if (!_lastWasFiltered)
        _linesController.add(line);
    }
Devon Carew's avatar
Devon Carew committed
587 588
  }

Devon Carew's avatar
Devon Carew committed
589 590
  void _stop() {
    // TODO(devoncarew): We should remove adb port forwarding here.
Devon Carew's avatar
Devon Carew committed
591

Devon Carew's avatar
Devon Carew committed
592
    _process?.kill();
Devon Carew's avatar
Devon Carew committed
593 594
  }
}
595 596 597 598 599 600 601 602 603 604

class _AndroidDevicePortForwarder extends DevicePortForwarder {
  _AndroidDevicePortForwarder(this.device);

  final AndroidDevice device;

  static int _extractPort(String portString) {
    return int.parse(portString.trim(), onError: (_) => null);
  }

605
  @override
606 607 608
  List<ForwardedPort> get forwardedPorts {
    final List<ForwardedPort> ports = <ForwardedPort>[];

609 610 611
    String stdout = runCheckedSync(device.adbCommandForDevice(
      <String>['forward', '--list']
    ));
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

    List<String> lines = LineSplitter.split(stdout).toList();
    for (String line in lines) {
      if (line.startsWith(device.id)) {
        List<String> splitLine = line.split("tcp:");

        // Sanity check splitLine.
        if (splitLine.length != 3)
          continue;

        // Attempt to extract ports.
        int hostPort = _extractPort(splitLine[1]);
        int devicePort = _extractPort(splitLine[2]);

        // Failed, skip.
        if ((hostPort == null) || (devicePort == null))
          continue;

        ports.add(new ForwardedPort(hostPort, devicePort));
      }
    }

    return ports;
  }

637
  @override
638
  Future<int> forward(int devicePort, { int hostPort }) async {
639 640 641 642 643
    if ((hostPort == null) || (hostPort == 0)) {
      // Auto select host port.
      hostPort = await findAvailablePort();
    }

644 645 646
    runCheckedSync(device.adbCommandForDevice(
      <String>['forward', 'tcp:$hostPort', 'tcp:$devicePort']
    ));
647 648 649 650

    return hostPort;
  }

651
  @override
Ian Hickson's avatar
Ian Hickson committed
652
  Future<Null> unforward(ForwardedPort forwardedPort) async {
653 654 655
    runCheckedSync(device.adbCommandForDevice(
      <String>['forward', '--remove', 'tcp:${forwardedPort.hostPort}']
    ));
656 657
  }
}