Am.java revision 8ffb0c0210857210a51d7a9a0f1afb73afbf8677
1/* 2** 3** Copyright 2007, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19package com.android.commands.am; 20 21import android.app.ActivityManager; 22import android.app.ActivityManagerNative; 23import android.app.IActivityController; 24import android.app.IActivityManager; 25import android.app.IInstrumentationWatcher; 26import android.app.Instrumentation; 27import android.content.ComponentName; 28import android.content.Context; 29import android.content.IIntentReceiver; 30import android.content.Intent; 31import android.net.Uri; 32import android.os.Bundle; 33import android.os.ParcelFileDescriptor; 34import android.os.RemoteException; 35import android.os.ServiceManager; 36import android.os.SystemProperties; 37import android.util.AndroidException; 38import android.view.IWindowManager; 39 40import java.io.BufferedReader; 41import java.io.File; 42import java.io.FileNotFoundException; 43import java.io.IOException; 44import java.io.InputStreamReader; 45import java.io.PrintStream; 46import java.net.URISyntaxException; 47import java.util.Iterator; 48import java.util.Set; 49 50public class Am { 51 52 private IActivityManager mAm; 53 private String[] mArgs; 54 private int mNextArg; 55 private String mCurArgData; 56 57 private boolean mDebugOption = false; 58 private boolean mWaitOption = false; 59 60 // These are magic strings understood by the Eclipse plugin. 61 private static final String FATAL_ERROR_CODE = "Error type 1"; 62 private static final String NO_SYSTEM_ERROR_CODE = "Error type 2"; 63 private static final String NO_CLASS_ERROR_CODE = "Error type 3"; 64 65 /** 66 * Command-line entry point. 67 * 68 * @param args The command-line arguments 69 */ 70 public static void main(String[] args) { 71 try { 72 (new Am()).run(args); 73 } catch (IllegalArgumentException e) { 74 showUsage(); 75 System.err.println("Error: " + e.getMessage()); 76 } catch (Exception e) { 77 System.err.println(e.toString()); 78 System.exit(1); 79 } 80 } 81 82 private void run(String[] args) throws Exception { 83 if (args.length < 1) { 84 showUsage(); 85 return; 86 } 87 88 mAm = ActivityManagerNative.getDefault(); 89 if (mAm == null) { 90 System.err.println(NO_SYSTEM_ERROR_CODE); 91 throw new AndroidException("Can't connect to activity manager; is the system running?"); 92 } 93 94 mArgs = args; 95 String op = args[0]; 96 mNextArg = 1; 97 98 if (op.equals("start")) { 99 runStart(); 100 } else if (op.equals("startservice")) { 101 runStartService(); 102 } else if (op.equals("force-stop")) { 103 runForceStop(); 104 } else if (op.equals("instrument")) { 105 runInstrument(); 106 } else if (op.equals("broadcast")) { 107 sendBroadcast(); 108 } else if (op.equals("profile")) { 109 runProfile(); 110 } else if (op.equals("dumpheap")) { 111 runDumpHeap(); 112 } else if (op.equals("monitor")) { 113 runMonitor(); 114 } else if (op.equals("screen-compat")) { 115 runScreenCompat(); 116 } else if (op.equals("display-size")) { 117 runDisplaySize(); 118 } else { 119 throw new IllegalArgumentException("Unknown command: " + op); 120 } 121 } 122 123 private Intent makeIntent() throws URISyntaxException { 124 Intent intent = new Intent(); 125 boolean hasIntentInfo = false; 126 127 mDebugOption = false; 128 mWaitOption = false; 129 Uri data = null; 130 String type = null; 131 132 String opt; 133 while ((opt=nextOption()) != null) { 134 if (opt.equals("-a")) { 135 intent.setAction(nextArgRequired()); 136 hasIntentInfo = true; 137 } else if (opt.equals("-d")) { 138 data = Uri.parse(nextArgRequired()); 139 hasIntentInfo = true; 140 } else if (opt.equals("-t")) { 141 type = nextArgRequired(); 142 hasIntentInfo = true; 143 } else if (opt.equals("-c")) { 144 intent.addCategory(nextArgRequired()); 145 hasIntentInfo = true; 146 } else if (opt.equals("-e") || opt.equals("--es")) { 147 String key = nextArgRequired(); 148 String value = nextArgRequired(); 149 intent.putExtra(key, value); 150 hasIntentInfo = true; 151 } else if (opt.equals("--esn")) { 152 String key = nextArgRequired(); 153 intent.putExtra(key, (String) null); 154 hasIntentInfo = true; 155 } else if (opt.equals("--ei")) { 156 String key = nextArgRequired(); 157 String value = nextArgRequired(); 158 intent.putExtra(key, Integer.valueOf(value)); 159 hasIntentInfo = true; 160 } else if (opt.equals("--eu")) { 161 String key = nextArgRequired(); 162 String value = nextArgRequired(); 163 intent.putExtra(key, Uri.parse(value)); 164 hasIntentInfo = true; 165 } else if (opt.equals("--eia")) { 166 String key = nextArgRequired(); 167 String value = nextArgRequired(); 168 String[] strings = value.split(","); 169 int[] list = new int[strings.length]; 170 for (int i = 0; i < strings.length; i++) { 171 list[i] = Integer.valueOf(strings[i]); 172 } 173 intent.putExtra(key, list); 174 hasIntentInfo = true; 175 } else if (opt.equals("--el")) { 176 String key = nextArgRequired(); 177 String value = nextArgRequired(); 178 intent.putExtra(key, Long.valueOf(value)); 179 hasIntentInfo = true; 180 } else if (opt.equals("--ela")) { 181 String key = nextArgRequired(); 182 String value = nextArgRequired(); 183 String[] strings = value.split(","); 184 long[] list = new long[strings.length]; 185 for (int i = 0; i < strings.length; i++) { 186 list[i] = Long.valueOf(strings[i]); 187 } 188 intent.putExtra(key, list); 189 hasIntentInfo = true; 190 } else if (opt.equals("--ez")) { 191 String key = nextArgRequired(); 192 String value = nextArgRequired(); 193 intent.putExtra(key, Boolean.valueOf(value)); 194 hasIntentInfo = true; 195 } else if (opt.equals("-n")) { 196 String str = nextArgRequired(); 197 ComponentName cn = ComponentName.unflattenFromString(str); 198 if (cn == null) throw new IllegalArgumentException("Bad component name: " + str); 199 intent.setComponent(cn); 200 hasIntentInfo = true; 201 } else if (opt.equals("-f")) { 202 String str = nextArgRequired(); 203 intent.setFlags(Integer.decode(str).intValue()); 204 } else if (opt.equals("--grant-read-uri-permission")) { 205 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 206 } else if (opt.equals("--grant-write-uri-permission")) { 207 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 208 } else if (opt.equals("--exclude-stopped-packages")) { 209 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 210 } else if (opt.equals("--include-stopped-packages")) { 211 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 212 } else if (opt.equals("--debug-log-resolution")) { 213 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 214 } else if (opt.equals("--activity-brought-to-front")) { 215 intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 216 } else if (opt.equals("--activity-clear-top")) { 217 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 218 } else if (opt.equals("--activity-clear-when-task-reset")) { 219 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 220 } else if (opt.equals("--activity-exclude-from-recents")) { 221 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 222 } else if (opt.equals("--activity-launched-from-history")) { 223 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 224 } else if (opt.equals("--activity-multiple-task")) { 225 intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 226 } else if (opt.equals("--activity-no-animation")) { 227 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 228 } else if (opt.equals("--activity-no-history")) { 229 intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 230 } else if (opt.equals("--activity-no-user-action")) { 231 intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); 232 } else if (opt.equals("--activity-previous-is-top")) { 233 intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 234 } else if (opt.equals("--activity-reorder-to-front")) { 235 intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 236 } else if (opt.equals("--activity-reset-task-if-needed")) { 237 intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 238 } else if (opt.equals("--activity-single-top")) { 239 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 240 } else if (opt.equals("--activity-clear-task")) { 241 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 242 } else if (opt.equals("--activity-task-on-home")) { 243 intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME); 244 } else if (opt.equals("--receiver-registered-only")) { 245 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 246 } else if (opt.equals("--receiver-replace-pending")) { 247 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 248 } else if (opt.equals("-D")) { 249 mDebugOption = true; 250 } else if (opt.equals("-W")) { 251 mWaitOption = true; 252 } else { 253 System.err.println("Error: Unknown option: " + opt); 254 showUsage(); 255 return null; 256 } 257 } 258 intent.setDataAndType(data, type); 259 260 String uri = nextArg(); 261 if (uri != null) { 262 Intent oldIntent = intent; 263 intent = Intent.parseUri(uri, 0); 264 if (oldIntent.getAction() != null) { 265 intent.setAction(oldIntent.getAction()); 266 } 267 if (oldIntent.getData() != null || oldIntent.getType() != null) { 268 intent.setDataAndType(oldIntent.getData(), oldIntent.getType()); 269 } 270 Set cats = oldIntent.getCategories(); 271 if (cats != null) { 272 Iterator it = cats.iterator(); 273 while (it.hasNext()) { 274 intent.addCategory((String)it.next()); 275 } 276 } 277 hasIntentInfo = true; 278 } 279 280 if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied"); 281 return intent; 282 } 283 284 private void runStartService() throws Exception { 285 Intent intent = makeIntent(); 286 System.out.println("Starting service: " + intent); 287 ComponentName cn = mAm.startService(null, intent, intent.getType()); 288 if (cn == null) { 289 System.err.println("Error: Not found; no service started."); 290 } 291 } 292 293 private void runStart() throws Exception { 294 Intent intent = makeIntent(); 295 System.out.println("Starting: " + intent); 296 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 297 // XXX should do something to determine the MIME type. 298 IActivityManager.WaitResult result = null; 299 int res; 300 if (mWaitOption) { 301 result = mAm.startActivityAndWait(null, intent, intent.getType(), 302 null, 0, null, null, 0, false, mDebugOption); 303 res = result.result; 304 } else { 305 res = mAm.startActivity(null, intent, intent.getType(), 306 null, 0, null, null, 0, false, mDebugOption); 307 } 308 PrintStream out = mWaitOption ? System.out : System.err; 309 boolean launched = false; 310 switch (res) { 311 case IActivityManager.START_SUCCESS: 312 launched = true; 313 break; 314 case IActivityManager.START_SWITCHES_CANCELED: 315 launched = true; 316 out.println( 317 "Warning: Activity not started because the " 318 + " current activity is being kept for the user."); 319 break; 320 case IActivityManager.START_DELIVERED_TO_TOP: 321 launched = true; 322 out.println( 323 "Warning: Activity not started, intent has " 324 + "been delivered to currently running " 325 + "top-most instance."); 326 break; 327 case IActivityManager.START_RETURN_INTENT_TO_CALLER: 328 launched = true; 329 out.println( 330 "Warning: Activity not started because intent " 331 + "should be handled by the caller"); 332 break; 333 case IActivityManager.START_TASK_TO_FRONT: 334 launched = true; 335 out.println( 336 "Warning: Activity not started, its current " 337 + "task has been brought to the front"); 338 break; 339 case IActivityManager.START_INTENT_NOT_RESOLVED: 340 out.println( 341 "Error: Activity not started, unable to " 342 + "resolve " + intent.toString()); 343 break; 344 case IActivityManager.START_CLASS_NOT_FOUND: 345 out.println(NO_CLASS_ERROR_CODE); 346 out.println("Error: Activity class " + 347 intent.getComponent().toShortString() 348 + " does not exist."); 349 break; 350 case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 351 out.println( 352 "Error: Activity not started, you requested to " 353 + "both forward and receive its result"); 354 break; 355 case IActivityManager.START_PERMISSION_DENIED: 356 out.println( 357 "Error: Activity not started, you do not " 358 + "have permission to access it."); 359 break; 360 default: 361 out.println( 362 "Error: Activity not started, unknown error code " + res); 363 break; 364 } 365 if (mWaitOption && launched) { 366 if (result == null) { 367 result = new IActivityManager.WaitResult(); 368 result.who = intent.getComponent(); 369 } 370 System.out.println("Status: " + (result.timeout ? "timeout" : "ok")); 371 if (result.who != null) { 372 System.out.println("Activity: " + result.who.flattenToShortString()); 373 } 374 if (result.thisTime >= 0) { 375 System.out.println("ThisTime: " + result.thisTime); 376 } 377 if (result.totalTime >= 0) { 378 System.out.println("TotalTime: " + result.totalTime); 379 } 380 System.out.println("Complete"); 381 } 382 } 383 384 private void runForceStop() throws Exception { 385 mAm.forceStopPackage(nextArgRequired()); 386 } 387 388 private void sendBroadcast() throws Exception { 389 Intent intent = makeIntent(); 390 IntentReceiver receiver = new IntentReceiver(); 391 System.out.println("Broadcasting: " + intent); 392 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false); 393 receiver.waitForFinish(); 394 } 395 396 private void runInstrument() throws Exception { 397 String profileFile = null; 398 boolean wait = false; 399 boolean rawMode = false; 400 boolean no_window_animation = false; 401 Bundle args = new Bundle(); 402 String argKey = null, argValue = null; 403 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 404 405 String opt; 406 while ((opt=nextOption()) != null) { 407 if (opt.equals("-p")) { 408 profileFile = nextArgRequired(); 409 } else if (opt.equals("-w")) { 410 wait = true; 411 } else if (opt.equals("-r")) { 412 rawMode = true; 413 } else if (opt.equals("-e")) { 414 argKey = nextArgRequired(); 415 argValue = nextArgRequired(); 416 args.putString(argKey, argValue); 417 } else if (opt.equals("--no_window_animation") 418 || opt.equals("--no-window-animation")) { 419 no_window_animation = true; 420 } else { 421 System.err.println("Error: Unknown option: " + opt); 422 showUsage(); 423 return; 424 } 425 } 426 427 String cnArg = nextArgRequired(); 428 ComponentName cn = ComponentName.unflattenFromString(cnArg); 429 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 430 431 InstrumentationWatcher watcher = null; 432 if (wait) { 433 watcher = new InstrumentationWatcher(); 434 watcher.setRawOutput(rawMode); 435 } 436 float[] oldAnims = null; 437 if (no_window_animation) { 438 oldAnims = wm.getAnimationScales(); 439 wm.setAnimationScale(0, 0.0f); 440 wm.setAnimationScale(1, 0.0f); 441 } 442 443 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) { 444 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 445 } 446 447 if (watcher != null) { 448 if (!watcher.waitForFinish()) { 449 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 450 } 451 } 452 453 if (oldAnims != null) { 454 wm.setAnimationScales(oldAnims); 455 } 456 } 457 458 static void removeWallOption() { 459 String props = SystemProperties.get("dalvik.vm.extra-opts"); 460 if (props != null && props.contains("-Xprofile:wallclock")) { 461 props = props.replace("-Xprofile:wallclock", ""); 462 props = props.trim(); 463 SystemProperties.set("dalvik.vm.extra-opts", props); 464 } 465 } 466 467 private void runProfile() throws Exception { 468 String profileFile = null; 469 boolean start = false; 470 boolean wall = false; 471 472 String process = null; 473 474 String cmd = nextArgRequired(); 475 if ("start".equals(cmd)) { 476 start = true; 477 wall = "--wall".equals(nextOption()); 478 process = nextArgRequired(); 479 } else if ("stop".equals(cmd)) { 480 process = nextArgRequired(); 481 } else { 482 // Compatibility with old syntax: process is specified first. 483 process = cmd; 484 cmd = nextArgRequired(); 485 if ("start".equals(cmd)) { 486 start = true; 487 } else if (!"stop".equals(cmd)) { 488 throw new IllegalArgumentException("Profile command " + process + " not valid"); 489 } 490 } 491 492 ParcelFileDescriptor fd = null; 493 494 if (start) { 495 profileFile = nextArgRequired(); 496 try { 497 fd = ParcelFileDescriptor.open( 498 new File(profileFile), 499 ParcelFileDescriptor.MODE_CREATE | 500 ParcelFileDescriptor.MODE_TRUNCATE | 501 ParcelFileDescriptor.MODE_READ_WRITE); 502 } catch (FileNotFoundException e) { 503 System.err.println("Error: Unable to open file: " + profileFile); 504 return; 505 } 506 } 507 508 try { 509 if (wall) { 510 // XXX doesn't work -- this needs to be set before booting. 511 String props = SystemProperties.get("dalvik.vm.extra-opts"); 512 if (props == null || !props.contains("-Xprofile:wallclock")) { 513 props = props + " -Xprofile:wallclock"; 514 //SystemProperties.set("dalvik.vm.extra-opts", props); 515 } 516 } else if (start) { 517 //removeWallOption(); 518 } 519 if (!mAm.profileControl(process, start, profileFile, fd)) { 520 wall = false; 521 throw new AndroidException("PROFILE FAILED on process " + process); 522 } 523 } finally { 524 if (!wall) { 525 //removeWallOption(); 526 } 527 } 528 } 529 530 private void runDumpHeap() throws Exception { 531 boolean managed = !"-n".equals(nextOption()); 532 String process = nextArgRequired(); 533 String heapFile = nextArgRequired(); 534 ParcelFileDescriptor fd = null; 535 536 try { 537 fd = ParcelFileDescriptor.open( 538 new File(heapFile), 539 ParcelFileDescriptor.MODE_CREATE | 540 ParcelFileDescriptor.MODE_TRUNCATE | 541 ParcelFileDescriptor.MODE_READ_WRITE); 542 } catch (FileNotFoundException e) { 543 System.err.println("Error: Unable to open file: " + heapFile); 544 return; 545 } 546 547 if (!mAm.dumpHeap(process, managed, heapFile, fd)) { 548 throw new AndroidException("HEAP DUMP FAILED on process " + process); 549 } 550 } 551 552 class MyActivityController extends IActivityController.Stub { 553 final String mGdbPort; 554 555 static final int STATE_NORMAL = 0; 556 static final int STATE_CRASHED = 1; 557 static final int STATE_EARLY_ANR = 2; 558 static final int STATE_ANR = 3; 559 560 int mState; 561 562 static final int RESULT_DEFAULT = 0; 563 564 static final int RESULT_CRASH_DIALOG = 0; 565 static final int RESULT_CRASH_KILL = 1; 566 567 static final int RESULT_EARLY_ANR_CONTINUE = 0; 568 static final int RESULT_EARLY_ANR_KILL = 1; 569 570 static final int RESULT_ANR_DIALOG = 0; 571 static final int RESULT_ANR_KILL = 1; 572 static final int RESULT_ANR_WAIT = 1; 573 574 int mResult; 575 576 Process mGdbProcess; 577 Thread mGdbThread; 578 boolean mGotGdbPrint; 579 580 MyActivityController(String gdbPort) { 581 mGdbPort = gdbPort; 582 } 583 584 @Override 585 public boolean activityResuming(String pkg) throws RemoteException { 586 synchronized (this) { 587 System.out.println("** Activity resuming: " + pkg); 588 } 589 return true; 590 } 591 592 @Override 593 public boolean activityStarting(Intent intent, String pkg) throws RemoteException { 594 synchronized (this) { 595 System.out.println("** Activity starting: " + pkg); 596 } 597 return true; 598 } 599 600 @Override 601 public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, 602 long timeMillis, String stackTrace) throws RemoteException { 603 synchronized (this) { 604 System.out.println("** ERROR: PROCESS CRASHED"); 605 System.out.println("processName: " + processName); 606 System.out.println("processPid: " + pid); 607 System.out.println("shortMsg: " + shortMsg); 608 System.out.println("longMsg: " + longMsg); 609 System.out.println("timeMillis: " + timeMillis); 610 System.out.println("stack:"); 611 System.out.print(stackTrace); 612 System.out.println("#"); 613 int result = waitControllerLocked(pid, STATE_CRASHED); 614 return result == RESULT_CRASH_KILL ? false : true; 615 } 616 } 617 618 @Override 619 public int appEarlyNotResponding(String processName, int pid, String annotation) 620 throws RemoteException { 621 synchronized (this) { 622 System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING"); 623 System.out.println("processName: " + processName); 624 System.out.println("processPid: " + pid); 625 System.out.println("annotation: " + annotation); 626 int result = waitControllerLocked(pid, STATE_EARLY_ANR); 627 if (result == RESULT_EARLY_ANR_KILL) return -1; 628 return 0; 629 } 630 } 631 632 @Override 633 public int appNotResponding(String processName, int pid, String processStats) 634 throws RemoteException { 635 synchronized (this) { 636 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 637 System.out.println("processName: " + processName); 638 System.out.println("processPid: " + pid); 639 System.out.println("processStats:"); 640 System.out.print(processStats); 641 System.out.println("#"); 642 int result = waitControllerLocked(pid, STATE_ANR); 643 if (result == RESULT_ANR_KILL) return -1; 644 if (result == RESULT_ANR_WAIT) return 1; 645 return 0; 646 } 647 } 648 649 void killGdbLocked() { 650 mGotGdbPrint = false; 651 if (mGdbProcess != null) { 652 System.out.println("Stopping gdbserver"); 653 mGdbProcess.destroy(); 654 mGdbProcess = null; 655 } 656 if (mGdbThread != null) { 657 mGdbThread.interrupt(); 658 mGdbThread = null; 659 } 660 } 661 662 int waitControllerLocked(int pid, int state) { 663 if (mGdbPort != null) { 664 killGdbLocked(); 665 666 try { 667 System.out.println("Starting gdbserver on port " + mGdbPort); 668 System.out.println("Do the following:"); 669 System.out.println(" adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort); 670 System.out.println(" gdbclient app_process :" + mGdbPort); 671 672 mGdbProcess = Runtime.getRuntime().exec(new String[] { 673 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid) 674 }); 675 final InputStreamReader converter = new InputStreamReader( 676 mGdbProcess.getInputStream()); 677 mGdbThread = new Thread() { 678 @Override 679 public void run() { 680 BufferedReader in = new BufferedReader(converter); 681 String line; 682 int count = 0; 683 while (true) { 684 synchronized (MyActivityController.this) { 685 if (mGdbThread == null) { 686 return; 687 } 688 if (count == 2) { 689 mGotGdbPrint = true; 690 MyActivityController.this.notifyAll(); 691 } 692 } 693 try { 694 line = in.readLine(); 695 if (line == null) { 696 return; 697 } 698 System.out.println("GDB: " + line); 699 count++; 700 } catch (IOException e) { 701 return; 702 } 703 } 704 } 705 }; 706 mGdbThread.start(); 707 708 // Stupid waiting for .5s. Doesn't matter if we end early. 709 try { 710 this.wait(500); 711 } catch (InterruptedException e) { 712 } 713 714 } catch (IOException e) { 715 System.err.println("Failure starting gdbserver: " + e); 716 killGdbLocked(); 717 } 718 } 719 mState = state; 720 System.out.println(""); 721 printMessageForState(); 722 723 while (mState != STATE_NORMAL) { 724 try { 725 wait(); 726 } catch (InterruptedException e) { 727 } 728 } 729 730 killGdbLocked(); 731 732 return mResult; 733 } 734 735 void resumeController(int result) { 736 synchronized (this) { 737 mState = STATE_NORMAL; 738 mResult = result; 739 notifyAll(); 740 } 741 } 742 743 void printMessageForState() { 744 switch (mState) { 745 case STATE_NORMAL: 746 System.out.println("Monitoring activity manager... available commands:"); 747 break; 748 case STATE_CRASHED: 749 System.out.println("Waiting after crash... available commands:"); 750 System.out.println("(c)ontinue: show crash dialog"); 751 System.out.println("(k)ill: immediately kill app"); 752 break; 753 case STATE_EARLY_ANR: 754 System.out.println("Waiting after early ANR... available commands:"); 755 System.out.println("(c)ontinue: standard ANR processing"); 756 System.out.println("(k)ill: immediately kill app"); 757 break; 758 case STATE_ANR: 759 System.out.println("Waiting after ANR... available commands:"); 760 System.out.println("(c)ontinue: show ANR dialog"); 761 System.out.println("(k)ill: immediately kill app"); 762 System.out.println("(w)ait: wait some more"); 763 break; 764 } 765 System.out.println("(q)uit: finish monitoring"); 766 } 767 768 void run() throws RemoteException { 769 try { 770 printMessageForState(); 771 772 mAm.setActivityController(this); 773 mState = STATE_NORMAL; 774 775 InputStreamReader converter = new InputStreamReader(System.in); 776 BufferedReader in = new BufferedReader(converter); 777 String line; 778 779 while ((line = in.readLine()) != null) { 780 boolean addNewline = true; 781 if (line.length() <= 0) { 782 addNewline = false; 783 } else if ("q".equals(line) || "quit".equals(line)) { 784 resumeController(RESULT_DEFAULT); 785 break; 786 } else if (mState == STATE_CRASHED) { 787 if ("c".equals(line) || "continue".equals(line)) { 788 resumeController(RESULT_CRASH_DIALOG); 789 } else if ("k".equals(line) || "kill".equals(line)) { 790 resumeController(RESULT_CRASH_KILL); 791 } else { 792 System.out.println("Invalid command: " + line); 793 } 794 } else if (mState == STATE_ANR) { 795 if ("c".equals(line) || "continue".equals(line)) { 796 resumeController(RESULT_ANR_DIALOG); 797 } else if ("k".equals(line) || "kill".equals(line)) { 798 resumeController(RESULT_ANR_KILL); 799 } else if ("w".equals(line) || "wait".equals(line)) { 800 resumeController(RESULT_ANR_WAIT); 801 } else { 802 System.out.println("Invalid command: " + line); 803 } 804 } else if (mState == STATE_EARLY_ANR) { 805 if ("c".equals(line) || "continue".equals(line)) { 806 resumeController(RESULT_EARLY_ANR_CONTINUE); 807 } else if ("k".equals(line) || "kill".equals(line)) { 808 resumeController(RESULT_EARLY_ANR_KILL); 809 } else { 810 System.out.println("Invalid command: " + line); 811 } 812 } else { 813 System.out.println("Invalid command: " + line); 814 } 815 816 synchronized (this) { 817 if (addNewline) { 818 System.out.println(""); 819 } 820 printMessageForState(); 821 } 822 } 823 824 } catch (IOException e) { 825 e.printStackTrace(); 826 } finally { 827 mAm.setActivityController(null); 828 } 829 } 830 } 831 832 private void runMonitor() throws Exception { 833 String opt; 834 String gdbPort = null; 835 while ((opt=nextOption()) != null) { 836 if (opt.equals("--gdb")) { 837 gdbPort = nextArgRequired(); 838 } else { 839 System.err.println("Error: Unknown option: " + opt); 840 showUsage(); 841 return; 842 } 843 } 844 845 MyActivityController controller = new MyActivityController(gdbPort); 846 controller.run(); 847 } 848 849 private void runScreenCompat() throws Exception { 850 String mode = nextArgRequired(); 851 boolean enabled; 852 if ("on".equals(mode)) { 853 enabled = true; 854 } else if ("off".equals(mode)) { 855 enabled = false; 856 } else { 857 System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode); 858 showUsage(); 859 return; 860 } 861 862 String packageName = nextArgRequired(); 863 do { 864 try { 865 mAm.setPackageScreenCompatMode(packageName, enabled 866 ? ActivityManager.COMPAT_MODE_ENABLED 867 : ActivityManager.COMPAT_MODE_DISABLED); 868 } catch (RemoteException e) { 869 } 870 packageName = nextArg(); 871 } while (packageName != null); 872 } 873 874 private void runDisplaySize() throws Exception { 875 String size = nextArgRequired(); 876 int m, n; 877 if ("reset".equals(size)) { 878 m = n = -1; 879 } else { 880 int div = size.indexOf('x'); 881 if (div <= 0 || div >= (size.length()-1)) { 882 System.err.println("Error: bad size " + size); 883 showUsage(); 884 return; 885 } 886 String mstr = size.substring(0, div); 887 String nstr = size.substring(div+1); 888 try { 889 m = Integer.parseInt(mstr); 890 n = Integer.parseInt(nstr); 891 } catch (NumberFormatException e) { 892 System.err.println("Error: bad number " + e); 893 showUsage(); 894 return; 895 } 896 } 897 898 if (m < n) { 899 int tmp = m; 900 m = n; 901 n = tmp; 902 } 903 904 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService( 905 Context.WINDOW_SERVICE)); 906 if (wm == null) { 907 System.err.println(NO_SYSTEM_ERROR_CODE); 908 throw new AndroidException("Can't connect to window manager; is the system running?"); 909 } 910 911 try { 912 if (m >= 0 && n >= 0) { 913 wm.setForcedDisplaySize(m, n); 914 } else { 915 wm.clearForcedDisplaySize(); 916 } 917 } catch (RemoteException e) { 918 } 919 } 920 921 private class IntentReceiver extends IIntentReceiver.Stub { 922 private boolean mFinished = false; 923 924 public synchronized void performReceive( 925 Intent intent, int rc, String data, Bundle ext, boolean ord, 926 boolean sticky) { 927 String line = "Broadcast completed: result=" + rc; 928 if (data != null) line = line + ", data=\"" + data + "\""; 929 if (ext != null) line = line + ", extras: " + ext; 930 System.out.println(line); 931 mFinished = true; 932 notifyAll(); 933 } 934 935 public synchronized void waitForFinish() { 936 try { 937 while (!mFinished) wait(); 938 } catch (InterruptedException e) { 939 throw new IllegalStateException(e); 940 } 941 } 942 } 943 944 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 945 private boolean mFinished = false; 946 private boolean mRawMode = false; 947 948 /** 949 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 950 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 951 * @param rawMode true for raw mode, false for pretty mode. 952 */ 953 public void setRawOutput(boolean rawMode) { 954 mRawMode = rawMode; 955 } 956 957 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 958 synchronized (this) { 959 // pretty printer mode? 960 String pretty = null; 961 if (!mRawMode && results != null) { 962 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 963 } 964 if (pretty != null) { 965 System.out.print(pretty); 966 } else { 967 if (results != null) { 968 for (String key : results.keySet()) { 969 System.out.println( 970 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 971 } 972 } 973 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 974 } 975 notifyAll(); 976 } 977 } 978 979 public void instrumentationFinished(ComponentName name, int resultCode, 980 Bundle results) { 981 synchronized (this) { 982 // pretty printer mode? 983 String pretty = null; 984 if (!mRawMode && results != null) { 985 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 986 } 987 if (pretty != null) { 988 System.out.println(pretty); 989 } else { 990 if (results != null) { 991 for (String key : results.keySet()) { 992 System.out.println( 993 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 994 } 995 } 996 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 997 } 998 mFinished = true; 999 notifyAll(); 1000 } 1001 } 1002 1003 public boolean waitForFinish() { 1004 synchronized (this) { 1005 while (!mFinished) { 1006 try { 1007 if (!mAm.asBinder().pingBinder()) { 1008 return false; 1009 } 1010 wait(1000); 1011 } catch (InterruptedException e) { 1012 throw new IllegalStateException(e); 1013 } 1014 } 1015 } 1016 return true; 1017 } 1018 } 1019 1020 private String nextOption() { 1021 if (mCurArgData != null) { 1022 String prev = mArgs[mNextArg - 1]; 1023 throw new IllegalArgumentException("No argument expected after \"" + prev + "\""); 1024 } 1025 if (mNextArg >= mArgs.length) { 1026 return null; 1027 } 1028 String arg = mArgs[mNextArg]; 1029 if (!arg.startsWith("-")) { 1030 return null; 1031 } 1032 mNextArg++; 1033 if (arg.equals("--")) { 1034 return null; 1035 } 1036 if (arg.length() > 1 && arg.charAt(1) != '-') { 1037 if (arg.length() > 2) { 1038 mCurArgData = arg.substring(2); 1039 return arg.substring(0, 2); 1040 } else { 1041 mCurArgData = null; 1042 return arg; 1043 } 1044 } 1045 mCurArgData = null; 1046 return arg; 1047 } 1048 1049 private String nextArg() { 1050 if (mCurArgData != null) { 1051 String arg = mCurArgData; 1052 mCurArgData = null; 1053 return arg; 1054 } else if (mNextArg < mArgs.length) { 1055 return mArgs[mNextArg++]; 1056 } else { 1057 return null; 1058 } 1059 } 1060 1061 private String nextArgRequired() { 1062 String arg = nextArg(); 1063 if (arg == null) { 1064 String prev = mArgs[mNextArg - 1]; 1065 throw new IllegalArgumentException("Argument expected after \"" + prev + "\""); 1066 } 1067 return arg; 1068 } 1069 1070 private static void showUsage() { 1071 System.err.println( 1072 "usage: am [subcommand] [options]\n" + 1073 "usage: am start [-D] [-W] <INTENT>\n" + 1074 " am startservice <INTENT>\n" + 1075 " am force-stop <PACKAGE>\n" + 1076 " am broadcast <INTENT>\n" + 1077 " am instrument [-r] [-e <NAME> <VALUE>] [-p] [-w]\n" + 1078 " [--no-window-animation] <COMPONENT>\n" + 1079 " am profile start <PROCESS> <FILE>\n" + 1080 " am profile stop <PROCESS>\n" + 1081 " am dumpheap [flags] <PROCESS> <FILE>\n" + 1082 " am monitor [--gdb <port>]\n" + 1083 " am screen-compat [on|off] <PACKAGE>\n" + 1084 " am display-size [reset|MxN]\n" + 1085 "\n" + 1086 "am start: start an Activity. Options are:\n" + 1087 " -D: enable debugging\n" + 1088 " -W: wait for launch to complete\n" + 1089 "\n" + 1090 "am startservice: start a Service.\n" + 1091 "\n" + 1092 "am force-stop: force stop everything associated with <PACKAGE>.\n" + 1093 "\n" + 1094 "am broadcast: send a broadcast Intent.\n" + 1095 "\n" + 1096 "am instrument: start an Instrumentation. Typically this target <COMPONENT>\n" + 1097 " is the form <TEST_PACKAGE>/<RUNNER_CLASS>. Options are:\n" + 1098 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with\n" + 1099 " [-e perf true] to generate raw output for performance measurements.\n" + 1100 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>. For test runners a\n" + 1101 " common form is [-e <testrunner_flag> <value>[,<value>...]].\n" + 1102 " -p <FILE>: write profiling data to <FILE>\n" + 1103 " -w: wait for instrumentation to finish before returning. Required for\n" + 1104 " test runners.\n" + 1105 " --no-window-animation: turn off window animations will running.\n" + 1106 "\n" + 1107 "am profile: start and stop profiler on a process.\n" + 1108 "\n" + 1109 "am dumpheap: dump the heap of a process. Options are:\n" + 1110 " -n: dump native heap instead of managed heap\n" + 1111 "\n" + 1112 "am monitor: start monitoring for crashes or ANRs.\n" + 1113 " --gdb: start gdbserv on the given port at crash/ANR\n" + 1114 "\n" + 1115 "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" + 1116 "\n" + 1117 "am display-size: override display size.\n" + 1118 "\n" + 1119 "<INTENT> specifications include these flags and arguments:\n" + 1120 " [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" + 1121 " [-c <CATEGORY> [-c <CATEGORY>] ...]\n" + 1122 " [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" + 1123 " [--esn <EXTRA_KEY> ...]\n" + 1124 " [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" + 1125 " [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" + 1126 " [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]\n" + 1127 " [--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]\n" + 1128 " [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]\n" + 1129 " [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]\n" + 1130 " [-n <COMPONENT>] [-f <FLAGS>]\n" + 1131 " [--grant-read-uri-permission] [--grant-write-uri-permission]\n" + 1132 " [--debug-log-resolution] [--exclude-stopped-packages]\n" + 1133 " [--include-stopped-packages]\n" + 1134 " [--activity-brought-to-front] [--activity-clear-top]\n" + 1135 " [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" + 1136 " [--activity-launched-from-history] [--activity-multiple-task]\n" + 1137 " [--activity-no-animation] [--activity-no-history]\n" + 1138 " [--activity-no-user-action] [--activity-previous-is-top]\n" + 1139 " [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" + 1140 " [--activity-single-top] [--activity-clear-task]\n" + 1141 " [--activity-task-on-home]\n" + 1142 " [--receiver-registered-only] [--receiver-replace-pending]\n" + 1143 " [<URI>]\n" 1144 ); 1145 } 1146} 1147