android_device.dart 28.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 '../android/android_sdk.dart';
11
import '../android/android_workflow.dart';
12
import '../android/apk.dart';
13
import '../application_package.dart';
14
import '../base/common.dart' show throwToolExit;
15
import '../base/file_system.dart';
16
import '../base/io.dart';
17
import '../base/logger.dart';
18
import '../base/port_scanner.dart';
19
import '../base/process.dart';
20
import '../base/process_manager.dart';
21
import '../base/utils.dart';
22
import '../build_info.dart';
23
import '../device.dart';
24
import '../globals.dart';
25
import '../protocol_discovery.dart';
26

27
import 'adb.dart';
28
import 'android.dart';
29
import 'android_sdk.dart';
30

31 32 33 34 35 36 37 38
enum _HardwareType { emulator, physical }

/// Map to help our `isLocalEmulator` detection.
const Map<String, _HardwareType> _knownHardware = const <String, _HardwareType>{
  'goldfish': _HardwareType.emulator,
  'qcom': _HardwareType.physical,
  'ranchu': _HardwareType.emulator,
  'samsungexynos7420': _HardwareType.physical,
39
  'samsungexynos7870': _HardwareType.physical,
40
  'samsungexynos8890': _HardwareType.physical,
41 42 43
  'samsungexynos8895': _HardwareType.physical,
};

44
class AndroidDevices extends PollingDeviceDiscovery {
45
  AndroidDevices() : super('Android devices');
46

47
  @override
48
  bool get supportsPlatform => true;
49

50
  @override
51
  bool get canListAnything => androidWorkflow.canListDevices;
52

53
  @override
54
  Future<List<Device>> pollingGetDevices() async => getAdbDevices();
55 56 57

  @override
  Future<List<String>> getDiagnostics() async => getAdbDeviceDiagnostics();
58 59
}

60
class AndroidDevice extends Device {
61 62 63 64
  AndroidDevice(
    String id, {
    this.productID,
    this.modelID,
65 66
    this.deviceCodeName
  }) : super(id);
67

68 69 70 71
  final String productID;
  final String modelID;
  final String deviceCodeName;

72
  Map<String, String> _properties;
73
  bool _isLocalEmulator;
74 75
  TargetPlatform _platform;

76
  Future<String> _getProperty(String name) async {
77 78
    if (_properties == null) {
      _properties = <String, String>{};
79

80
      final List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
81
      printTrace(propCommand.join(' '));
82 83

      try {
84
        // We pass an encoding of latin1 so that we don't try and interpret the
85
        // `adb shell getprop` result as UTF8.
86
        final ProcessResult result = await processManager.run(
87
          propCommand,
88 89
          stdoutEncoding: latin1,
          stderrEncoding: latin1,
90
        ).timeout(const Duration(seconds: 5));
91 92 93
        if (result.exitCode == 0) {
          _properties = parseAdbDeviceProperties(result.stdout);
        } else {
94 95
          printError('Error retrieving device properties for $name:');
          printError(result.stderr);
96
        }
97 98 99
      } on TimeoutException catch (_) {
        throwToolExit('adb not responding');
      } on ProcessException catch (error) {
100
        printError('Error retrieving device properties for $name: $error');
101 102
      }
    }
103

104 105
    return _properties[name];
  }
106

107
  @override
108
  Future<bool> get isLocalEmulator async {
109
    if (_isLocalEmulator == null) {
110 111 112 113 114 115 116 117 118 119 120
      final String hardware = await _getProperty('ro.hardware');
      printTrace('ro.hardware = $hardware');
      if (_knownHardware.containsKey(hardware)) {
        // Look for known hardware models.
        _isLocalEmulator = _knownHardware[hardware] == _HardwareType.emulator;
      } else {
        // Fall back to a best-effort heuristic-based approach.
        final String characteristics = await _getProperty('ro.build.characteristics');
        printTrace('ro.build.characteristics = $characteristics');
        _isLocalEmulator = characteristics != null && characteristics.contains('emulator');
      }
121 122 123 124 125
    }
    return _isLocalEmulator;
  }

