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

import 'package:path/path.dart' as path;

11
import '../android/android_sdk.dart';
12
import '../application_package.dart';
13 14
import '../base/common.dart';
import '../base/os.dart';
15 16 17 18
import '../base/process.dart';
import '../build_configuration.dart';
import '../device.dart';
import '../flx.dart' as flx;
19
import '../globals.dart';
20
import '../toolchain.dart';
21
import 'adb.dart';
22 23
import 'android.dart';

24 25
const String _defaultAdbPath = 'adb';

26 27 28 29 30 31
// 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';

32 33
class AndroidDevices extends PollingDeviceDiscovery {
  AndroidDevices() : super('AndroidDevices');
34 35

  bool get supportsPlatform => true;
36
  List<Device> pollingGetDevices() => getAdbDevices();
37 38
}

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

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

51 52
  bool get isLocalEmulator => false;

53
  _AdbLogReader _logReader;
54
  _AndroidDevicePortForwarder _portForwarder;
55

56
  List<String> adbCommandForDevice(List<String> args) {
57
    return <String>[androidSdk.adbPath, '-s', id]..addAll(args);
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  }

  bool _isValidAdbVersion(String adbVersion) {
    // Sample output: 'Android Debug Bridge version 1.0.31'
    Match versionFields =
        new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
    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;
    }
79
    printError(
80 81 82 83
        'Unrecognized adb version string $adbVersion. Skipping version check.');
    return true;
  }

