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