  @override
126
  Future<TargetPlatform> get targetPlatform async {
127
    if (_platform == null) {
128
      // http://developer.android.com/ndk/guides/abis.html (x86, armeabi-v7a, ...)
129
      switch (await _getProperty('ro.product.cpu.abi')) {
130 131 132
        case 'arm64-v8a':
          _platform = TargetPlatform.android_arm64;
          break;
133 134 135 136 137 138 139 140 141
        case 'x86_64':
          _platform = TargetPlatform.android_x64;
          break;
        case 'x86':
          _platform = TargetPlatform.android_x86;
          break;
        default:
          _platform = TargetPlatform.android_arm;
          break;
142
      }
143 144
    }

145
    return _platform;
146
  }
147

148
  @override
149 150
  Future<String> get sdkNameAndVersion async =>
      'Android ${await _sdkVersion} (API ${await _apiVersion})';
151

152
  Future<String> get _sdkVersion => _getProperty('ro.build.version.release');
153

154
  Future<String> get _apiVersion => _getProperty('ro.build.version.sdk');
155

156
  _AdbLogReader _logReader;
157
  _AndroidDevicePortForwarder _portForwarder;
158

159
  List<String> adbCommandForDevice(List<String> args) {
160
    return <String>[getAdbPath(androidSdk), '-s', id]..addAll(args);
161 162 163 164
  }

  bool _isValidAdbVersion(String adbVersion) {
    // Sample output: 'Android Debug Bridge version 1.0.31'
165
    final Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
166
    if (versionFields != null) {
167 168 169
      final int majorVersion = int.parse(versionFields[1]);
      final int minorVersion = int.parse(versionFields[2]);
      final int patchVersion = int.parse(versionFields[3]);
170 171 172 173 174 175 176 177 178 179 180
      if (majorVersion > 1) {
        return true;
      }
      if (majorVersion == 1 && minorVersion > 0) {
        return true;
      }
      if (majorVersion == 1 && minorVersion == 0 && patchVersion >= 32) {
        return true;
      }
      return false;
    }
181
    printError(
182 183 184 185
        'Unrecognized adb version string $adbVersion. Skipping version check.');
    return true;
  }

186
  Future<bool> _checkForSupportedAdbVersion() async {
187 188 189
    if (androidSdk == null)
      return false;

190
    try {
191 192
      final RunResult adbVersion = await runCheckedAsync(<String>[getAdbPath(androidSdk), 'version']);
      if (_isValidAdbVersion(adbVersion.stdout))
193
        return true;
194
      printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.32 or later.');
195
    } catch (error, trace) {
196
      printError('Error running ADB: $error', stackTrace: trace);
197
    }
198

199 200 201
    return false;
  }

202
  Future<bool> _checkForSupportedAndroidVersion() async {
203 204 205 206 207
    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 *
208
      await runCheckedAsync(<String>[getAdbPath(androidSdk), 'start-server']);
209 210

      // Sample output: '22'
211
      final String sdkVersion = await _getProperty('ro.build.version.sdk');
212

213
      final int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
214
      if (sdkVersionParsed == null) {
215
        printError('Unexpected response from getprop: "$sdkVersion"');
216 217
        return false;
      }
218

219
      if (sdkVersionParsed < minApiLevel) {
220
        printError(
221 222 223 224
          'The Android version ($sdkVersion) on the target device is too old. Please '
          'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.');
        return false;
      }
225

226 227
      return true;
    } catch (e) {
228
      printError('Unexpected failure from adb: $e');
229
      return false;
230 231 232 233 234 235 236
    }
  }

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

237 238 239
  Future<String> _getDeviceApkSha1(ApplicationPackage app) async {
    final RunResult result = await runAsync(adbCommandForDevice(<String>['shell', 'cat', _getDeviceSha1Path(app)]));
    return result.stdout;
240 241
  }

242
  String _getSourceSha1(ApplicationPackage app) {
243 244
    final AndroidApk apk = app;
    final File shaFile = fs.file('${apk.apkPath}.sha1');
Devon Carew's avatar
Devon Carew committed
245
    return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
246 247
  }

248
  @override
