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