84 85 86 87
  bool _checkForSupportedAdbVersion() {
    if (androidSdk == null)
      return false;

88
    try {
89 90
      String adbVersion = runCheckedSync(<String>[androidSdk.adbPath, 'version']);
      if (_isValidAdbVersion(adbVersion))
91
        return true;
92 93 94
      printError('The ADB at "${androidSdk.adbPath}" is too old; please install version 1.0.32 or later.');
    } catch (error, trace) {
      printError('Error running ADB: $error', trace);
95
    }
96

97 98 99 100 101 102 103 104 105
    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 *
106
      runCheckedSync(<String>[androidSdk.adbPath, 'start-server']);
107 108

      // Sample output: '22'
109 110 111
      String sdkVersion = runCheckedSync(
        adbCommandForDevice(<String>['shell', 'getprop', 'ro.build.version.sdk'])
      ).trimRight();
112

113
      int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
114
      if (sdkVersionParsed == null) {
115
        printError('Unexpected response from getprop: "$sdkVersion"');
116 117
        return false;
      }
118

119
      if (sdkVersionParsed < minApiLevel) {
120
        printError(
121 122 123 124
          'The Android version ($sdkVersion) on the target device is too old. Please '
          'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.');
        return false;
      }
125

126 127
      return true;
    } catch (e) {
128
      printError('Unexpected failure from adb: $e');
129
      return false;
130 131 132 133 134 135 136 137
    }
  }

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

  String _getDeviceApkSha1(ApplicationPackage app) {
138
    return runCheckedSync(adbCommandForDevice(<String>['shell', 'cat', _getDeviceSha1Path(app)]));
139 140 141
  }

  String _getSourceSha1(ApplicationPackage app) {
Devon Carew's avatar
Devon Carew committed
142 143
    File shaFile = new File('${app.localPath}.sha1');
    return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
144 145 146 147 148 149
  }

  String get name => modelID;

  @override
  bool isAppInstalled(ApplicationPackage app) {
Devon Carew's avatar
Devon Carew committed
150 151
    // Just check for the existence of the application SHA.
    return _getDeviceApkSha1(app) == _getSourceSha1(app);
152 153 154 155 156
  }

  @override
  bool installApp(ApplicationPackage app) {
    if (!FileSystemEntity.isFileSync(app.localPath)) {
157
      printError('"${app.localPath}" does not exist.');
158 159 160
      return false;
    }

161 162 163
    if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
      return false;

164 165 166
    printStatus('Installing ${app.name} on device.');
    runCheckedSync(adbCommandForDevice(<String>['install', '-r', app.localPath]));
    runCheckedSync(adbCommandForDevice(<String>['shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app)]));
167 168 169
    return true;
  }

170 171 172
  Future _forwardObservatoryPort(int port) async {
    bool portWasZero = port == 0;

173
    try {
174
      // Set up port forwarding for observatory.
175 176
      port = await portForwarder.forward(observatoryDefaultPort,
                                         hostPort: port);
177 178
      if (portWasZero)
        printStatus('Observatory listening on http://127.0.0.1:$port');
179
    } catch (e) {
180
      printError('Unable to forward Observatory port $port: $e');
181 182 183
    }
  }

184
  Future<bool> startBundle(AndroidApk apk, String bundlePath, {
185 186 187
    bool checked: true,
    bool traceStartup: false,
    String route,
188 189 190 191
    bool clearLogs: false,
    bool startPaused: false,
    int debugPort: observatoryDefaultPort
  }) async {
192
    printTrace('$this startBundle');
193 194

    if (!FileSystemEntity.isFileSync(bundlePath)) {
195
      printError('Cannot find $bundlePath');
196 197 198
      return false;
    }

199
    await _forwardObservatoryPort(debugPort);
200 201 202 203

    if (clearLogs)
      this.clearLogs();

204
    runCheckedSync(adbCommandForDevice(<String>['push', bundlePath, _deviceBundlePath]));
205

206
    List<String> cmd = adbCommandForDevice(<String>[
207 208
      'shell', 'am', 'start',
      '-a', 'android.intent.action.RUN',
209
      '-d', _deviceBundlePath,
210
      '-f', '0x20000000',  // FLAG_ACTIVITY_SINGLE_TOP
211
      '--ez', 'enable-background-compilation', 'true',
212 213
    ]);
    if (checked)
214
      cmd.addAll(<String>['--ez', 'enable-checked-mode', 'true']);
215
    if (traceStartup)
216
      cmd.addAll(<String>['--ez', 'trace-startup', 'true']);
217
    if (startPaused)
218
      cmd.addAll(<String>['--ez', 'start-paused', 'true']);
219
    if (route != null)
220
      cmd.addAll(<String>['--es', 'route', route]);
221
    cmd.add(apk.launchActivity);
222 223 224 225 226 227
    String result = runCheckedSync(cmd);
    // This invocation returns 0 even when it fails.
    if (result.contains('Error: ')) {
      printError(result.trim());
      return false;
    }
228 229 230 231 232 233 234 235 236 237
    return true;
  }

  @override
  Future<bool> startApp(
    ApplicationPackage package,
    Toolchain toolchain, {
    String mainPath,
    String route,
    bool checked: true,
Devon Carew's avatar
Devon Carew committed
238
    bool clearLogs: false,
239 240
    bool startPaused: false,
    int debugPort: observatoryDefaultPort,
241
    Map<String, dynamic> platformArgs
242
  }) async {
243 244 245
    if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
      return false;

Devon Carew's avatar
Devon Carew committed
246
    String localBundlePath = await flx.buildFlx(
247 248
      toolchain,
      mainPath: mainPath
249 250 251 252
    );

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

Devon Carew's avatar
Devon Carew committed
253 254 255 256 257 258 259 260 261 262 263 264 265
    if (await startBundle(
      package,
      localBundlePath,
      checked: checked,
      traceStartup: platformArgs['trace-startup'],
      route: route,
      clearLogs: clearLogs,
      startPaused: startPaused,
      debugPort: debugPort
    )) {
      return true;
    } else {
      return false;
266
    }
267 268
  }

269 270 271
  Future<bool> stopApp(ApplicationPackage app) {
    List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
    return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
272 273 274 275 276 277
  }

  @override
  TargetPlatform get platform => TargetPlatform.android;

  void clearLogs() {
278
    runSync(adbCommandForDevice(<String>['logcat', '-c']));
279 280
  }

281 282 283 284 285
  DeviceLogReader get logReader {
    if (_logReader == null)
      _logReader = new _AdbLogReader(this);
    return _logReader;
  }
286

287 288 289 290 291 292 293
  DevicePortForwarder get portForwarder {
    if (_portForwarder == null)
      _portForwarder = new _AndroidDevicePortForwarder(this);

    return _portForwarder;
  }

294
  void startTracing(AndroidApk apk) {
295
    runCheckedSync(adbCommandForDevice(<String>[
296 297 298 299 300 301 302 303
      'shell',
      'am',
      'broadcast',
      '-a',
      '${apk.id}.TRACING_START'
    ]));
  }

304 305
  /// 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.
306
  String get lastLogcatTimestamp {
307
    String output = runCheckedSync(adbCommandForDevice(<String>[
308
      'logcat', '-v', 'time', '-t', '1'
309
    ]));
310 311 312

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

316
  Future<String> stopTracing(AndroidApk apk, { String outPath }) async {
317 318
    // Workaround for logcat -c not always working:
    // http://stackoverflow.com/questions/25645012/logcat-on-android-l-not-clearing-after-unplugging-and-reconnecting
319
    String beforeStop = lastLogcatTimestamp;
320
    runCheckedSync(adbCommandForDevice(<String>[
321 322 323 324 325 326 327 328 329 330
      'shell',
      'am',
      'broadcast',
      '-a',
      '${apk.id}.TRACING_STOP'
    ]));

    RegExp traceRegExp = new RegExp(r'Saving trace to (\S+)', multiLine: true);
    RegExp completeRegExp = new RegExp(r'Trace complete', multiLine: true);

Ian Hickson's avatar
Ian Hickson committed
331
    String tracePath;
332 333
    bool isComplete = false;
    while (!isComplete) {
334
      List<String> args = <String>['logcat', '-d'];
335 336 337
      if (beforeStop != null)
        args.addAll(<String>['-T', beforeStop]);
      String logs = runCheckedSync(adbCommandForDevice(args));
338 339 340 341 342 343 344 345 346
      Match fileMatch = traceRegExp.firstMatch(logs);
      if (fileMatch != null && fileMatch[1] != null) {
        tracePath = fileMatch[1];
      }
      isComplete = completeRegExp.hasMatch(logs);
    }

    if (tracePath != null) {
      String localPath = (outPath != null) ? outPath : path.basename(tracePath);
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

      // Run cat via ADB to print the captured trace file.  (adb pull will be unable
      // to access the file if it does not have root permissions)
      IOSink catOutput = new File(localPath).openWrite();
      List<String> catCommand = adbCommandForDevice(
          <String>['shell', 'run-as', apk.id, 'cat', tracePath]
      );
      Process catProcess = await Process.start(catCommand[0],
          catCommand.getRange(1, catCommand.length).toList());
      catProcess.stdout.pipe(catOutput);
      int exitCode = await catProcess.exitCode;
      if (exitCode != 0)
        throw 'Error code $exitCode returned when running ${catCommand.join(" ")}';

      runSync(adbCommandForDevice(
          <String>['shell', 'run-as', apk.id, 'rm', tracePath]
      ));
364 365
      return localPath;
    }
366
    printError('No trace file detected. '
367 368 369 370
        'Did you remember to start the trace before stopping it?');
    return null;
  }

371 372
  bool isSupported() => true;

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
  Future<bool> refreshSnapshot(AndroidApk apk, String snapshotPath) async {
    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,
      apk.launchActivity,
    ]);
    runCheckedSync(cmd);
    return true;
  }
392
}
393

394
List<AndroidDevice> getAdbDevices() {
395 396
  String adbPath = getAdbPath(androidSdk);
  if (adbPath == null)
397
    return <AndroidDevice>[];
398

399
  List<AndroidDevice> devices = [];
400

401
  List<String> output = runSync(<String>[adbPath, 'devices', '-l']).trim().split('\n');
402 403 404 405 406 407 408 409 410 411

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

  // 0149947A0D01500C       device usb:340787200X
  RegExp deviceRegex2 = new RegExp(r'^(\S+)\s+device\s+\S+$');
  RegExp unauthorizedRegex = new RegExp(r'^(\S+)\s+unauthorized\s+\S+$');
  RegExp offlineRegex = new RegExp(r'^(\S+)\s+offline\s+\S+$');

412
  // Skip the first line, which is always 'List of devices attached'.
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  for (String line in output.skip(1)) {
    // Skip lines like:
    // * daemon not running. starting it now on port 5037 *
    // * daemon started successfully *
    if (line.startsWith('* daemon '))
      continue;

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

    if (deviceRegex1.hasMatch(line)) {
      Match match = deviceRegex1.firstMatch(line);
      String deviceID = match[1];
      String productID = match[2];
      String modelID = match[3];
      String deviceCodeName = match[4];

      if (modelID != null)
431
        modelID = cleanAdbDeviceName(modelID);
432 433

      devices.add(new AndroidDevice(
434 435 436
        deviceID,
        productID: productID,
        modelID: modelID,
437
        deviceCodeName: deviceCodeName
438 439 440 441
      ));
    } else if (deviceRegex2.hasMatch(line)) {
      Match match = deviceRegex2.firstMatch(line);
      String deviceID = match[1];
442
      devices.add(new AndroidDevice(deviceID));
443 444 445
    } else if (unauthorizedRegex.hasMatch(line)) {
      Match match = unauthorizedRegex.firstMatch(line);
      String deviceID = match[1];
446
      printError(
447 448 449 450 451 452
        'Device $deviceID is not authorized.\n'
        'You might need to check your device for an authorization dialog.'
      );
    } else if (offlineRegex.hasMatch(line)) {
      Match match = offlineRegex.firstMatch(line);
      String deviceID = match[1];
453
      printError('Device $deviceID is offline.');
454
    } else {
455
      printError(
456 457 458 459 460 461 462 463
        'Unexpected failure parsing device information from adb output:\n'
        '$line\n'
        'Please report a bug at https://github.com/flutter/flutter/issues/new');
    }
  }
  return devices;
}

464
/// A log reader that logs from `adb logcat`.
Devon Carew's avatar
Devon Carew committed
465 466 467 468 469
class _AdbLogReader extends DeviceLogReader {
  _AdbLogReader(this.device);

  final AndroidDevice device;

470 471 472 473 474 475 476 477 478
  final StreamController<String> _linesStreamController =
      new StreamController<String>.broadcast();

  Process _process;
  StreamSubscription _stdoutSubscription;
  StreamSubscription _stderrSubscription;

  Stream<String> get lines => _linesStreamController.stream;

479
  String get name => device.name;
Devon Carew's avatar
Devon Carew committed
480

481 482
  bool get isReading => _process != null;

483
  Future get finished => _process != null ? _process.exitCode : new Future.value(0);
484 485

  Future start() async {
486 487
    if (_process != null)
      throw new StateError('_AdbLogReader must be stopped before it can be started.');
488 489

    // Start the adb logcat process.
490
    List<String> args = <String>['logcat', '-v', 'tag'];
491 492 493
    String lastTimestamp = device.lastLogcatTimestamp;
    if (lastTimestamp != null)
      args.addAll(<String>['-T', lastTimestamp]);
494
    args.addAll(<String>['-s', 'flutter:V', 'ActivityManager:W', 'System.err:W', '*:F']);
495
    _process = await runCommand(device.adbCommandForDevice(args));
496 497 498 499 500 501 502 503 504 505
    _stdoutSubscription =
        _process.stdout.transform(UTF8.decoder)
                       .transform(const LineSplitter()).listen(_onLine);
    _stderrSubscription =
        _process.stderr.transform(UTF8.decoder)
                       .transform(const LineSplitter()).listen(_onLine);
    _process.exitCode.then(_onExit);
  }

  Future stop() async {
506 507 508
    if (_process == null)
      throw new StateError('_AdbLogReader must be started before it can be stopped.');

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    _stdoutSubscription?.cancel();
    _stdoutSubscription = null;
    _stderrSubscription?.cancel();
    _stderrSubscription = null;
    await _process.kill();
    _process = null;
  }

  void _onExit(int exitCode) {
    _stdoutSubscription?.cancel();
    _stdoutSubscription = null;
    _stderrSubscription?.cancel();
    _stderrSubscription = null;
    _process = null;
  }

  void _onLine(String line) {
    _linesStreamController.add(line);
Devon Carew's avatar
Devon Carew committed
527 528 529 530 531 532 533
  }

  int get hashCode => name.hashCode;

  bool operator ==(dynamic other) {
    if (identical(this, other))
      return true;
534 535 536
    if (other is! _AdbLogReader)
      return false;
    return other.device.id == device.id;
Devon Carew's avatar
Devon Carew committed
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

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

  final AndroidDevice device;

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

  List<ForwardedPort> get forwardedPorts {
    final List<ForwardedPort> ports = <ForwardedPort>[];

    String stdout = runCheckedSync(
      <String>[
        androidSdk.adbPath,
        'forward',
        '--list'
      ]);

    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;
  }

  Future<int> forward(int devicePort, {int hostPort: null}) async {
    if ((hostPort == null) || (hostPort == 0)) {
      // Auto select host port.
      hostPort = await findAvailablePort();
    }

    runCheckedSync(
      <String>[
        androidSdk.adbPath,
        'forward',
        'tcp:$hostPort',
        'tcp:$devicePort',
      ]);

    return hostPort;
  }

  Future unforward(ForwardedPort forwardedPort) async {
    runCheckedSync(
      <String>[
        androidSdk.adbPath,
        'forward',
        '--remove',
        'tcp:${forwardedPort.hostPort}'
      ]);
  }
}