249 250 251
  String get name => modelID;

  @override
252
  Future<bool> isAppInstalled(ApplicationPackage app) async {
253
    // This call takes 400ms - 600ms.
254 255 256 257 258 259 260
    try {
      final RunResult listOut = await runCheckedAsync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
      return LineSplitter.split(listOut.stdout).contains('package:${app.id}');
    } catch (error) {
      printTrace('$error');
      return false;
    }
261 262
  }

263
  @override
264 265
  Future<bool> isLatestBuildInstalled(ApplicationPackage app) async {
    final String installedSha1 = await _getDeviceApkSha1(app);
266 267 268
    return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app);
  }

269
  @override
270
  Future<bool> installApp(ApplicationPackage app) async {
271
    final AndroidApk apk = app;
272
    if (!fs.isFileSync(apk.apkPath)) {
273
      printError('"${apk.apkPath}" does not exist.');
274 275 276
      return false;
    }

277
    if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion())
278 279
      return false;

280
    final Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true);
281
    final RunResult installResult = await runAsync(adbCommandForDevice(<String>['install', '-r', apk.apkPath]));
Devon Carew's avatar
Devon Carew committed
282
    status.stop();
283 284
    // Some versions of adb exit with exit code 0 even on failure :(
    // Parsing the output to check for failures.
285
    final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
286
    final String failure = failureExp.stringMatch(installResult.stdout);
287 288 289 290
    if (failure != null) {
      printError('Package install error: $failure');
      return false;
    }
291 292
    if (installResult.exitCode != 0) {
      printError('Error: ADB exited with exit code ${installResult.exitCode}');
293
      printError('$installResult');
294 295
      return false;
    }
296

297 298 299
    await runCheckedAsync(adbCommandForDevice(<String>[
      'shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app)
    ]));
300 301 302
    return true;
  }

303
  @override
304
  Future<bool> uninstallApp(ApplicationPackage app) async {
305
    if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion())
306 307
      return false;

308
    final String uninstallOut = (await runCheckedAsync(adbCommandForDevice(<String>['uninstall', app.id]))).stdout;
309 310
    final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
    final String failure = failureExp.stringMatch(uninstallOut);
311 312 313 314 315 316 317 318
    if (failure != null) {
      printError('Package uninstall error: $failure');
      return false;
    }

    return true;
  }

319
  Future<bool> _installLatestApp(ApplicationPackage package) async {
320
    final bool wasInstalled = await isAppInstalled(package);
321
    if (wasInstalled) {
322
      if (await isLatestBuildInstalled(package)) {
323
        printTrace('Latest build already installed.');
324 325 326 327
        return true;
      }
    }
    printTrace('Installing APK.');
328
    if (!await installApp(package)) {
329 330 331
      printTrace('Warning: Failed to install APK.');
      if (wasInstalled) {
        printStatus('Uninstalling old version...');
332
        if (!await uninstallApp(package)) {
333 334 335
          printError('Error: Uninstalling old version failed.');
          return false;
        }
336
        if (!await installApp(package)) {
337 338 339 340 341
          printError('Error: Failed to install APK again.');
          return false;
        }
        return true;
      }
342 343 344 345 346
      return false;
    }
    return true;
  }

347 348
  @override
  Future<LaunchResult> startApp(
349
    ApplicationPackage package, {
350
    String mainPath,
351
    String route,
352 353
    DebuggingOptions debuggingOptions,
    Map<String, dynamic> platformArgs,
354 355
    bool prebuiltApplication: false,
    bool applicationNeedsRebuild: false,
356
    bool usesTerminalUi: true,
357
    bool ipv6: false,
358
  }) async {
359
    if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion())
360
      return new LaunchResult.failed();
361

362 363 364 365
    final TargetPlatform devicePlatform = await targetPlatform;
    if (!(devicePlatform == TargetPlatform.android_arm ||
          devicePlatform == TargetPlatform.android_arm64) &&
        !debuggingOptions.buildInfo.isDebug) {
366 367 368 369
      printError('Profile and release builds are only supported on ARM targets.');
      return new LaunchResult.failed();
    }

