android_device.dart 16.5 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 54
  _AdbLogReader _logReader;

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

  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;
    }
78
    printError(
79 80 81 82
        'Unrecognized adb version string $adbVersion. Skipping version check.');
    return true;
  }

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

87
    try {
88 89
      String adbVersion = runCheckedSync(<String>[androidSdk.adbPath, 'version']);
      if (_isValidAdbVersion(adbVersion))
90
        return true;
91 92 93
      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);
94
    }
95

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

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

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

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

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

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

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

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

  String get name => modelID;

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

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

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

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

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

172 173 174 175 176 177 178
    if (port == 0) {
      // Auto-bind to a port. Set up forwarding for that port. Emit a stdout
      // message similar to the command-line VM so that tools can parse the output.
      // "Observatory listening on http://127.0.0.1:52111"
      port = await findAvailablePort();
    }

179
    try {
180
      // Set up port forwarding for observatory.
181 182 183 184
      runCheckedSync(adbCommandForDevice(<String>[
        'forward', 'tcp:$port', 'tcp:$observatoryDefaultPort'
      ]));

185 186
      if (portWasZero)
        printStatus('Observatory listening on http://127.0.0.1:$port');
187
    } catch (e) {
188
      printError('Unable to forward Observatory port $port: $e');
189 190 191
    }
  }

192
  Future<bool> startBundle(AndroidApk apk, String bundlePath, {
193 194 195
    bool checked: true,
    bool traceStartup: false,
    String route,
196 197 198 199
    bool clearLogs: false,
    bool startPaused: false,
    int debugPort: observatoryDefaultPort
  }) async {
200
    printTrace('$this startBundle');
201 202

    if (!FileSystemEntity.isFileSync(bundlePath)) {
203
      printError('Cannot find $bundlePath');
204 205 206
      return false;
    }

207
    await _forwardObservatoryPort(debugPort);
208 209 210 211

    if (clearLogs)
      this.clearLogs();

212
    runCheckedSync(adbCommandForDevice(<String>['push', bundlePath, _deviceBundlePath]));
213

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

  @override
  Future<bool> startApp(
    ApplicationPackage package,
    Toolchain toolchain, {
    String mainPath,
    String route,
    bool checked: true,
Devon Carew's avatar
Devon Carew committed
246
    bool clearLogs: false,
247 248
    bool startPaused: false,
    int debugPort: observatoryDefaultPort,
249
    Map<String, dynamic> platformArgs
250
  }) async {
251 252 253
    if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
      return false;

Devon Carew's avatar
Devon Carew committed
254
    String localBundlePath = await flx.buildFlx(
255 256
      toolchain,
      mainPath: mainPath
257 258 259 260
    );

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

Devon Carew's avatar
Devon Carew committed
261 262 263 264 265 266 267 268 269 270 271 272 273
    if (await startBundle(
      package,
      localBundlePath,
      checked: checked,
      traceStartup: platformArgs['trace-startup'],
      route: route,
      clearLogs: clearLogs,
      startPaused: startPaused,
      debugPort: debugPort
    )) {
      return true;
    } else {
      return false;
274
    }
275 276
  }

277 278 279
  Future<bool> stopApp(ApplicationPackage app) {
    List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
    return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
280 281 282 283 284 285
  }

  @override
  TargetPlatform get platform => TargetPlatform.android;

  void clearLogs() {
286
    runSync(adbCommandForDevice(<String>['logcat', '-c']));
287 288
  }

289 290 291 292 293
  DeviceLogReader get logReader {
    if (_logReader == null)
      _logReader = new _AdbLogReader(this);
    return _logReader;
  }
294 295

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

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

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

317
  Future<String> stopTracing(AndroidApk apk, { String outPath }) async {
318 319
    // Workaround for logcat -c not always working:
    // http://stackoverflow.com/questions/25645012/logcat-on-android-l-not-clearing-after-unplugging-and-reconnecting
320
    String beforeStop = lastLogcatTimestamp;
321
    runCheckedSync(adbCommandForDevice(<String>[
322 323 324 325 326 327 328 329 330 331 332 333 334
      '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);

    String tracePath = null;
    bool isComplete = false;
    while (!isComplete) {
335
      List<String> args = <String>['logcat', '-d'];
336 337 338
      if (beforeStop != null)
        args.addAll(<String>['-T', beforeStop]);
      String logs = runCheckedSync(adbCommandForDevice(args));
339 340 341 342 343 344 345 346 347
      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);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

      // 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]
      ));
365 366
      return localPath;
    }
367
    printError('No trace file detected. '
368 369 370 371
        'Did you remember to start the trace before stopping it?');
    return null;
  }

372 373
  bool isSupported() => true;

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  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;
  }
393
}
394

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

400
  List<AndroidDevice> devices = [];
401

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

  // 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+$');

413
  // Skip the first line, which is always 'List of devices attached'.
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  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)
432
        modelID = cleanAdbDeviceName(modelID);
433 434

      devices.add(new AndroidDevice(
435 436 437
        deviceID,
        productID: productID,
        modelID: modelID,
438
        deviceCodeName: deviceCodeName
439 440 441 442
      ));
    } else if (deviceRegex2.hasMatch(line)) {
      Match match = deviceRegex2.firstMatch(line);
      String deviceID = match[1];
443
      devices.add(new AndroidDevice(deviceID));
444 445 446
    } else if (unauthorizedRegex.hasMatch(line)) {
      Match match = unauthorizedRegex.firstMatch(line);
      String deviceID = match[1];
447
      printError(
448 449 450 451 452 453
        '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];
454
      printError('Device $deviceID is offline.');
455
    } else {
456
      printError(
457 458 459 460 461 462 463 464
        '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;
}

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

  final AndroidDevice device;

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

  Process _process;
  StreamSubscription _stdoutSubscription;
  StreamSubscription _stderrSubscription;

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

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

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

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

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

    // Start the adb logcat process.
491
    List<String> args = <String>['logcat', '-v', 'tag'];
492 493 494
    String lastTimestamp = device.lastLogcatTimestamp;
    if (lastTimestamp != null)
      args.addAll(<String>['-T', lastTimestamp]);
495
    args.addAll(<String>['-s', 'flutter:V', 'ActivityManager:W', 'System.err:W', '*:F']);
496
    _process = await runCommand(device.adbCommandForDevice(args));
497 498 499 500 501 502 503 504 505 506
    _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 {
507 508 509
    if (_process == null)
      throw new StateError('_AdbLogReader must be started before it can be stopped.');

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    _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
528 529 530 531 532 533 534
  }

  int get hashCode => name.hashCode;

  bool operator ==(dynamic other) {
    if (identical(this, other))
      return true;
535 536 537
    if (other is! _AdbLogReader)
      return false;
    return other.device.id == device.id;
Devon Carew's avatar
Devon Carew committed
538 539
  }
}