Am.java revision 4cc863338d5e43b6189e05498d7cb53ebba135e1
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 static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
22import static android.app.ActivityManager.RESIZE_MODE_SYSTEM;
23import static android.app.ActivityManager.RESIZE_MODE_USER;
24
25import android.app.ActivityManager;
26import android.app.ActivityManager.StackInfo;
27import android.app.ActivityManagerNative;
28import android.app.IActivityContainer;
29import android.app.IActivityController;
30import android.app.IActivityManager;
31import android.app.IInstrumentationWatcher;
32import android.app.Instrumentation;
33import android.app.IStopUserCallback;
34import android.app.ProfilerInfo;
35import android.app.UiAutomationConnection;
36import android.app.usage.ConfigurationStats;
37import android.app.usage.IUsageStatsManager;
38import android.app.usage.UsageStatsManager;
39import android.content.ComponentCallbacks2;
40import android.content.ComponentName;
41import android.content.Context;
42import android.content.IIntentReceiver;
43import android.content.Intent;
44import android.content.pm.IPackageManager;
45import android.content.pm.ParceledListSlice;
46import android.content.pm.ResolveInfo;
47import android.content.pm.UserInfo;
48import android.content.res.Configuration;
49import android.graphics.Rect;
50import android.net.Uri;
51import android.os.Binder;
52import android.os.Build;
53import android.os.Bundle;
54import android.os.ParcelFileDescriptor;
55import android.os.RemoteException;
56import android.os.SELinux;
57import android.os.ServiceManager;
58import android.os.ShellCommand;
59import android.os.SystemClock;
60import android.os.SystemProperties;
61import android.os.UserHandle;
62import android.text.TextUtils;
63import android.util.AndroidException;
64import android.util.ArrayMap;
65import android.view.IWindowManager;
66
67import com.android.internal.os.BaseCommand;
68import com.android.internal.util.HexDump;
69import com.android.internal.util.Preconditions;
70
71import java.io.BufferedReader;
72import java.io.File;
73import java.io.FileNotFoundException;
74import java.io.IOException;
75import java.io.InputStreamReader;
76import java.io.PrintStream;
77import java.io.PrintWriter;
78import java.net.URISyntaxException;
79import java.util.ArrayList;
80import java.util.Collections;
81import java.util.Comparator;
82import java.util.HashSet;
83import java.util.List;
84
85public class Am extends BaseCommand {
86
87    private static final String SHELL_PACKAGE_NAME = "com.android.shell";
88
89    // Is the object moving in a positive direction?
90    private static final boolean MOVING_FORWARD = true;
91    // Is the object moving in the horizontal plan?
92    private static final boolean MOVING_HORIZONTALLY = true;
93    // Is the object current point great then its target point?
94    private static final boolean GREATER_THAN_TARGET = true;
95    // Amount we reduce the stack size by when testing a task re-size.
96    private static final int STACK_BOUNDS_INSET = 10;
97
98    private IActivityManager mAm;
99
100    private int mStartFlags = 0;
101    private boolean mWaitOption = false;
102    private boolean mStopOption = false;
103
104    private int mRepeat = 0;
105    private int mUserId;
106    private String mReceiverPermission;
107
108    private String mProfileFile;
109    private int mSamplingInterval;
110    private boolean mAutoStop;
111
112    /**
113     * Command-line entry point.
114     *
115     * @param args The command-line arguments
116     */
117    public static void main(String[] args) {
118        (new Am()).run(args);
119    }
120
121    @Override
122    public void onShowUsage(PrintStream out) {
123        PrintWriter pw = new PrintWriter(out);
124        pw.println(
125                "usage: am [subcommand] [options]\n" +
126                "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" +
127                "               [--sampling INTERVAL] [-R COUNT] [-S]\n" +
128                "               [--track-allocation] [--user <USER_ID> | current] <INTENT>\n" +
129                "       am startservice [--user <USER_ID> | current] <INTENT>\n" +
130                "       am stopservice [--user <USER_ID> | current] <INTENT>\n" +
131                "       am force-stop [--user <USER_ID> | all | current] <PACKAGE>\n" +
132                "       am kill [--user <USER_ID> | all | current] <PACKAGE>\n" +
133                "       am kill-all\n" +
134                "       am broadcast [--user <USER_ID> | all | current] <INTENT>\n" +
135                "       am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" +
136                "               [--user <USER_ID> | current]\n" +
137                "               [--no-window-animation] [--abi <ABI>] <COMPONENT>\n" +
138                "       am profile start [--user <USER_ID> current] [--sampling INTERVAL] <PROCESS> <FILE>\n" +
139                "       am profile stop [--user <USER_ID> current] [<PROCESS>]\n" +
140                "       am dumpheap [--user <USER_ID> current] [-n] <PROCESS> <FILE>\n" +
141                "       am set-debug-app [-w] [--persistent] <PACKAGE>\n" +
142                "       am clear-debug-app\n" +
143                "       am set-watch-heap <PROCESS> <MEM-LIMIT>\n" +
144                "       am clear-watch-heap\n" +
145                "       am bug-report [--progress]\n" +
146                "       am monitor [--gdb <port>]\n" +
147                "       am hang [--allow-restart]\n" +
148                "       am restart\n" +
149                "       am idle-maintenance\n" +
150                "       am screen-compat [on|off] <PACKAGE>\n" +
151                "       am package-importance <PACKAGE>\n" +
152                "       am to-uri [INTENT]\n" +
153                "       am to-intent-uri [INTENT]\n" +
154                "       am to-app-uri [INTENT]\n" +
155                "       am switch-user <USER_ID>\n" +
156                "       am start-user <USER_ID>\n" +
157                "       am unlock-user <USER_ID> [TOKEN_HEX]\n" +
158                "       am stop-user [-w] [-f] <USER_ID>\n" +
159                "       am stack start <DISPLAY_ID> <INTENT>\n" +
160                "       am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" +
161                "       am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
162                "       am stack size-docked-stack-test: <STEP_SIZE> <l|t|r|b> [DELAY_MS]\n" +
163                "       am stack move-top-activity-to-pinned-stack: <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
164                "       am stack positiontask <TASK_ID> <STACK_ID> <POSITION>\n" +
165                "       am stack list\n" +
166                "       am stack info <STACK_ID>\n" +
167                "       am task lock <TASK_ID>\n" +
168                "       am task lock stop\n" +
169                "       am task resizeable <TASK_ID> [true|false]\n" +
170                "       am task resize <TASK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
171                "       am task drag-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" +
172                "       am task size-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" +
173                "       am get-config\n" +
174                "       am suppress-resize-config-changes <true|false>\n" +
175                "       am set-inactive [--user <USER_ID>] <PACKAGE> true|false\n" +
176                "       am get-inactive [--user <USER_ID>] <PACKAGE>\n" +
177                "       am send-trim-memory [--user <USER_ID>] <PROCESS>\n" +
178                "               [HIDDEN|RUNNING_MODERATE|BACKGROUND|RUNNING_LOW|MODERATE|RUNNING_CRITICAL|COMPLETE]\n" +
179                "       am get-current-user\n" +
180                "\n" +
181                "am start: start an Activity.  Options are:\n" +
182                "    -D: enable debugging\n" +
183                "    -W: wait for launch to complete\n" +
184                "    --start-profiler <FILE>: start profiler and send results to <FILE>\n" +
185                "    --sampling INTERVAL: use sample profiling with INTERVAL microseconds\n" +
186                "        between samples (use with --start-profiler)\n" +
187                "    -P <FILE>: like above, but profiling stops when app goes idle\n" +
188                "    -R: repeat the activity launch <COUNT> times.  Prior to each repeat,\n" +
189                "        the top activity will be finished.\n" +
190                "    -S: force stop the target app before starting the activity\n" +
191                "    --track-allocation: enable tracking of object allocations\n" +
192                "    --user <USER_ID> | current: Specify which user to run as; if not\n" +
193                "        specified then run as the current user.\n" +
194                "\n" +
195                "am startservice: start a Service.  Options are:\n" +
196                "    --user <USER_ID> | current: Specify which user to run as; if not\n" +
197                "        specified then run as the current user.\n" +
198                "\n" +
199                "am stopservice: stop a Service.  Options are:\n" +
200                "    --user <USER_ID> | current: Specify which user to run as; if not\n" +
201                "        specified then run as the current user.\n" +
202                "\n" +
203                "am force-stop: force stop everything associated with <PACKAGE>.\n" +
204                "    --user <USER_ID> | all | current: Specify user to force stop;\n" +
205                "        all users if not specified.\n" +
206                "\n" +
207                "am kill: Kill all processes associated with <PACKAGE>.  Only kills.\n" +
208                "  processes that are safe to kill -- that is, will not impact the user\n" +
209                "  experience.\n" +
210                "    --user <USER_ID> | all | current: Specify user whose processes to kill;\n" +
211                "        all users if not specified.\n" +
212                "\n" +
213                "am kill-all: Kill all background processes.\n" +
214                "\n" +
215                "am broadcast: send a broadcast Intent.  Options are:\n" +
216                "    --user <USER_ID> | all | current: Specify which user to send to; if not\n" +
217                "        specified then send to all users.\n" +
218                "    --receiver-permission <PERMISSION>: Require receiver to hold permission.\n" +
219                "\n" +
220                "am instrument: start an Instrumentation.  Typically this target <COMPONENT>\n" +
221                "  is the form <TEST_PACKAGE>/<RUNNER_CLASS>.  Options are:\n" +
222                "    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT).  Use with\n" +
223                "        [-e perf true] to generate raw output for performance measurements.\n" +
224                "    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>.  For test runners a\n" +
225                "        common form is [-e <testrunner_flag> <value>[,<value>...]].\n" +
226                "    -p <FILE>: write profiling data to <FILE>\n" +
227                "    -w: wait for instrumentation to finish before returning.  Required for\n" +
228                "        test runners.\n" +
229                "    --user <USER_ID> | current: Specify user instrumentation runs in;\n" +
230                "        current user if not specified.\n" +
231                "    --no-window-animation: turn off window animations while running.\n" +
232                "    --abi <ABI>: Launch the instrumented process with the selected ABI.\n"  +
233                "        This assumes that the process supports the selected ABI.\n" +
234                "\n" +
235                "am trace-ipc: Trace IPC transactions.\n" +
236                "  start: start tracing IPC transactions.\n" +
237                "  stop: stop tracing IPC transactions and dump the results to file.\n" +
238                "    --dump-file <FILE>: Specify the file the trace should be dumped to.\n" +
239                "\n" +
240                "am profile: start and stop profiler on a process.  The given <PROCESS> argument\n" +
241                "  may be either a process name or pid.  Options are:\n" +
242                "    --user <USER_ID> | current: When supplying a process name,\n" +
243                "        specify user of process to profile; uses current user if not specified.\n" +
244                "\n" +
245                "am dumpheap: dump the heap of a process.  The given <PROCESS> argument may\n" +
246                "  be either a process name or pid.  Options are:\n" +
247                "    -n: dump native heap instead of managed heap\n" +
248                "    --user <USER_ID> | current: When supplying a process name,\n" +
249                "        specify user of process to dump; uses current user if not specified.\n" +
250                "\n" +
251                "am set-debug-app: set application <PACKAGE> to debug.  Options are:\n" +
252                "    -w: wait for debugger when application starts\n" +
253                "    --persistent: retain this value\n" +
254                "\n" +
255                "am clear-debug-app: clear the previously set-debug-app.\n" +
256                "\n" +
257                "am set-watch-heap: start monitoring pss size of <PROCESS>, if it is at or\n" +
258                "    above <HEAP-LIMIT> then a heap dump is collected for the user to report\n" +
259                "\n" +
260                "am clear-watch-heap: clear the previously set-watch-heap.\n" +
261                "\n" +
262                "am bug-report: request bug report generation; will launch a notification\n" +
263                "    when done to select where it should be delivered. Options are: \n" +
264                "   --progress: will launch a notification right away to show its progress.\n" +
265                "\n" +
266                "am monitor: start monitoring for crashes or ANRs.\n" +
267                "    --gdb: start gdbserv on the given port at crash/ANR\n" +
268                "\n" +
269                "am hang: hang the system.\n" +
270                "    --allow-restart: allow watchdog to perform normal system restart\n" +
271                "\n" +
272                "am restart: restart the user-space system.\n" +
273                "\n" +
274                "am idle-maintenance: perform idle maintenance now.\n" +
275                "\n" +
276                "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" +
277                "\n" +
278                "am package-importance: print current importance of <PACKAGE>.\n" +
279                "\n" +
280                "am to-uri: print the given Intent specification as a URI.\n" +
281                "\n" +
282                "am to-intent-uri: print the given Intent specification as an intent: URI.\n" +
283                "\n" +
284                "am to-app-uri: print the given Intent specification as an android-app: URI.\n" +
285                "\n" +
286                "am switch-user: switch to put USER_ID in the foreground, starting\n" +
287                "  execution of that user if it is currently stopped.\n" +
288                "\n" +
289                "am start-user: start USER_ID in background if it is currently stopped,\n" +
290                "  use switch-user if you want to start the user in foreground.\n" +
291                "\n" +
292                "am stop-user: stop execution of USER_ID, not allowing it to run any\n" +
293                "  code until a later explicit start or switch to it.\n" +
294                "  -w: wait for stop-user to complete.\n" +
295                "  -f: force stop even if there are related users that cannot be stopped.\n" +
296                "\n" +
297                "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" +
298                "\n" +
299                "am stack movetask: move <TASK_ID> from its current stack to the top (true) or" +
300                "   bottom (false) of <STACK_ID>.\n" +
301                "\n" +
302                "am stack resize: change <STACK_ID> size and position to <LEFT,TOP,RIGHT,BOTTOM>." +
303                "\n" +
304                "am stack size-docked-stack-test: test command for sizing docked stack by\n" +
305                "   <STEP_SIZE> increments from the side <l>eft, <t>op, <r>ight, or <b>ottom\n" +
306                "   applying the optional [DELAY_MS] between each step.\n" +
307                "\n" +
308                "am stack move-top-activity-to-pinned-stack: moves the top activity from\n" +
309                "   <STACK_ID> to the pinned stack using <LEFT,TOP,RIGHT,BOTTOM> for the\n" +
310                "   bounds of the pinned stack.\n" +
311                "\n" +
312                "am stack positiontask: place <TASK_ID> in <STACK_ID> at <POSITION>" +
313                "\n" +
314                "am stack list: list all of the activity stacks and their sizes.\n" +
315                "\n" +
316                "am stack info: display the information about activity stack <STACK_ID>.\n" +
317                "\n" +
318                "am task lock: bring <TASK_ID> to the front and don't allow other tasks to run.\n" +
319                "\n" +
320                "am task lock stop: end the current task lock.\n" +
321                "\n" +
322                "am task resizeable: change if <TASK_ID> is resizeable (true) or not (false).\n" +
323                "\n" +
324                "am task resize: makes sure <TASK_ID> is in a stack with the specified bounds.\n" +
325                "   Forces the task to be resizeable and creates a stack if no existing stack\n" +
326                "   has the specified bounds.\n" +
327                "\n" +
328                "am task drag-task-test: test command for dragging/moving <TASK_ID> by\n" +
329                "   <STEP_SIZE> increments around the screen applying the optional [DELAY_MS]\n" +
330                "   between each step.\n" +
331                "\n" +
332                "am task size-task-test: test command for sizing <TASK_ID> by <STEP_SIZE>" +
333                "   increments within the screen applying the optional [DELAY_MS] between\n" +
334                "   each step.\n" +
335                "\n" +
336                "am get-config: retrieve the configuration and any recent configurations\n" +
337                "  of the device.\n" +
338                "am suppress-resize-config-changes: suppresses configuration changes due to\n" +
339                "  user resizing an activity/task.\n" +
340                "\n" +
341                "am set-inactive: sets the inactive state of an app.\n" +
342                "\n" +
343                "am get-inactive: returns the inactive state of an app.\n" +
344                "\n" +
345                "am send-trim-memory: send a memory trim event to a <PROCESS>.\n" +
346                "\n" +
347                "am get-current-user: returns id of the current foreground user.\n" +
348                "\n"
349        );
350        Intent.printIntentArgsHelp(pw, "");
351        pw.flush();
352    }
353
354    @Override
355    public void onRun() throws Exception {
356
357        mAm = ActivityManagerNative.getDefault();
358        if (mAm == null) {
359            System.err.println(NO_SYSTEM_ERROR_CODE);
360            throw new AndroidException("Can't connect to activity manager; is the system running?");
361        }
362
363        String op = nextArgRequired();
364
365        if (op.equals("start")) {
366            runStart();
367        } else if (op.equals("startservice")) {
368            runStartService();
369        } else if (op.equals("stopservice")) {
370            runStopService();
371        } else if (op.equals("force-stop")) {
372            runForceStop();
373        } else if (op.equals("kill")) {
374            runKill();
375        } else if (op.equals("kill-all")) {
376            runKillAll();
377        } else if (op.equals("instrument")) {
378            runInstrument();
379        } else if (op.equals("trace-ipc")) {
380            runTraceIpc();
381        } else if (op.equals("broadcast")) {
382            sendBroadcast();
383        } else if (op.equals("profile")) {
384            runProfile();
385        } else if (op.equals("dumpheap")) {
386            runDumpHeap();
387        } else if (op.equals("set-debug-app")) {
388            runSetDebugApp();
389        } else if (op.equals("clear-debug-app")) {
390            runClearDebugApp();
391        } else if (op.equals("set-watch-heap")) {
392            runSetWatchHeap();
393        } else if (op.equals("clear-watch-heap")) {
394            runClearWatchHeap();
395        } else if (op.equals("bug-report")) {
396            runBugReport();
397        } else if (op.equals("monitor")) {
398            runMonitor();
399        } else if (op.equals("hang")) {
400            runHang();
401        } else if (op.equals("restart")) {
402            runRestart();
403        } else if (op.equals("idle-maintenance")) {
404            runIdleMaintenance();
405        } else if (op.equals("screen-compat")) {
406            runScreenCompat();
407        } else if (op.equals("package-importance")) {
408            runPackageImportance();
409        } else if (op.equals("to-uri")) {
410            runToUri(0);
411        } else if (op.equals("to-intent-uri")) {
412            runToUri(Intent.URI_INTENT_SCHEME);
413        } else if (op.equals("to-app-uri")) {
414            runToUri(Intent.URI_ANDROID_APP_SCHEME);
415        } else if (op.equals("switch-user")) {
416            runSwitchUser();
417        } else if (op.equals("start-user")) {
418            runStartUserInBackground();
419        } else if (op.equals("unlock-user")) {
420            runUnlockUser();
421        } else if (op.equals("stop-user")) {
422            runStopUser();
423        } else if (op.equals("stack")) {
424            runStack();
425        } else if (op.equals("task")) {
426            runTask();
427        } else if (op.equals("get-config")) {
428            runGetConfig();
429        } else if (op.equals("suppress-resize-config-changes")) {
430            runSuppressResizeConfigChanges();
431        } else if (op.equals("set-inactive")) {
432            runSetInactive();
433        } else if (op.equals("get-inactive")) {
434            runGetInactive();
435        } else if (op.equals("send-trim-memory")) {
436            runSendTrimMemory();
437        } else if (op.equals("get-current-user")) {
438            runGetCurrentUser();
439        } else {
440            showError("Error: unknown command '" + op + "'");
441        }
442    }
443
444    int parseUserArg(String arg) {
445        int userId;
446        if ("all".equals(arg)) {
447            userId = UserHandle.USER_ALL;
448        } else if ("current".equals(arg) || "cur".equals(arg)) {
449            userId = UserHandle.USER_CURRENT;
450        } else {
451            userId = Integer.parseInt(arg);
452        }
453        return userId;
454    }
455
456    private Intent makeIntent(int defUser) throws URISyntaxException {
457        mStartFlags = 0;
458        mWaitOption = false;
459        mStopOption = false;
460        mRepeat = 0;
461        mProfileFile = null;
462        mSamplingInterval = 0;
463        mAutoStop = false;
464        mUserId = defUser;
465
466        return Intent.parseCommandArgs(mArgs, new Intent.CommandOptionHandler() {
467            @Override
468            public boolean handleOption(String opt, ShellCommand cmd) {
469                if (opt.equals("-D")) {
470                    mStartFlags |= ActivityManager.START_FLAG_DEBUG;
471                } else if (opt.equals("-W")) {
472                    mWaitOption = true;
473                } else if (opt.equals("-P")) {
474                    mProfileFile = nextArgRequired();
475                    mAutoStop = true;
476                } else if (opt.equals("--start-profiler")) {
477                    mProfileFile = nextArgRequired();
478                    mAutoStop = false;
479                } else if (opt.equals("--sampling")) {
480                    mSamplingInterval = Integer.parseInt(nextArgRequired());
481                } else if (opt.equals("-R")) {
482                    mRepeat = Integer.parseInt(nextArgRequired());
483                } else if (opt.equals("-S")) {
484                    mStopOption = true;
485                } else if (opt.equals("--track-allocation")) {
486                    mStartFlags |= ActivityManager.START_FLAG_TRACK_ALLOCATION;
487                } else if (opt.equals("--user")) {
488                    mUserId = parseUserArg(nextArgRequired());
489                } else if (opt.equals("--receiver-permission")) {
490                    mReceiverPermission = nextArgRequired();
491                } else {
492                    return false;
493                }
494                return true;
495            }
496        });
497    }
498
499    private void runStartService() throws Exception {
500        Intent intent = makeIntent(UserHandle.USER_CURRENT);
501        if (mUserId == UserHandle.USER_ALL) {
502            System.err.println("Error: Can't start activity with user 'all'");
503            return;
504        }
505        System.out.println("Starting service: " + intent);
506        ComponentName cn = mAm.startService(null, intent, intent.getType(),
507                SHELL_PACKAGE_NAME, mUserId);
508        if (cn == null) {
509            System.err.println("Error: Not found; no service started.");
510        } else if (cn.getPackageName().equals("!")) {
511            System.err.println("Error: Requires permission " + cn.getClassName());
512        } else if (cn.getPackageName().equals("!!")) {
513            System.err.println("Error: " + cn.getClassName());
514        }
515    }
516
517    private void runStopService() throws Exception {
518        Intent intent = makeIntent(UserHandle.USER_CURRENT);
519        if (mUserId == UserHandle.USER_ALL) {
520            System.err.println("Error: Can't stop activity with user 'all'");
521            return;
522        }
523        System.out.println("Stopping service: " + intent);
524        int result = mAm.stopService(null, intent, intent.getType(), mUserId);
525        if (result == 0) {
526            System.err.println("Service not stopped: was not running.");
527        } else if (result == 1) {
528            System.err.println("Service stopped");
529        } else if (result == -1) {
530            System.err.println("Error stopping service");
531        }
532    }
533
534    private void runStart() throws Exception {
535        Intent intent = makeIntent(UserHandle.USER_CURRENT);
536
537        if (mUserId == UserHandle.USER_ALL) {
538            System.err.println("Error: Can't start service with user 'all'");
539            return;
540        }
541
542        String mimeType = intent.getType();
543        if (mimeType == null && intent.getData() != null
544                && "content".equals(intent.getData().getScheme())) {
545            mimeType = mAm.getProviderMimeType(intent.getData(), mUserId);
546        }
547
548        do {
549            if (mStopOption) {
550                String packageName;
551                if (intent.getComponent() != null) {
552                    packageName = intent.getComponent().getPackageName();
553                } else {
554                    IPackageManager pm = IPackageManager.Stub.asInterface(
555                            ServiceManager.getService("package"));
556                    if (pm == null) {
557                        System.err.println("Error: Package manager not running; aborting");
558                        return;
559                    }
560                    List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0,
561                            mUserId);
562                    if (activities == null || activities.size() <= 0) {
563                        System.err.println("Error: Intent does not match any activities: "
564                                + intent);
565                        return;
566                    } else if (activities.size() > 1) {
567                        System.err.println("Error: Intent matches multiple activities; can't stop: "
568                                + intent);
569                        return;
570                    }
571                    packageName = activities.get(0).activityInfo.packageName;
572                }
573                System.out.println("Stopping: " + packageName);
574                mAm.forceStopPackage(packageName, mUserId);
575                Thread.sleep(250);
576            }
577
578            System.out.println("Starting: " + intent);
579            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
580
581            ParcelFileDescriptor fd = null;
582            ProfilerInfo profilerInfo = null;
583
584            if (mProfileFile != null) {
585                try {
586                    fd = openForSystemServer(
587                            new File(mProfileFile),
588                            ParcelFileDescriptor.MODE_CREATE |
589                            ParcelFileDescriptor.MODE_TRUNCATE |
590                            ParcelFileDescriptor.MODE_READ_WRITE);
591                } catch (FileNotFoundException e) {
592                    System.err.println("Error: Unable to open file: " + mProfileFile);
593                    System.err.println("Consider using a file under /data/local/tmp/");
594                    return;
595                }
596                profilerInfo = new ProfilerInfo(mProfileFile, fd, mSamplingInterval, mAutoStop);
597            }
598
599            IActivityManager.WaitResult result = null;
600            int res;
601            final long startTime = SystemClock.uptimeMillis();
602            if (mWaitOption) {
603                result = mAm.startActivityAndWait(null, null, intent, mimeType,
604                            null, null, 0, mStartFlags, profilerInfo, null, mUserId);
605                res = result.result;
606            } else {
607                res = mAm.startActivityAsUser(null, null, intent, mimeType,
608                        null, null, 0, mStartFlags, profilerInfo, null, mUserId);
609            }
610            final long endTime = SystemClock.uptimeMillis();
611            PrintStream out = mWaitOption ? System.out : System.err;
612            boolean launched = false;
613            switch (res) {
614                case ActivityManager.START_SUCCESS:
615                    launched = true;
616                    break;
617                case ActivityManager.START_SWITCHES_CANCELED:
618                    launched = true;
619                    out.println(
620                            "Warning: Activity not started because the "
621                            + " current activity is being kept for the user.");
622                    break;
623                case ActivityManager.START_DELIVERED_TO_TOP:
624                    launched = true;
625                    out.println(
626                            "Warning: Activity not started, intent has "
627                            + "been delivered to currently running "
628                            + "top-most instance.");
629                    break;
630                case ActivityManager.START_RETURN_INTENT_TO_CALLER:
631                    launched = true;
632                    out.println(
633                            "Warning: Activity not started because intent "
634                            + "should be handled by the caller");
635                    break;
636                case ActivityManager.START_TASK_TO_FRONT:
637                    launched = true;
638                    out.println(
639                            "Warning: Activity not started, its current "
640                            + "task has been brought to the front");
641                    break;
642                case ActivityManager.START_INTENT_NOT_RESOLVED:
643                    out.println(
644                            "Error: Activity not started, unable to "
645                            + "resolve " + intent.toString());
646                    break;
647                case ActivityManager.START_CLASS_NOT_FOUND:
648                    out.println(NO_CLASS_ERROR_CODE);
649                    out.println("Error: Activity class " +
650                            intent.getComponent().toShortString()
651                            + " does not exist.");
652                    break;
653                case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
654                    out.println(
655                            "Error: Activity not started, you requested to "
656                            + "both forward and receive its result");
657                    break;
658                case ActivityManager.START_PERMISSION_DENIED:
659                    out.println(
660                            "Error: Activity not started, you do not "
661                            + "have permission to access it.");
662                    break;
663                case ActivityManager.START_NOT_VOICE_COMPATIBLE:
664                    out.println(
665                            "Error: Activity not started, voice control not allowed for: "
666                                    + intent);
667                    break;
668                case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY:
669                    out.println(
670                            "Error: Not allowed to start background user activity"
671                            + " that shouldn't be displayed for all users.");
672                    break;
673                default:
674                    out.println(
675                            "Error: Activity not started, unknown error code " + res);
676                    break;
677            }
678            if (mWaitOption && launched) {
679                if (result == null) {
680                    result = new IActivityManager.WaitResult();
681                    result.who = intent.getComponent();
682                }
683                System.out.println("Status: " + (result.timeout ? "timeout" : "ok"));
684                if (result.who != null) {
685                    System.out.println("Activity: " + result.who.flattenToShortString());
686                }
687                if (result.thisTime >= 0) {
688                    System.out.println("ThisTime: " + result.thisTime);
689                }
690                if (result.totalTime >= 0) {
691                    System.out.println("TotalTime: " + result.totalTime);
692                }
693                System.out.println("WaitTime: " + (endTime-startTime));
694                System.out.println("Complete");
695            }
696            mRepeat--;
697            if (mRepeat > 1) {
698                mAm.unhandledBack();
699            }
700        } while (mRepeat > 1);
701    }
702
703    private void runForceStop() throws Exception {
704        int userId = UserHandle.USER_ALL;
705
706        String opt;
707        while ((opt=nextOption()) != null) {
708            if (opt.equals("--user")) {
709                userId = parseUserArg(nextArgRequired());
710            } else {
711                System.err.println("Error: Unknown option: " + opt);
712                return;
713            }
714        }
715        mAm.forceStopPackage(nextArgRequired(), userId);
716    }
717
718    private void runKill() throws Exception {
719        int userId = UserHandle.USER_ALL;
720
721        String opt;
722        while ((opt=nextOption()) != null) {
723            if (opt.equals("--user")) {
724                userId = parseUserArg(nextArgRequired());
725            } else {
726                System.err.println("Error: Unknown option: " + opt);
727                return;
728            }
729        }
730        mAm.killBackgroundProcesses(nextArgRequired(), userId);
731    }
732
733    private void runKillAll() throws Exception {
734        mAm.killAllBackgroundProcesses();
735    }
736
737    private void sendBroadcast() throws Exception {
738        Intent intent = makeIntent(UserHandle.USER_CURRENT);
739        IntentReceiver receiver = new IntentReceiver();
740        String[] requiredPermissions = mReceiverPermission == null ? null
741                : new String[] {mReceiverPermission};
742        System.out.println("Broadcasting: " + intent);
743        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, requiredPermissions,
744                android.app.AppOpsManager.OP_NONE, null, true, false, mUserId);
745        receiver.waitForFinish();
746    }
747
748    private void runInstrument() throws Exception {
749        String profileFile = null;
750        boolean wait = false;
751        boolean rawMode = false;
752        boolean no_window_animation = false;
753        int userId = UserHandle.USER_CURRENT;
754        Bundle args = new Bundle();
755        String argKey = null, argValue = null;
756        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
757        String abi = null;
758
759        String opt;
760        while ((opt=nextOption()) != null) {
761            if (opt.equals("-p")) {
762                profileFile = nextArgRequired();
763            } else if (opt.equals("-w")) {
764                wait = true;
765            } else if (opt.equals("-r")) {
766                rawMode = true;
767            } else if (opt.equals("-e")) {
768                argKey = nextArgRequired();
769                argValue = nextArgRequired();
770                args.putString(argKey, argValue);
771            } else if (opt.equals("--no_window_animation")
772                    || opt.equals("--no-window-animation")) {
773                no_window_animation = true;
774            } else if (opt.equals("--user")) {
775                userId = parseUserArg(nextArgRequired());
776            } else if (opt.equals("--abi")) {
777                abi = nextArgRequired();
778            } else {
779                System.err.println("Error: Unknown option: " + opt);
780                return;
781            }
782        }
783
784        if (userId == UserHandle.USER_ALL) {
785            System.err.println("Error: Can't start instrumentation with user 'all'");
786            return;
787        }
788
789        String cnArg = nextArgRequired();
790        ComponentName cn = ComponentName.unflattenFromString(cnArg);
791        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
792
793        InstrumentationWatcher watcher = null;
794        UiAutomationConnection connection = null;
795        if (wait) {
796            watcher = new InstrumentationWatcher();
797            watcher.setRawOutput(rawMode);
798            connection = new UiAutomationConnection();
799        }
800
801        float[] oldAnims = null;
802        if (no_window_animation) {
803            oldAnims = wm.getAnimationScales();
804            wm.setAnimationScale(0, 0.0f);
805            wm.setAnimationScale(1, 0.0f);
806        }
807
808        if (abi != null) {
809            final String[] supportedAbis = Build.SUPPORTED_ABIS;
810            boolean matched = false;
811            for (String supportedAbi : supportedAbis) {
812                if (supportedAbi.equals(abi)) {
813                    matched = true;
814                    break;
815                }
816            }
817
818            if (!matched) {
819                throw new AndroidException(
820                        "INSTRUMENTATION_FAILED: Unsupported instruction set " + abi);
821            }
822        }
823
824        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, abi)) {
825            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
826        }
827
828        if (watcher != null) {
829            if (!watcher.waitForFinish()) {
830                System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
831            }
832        }
833
834        if (oldAnims != null) {
835            wm.setAnimationScales(oldAnims);
836        }
837    }
838
839    private void runTraceIpc() throws Exception {
840        String op = nextArgRequired();
841        if (op.equals("start")) {
842            runTraceIpcStart();
843        } else if (op.equals("stop")) {
844            runTraceIpcStop();
845        } else {
846            showError("Error: unknown command '" + op + "'");
847            return;
848        }
849    }
850
851    private void runTraceIpcStart() throws Exception {
852        System.out.println("Starting IPC tracing.");
853        mAm.startBinderTracking();
854    }
855
856    private void runTraceIpcStop() throws Exception {
857        String opt;
858        String filename = null;
859        while ((opt=nextOption()) != null) {
860            if (opt.equals("--dump-file")) {
861                filename = nextArgRequired();
862            } else {
863                System.err.println("Error: Unknown option: " + opt);
864                return;
865            }
866        }
867        if (filename == null) {
868            System.err.println("Error: Specify filename to dump logs to.");
869            return;
870        }
871
872        ParcelFileDescriptor fd = null;
873
874        try {
875            File file = new File(filename);
876            file.delete();
877            fd = openForSystemServer(file,
878                    ParcelFileDescriptor.MODE_CREATE |
879                            ParcelFileDescriptor.MODE_TRUNCATE |
880                            ParcelFileDescriptor.MODE_READ_WRITE);
881        } catch (FileNotFoundException e) {
882            System.err.println("Error: Unable to open file: " + filename);
883            System.err.println("Consider using a file under /data/local/tmp/");
884            return;
885        }
886
887        ;
888        if (!mAm.stopBinderTrackingAndDump(fd)) {
889            throw new AndroidException("STOP TRACE FAILED.");
890        }
891
892        System.out.println("Stopped IPC tracing. Dumping logs to: " + filename);
893    }
894
895    static void removeWallOption() {
896        String props = SystemProperties.get("dalvik.vm.extra-opts");
897        if (props != null && props.contains("-Xprofile:wallclock")) {
898            props = props.replace("-Xprofile:wallclock", "");
899            props = props.trim();
900            SystemProperties.set("dalvik.vm.extra-opts", props);
901        }
902    }
903
904    private void runProfile() throws Exception {
905        String profileFile = null;
906        boolean start = false;
907        boolean wall = false;
908        int userId = UserHandle.USER_CURRENT;
909        int profileType = 0;
910        mSamplingInterval = 0;
911
912        String process = null;
913
914        String cmd = nextArgRequired();
915
916        if ("start".equals(cmd)) {
917            start = true;
918            String opt;
919            while ((opt=nextOption()) != null) {
920                if (opt.equals("--user")) {
921                    userId = parseUserArg(nextArgRequired());
922                } else if (opt.equals("--wall")) {
923                    wall = true;
924                } else if (opt.equals("--sampling")) {
925                    mSamplingInterval = Integer.parseInt(nextArgRequired());
926                } else {
927                    System.err.println("Error: Unknown option: " + opt);
928                    return;
929                }
930            }
931            process = nextArgRequired();
932        } else if ("stop".equals(cmd)) {
933            String opt;
934            while ((opt=nextOption()) != null) {
935                if (opt.equals("--user")) {
936                    userId = parseUserArg(nextArgRequired());
937                } else {
938                    System.err.println("Error: Unknown option: " + opt);
939                    return;
940                }
941            }
942            process = nextArg();
943        } else {
944            // Compatibility with old syntax: process is specified first.
945            process = cmd;
946            cmd = nextArgRequired();
947            if ("start".equals(cmd)) {
948                start = true;
949            } else if (!"stop".equals(cmd)) {
950                throw new IllegalArgumentException("Profile command " + process + " not valid");
951            }
952        }
953
954        if (userId == UserHandle.USER_ALL) {
955            System.err.println("Error: Can't profile with user 'all'");
956            return;
957        }
958
959        ParcelFileDescriptor fd = null;
960        ProfilerInfo profilerInfo = null;
961
962        if (start) {
963            profileFile = nextArgRequired();
964            try {
965                fd = openForSystemServer(
966                        new File(profileFile),
967                        ParcelFileDescriptor.MODE_CREATE |
968                        ParcelFileDescriptor.MODE_TRUNCATE |
969                        ParcelFileDescriptor.MODE_READ_WRITE);
970            } catch (FileNotFoundException e) {
971                System.err.println("Error: Unable to open file: " + profileFile);
972                System.err.println("Consider using a file under /data/local/tmp/");
973                return;
974            }
975            profilerInfo = new ProfilerInfo(profileFile, fd, mSamplingInterval, false);
976        }
977
978        try {
979            if (wall) {
980                // XXX doesn't work -- this needs to be set before booting.
981                String props = SystemProperties.get("dalvik.vm.extra-opts");
982                if (props == null || !props.contains("-Xprofile:wallclock")) {
983                    props = props + " -Xprofile:wallclock";
984                    //SystemProperties.set("dalvik.vm.extra-opts", props);
985                }
986            } else if (start) {
987                //removeWallOption();
988            }
989            if (!mAm.profileControl(process, userId, start, profilerInfo, profileType)) {
990                wall = false;
991                throw new AndroidException("PROFILE FAILED on process " + process);
992            }
993        } finally {
994            if (!wall) {
995                //removeWallOption();
996            }
997        }
998    }
999
1000    private void runDumpHeap() throws Exception {
1001        boolean managed = true;
1002        int userId = UserHandle.USER_CURRENT;
1003
1004        String opt;
1005        while ((opt=nextOption()) != null) {
1006            if (opt.equals("--user")) {
1007                userId = parseUserArg(nextArgRequired());
1008                if (userId == UserHandle.USER_ALL) {
1009                    System.err.println("Error: Can't dump heap with user 'all'");
1010                    return;
1011                }
1012            } else if (opt.equals("-n")) {
1013                managed = false;
1014            } else {
1015                System.err.println("Error: Unknown option: " + opt);
1016                return;
1017            }
1018        }
1019        String process = nextArgRequired();
1020        String heapFile = nextArgRequired();
1021        ParcelFileDescriptor fd = null;
1022
1023        try {
1024            File file = new File(heapFile);
1025            file.delete();
1026            fd = openForSystemServer(file,
1027                    ParcelFileDescriptor.MODE_CREATE |
1028                    ParcelFileDescriptor.MODE_TRUNCATE |
1029                    ParcelFileDescriptor.MODE_READ_WRITE);
1030        } catch (FileNotFoundException e) {
1031            System.err.println("Error: Unable to open file: " + heapFile);
1032            System.err.println("Consider using a file under /data/local/tmp/");
1033            return;
1034        }
1035
1036        if (!mAm.dumpHeap(process, userId, managed, heapFile, fd)) {
1037            throw new AndroidException("HEAP DUMP FAILED on process " + process);
1038        }
1039    }
1040
1041    private void runSetDebugApp() throws Exception {
1042        boolean wait = false;
1043        boolean persistent = false;
1044
1045        String opt;
1046        while ((opt=nextOption()) != null) {
1047            if (opt.equals("-w")) {
1048                wait = true;
1049            } else if (opt.equals("--persistent")) {
1050                persistent = true;
1051            } else {
1052                System.err.println("Error: Unknown option: " + opt);
1053                return;
1054            }
1055        }
1056
1057        String pkg = nextArgRequired();
1058        mAm.setDebugApp(pkg, wait, persistent);
1059    }
1060
1061    private void runClearDebugApp() throws Exception {
1062        mAm.setDebugApp(null, false, true);
1063    }
1064
1065    private void runSetWatchHeap() throws Exception {
1066        String proc = nextArgRequired();
1067        String limit = nextArgRequired();
1068        mAm.setDumpHeapDebugLimit(proc, 0, Long.parseLong(limit), null);
1069    }
1070
1071    private void runClearWatchHeap() throws Exception {
1072        String proc = nextArgRequired();
1073        mAm.setDumpHeapDebugLimit(proc, 0, -1, null);
1074    }
1075
1076    private void runBugReport() throws Exception {
1077        String opt;
1078        boolean progress = false;
1079        while ((opt=nextOption()) != null) {
1080            if (opt.equals("--progress")) {
1081                progress = true;
1082            } else {
1083                System.err.println("Error: Unknown option: " + opt);
1084                return;
1085            }
1086        }
1087        mAm.requestBugReport(progress);
1088        System.out.println("Your lovely bug report is being created; please be patient.");
1089    }
1090
1091    private void runSwitchUser() throws Exception {
1092        String user = nextArgRequired();
1093        mAm.switchUser(Integer.parseInt(user));
1094    }
1095
1096    private void runStartUserInBackground() throws Exception {
1097        String user = nextArgRequired();
1098        boolean success = mAm.startUserInBackground(Integer.parseInt(user));
1099        if (success) {
1100            System.out.println("Success: user started");
1101        } else {
1102            System.err.println("Error: could not start user");
1103        }
1104    }
1105
1106    private void runUnlockUser() throws Exception {
1107        int userId = Integer.parseInt(nextArgRequired());
1108        String tokenHex = nextArg();
1109        byte[] token = null;
1110        if (tokenHex != null) {
1111            token = HexDump.hexStringToByteArray(tokenHex);
1112        }
1113        boolean success = mAm.unlockUser(userId, token);
1114        if (success) {
1115            System.out.println("Success: user unlocked");
1116        } else {
1117            System.err.println("Error: could not unlock user");
1118        }
1119    }
1120
1121    private static class StopUserCallback extends IStopUserCallback.Stub {
1122        private boolean mFinished = false;
1123
1124        public synchronized void waitForFinish() {
1125            try {
1126                while (!mFinished) wait();
1127            } catch (InterruptedException e) {
1128                throw new IllegalStateException(e);
1129            }
1130        }
1131
1132        @Override
1133        public synchronized void userStopped(int userId) {
1134            mFinished = true;
1135            notifyAll();
1136        }
1137
1138        @Override
1139        public synchronized void userStopAborted(int userId) {
1140            mFinished = true;
1141            notifyAll();
1142        }
1143    }
1144
1145    private void runStopUser() throws Exception {
1146        boolean wait = false;
1147        boolean force = false;
1148        String opt;
1149        while ((opt = nextOption()) != null) {
1150            if ("-w".equals(opt)) {
1151                wait = true;
1152            } else if ("-f".equals(opt)) {
1153                force = true;
1154            } else {
1155                System.err.println("Error: unknown option: " + opt);
1156                return;
1157            }
1158        }
1159        int user = Integer.parseInt(nextArgRequired());
1160        StopUserCallback callback = wait ? new StopUserCallback() : null;
1161
1162        int res = mAm.stopUser(user, force, callback);
1163        if (res != ActivityManager.USER_OP_SUCCESS) {
1164            String txt = "";
1165            switch (res) {
1166                case ActivityManager.USER_OP_IS_CURRENT:
1167                    txt = " (Can't stop current user)";
1168                    break;
1169                case ActivityManager.USER_OP_UNKNOWN_USER:
1170                    txt = " (Unknown user " + user + ")";
1171                    break;
1172                case ActivityManager.USER_OP_ERROR_IS_SYSTEM:
1173                    txt = " (System user cannot be stopped)";
1174                    break;
1175                case ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP:
1176                    txt = " (Can't stop user " + user
1177                            + " - one of its related users can't be stopped)";
1178                    break;
1179            }
1180            System.err.println("Switch failed: " + res + txt);
1181        } else if (callback != null) {
1182            callback.waitForFinish();
1183        }
1184    }
1185
1186    class MyActivityController extends IActivityController.Stub {
1187        final String mGdbPort;
1188
1189        static final int STATE_NORMAL = 0;
1190        static final int STATE_CRASHED = 1;
1191        static final int STATE_EARLY_ANR = 2;
1192        static final int STATE_ANR = 3;
1193
1194        int mState;
1195
1196        static final int RESULT_DEFAULT = 0;
1197
1198        static final int RESULT_CRASH_DIALOG = 0;
1199        static final int RESULT_CRASH_KILL = 1;
1200
1201        static final int RESULT_EARLY_ANR_CONTINUE = 0;
1202        static final int RESULT_EARLY_ANR_KILL = 1;
1203
1204        static final int RESULT_ANR_DIALOG = 0;
1205        static final int RESULT_ANR_KILL = 1;
1206        static final int RESULT_ANR_WAIT = 1;
1207
1208        int mResult;
1209
1210        Process mGdbProcess;
1211        Thread mGdbThread;
1212        boolean mGotGdbPrint;
1213
1214        MyActivityController(String gdbPort) {
1215            mGdbPort = gdbPort;
1216        }
1217
1218        @Override
1219        public boolean activityResuming(String pkg) {
1220            synchronized (this) {
1221                System.out.println("** Activity resuming: " + pkg);
1222            }
1223            return true;
1224        }
1225
1226        @Override
1227        public boolean activityStarting(Intent intent, String pkg) {
1228            synchronized (this) {
1229                System.out.println("** Activity starting: " + pkg);
1230            }
1231            return true;
1232        }
1233
1234        @Override
1235        public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
1236                long timeMillis, String stackTrace) {
1237            synchronized (this) {
1238                System.out.println("** ERROR: PROCESS CRASHED");
1239                System.out.println("processName: " + processName);
1240                System.out.println("processPid: " + pid);
1241                System.out.println("shortMsg: " + shortMsg);
1242                System.out.println("longMsg: " + longMsg);
1243                System.out.println("timeMillis: " + timeMillis);
1244                System.out.println("stack:");
1245                System.out.print(stackTrace);
1246                System.out.println("#");
1247                int result = waitControllerLocked(pid, STATE_CRASHED);
1248                return result == RESULT_CRASH_KILL ? false : true;
1249            }
1250        }
1251
1252        @Override
1253        public int appEarlyNotResponding(String processName, int pid, String annotation) {
1254            synchronized (this) {
1255                System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING");
1256                System.out.println("processName: " + processName);
1257                System.out.println("processPid: " + pid);
1258                System.out.println("annotation: " + annotation);
1259                int result = waitControllerLocked(pid, STATE_EARLY_ANR);
1260                if (result == RESULT_EARLY_ANR_KILL) return -1;
1261                return 0;
1262            }
1263        }
1264
1265        @Override
1266        public int appNotResponding(String processName, int pid, String processStats) {
1267            synchronized (this) {
1268                System.out.println("** ERROR: PROCESS NOT RESPONDING");
1269                System.out.println("processName: " + processName);
1270                System.out.println("processPid: " + pid);
1271                System.out.println("processStats:");
1272                System.out.print(processStats);
1273                System.out.println("#");
1274                int result = waitControllerLocked(pid, STATE_ANR);
1275                if (result == RESULT_ANR_KILL) return -1;
1276                if (result == RESULT_ANR_WAIT) return 1;
1277                return 0;
1278            }
1279        }
1280
1281        @Override
1282        public int systemNotResponding(String message) {
1283            synchronized (this) {
1284                System.out.println("** ERROR: PROCESS NOT RESPONDING");
1285                System.out.println("message: " + message);
1286                System.out.println("#");
1287                System.out.println("Allowing system to die.");
1288                return -1;
1289            }
1290        }
1291
1292        void killGdbLocked() {
1293            mGotGdbPrint = false;
1294            if (mGdbProcess != null) {
1295                System.out.println("Stopping gdbserver");
1296                mGdbProcess.destroy();
1297                mGdbProcess = null;
1298            }
1299            if (mGdbThread != null) {
1300                mGdbThread.interrupt();
1301                mGdbThread = null;
1302            }
1303        }
1304
1305        int waitControllerLocked(int pid, int state) {
1306            if (mGdbPort != null) {
1307                killGdbLocked();
1308
1309                try {
1310                    System.out.println("Starting gdbserver on port " + mGdbPort);
1311                    System.out.println("Do the following:");
1312                    System.out.println("  adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort);
1313                    System.out.println("  gdbclient app_process :" + mGdbPort);
1314
1315                    mGdbProcess = Runtime.getRuntime().exec(new String[] {
1316                            "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid)
1317                    });
1318                    final InputStreamReader converter = new InputStreamReader(
1319                            mGdbProcess.getInputStream());
1320                    mGdbThread = new Thread() {
1321                        @Override
1322                        public void run() {
1323                            BufferedReader in = new BufferedReader(converter);
1324                            String line;
1325                            int count = 0;
1326                            while (true) {
1327                                synchronized (MyActivityController.this) {
1328                                    if (mGdbThread == null) {
1329                                        return;
1330                                    }
1331                                    if (count == 2) {
1332                                        mGotGdbPrint = true;
1333                                        MyActivityController.this.notifyAll();
1334                                    }
1335                                }
1336                                try {
1337                                    line = in.readLine();
1338                                    if (line == null) {
1339                                        return;
1340                                    }
1341                                    System.out.println("GDB: " + line);
1342                                    count++;
1343                                } catch (IOException e) {
1344                                    return;
1345                                }
1346                            }
1347                        }
1348                    };
1349                    mGdbThread.start();
1350
1351                    // Stupid waiting for .5s.  Doesn't matter if we end early.
1352                    try {
1353                        this.wait(500);
1354                    } catch (InterruptedException e) {
1355                    }
1356
1357                } catch (IOException e) {
1358                    System.err.println("Failure starting gdbserver: " + e);
1359                    killGdbLocked();
1360                }
1361            }
1362            mState = state;
1363            System.out.println("");
1364            printMessageForState();
1365
1366            while (mState != STATE_NORMAL) {
1367                try {
1368                    wait();
1369                } catch (InterruptedException e) {
1370                }
1371            }
1372
1373            killGdbLocked();
1374
1375            return mResult;
1376        }
1377
1378        void resumeController(int result) {
1379            synchronized (this) {
1380                mState = STATE_NORMAL;
1381                mResult = result;
1382                notifyAll();
1383            }
1384        }
1385
1386        void printMessageForState() {
1387            switch (mState) {
1388                case STATE_NORMAL:
1389                    System.out.println("Monitoring activity manager...  available commands:");
1390                    break;
1391                case STATE_CRASHED:
1392                    System.out.println("Waiting after crash...  available commands:");
1393                    System.out.println("(c)ontinue: show crash dialog");
1394                    System.out.println("(k)ill: immediately kill app");
1395                    break;
1396                case STATE_EARLY_ANR:
1397                    System.out.println("Waiting after early ANR...  available commands:");
1398                    System.out.println("(c)ontinue: standard ANR processing");
1399                    System.out.println("(k)ill: immediately kill app");
1400                    break;
1401                case STATE_ANR:
1402                    System.out.println("Waiting after ANR...  available commands:");
1403                    System.out.println("(c)ontinue: show ANR dialog");
1404                    System.out.println("(k)ill: immediately kill app");
1405                    System.out.println("(w)ait: wait some more");
1406                    break;
1407            }
1408            System.out.println("(q)uit: finish monitoring");
1409        }
1410
1411        void run() throws RemoteException {
1412            try {
1413                printMessageForState();
1414
1415                mAm.setActivityController(this);
1416                mState = STATE_NORMAL;
1417
1418                InputStreamReader converter = new InputStreamReader(System.in);
1419                BufferedReader in = new BufferedReader(converter);
1420                String line;
1421
1422                while ((line = in.readLine()) != null) {
1423                    boolean addNewline = true;
1424                    if (line.length() <= 0) {
1425                        addNewline = false;
1426                    } else if ("q".equals(line) || "quit".equals(line)) {
1427                        resumeController(RESULT_DEFAULT);
1428                        break;
1429                    } else if (mState == STATE_CRASHED) {
1430                        if ("c".equals(line) || "continue".equals(line)) {
1431                            resumeController(RESULT_CRASH_DIALOG);
1432                        } else if ("k".equals(line) || "kill".equals(line)) {
1433                            resumeController(RESULT_CRASH_KILL);
1434                        } else {
1435                            System.out.println("Invalid command: " + line);
1436                        }
1437                    } else if (mState == STATE_ANR) {
1438                        if ("c".equals(line) || "continue".equals(line)) {
1439                            resumeController(RESULT_ANR_DIALOG);
1440                        } else if ("k".equals(line) || "kill".equals(line)) {
1441                            resumeController(RESULT_ANR_KILL);
1442                        } else if ("w".equals(line) || "wait".equals(line)) {
1443                            resumeController(RESULT_ANR_WAIT);
1444                        } else {
1445                            System.out.println("Invalid command: " + line);
1446                        }
1447                    } else if (mState == STATE_EARLY_ANR) {
1448                        if ("c".equals(line) || "continue".equals(line)) {
1449                            resumeController(RESULT_EARLY_ANR_CONTINUE);
1450                        } else if ("k".equals(line) || "kill".equals(line)) {
1451                            resumeController(RESULT_EARLY_ANR_KILL);
1452                        } else {
1453                            System.out.println("Invalid command: " + line);
1454                        }
1455                    } else {
1456                        System.out.println("Invalid command: " + line);
1457                    }
1458
1459                    synchronized (this) {
1460                        if (addNewline) {
1461                            System.out.println("");
1462                        }
1463                        printMessageForState();
1464                    }
1465                }
1466
1467            } catch (IOException e) {
1468                e.printStackTrace();
1469            } finally {
1470                mAm.setActivityController(null);
1471            }
1472        }
1473    }
1474
1475    private void runMonitor() throws Exception {
1476        String opt;
1477        String gdbPort = null;
1478        while ((opt=nextOption()) != null) {
1479            if (opt.equals("--gdb")) {
1480                gdbPort = nextArgRequired();
1481            } else {
1482                System.err.println("Error: Unknown option: " + opt);
1483                return;
1484            }
1485        }
1486
1487        MyActivityController controller = new MyActivityController(gdbPort);
1488        controller.run();
1489    }
1490
1491    private void runHang() throws Exception {
1492        String opt;
1493        boolean allowRestart = false;
1494        while ((opt=nextOption()) != null) {
1495            if (opt.equals("--allow-restart")) {
1496                allowRestart = true;
1497            } else {
1498                System.err.println("Error: Unknown option: " + opt);
1499                return;
1500            }
1501        }
1502
1503        System.out.println("Hanging the system...");
1504        mAm.hang(new Binder(), allowRestart);
1505    }
1506
1507    private void runRestart() throws Exception {
1508        String opt;
1509        while ((opt=nextOption()) != null) {
1510            System.err.println("Error: Unknown option: " + opt);
1511            return;
1512        }
1513
1514        System.out.println("Restart the system...");
1515        mAm.restart();
1516    }
1517
1518    private void runIdleMaintenance() throws Exception {
1519        String opt;
1520        while ((opt=nextOption()) != null) {
1521            System.err.println("Error: Unknown option: " + opt);
1522            return;
1523        }
1524
1525        System.out.println("Performing idle maintenance...");
1526        Intent intent = new Intent(
1527                "com.android.server.task.controllers.IdleController.ACTION_TRIGGER_IDLE");
1528        mAm.broadcastIntent(null, intent, null, null, 0, null, null, null,
1529                android.app.AppOpsManager.OP_NONE, null, true, false, UserHandle.USER_ALL);
1530    }
1531
1532    private void runScreenCompat() throws Exception {
1533        String mode = nextArgRequired();
1534        boolean enabled;
1535        if ("on".equals(mode)) {
1536            enabled = true;
1537        } else if ("off".equals(mode)) {
1538            enabled = false;
1539        } else {
1540            System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode);
1541            return;
1542        }
1543
1544        String packageName = nextArgRequired();
1545        do {
1546            try {
1547                mAm.setPackageScreenCompatMode(packageName, enabled
1548                        ? ActivityManager.COMPAT_MODE_ENABLED
1549                        : ActivityManager.COMPAT_MODE_DISABLED);
1550            } catch (RemoteException e) {
1551            }
1552            packageName = nextArg();
1553        } while (packageName != null);
1554    }
1555
1556    private void runPackageImportance() throws Exception {
1557        String packageName = nextArgRequired();
1558        try {
1559            int procState = mAm.getPackageProcessState(packageName, "com.android.shell");
1560            System.out.println(
1561                    ActivityManager.RunningAppProcessInfo.procStateToImportance(procState));
1562        } catch (RemoteException e) {
1563        }
1564    }
1565
1566    private void runToUri(int flags) throws Exception {
1567        Intent intent = makeIntent(UserHandle.USER_CURRENT);
1568        System.out.println(intent.toUri(flags));
1569    }
1570
1571    private class IntentReceiver extends IIntentReceiver.Stub {
1572        private boolean mFinished = false;
1573
1574        @Override
1575        public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
1576                boolean ordered, boolean sticky, int sendingUser) {
1577            String line = "Broadcast completed: result=" + resultCode;
1578            if (data != null) line = line + ", data=\"" + data + "\"";
1579            if (extras != null) line = line + ", extras: " + extras;
1580            System.out.println(line);
1581            synchronized (this) {
1582              mFinished = true;
1583              notifyAll();
1584            }
1585        }
1586
1587        public synchronized void waitForFinish() {
1588            try {
1589                while (!mFinished) wait();
1590            } catch (InterruptedException e) {
1591                throw new IllegalStateException(e);
1592            }
1593        }
1594    }
1595
1596    private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
1597        private boolean mFinished = false;
1598        private boolean mRawMode = false;
1599
1600        /**
1601         * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode",
1602         * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
1603         * @param rawMode true for raw mode, false for pretty mode.
1604         */
1605        public void setRawOutput(boolean rawMode) {
1606            mRawMode = rawMode;
1607        }
1608
1609        @Override
1610        public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
1611            synchronized (this) {
1612                // pretty printer mode?
1613                String pretty = null;
1614                if (!mRawMode && results != null) {
1615                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1616                }
1617                if (pretty != null) {
1618                    System.out.print(pretty);
1619                } else {
1620                    if (results != null) {
1621                        for (String key : results.keySet()) {
1622                            System.out.println(
1623                                    "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
1624                        }
1625                    }
1626                    System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
1627                }
1628                notifyAll();
1629            }
1630        }
1631
1632        @Override
1633        public void instrumentationFinished(ComponentName name, int resultCode,
1634                Bundle results) {
1635            synchronized (this) {
1636                // pretty printer mode?
1637                String pretty = null;
1638                if (!mRawMode && results != null) {
1639                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1640                }
1641                if (pretty != null) {
1642                    System.out.println(pretty);
1643                } else {
1644                    if (results != null) {
1645                        for (String key : results.keySet()) {
1646                            System.out.println(
1647                                    "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
1648                        }
1649                    }
1650                    System.out.println("INSTRUMENTATION_CODE: " + resultCode);
1651                }
1652                mFinished = true;
1653                notifyAll();
1654            }
1655        }
1656
1657        public boolean waitForFinish() {
1658            synchronized (this) {
1659                while (!mFinished) {
1660                    try {
1661                        if (!mAm.asBinder().pingBinder()) {
1662                            return false;
1663                        }
1664                        wait(1000);
1665                    } catch (InterruptedException e) {
1666                        throw new IllegalStateException(e);
1667                    }
1668                }
1669            }
1670            return true;
1671        }
1672    }
1673
1674    private void runStack() throws Exception {
1675        String op = nextArgRequired();
1676        switch (op) {
1677            case "start":
1678                runStackStart();
1679                break;
1680            case "movetask":
1681                runStackMoveTask();
1682                break;
1683            case "resize":
1684                runStackResize();
1685                break;
1686            case "positiontask":
1687                runStackPositionTask();
1688                break;
1689            case "list":
1690                runStackList();
1691                break;
1692            case "info":
1693                runStackInfo();
1694                break;
1695            case "move-top-activity-to-pinned-stack":
1696                runMoveTopActivityToPinnedStack();
1697                break;
1698            case "size-docked-stack-test":
1699                runStackSizeDockedStackTest();
1700                break;
1701            default:
1702                showError("Error: unknown command '" + op + "'");
1703                break;
1704        }
1705    }
1706
1707    private void runStackStart() throws Exception {
1708        String displayIdStr = nextArgRequired();
1709        int displayId = Integer.valueOf(displayIdStr);
1710        Intent intent = makeIntent(UserHandle.USER_CURRENT);
1711
1712        try {
1713            IActivityContainer container = mAm.createStackOnDisplay(displayId);
1714            if (container != null) {
1715                container.startActivity(intent);
1716            }
1717        } catch (RemoteException e) {
1718        }
1719    }
1720
1721    private void runStackMoveTask() throws Exception {
1722        String taskIdStr = nextArgRequired();
1723        int taskId = Integer.valueOf(taskIdStr);
1724        String stackIdStr = nextArgRequired();
1725        int stackId = Integer.valueOf(stackIdStr);
1726        String toTopStr = nextArgRequired();
1727        final boolean toTop;
1728        if ("true".equals(toTopStr)) {
1729            toTop = true;
1730        } else if ("false".equals(toTopStr)) {
1731            toTop = false;
1732        } else {
1733            System.err.println("Error: bad toTop arg: " + toTopStr);
1734            return;
1735        }
1736
1737        try {
1738            mAm.moveTaskToStack(taskId, stackId, toTop);
1739        } catch (RemoteException e) {
1740        }
1741    }
1742
1743    private void runStackResize() throws Exception {
1744        String stackIdStr = nextArgRequired();
1745        int stackId = Integer.valueOf(stackIdStr);
1746        final Rect bounds = getBounds();
1747        if (bounds == null) {
1748            System.err.println("Error: invalid input bounds");
1749            return;
1750        }
1751        resizeStack(stackId, bounds, 0);
1752    }
1753
1754    private void resizeStack(int stackId, Rect bounds, int delayMs) throws Exception {
1755        if (bounds == null) {
1756            showError("Error: invalid input bounds");
1757            return;
1758        }
1759
1760        try {
1761            mAm.resizeStack(stackId, bounds, false);
1762            Thread.sleep(delayMs);
1763        } catch (RemoteException e) {
1764            showError("Error: resizing stack " + e);
1765        } catch (InterruptedException e) {
1766        }
1767    }
1768
1769    private void runStackPositionTask() throws Exception {
1770        String taskIdStr = nextArgRequired();
1771        int taskId = Integer.valueOf(taskIdStr);
1772        String stackIdStr = nextArgRequired();
1773        int stackId = Integer.valueOf(stackIdStr);
1774        String positionStr = nextArgRequired();
1775        int position = Integer.valueOf(positionStr);
1776
1777        try {
1778            mAm.positionTaskInStack(taskId, stackId, position);
1779        } catch (RemoteException e) {
1780        }
1781    }
1782
1783    private void runStackList() throws Exception {
1784        try {
1785            List<StackInfo> stacks = mAm.getAllStackInfos();
1786            for (StackInfo info : stacks) {
1787                System.out.println(info);
1788            }
1789        } catch (RemoteException e) {
1790        }
1791    }
1792
1793    private void runStackInfo() throws Exception {
1794        try {
1795            String stackIdStr = nextArgRequired();
1796            int stackId = Integer.valueOf(stackIdStr);
1797            StackInfo info = mAm.getStackInfo(stackId);
1798            System.out.println(info);
1799        } catch (RemoteException e) {
1800        }
1801    }
1802
1803    private void runMoveTopActivityToPinnedStack() throws Exception {
1804        int stackId = Integer.valueOf(nextArgRequired());
1805        final Rect bounds = getBounds();
1806        if (bounds == null) {
1807            System.err.println("Error: invalid input bounds");
1808            return;
1809        }
1810
1811        try {
1812            if (!mAm.moveTopActivityToPinnedStack(stackId, bounds)) {
1813                showError("Didn't move top activity to pinned stack.");
1814            }
1815        } catch (RemoteException e) {
1816            showError("Unable to move top activity: " + e);
1817            return;
1818        }
1819    }
1820
1821    private void runStackSizeDockedStackTest() throws Exception {
1822        final int stepSize = Integer.valueOf(nextArgRequired());
1823        final String side = nextArgRequired();
1824        final String delayStr = nextArg();
1825        final int delayMs = (delayStr != null) ? Integer.valueOf(delayStr) : 0;
1826
1827        Rect bounds;
1828        try {
1829            StackInfo info = mAm.getStackInfo(DOCKED_STACK_ID);
1830            if (info == null) {
1831                showError("Docked stack doesn't exist");
1832                return;
1833            }
1834            if (info.bounds == null) {
1835                showError("Docked stack doesn't have a bounds");
1836                return;
1837            }
1838            bounds = info.bounds;
1839        } catch (RemoteException e) {
1840            showError("Unable to get docked stack info:" + e);
1841            return;
1842        }
1843
1844        final boolean horizontalGrowth = "l".equals(side) || "r".equals(side);
1845        final int changeSize = (horizontalGrowth ? bounds.width() : bounds.height()) / 2;
1846        int currentPoint;
1847        switch (side) {
1848            case "l":
1849                currentPoint = bounds.left;
1850                break;
1851            case "r":
1852                currentPoint = bounds.right;
1853                break;
1854            case "t":
1855                currentPoint = bounds.top;
1856                break;
1857            case "b":
1858                currentPoint = bounds.bottom;
1859                break;
1860            default:
1861                showError("Unknown growth side: " + side);
1862                return;
1863        }
1864
1865        final int startPoint = currentPoint;
1866        final int minPoint = currentPoint - changeSize;
1867        final int maxPoint = currentPoint + changeSize;
1868
1869        int maxChange;
1870        System.out.println("Shrinking docked stack side=" + side);
1871        while (currentPoint > minPoint) {
1872            maxChange = Math.min(stepSize, currentPoint - minPoint);
1873            currentPoint -= maxChange;
1874            setBoundsSide(bounds, side, currentPoint);
1875            resizeStack(DOCKED_STACK_ID, bounds, delayMs);
1876        }
1877
1878        System.out.println("Growing docked stack side=" + side);
1879        while (currentPoint < maxPoint) {
1880            maxChange = Math.min(stepSize, maxPoint - currentPoint);
1881            currentPoint += maxChange;
1882            setBoundsSide(bounds, side, currentPoint);
1883            resizeStack(DOCKED_STACK_ID, bounds, delayMs);
1884        }
1885
1886        System.out.println("Back to Original size side=" + side);
1887        while (currentPoint > startPoint) {
1888            maxChange = Math.min(stepSize, currentPoint - startPoint);
1889            currentPoint -= maxChange;
1890            setBoundsSide(bounds, side, currentPoint);
1891            resizeStack(DOCKED_STACK_ID, bounds, delayMs);
1892        }
1893    }
1894
1895    private void setBoundsSide(Rect bounds, String side, int value) {
1896        switch (side) {
1897            case "l":
1898                bounds.left = value;
1899                break;
1900            case "r":
1901                bounds.right = value;
1902                break;
1903            case "t":
1904                bounds.top = value;
1905                break;
1906            case "b":
1907                bounds.bottom = value;
1908                break;
1909            default:
1910                showError("Unknown set side: " + side);
1911                break;
1912        }
1913    }
1914
1915    private void runTask() throws Exception {
1916        String op = nextArgRequired();
1917        if (op.equals("lock")) {
1918            runTaskLock();
1919        } else if (op.equals("resizeable")) {
1920            runTaskResizeable();
1921        } else if (op.equals("resize")) {
1922            runTaskResize();
1923        } else if (op.equals("drag-task-test")) {
1924            runTaskDragTaskTest();
1925        } else if (op.equals("size-task-test")) {
1926            runTaskSizeTaskTest();
1927        } else {
1928            showError("Error: unknown command '" + op + "'");
1929            return;
1930        }
1931    }
1932
1933    private void runTaskLock() throws Exception {
1934        String taskIdStr = nextArgRequired();
1935        try {
1936            if (taskIdStr.equals("stop")) {
1937                mAm.stopLockTaskMode();
1938            } else {
1939                int taskId = Integer.valueOf(taskIdStr);
1940                mAm.startLockTaskMode(taskId);
1941            }
1942            System.err.println("Activity manager is " + (mAm.isInLockTaskMode() ? "" : "not ") +
1943                    "in lockTaskMode");
1944        } catch (RemoteException e) {
1945        }
1946    }
1947
1948    private void runTaskResizeable() throws Exception {
1949        final String taskIdStr = nextArgRequired();
1950        final int taskId = Integer.valueOf(taskIdStr);
1951        final String resizeableStr = nextArgRequired();
1952        final boolean resizeable = Boolean.valueOf(resizeableStr);
1953
1954        try {
1955            mAm.setTaskResizeable(taskId, resizeable);
1956        } catch (RemoteException e) {
1957        }
1958    }
1959
1960    private void runTaskResize() throws Exception {
1961        final String taskIdStr = nextArgRequired();
1962        final int taskId = Integer.valueOf(taskIdStr);
1963        final Rect bounds = getBounds();
1964        if (bounds == null) {
1965            System.err.println("Error: invalid input bounds");
1966            return;
1967        }
1968        taskResize(taskId, bounds, 0, false);
1969    }
1970
1971    private void taskResize(int taskId, Rect bounds, int delay_ms, boolean pretendUserResize) {
1972        try {
1973            final int resizeMode = pretendUserResize ? RESIZE_MODE_USER : RESIZE_MODE_SYSTEM;
1974            mAm.resizeTask(taskId, bounds, resizeMode);
1975            Thread.sleep(delay_ms);
1976        } catch (RemoteException e) {
1977            System.err.println("Error changing task bounds: " + e);
1978        } catch (InterruptedException e) {
1979        }
1980    }
1981
1982    private void runTaskDragTaskTest() {
1983        final int taskId = Integer.valueOf(nextArgRequired());
1984        final int stepSize = Integer.valueOf(nextArgRequired());
1985        final String delayStr = nextArg();
1986        final int delay_ms = (delayStr != null) ? Integer.valueOf(delayStr) : 0;
1987        final StackInfo stackInfo;
1988        Rect taskBounds;
1989        try {
1990            stackInfo = mAm.getStackInfo(mAm.getFocusedStackId());
1991            taskBounds = mAm.getTaskBounds(taskId);
1992        } catch (RemoteException e) {
1993            System.err.println("Error getting focus stack info or task bounds: " + e);
1994            return;
1995        }
1996        final Rect stackBounds = stackInfo.bounds;
1997        int travelRight = stackBounds.width() - taskBounds.width();
1998        int travelLeft = -travelRight;
1999        int travelDown = stackBounds.height() - taskBounds.height();
2000        int travelUp = -travelDown;
2001        int passes = 0;
2002
2003        // We do 2 passes to get back to the original location of the task.
2004        while (passes < 2) {
2005            // Move right
2006            System.out.println("Moving right...");
2007            travelRight = moveTask(taskId, taskBounds, stackBounds, stepSize,
2008                    travelRight, MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms);
2009            System.out.println("Still need to travel right by " + travelRight);
2010
2011            // Move down
2012            System.out.println("Moving down...");
2013            travelDown = moveTask(taskId, taskBounds, stackBounds, stepSize,
2014                    travelDown, MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms);
2015            System.out.println("Still need to travel down by " + travelDown);
2016
2017            // Move left
2018            System.out.println("Moving left...");
2019            travelLeft = moveTask(taskId, taskBounds, stackBounds, stepSize,
2020                    travelLeft, !MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms);
2021            System.out.println("Still need to travel left by " + travelLeft);
2022
2023            // Move up
2024            System.out.println("Moving up...");
2025            travelUp = moveTask(taskId, taskBounds, stackBounds, stepSize,
2026                    travelUp, !MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms);
2027            System.out.println("Still need to travel up by " + travelUp);
2028
2029            try {
2030                taskBounds = mAm.getTaskBounds(taskId);
2031            } catch (RemoteException e) {
2032                System.err.println("Error getting task bounds: " + e);
2033                return;
2034            }
2035            passes++;
2036        }
2037    }
2038
2039    private int moveTask(int taskId, Rect taskRect, Rect stackRect, int stepSize,
2040            int maxToTravel, boolean movingForward, boolean horizontal, int delay_ms) {
2041        int maxMove;
2042        if (movingForward) {
2043            while (maxToTravel > 0
2044                    && ((horizontal && taskRect.right < stackRect.right)
2045                        ||(!horizontal && taskRect.bottom < stackRect.bottom))) {
2046                if (horizontal) {
2047                    maxMove = Math.min(stepSize, stackRect.right - taskRect.right);
2048                    maxToTravel -= maxMove;
2049                    taskRect.right += maxMove;
2050                    taskRect.left += maxMove;
2051                } else {
2052                    maxMove = Math.min(stepSize, stackRect.bottom - taskRect.bottom);
2053                    maxToTravel -= maxMove;
2054                    taskRect.top += maxMove;
2055                    taskRect.bottom += maxMove;
2056                }
2057                taskResize(taskId, taskRect, delay_ms, false);
2058            }
2059        } else {
2060            while (maxToTravel < 0
2061                    && ((horizontal && taskRect.left > stackRect.left)
2062                    ||(!horizontal && taskRect.top > stackRect.top))) {
2063                if (horizontal) {
2064                    maxMove = Math.min(stepSize, taskRect.left - stackRect.left);
2065                    maxToTravel -= maxMove;
2066                    taskRect.right -= maxMove;
2067                    taskRect.left -= maxMove;
2068                } else {
2069                    maxMove = Math.min(stepSize, taskRect.top - stackRect.top);
2070                    maxToTravel -= maxMove;
2071                    taskRect.top -= maxMove;
2072                    taskRect.bottom -= maxMove;
2073                }
2074                taskResize(taskId, taskRect, delay_ms, false);
2075            }
2076        }
2077        // Return the remaining distance we didn't travel because we reached the target location.
2078        return maxToTravel;
2079    }
2080
2081    private void runTaskSizeTaskTest() {
2082        final int taskId = Integer.valueOf(nextArgRequired());
2083        final int stepSize = Integer.valueOf(nextArgRequired());
2084        final String delayStr = nextArg();
2085        final int delay_ms = (delayStr != null) ? Integer.valueOf(delayStr) : 0;
2086        final StackInfo stackInfo;
2087        final Rect initialTaskBounds;
2088        try {
2089            stackInfo = mAm.getStackInfo(mAm.getFocusedStackId());
2090            initialTaskBounds = mAm.getTaskBounds(taskId);
2091        } catch (RemoteException e) {
2092            System.err.println("Error getting focus stack info or task bounds: " + e);
2093            return;
2094        }
2095        final Rect stackBounds = stackInfo.bounds;
2096        stackBounds.inset(STACK_BOUNDS_INSET, STACK_BOUNDS_INSET);
2097        final Rect currentTaskBounds = new Rect(initialTaskBounds);
2098
2099        // Size by top-left
2100        System.out.println("Growing top-left");
2101        do {
2102            currentTaskBounds.top -= getStepSize(
2103                    currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET);
2104
2105            currentTaskBounds.left -= getStepSize(
2106                    currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET);
2107
2108            taskResize(taskId, currentTaskBounds, delay_ms, true);
2109        } while (stackBounds.top < currentTaskBounds.top
2110                || stackBounds.left < currentTaskBounds.left);
2111
2112        // Back to original size
2113        System.out.println("Shrinking top-left");
2114        do {
2115            currentTaskBounds.top += getStepSize(
2116                    currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET);
2117
2118            currentTaskBounds.left += getStepSize(
2119                    currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET);
2120
2121            taskResize(taskId, currentTaskBounds, delay_ms, true);
2122        } while (initialTaskBounds.top > currentTaskBounds.top
2123                || initialTaskBounds.left > currentTaskBounds.left);
2124
2125        // Size by top-right
2126        System.out.println("Growing top-right");
2127        do {
2128            currentTaskBounds.top -= getStepSize(
2129                    currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET);
2130
2131            currentTaskBounds.right += getStepSize(
2132                    currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET);
2133
2134            taskResize(taskId, currentTaskBounds, delay_ms, true);
2135        } while (stackBounds.top < currentTaskBounds.top
2136                || stackBounds.right > currentTaskBounds.right);
2137
2138        // Back to original size
2139        System.out.println("Shrinking top-right");
2140        do {
2141            currentTaskBounds.top += getStepSize(
2142                    currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET);
2143
2144            currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right,
2145                    stepSize, GREATER_THAN_TARGET);
2146
2147            taskResize(taskId, currentTaskBounds, delay_ms, true);
2148        } while (initialTaskBounds.top > currentTaskBounds.top
2149                || initialTaskBounds.right < currentTaskBounds.right);
2150
2151        // Size by bottom-left
2152        System.out.println("Growing bottom-left");
2153        do {
2154            currentTaskBounds.bottom += getStepSize(
2155                    currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET);
2156
2157            currentTaskBounds.left -= getStepSize(
2158                    currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET);
2159
2160            taskResize(taskId, currentTaskBounds, delay_ms, true);
2161        } while (stackBounds.bottom > currentTaskBounds.bottom
2162                || stackBounds.left < currentTaskBounds.left);
2163
2164        // Back to original size
2165        System.out.println("Shrinking bottom-left");
2166        do {
2167            currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom,
2168                    initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET);
2169
2170            currentTaskBounds.left += getStepSize(
2171                    currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET);
2172
2173            taskResize(taskId, currentTaskBounds, delay_ms, true);
2174        } while (initialTaskBounds.bottom < currentTaskBounds.bottom
2175                || initialTaskBounds.left > currentTaskBounds.left);
2176
2177        // Size by bottom-right
2178        System.out.println("Growing bottom-right");
2179        do {
2180            currentTaskBounds.bottom += getStepSize(
2181                    currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET);
2182
2183            currentTaskBounds.right += getStepSize(
2184                    currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET);
2185
2186            taskResize(taskId, currentTaskBounds, delay_ms, true);
2187        } while (stackBounds.bottom > currentTaskBounds.bottom
2188                || stackBounds.right > currentTaskBounds.right);
2189
2190        // Back to original size
2191        System.out.println("Shrinking bottom-right");
2192        do {
2193            currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom,
2194                    initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET);
2195
2196            currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right,
2197                    stepSize, GREATER_THAN_TARGET);
2198
2199            taskResize(taskId, currentTaskBounds, delay_ms, true);
2200        } while (initialTaskBounds.bottom < currentTaskBounds.bottom
2201                || initialTaskBounds.right < currentTaskBounds.right);
2202    }
2203
2204    private int getStepSize(int current, int target, int inStepSize, boolean greaterThanTarget) {
2205        int stepSize = 0;
2206        if (greaterThanTarget && target < current) {
2207            current -= inStepSize;
2208            stepSize = inStepSize;
2209            if (target > current) {
2210                stepSize -= (target - current);
2211            }
2212        }
2213        if (!greaterThanTarget && target > current) {
2214            current += inStepSize;
2215            stepSize = inStepSize;
2216            if (target < current) {
2217                stepSize += (current - target);
2218            }
2219        }
2220        return stepSize;
2221    }
2222
2223    private List<Configuration> getRecentConfigurations(int days) {
2224        IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2225                    Context.USAGE_STATS_SERVICE));
2226        final long now = System.currentTimeMillis();
2227        final long nDaysAgo = now - (days * 24 * 60 * 60 * 1000);
2228        try {
2229            @SuppressWarnings("unchecked")
2230            ParceledListSlice<ConfigurationStats> configStatsSlice = usm.queryConfigurationStats(
2231                    UsageStatsManager.INTERVAL_BEST, nDaysAgo, now, "com.android.shell");
2232            if (configStatsSlice == null) {
2233                return Collections.emptyList();
2234            }
2235
2236            final ArrayMap<Configuration, Integer> recentConfigs = new ArrayMap<>();
2237            final List<ConfigurationStats> configStatsList = configStatsSlice.getList();
2238            final int configStatsListSize = configStatsList.size();
2239            for (int i = 0; i < configStatsListSize; i++) {
2240                final ConfigurationStats stats = configStatsList.get(i);
2241                final int indexOfKey = recentConfigs.indexOfKey(stats.getConfiguration());
2242                if (indexOfKey < 0) {
2243                    recentConfigs.put(stats.getConfiguration(), stats.getActivationCount());
2244                } else {
2245                    recentConfigs.setValueAt(indexOfKey,
2246                            recentConfigs.valueAt(indexOfKey) + stats.getActivationCount());
2247                }
2248            }
2249
2250            final Comparator<Configuration> comparator = new Comparator<Configuration>() {
2251                @Override
2252                public int compare(Configuration a, Configuration b) {
2253                    return recentConfigs.get(b).compareTo(recentConfigs.get(a));
2254                }
2255            };
2256
2257            ArrayList<Configuration> configs = new ArrayList<>(recentConfigs.size());
2258            configs.addAll(recentConfigs.keySet());
2259            Collections.sort(configs, comparator);
2260            return configs;
2261
2262        } catch (RemoteException e) {
2263            return Collections.emptyList();
2264        }
2265    }
2266
2267    private void runGetConfig() throws Exception {
2268        int days = 14;
2269        String option = nextOption();
2270        if (option != null) {
2271            if (!option.equals("--days")) {
2272                throw new IllegalArgumentException("unrecognized option " + option);
2273            }
2274
2275            days = Integer.parseInt(nextArgRequired());
2276            if (days <= 0) {
2277                throw new IllegalArgumentException("--days must be a positive integer");
2278            }
2279        }
2280
2281        try {
2282            Configuration config = mAm.getConfiguration();
2283            if (config == null) {
2284                System.err.println("Activity manager has no configuration");
2285                return;
2286            }
2287
2288            System.out.println("config: " + Configuration.resourceQualifierString(config));
2289            System.out.println("abi: " + TextUtils.join(",", Build.SUPPORTED_ABIS));
2290
2291            final List<Configuration> recentConfigs = getRecentConfigurations(days);
2292            final int recentConfigSize = recentConfigs.size();
2293            if (recentConfigSize > 0) {
2294                System.out.println("recentConfigs:");
2295            }
2296
2297            for (int i = 0; i < recentConfigSize; i++) {
2298                System.out.println("  config: " + Configuration.resourceQualifierString(
2299                        recentConfigs.get(i)));
2300            }
2301
2302        } catch (RemoteException e) {
2303        }
2304    }
2305
2306    private void runSuppressResizeConfigChanges() throws Exception {
2307        boolean suppress = Boolean.valueOf(nextArgRequired());
2308
2309        try {
2310            mAm.suppressResizeConfigChanges(suppress);
2311        } catch (RemoteException e) {
2312            System.err.println("Error suppressing resize config changes: " + e);
2313        }
2314    }
2315
2316    private void runSetInactive() throws Exception {
2317        int userId = UserHandle.USER_CURRENT;
2318
2319        String opt;
2320        while ((opt=nextOption()) != null) {
2321            if (opt.equals("--user")) {
2322                userId = parseUserArg(nextArgRequired());
2323            } else {
2324                System.err.println("Error: Unknown option: " + opt);
2325                return;
2326            }
2327        }
2328        String packageName = nextArgRequired();
2329        String value = nextArgRequired();
2330
2331        IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2332                Context.USAGE_STATS_SERVICE));
2333        usm.setAppInactive(packageName, Boolean.parseBoolean(value), userId);
2334    }
2335
2336    private void runGetInactive() throws Exception {
2337        int userId = UserHandle.USER_CURRENT;
2338
2339        String opt;
2340        while ((opt=nextOption()) != null) {
2341            if (opt.equals("--user")) {
2342                userId = parseUserArg(nextArgRequired());
2343            } else {
2344                System.err.println("Error: Unknown option: " + opt);
2345                return;
2346            }
2347        }
2348        String packageName = nextArgRequired();
2349
2350        IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2351                Context.USAGE_STATS_SERVICE));
2352        boolean isIdle = usm.isAppInactive(packageName, userId);
2353        System.out.println("Idle=" + isIdle);
2354    }
2355
2356    private void runSendTrimMemory() throws Exception {
2357        int userId = UserHandle.USER_CURRENT;
2358        String opt;
2359        while ((opt = nextOption()) != null) {
2360            if (opt.equals("--user")) {
2361                userId = parseUserArg(nextArgRequired());
2362                if (userId == UserHandle.USER_ALL) {
2363                    System.err.println("Error: Can't use user 'all'");
2364                    return;
2365                }
2366            } else {
2367                System.err.println("Error: Unknown option: " + opt);
2368                return;
2369            }
2370        }
2371
2372        String proc = nextArgRequired();
2373        String levelArg = nextArgRequired();
2374        int level;
2375        switch (levelArg) {
2376            case "HIDDEN":
2377                level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
2378                break;
2379            case "RUNNING_MODERATE":
2380                level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
2381                break;
2382            case "BACKGROUND":
2383                level = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
2384                break;
2385            case "RUNNING_LOW":
2386                level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
2387                break;
2388            case "MODERATE":
2389                level = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
2390                break;
2391            case "RUNNING_CRITICAL":
2392                level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
2393                break;
2394            case "COMPLETE":
2395                level = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
2396                break;
2397            default:
2398                System.err.println("Error: Unknown level option: " + levelArg);
2399                return;
2400        }
2401        if (!mAm.setProcessMemoryTrimLevel(proc, userId, level)) {
2402            System.err.println("Error: Failure to set the level - probably Unknown Process: " +
2403                               proc);
2404        }
2405    }
2406
2407    private void runGetCurrentUser() throws Exception {
2408        UserInfo currentUser = Preconditions.checkNotNull(mAm.getCurrentUser(),
2409                "Current user not set");
2410        System.out.println(currentUser.id);
2411    }
2412
2413    /**
2414     * Open the given file for sending into the system process. This verifies
2415     * with SELinux that the system will have access to the file.
2416     */
2417    private static ParcelFileDescriptor openForSystemServer(File file, int mode)
2418            throws FileNotFoundException {
2419        final ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, mode);
2420        final String tcon = SELinux.getFileContext(file.getAbsolutePath());
2421        if (!SELinux.checkSELinuxAccess("u:r:system_server:s0", tcon, "file", "read")) {
2422            throw new FileNotFoundException("System server has no access to file context " + tcon);
2423        }
2424        return fd;
2425    }
2426
2427    private Rect getBounds() {
2428        String leftStr = nextArgRequired();
2429        int left = Integer.valueOf(leftStr);
2430        String topStr = nextArgRequired();
2431        int top = Integer.valueOf(topStr);
2432        String rightStr = nextArgRequired();
2433        int right = Integer.valueOf(rightStr);
2434        String bottomStr = nextArgRequired();
2435        int bottom = Integer.valueOf(bottomStr);
2436        if (left < 0) {
2437            System.err.println("Error: bad left arg: " + leftStr);
2438            return null;
2439        }
2440        if (top < 0) {
2441            System.err.println("Error: bad top arg: " + topStr);
2442            return null;
2443        }
2444        if (right <= 0) {
2445            System.err.println("Error: bad right arg: " + rightStr);
2446            return null;
2447        }
2448        if (bottom <= 0) {
2449            System.err.println("Error: bad bottom arg: " + bottomStr);
2450            return null;
2451        }
2452        return new Rect(left, top, right, bottom);
2453    }
2454}
2455