370 371 372 373
    BuildInfo buildInfo = debuggingOptions.buildInfo;
    if (buildInfo.targetPlatform == null && devicePlatform == TargetPlatform.android_arm64)
      buildInfo = buildInfo.withTargetPlatform(TargetPlatform.android_arm64);

374 375
    if (!prebuiltApplication) {
      printTrace('Building APK');
376
      await buildApk(
377
          target: mainPath,
378
          buildInfo: buildInfo,
379
      );
380 381
      // Package has been built, so we can get the updated application ID and
      // activity name from the .apk.
382
      package = await AndroidApk.fromCurrentDirectory();
383 384
    }

385 386 387
    printTrace("Stopping app '${package.name}' on $name.");
    await stopApp(package);

388
    if (!await _installLatestApp(package))
389
      return new LaunchResult.failed();
390

391 392 393
    final bool traceStartup = platformArgs['trace-startup'] ?? false;
    final AndroidApk apk = package;
    printTrace('$this startApp');
394

395
    ProtocolDiscovery observatoryDiscovery;
396

397
    if (debuggingOptions.debuggingEnabled) {
398
      // TODO(devoncarew): Remember the forwarding information (so we can later remove the
399
      // port forwarding or set it up again when adb fails on us).
400
      observatoryDiscovery = new ProtocolDiscovery.observatory(
401 402 403 404 405
        getLogReader(),
        portForwarder: portForwarder,
        hostPort: debuggingOptions.observatoryPort,
        ipv6: ipv6,
      );
Devon Carew's avatar
Devon Carew committed
406
    }
407

408 409
    List<String> cmd;

410 411 412
    cmd = adbCommandForDevice(<String>[
      'shell', 'am', 'start',
      '-a', 'android.intent.action.RUN',
413
      '-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP
414
      '--ez', 'enable-background-compilation', 'true',
415
      '--ez', 'enable-dart-profiling', 'true',
416
    ]);
417

418
    if (traceStartup)
419
      cmd.addAll(<String>['--ez', 'trace-startup', 'true']);
420
    if (route != null)
421
      cmd.addAll(<String>['--es', 'route', route]);
422 423
    if (debuggingOptions.enableSoftwareRendering)
      cmd.addAll(<String>['--ez', 'enable-software-rendering', 'true']);
424 425
    if (debuggingOptions.skiaDeterministicRendering)
      cmd.addAll(<String>['--ez', 'skia-deterministic-rendering', 'true']);
426 427
    if (debuggingOptions.traceSkia)
      cmd.addAll(<String>['--ez', 'trace-skia', 'true']);
428
    if (debuggingOptions.debuggingEnabled) {
429
      if (debuggingOptions.buildInfo.isDebug)
Devon Carew's avatar
Devon Carew committed
430
        cmd.addAll(<String>['--ez', 'enable-checked-mode', 'true']);
431
      if (debuggingOptions.startPaused)
Devon Carew's avatar
Devon Carew committed
432
        cmd.addAll(<String>['--ez', 'start-paused', 'true']);
433 434
      if (debuggingOptions.useTestFonts)
        cmd.addAll(<String>['--ez', 'use-test-fonts', 'true']);
Devon Carew's avatar
Devon Carew committed
435
    }
436
    cmd.add(apk.launchActivity);
437
    final String result = (await runCheckedAsync(cmd)).stdout;
438 439 440
    // This invocation returns 0 even when it fails.
    if (result.contains('Error: ')) {
      printError(result.trim());
Devon Carew's avatar
Devon Carew committed
441
      return new LaunchResult.failed();
442
    }
443

444
    if (!debuggingOptions.debuggingEnabled)
Devon Carew's avatar
Devon Carew committed
445
      return new LaunchResult.succeeded();
Devon Carew's avatar
Devon Carew committed
446

447 448 449
    // 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...');
450

451
    // TODO(danrubel) Waiting for observatory services can be made common across all devices.
