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