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