452
    try {
453 454 455
      Uri observatoryUri;

      if (debuggingOptions.buildInfo.isDebug || debuggingOptions.buildInfo.isProfile) {
456
        observatoryUri = await observatoryDiscovery.uri;
Devon Carew's avatar
Devon Carew committed
457
      }
458

459
      return new LaunchResult.succeeded(observatoryUri: observatoryUri);
460 461 462 463
    } catch (error) {
      printError('Error waiting for a debug connection: $error');
      return new LaunchResult.failed();
    } finally {
464
      await observatoryDiscovery.cancel();
Devon Carew's avatar
Devon Carew committed
465
    }
466 467
  }

468 469 470
  @override
  bool get supportsHotMode => true;

471
  @override
472
  Future<bool> stopApp(ApplicationPackage app) {
473
    final List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
474
    return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
475 476
  }

477
  @override
478
  void clearLogs() {
479
    runSync(adbCommandForDevice(<String>['logcat', '-c']));
480 481
  }

482
  @override
483 484 485
  DeviceLogReader getLogReader({ApplicationPackage app}) {
    // The Android log reader isn't app-specific.
    _logReader ??= new _AdbLogReader(this);
486 487
    return _logReader;
  }
488

489
  @override
490
  DevicePortForwarder get portForwarder => _portForwarder ??= new _AndroidDevicePortForwarder(this);
491

492
  static final RegExp _timeRegExp = new RegExp(r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}', multiLine: true);
493

494
  /// Return the most recent timestamp in the Android log or null if there is
495
  /// no available timestamp. The format can be passed to logcat's -T option.
496
  String get lastLogcatTimestamp {
497
    final String output = runCheckedSync(adbCommandForDevice(<String>[
498
      'logcat', '-v', 'time', '-t', '1'
499
    ]));
500

501
    final Match timeMatch = _timeRegExp.firstMatch(output);
502
    return timeMatch?.group(0);
503 504
  }

505
  @override
506 507
  bool isSupported() => true;

Devon Carew's avatar
Devon Carew committed
508 509 510 511
  @override
  bool get supportsScreenshot => true;

  @override
512
  Future<Null> takeScreenshot(File outputFile) async {
Devon Carew's avatar
Devon Carew committed
513
    const String remotePath = '/data/local/tmp/flutter_screenshot.png';
514 515 516
    await runCheckedAsync(adbCommandForDevice(<String>['shell', 'screencap', '-p', remotePath]));
    await runCheckedAsync(adbCommandForDevice(<String>['pull', remotePath, outputFile.path]));
    await runCheckedAsync(adbCommandForDevice(<String>['shell', 'rm', remotePath]));
Devon Carew's avatar
Devon Carew committed
517
  }
518 519

  @override
520
  Future<List<DiscoveredApp>> discoverApps() async {
521 522 523 524
    final RegExp discoverExp = new RegExp(r'DISCOVER: (.*)');
    final List<DiscoveredApp> result = <DiscoveredApp>[];
    final StreamSubscription<String> logs = getLogReader().logLines.listen((String line) {
      final Match match = discoverExp.firstMatch(line);
525
      if (match != null) {
526
        final Map<String, dynamic> app = json.decode(match.group(1));
527
        result.add(new DiscoveredApp(app['id'], app['observatoryPort']));
528 529 530
      }
    });

531
    await runCheckedAsync(adbCommandForDevice(<String>[
532 533 534
      'shell', 'am', 'broadcast', '-a', 'io.flutter.view.DISCOVER'
    ]));

535 536 537 538
    await waitGroup<Null>(<Future<Null>>[
      new Future<Null>.delayed(const Duration(seconds: 1)),
      logs.cancel(),
    ]);
539
    return result;
540
  }
541
}
542

543
Map<String, String> parseAdbDeviceProperties(String str) {
544
  final Map<String, String> properties = <String, String>{};
545 546 547 548 549 550
  final RegExp propertyExp = new RegExp(r'\[(.*?)\]: \[(.*?)\]');
  for (Match match in propertyExp.allMatches(str))
    properties[match.group(1)] = match.group(2);
  return properties;
}

