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