551
/// Return the list of connected ADB devices.
552 553 554 555 556
List<AndroidDevice> getAdbDevices() {
  final String adbPath = getAdbPath(androidSdk);
  if (adbPath == null)
    return <AndroidDevice>[];
  final String text = runSync(<String>[adbPath, 'devices', '-l']);
557
  final List<AndroidDevice> devices = <AndroidDevice>[];
558 559 560 561 562 563 564 565 566 567 568 569 570
  parseADBDeviceOutput(text, devices: devices);
  return devices;
}

/// Get diagnostics about issues with any connected devices.
Future<List<String>> getAdbDeviceDiagnostics() async {
  final String adbPath = getAdbPath(androidSdk);
  if (adbPath == null)
    return <String>[];

  final RunResult result = await runAsync(<String>[adbPath, 'devices', '-l']);
  if (result.exitCode != 0) {
    return <String>[];
571
  } else {
572 573 574 575
    final String text = result.stdout;
    final List<String> diagnostics = <String>[];
    parseADBDeviceOutput(text, diagnostics: diagnostics);
    return diagnostics;
576
  }
577 578 579 580
}

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

582 583 584 585 586 587 588 589
/// Parse the given `adb devices` output in [text], and fill out the given list
/// of devices and possible device issue diagnostics. Either argument can be null,
/// in which case information for that parameter won't be populated.
@visibleForTesting
void parseADBDeviceOutput(String text, {
  List<AndroidDevice> devices,
  List<String> diagnostics
}) {
590 591
  // Check for error messages from adb
  if (!text.contains('List of devices')) {
592 593
    diagnostics?.add(text);
    return;
594 595 596
  }

  for (String line in text.trim().split('\n')) {
597
    // Skip lines like: * daemon started successfully *
598 599 600
    if (line.startsWith('* daemon '))
      continue;

601
    // Skip lines about adb server and client version not matching
602
    if (line.startsWith(new RegExp(r'adb server (version|is out of date)'))) {
603
      diagnostics?.add(line);
604 605 606
      continue;
    }

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

610
    if (_kDeviceRegex.hasMatch(line)) {
611
      final Match match = _kDeviceRegex.firstMatch(line);
612

613 614
      final String deviceID = match[1];
      final String deviceState = match[2];
615 616
      String rest = match[3];

617
      final Map<String, String> info = <String, String>{};
618 619 620 621
      if (rest != null && rest.isNotEmpty) {
        rest = rest.trim();
        for (String data in rest.split(' ')) {
          if (data.contains(':')) {
622
            final List<String> fields = data.split(':');
623 624 625 626 627 628 629
            info[fields[0]] = fields[1];
          }
        }
      }

      if (info['model'] != null)
        info['model'] = cleanAdbDeviceName(info['model']);
630 631

      if (deviceState == 'unauthorized') {
632
        diagnostics?.add(
633 634 635 636
          'Device $deviceID is not authorized.\n'
          'You might need to check your device for an authorization dialog.'
        );
      } else if (deviceState == 'offline') {
637
        diagnostics?.add('Device $deviceID is offline.');
638
      } else {
639
        devices?.add(new AndroidDevice(
640 641 642 643 644
          deviceID,
          productID: info['product'],
          modelID: info['model'] ?? deviceID,
          deviceCodeName: info['device']
        ));
645
      }
646
    } else {
647
      diagnostics?.add(
648 649 650 651 652 653 654
        'Unexpected failure parsing device information from adb output:\n'
        '$line\n'
        'Please report a bug at https://github.com/flutter/flutter/issues/new');
    }
  }
}

655
/// A log reader that logs from `adb logcat`.
Devon Carew's avatar
Devon Carew committed
656
class _AdbLogReader extends DeviceLogReader {
Devon Carew's avatar
Devon Carew committed
657 658 659 660 661 662
  _AdbLogReader(this.device) {
    _linesController = new StreamController<String>.broadcast(
      onListen: _start,
      onCancel: _stop
    );
  }
Devon Carew's avatar
Devon Carew committed
663 664 665

  final AndroidDevice device;

Devon Carew's avatar
Devon Carew committed
666
  StreamController<String> _linesController;
667
  Process _process;
668

669
  @override
Devon Carew's avatar
Devon Carew committed
670
  Stream<String> get logLines => _linesController.stream;
671

672
  @override
673
  String get name => device.name;
Devon Carew's avatar
Devon Carew committed
674

675 676 677 678 679 680 681 682 683 684
  DateTime _timeOrigin;

  DateTime _adbTimestampToDateTime(String adbTimestamp) {
    // The adb timestamp format is: mm-dd hours:minutes:seconds.milliseconds
    // Dart's DateTime parse function accepts this format so long as we provide
    // the year, resulting in:
    // yyyy-mm-dd hours:minutes:seconds.milliseconds.
    return DateTime.parse('${new DateTime.now().year}-$adbTimestamp');
  }

Devon Carew's avatar
Devon Carew committed
685
  void _start() {
686
    // Start the adb logcat process.
687 688
    final List<String> args = <String>['logcat', '-v', 'time'];
    final String lastTimestamp = device.lastLogcatTimestamp;
689 690 691 692
    if (lastTimestamp != null)
        _timeOrigin = _adbTimestampToDateTime(lastTimestamp);
    else
        _timeOrigin = null;
693
    runCommand(device.adbCommandForDevice(args)).then<Null>((Process process) {
Devon Carew's avatar
Devon Carew committed
694
      _process = process;
695
      const Utf8Decoder decoder = const Utf8Decoder(allowMalformed: true);
696 697
      _process.stdout.transform(decoder).transform(const LineSplitter()).listen(_onLine);
      _process.stderr.transform(decoder).transform(const LineSplitter()).listen(_onLine);
698
      _process.exitCode.whenComplete(() {
Devon Carew's avatar
Devon Carew committed
699 700 701 702
        if (_linesController.hasListener)
          _linesController.close();
      });
    });
703 704
  }

705 706
  // 'W/ActivityManager(pid): '
  static final RegExp _logFormat = new RegExp(r'^[VDIWEF]\/.*?\(\s*(\d+)\):\s');
707 708 709

  static final List<RegExp> _whitelistedTags = <RegExp>[
    new RegExp(r'^[VDIWEF]\/flutter[^:]*:\s+', caseSensitive: false),
710
    new RegExp(r'^[IE]\/DartVM[^:]*:\s+'),
711
    new RegExp(r'^[WEF]\/AndroidRuntime:\s+'),
712
    new RegExp(r'^[WEF]\/ActivityManager:\s+.*(\bflutter\b|\bdomokit\b|\bsky\b)'),
713 714 715 716
    new RegExp(r'^[WEF]\/System\.err:\s+'),
    new RegExp(r'^[F]\/[\S^:]+:\s+')
  ];

717 718 719 720 721 722 723 724 725
  // 'F/libc(pid): Fatal signal 11'
  static final RegExp _fatalLog = new RegExp(r'^F\/libc\s*\(\s*\d+\):\sFatal signal (\d+)');

  // 'I/DEBUG(pid): ...'
  static final RegExp _tombstoneLine = new RegExp(r'^[IF]\/DEBUG\s*\(\s*\d+\):\s(.+)$');

  // 'I/DEBUG(pid): Tombstone written to: '
  static final RegExp _tombstoneTerminator = new RegExp(r'^Tombstone written to:\s');

726 727 728
  // we default to true in case none of the log lines match
  bool _acceptedLastLine = true;

729 730 731 732 733
  // Whether a fatal crash is happening or not.
  // During a fatal crash only lines from the crash are accepted, the rest are
  // dropped.
  bool _fatalCrash = false;

734 735 736
  // The format of the line is controlled by the '-v' parameter passed to
  // adb logcat. We are currently passing 'time', which has the format:
  // mm-dd hh:mm:ss.milliseconds Priority/Tag( PID): ....
737
  void _onLine(String line) {
738 739 740 741 742 743
    final Match timeMatch = AndroidDevice._timeRegExp.firstMatch(line);
    if (timeMatch == null) {
      return;
    }
    if (_timeOrigin != null) {
      final String timestamp = timeMatch.group(0);
744
      final DateTime time = _adbTimestampToDateTime(timestamp);
745
      if (!time.isAfter(_timeOrigin)) {
746 747 748 749 750 751 752 753 754
        // Ignore log messages before the origin.
        return;
      }
    }
    if (line.length == timeMatch.end) {
      return;
    }
    // Chop off the time.
    line = line.substring(timeMatch.end + 1);
755 756 757
    final Match logMatch = _logFormat.firstMatch(line);
    if (logMatch != null) {
      bool acceptLine = false;
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

      if (_fatalCrash) {
        // While a fatal crash is going on, only accept lines from the crash
        // Otherwise the crash log in the console may get interrupted

        final Match fatalMatch = _tombstoneLine.firstMatch(line);

        if (fatalMatch != null) {
          acceptLine = true;

          line = fatalMatch[1];

          if (_tombstoneTerminator.hasMatch(fatalMatch[1])) {
            // Hit crash terminator, stop logging the crash info
            _fatalCrash = false;
          }
        }
      } else if (appPid != null && int.parse(logMatch.group(1)) == appPid) {
776
        acceptLine = true;
777 778 779 780 781

        if (_fatalLog.hasMatch(line)) {
          // Hit fatal signal, app is now crashing
          _fatalCrash = true;
        }
782 783 784 785
      } else {
        // Filter on approved names and levels.
        acceptLine = _whitelistedTags.any((RegExp re) => re.hasMatch(line));
      }
786

787 788 789 790
      if (acceptLine) {
        _acceptedLastLine = true;
        _linesController.add(line);
        return;
791
      }
792 793 794 795 796
      _acceptedLastLine = false;
    } else if (line == '--------- beginning of system' ||
               line == '--------- beginning of main' ) {
      // hide the ugly adb logcat log boundaries at the start
      _acceptedLastLine = false;
797
    } else {
798 799 800
      // If it doesn't match the log pattern at all, then pass it through if we
      // passed the last matching line through. It might be a multiline message.
      if (_acceptedLastLine) {
801
        _linesController.add(line);
802 803
        return;
      }
804
    }
Devon Carew's avatar
Devon Carew committed
805 806
  }

Devon Carew's avatar
Devon Carew committed
807 808
  void _stop() {
    // TODO(devoncarew): We should remove adb port forwarding here.
Devon Carew's avatar
Devon Carew committed
809

Devon Carew's avatar
Devon Carew committed
810
    _process?.kill();
Devon Carew's avatar
Devon Carew committed
811 812
  }
}
813 814 815 816 817 818 819 820 821 822

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

  final AndroidDevice device;

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

823
  @override
824 825 826
  List<ForwardedPort> get forwardedPorts {
    final List<ForwardedPort> ports = <ForwardedPort>[];

827
    final String stdout = runCheckedSync(device.adbCommandForDevice(
828 829
      <String>['forward', '--list']
    ));
830

831
    final List<String> lines = LineSplitter.split(stdout).toList();
832 833
    for (String line in lines) {
      if (line.startsWith(device.id)) {
834
        final List<String> splitLine = line.split('tcp:');
835 836 837 838 839 840

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

        // Attempt to extract ports.
841 842
        final int hostPort = _extractPort(splitLine[1]);
        final int devicePort = _extractPort(splitLine[2]);
843 844 845 846 847 848 849 850 851 852 853 854

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

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

    return ports;
  }

855
  @override
856
  Future<int> forward(int devicePort, { int hostPort }) async {
857 858
    if ((hostPort == null) || (hostPort == 0)) {
      // Auto select host port.
859
      hostPort = await portScanner.findAvailablePort();
860 861
    }

862
    await runCheckedAsync(device.adbCommandForDevice(
863 864
      <String>['forward', 'tcp:$hostPort', 'tcp:$devicePort']
    ));
865 866 867 868

    return hostPort;
  }

869
  @override
Ian Hickson's avatar
Ian Hickson committed
870
  Future<Null> unforward(ForwardedPort forwardedPort) async {
871
    await runCheckedAsync(device.adbCommandForDevice(
872 873
      <String>['forward', '--remove', 'tcp:${forwardedPort.hostPort}']
    ));
874 875
  }
}