PackageManagerShellCommand.java revision cae13b0afff4b1ef3da25a31f2eb9b16faa14a4b
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import android.app.ActivityManager;
20import android.content.ComponentName;
21import android.content.IIntentReceiver;
22import android.content.IIntentSender;
23import android.content.Intent;
24import android.content.IntentSender;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.FeatureInfo;
27import android.content.pm.IPackageManager;
28import android.content.pm.InstrumentationInfo;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageInstaller;
31import android.content.pm.PackageItemInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ParceledListSlice;
34import android.content.pm.PermissionGroupInfo;
35import android.content.pm.PermissionInfo;
36import android.content.pm.PackageInstaller.SessionInfo;
37import android.content.pm.PackageInstaller.SessionParams;
38import android.content.pm.ResolveInfo;
39import android.content.res.AssetManager;
40import android.content.res.Resources;
41import android.net.Uri;
42import android.os.Binder;
43import android.os.Build;
44import android.os.Bundle;
45import android.os.RemoteException;
46import android.os.ShellCommand;
47import android.os.SystemProperties;
48import android.os.UserHandle;
49import android.text.TextUtils;
50import android.util.PrintWriterPrinter;
51import com.android.internal.util.SizedInputStream;
52
53import dalvik.system.DexFile;
54
55import libcore.io.IoUtils;
56
57import java.io.File;
58import java.io.FileInputStream;
59import java.io.IOException;
60import java.io.InputStream;
61import java.io.OutputStream;
62import java.io.PrintWriter;
63import java.net.URISyntaxException;
64import java.util.ArrayList;
65import java.util.Collections;
66import java.util.Comparator;
67import java.util.List;
68import java.util.WeakHashMap;
69import java.util.concurrent.SynchronousQueue;
70import java.util.concurrent.TimeUnit;
71
72class PackageManagerShellCommand extends ShellCommand {
73    final IPackageManager mInterface;
74    final private WeakHashMap<String, Resources> mResourceCache =
75            new WeakHashMap<String, Resources>();
76    int mTargetUser;
77    boolean mBrief;
78    boolean mComponents;
79
80    PackageManagerShellCommand(PackageManagerService service) {
81        mInterface = service;
82    }
83
84    @Override
85    public int onCommand(String cmd) {
86        if (cmd == null) {
87            return handleDefaultCommands(cmd);
88        }
89
90        final PrintWriter pw = getOutPrintWriter();
91        try {
92            switch(cmd) {
93                case "install":
94                    return runInstall();
95                case "install-abandon":
96                case "install-destroy":
97                    return runInstallAbandon();
98                case "install-commit":
99                    return runInstallCommit();
100                case "install-create":
101                    return runInstallCreate();
102                case "install-remove":
103                    return runInstallRemove();
104                case "install-write":
105                    return runInstallWrite();
106                case "compile":
107                    return runCompile();
108                case "dump-profiles":
109                    return runDumpProfiles();
110                case "list":
111                    return runList();
112                case "uninstall":
113                    return runUninstall();
114                case "resolve-activity":
115                    return runResolveActivity();
116                case "query-activities":
117                    return runQueryIntentActivities();
118                case "query-services":
119                    return runQueryIntentServices();
120                case "query-receivers":
121                    return runQueryIntentReceivers();
122                case "suspend":
123                    return runSuspend(true);
124                case "unsuspend":
125                    return runSuspend(false);
126                case "set-home-activity":
127                    return runSetHomeActivity();
128                default:
129                    return handleDefaultCommands(cmd);
130            }
131        } catch (RemoteException e) {
132            pw.println("Remote exception: " + e);
133        }
134        return -1;
135    }
136
137    private int runInstall() throws RemoteException {
138        final PrintWriter pw = getOutPrintWriter();
139        final InstallParams params = makeInstallParams();
140        final int sessionId = doCreateSession(params.sessionParams,
141                params.installerPackageName, params.userId);
142        boolean abandonSession = true;
143        try {
144            final String inPath = getNextArg();
145            if (inPath == null && params.sessionParams.sizeBytes == 0) {
146                pw.println("Error: must either specify a package size or an APK file");
147                return 1;
148            }
149            if (doWriteSplit(sessionId, inPath, params.sessionParams.sizeBytes, "base.apk",
150                    false /*logSuccess*/) != PackageInstaller.STATUS_SUCCESS) {
151                return 1;
152            }
153            if (doCommitSession(sessionId, false /*logSuccess*/)
154                    != PackageInstaller.STATUS_SUCCESS) {
155                return 1;
156            }
157            abandonSession = false;
158            pw.println("Success");
159            return 0;
160        } finally {
161            if (abandonSession) {
162                try {
163                    doAbandonSession(sessionId, false /*logSuccess*/);
164                } catch (Exception ignore) {
165                }
166            }
167        }
168    }
169
170    private int runSuspend(boolean suspendedState) {
171        final PrintWriter pw = getOutPrintWriter();
172        int userId = UserHandle.USER_SYSTEM;
173        String opt;
174        while ((opt = getNextOption()) != null) {
175            switch (opt) {
176                case "--user":
177                    userId = UserHandle.parseUserArg(getNextArgRequired());
178                    break;
179                default:
180                    pw.println("Error: Unknown option: " + opt);
181                    return 1;
182            }
183        }
184
185        String packageName = getNextArg();
186        if (packageName == null) {
187            pw.println("Error: package name not specified");
188            return 1;
189        }
190
191        try {
192            mInterface.setPackagesSuspendedAsUser(new String[]{packageName}, suspendedState,
193                    userId);
194            pw.println("Package " + packageName + " new suspended state: "
195                    + mInterface.isPackageSuspendedForUser(packageName, userId));
196            return 0;
197        } catch (RemoteException | IllegalArgumentException e) {
198            pw.println(e.toString());
199            return 1;
200        }
201    }
202
203    private int runInstallAbandon() throws RemoteException {
204        final int sessionId = Integer.parseInt(getNextArg());
205        return doAbandonSession(sessionId, true /*logSuccess*/);
206    }
207
208    private int runInstallCommit() throws RemoteException {
209        final int sessionId = Integer.parseInt(getNextArg());
210        return doCommitSession(sessionId, true /*logSuccess*/);
211    }
212
213    private int runInstallCreate() throws RemoteException {
214        final PrintWriter pw = getOutPrintWriter();
215        final InstallParams installParams = makeInstallParams();
216        final int sessionId = doCreateSession(installParams.sessionParams,
217                installParams.installerPackageName, installParams.userId);
218
219        // NOTE: adb depends on parsing this string
220        pw.println("Success: created install session [" + sessionId + "]");
221        return 0;
222    }
223
224    private int runInstallWrite() throws RemoteException {
225        long sizeBytes = -1;
226
227        String opt;
228        while ((opt = getNextOption()) != null) {
229            if (opt.equals("-S")) {
230                sizeBytes = Long.parseLong(getNextArg());
231            } else {
232                throw new IllegalArgumentException("Unknown option: " + opt);
233            }
234        }
235
236        final int sessionId = Integer.parseInt(getNextArg());
237        final String splitName = getNextArg();
238        final String path = getNextArg();
239        return doWriteSplit(sessionId, path, sizeBytes, splitName, true /*logSuccess*/);
240    }
241
242    private int runInstallRemove() throws RemoteException {
243        final PrintWriter pw = getOutPrintWriter();
244
245        final int sessionId = Integer.parseInt(getNextArg());
246
247        final String splitName = getNextArg();
248        if (splitName == null) {
249            pw.println("Error: split name not specified");
250            return 1;
251        }
252        return doRemoveSplit(sessionId, splitName, true /*logSuccess*/);
253    }
254
255    private int runCompile() throws RemoteException {
256        final PrintWriter pw = getOutPrintWriter();
257        boolean checkProfiles = SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
258        boolean forceCompilation = false;
259        boolean allPackages = false;
260        boolean clearProfileData = false;
261        String compilerFilter = null;
262        String compilationReason = null;
263        String checkProfilesRaw = null;
264
265        String opt;
266        while ((opt = getNextOption()) != null) {
267            switch (opt) {
268                case "-a":
269                    allPackages = true;
270                    break;
271                case "-c":
272                    clearProfileData = true;
273                    break;
274                case "-f":
275                    forceCompilation = true;
276                    break;
277                case "-m":
278                    compilerFilter = getNextArgRequired();
279                    break;
280                case "-r":
281                    compilationReason = getNextArgRequired();
282                    break;
283                case "--check-prof":
284                    checkProfilesRaw = getNextArgRequired();
285                    break;
286                case "--reset":
287                    forceCompilation = true;
288                    clearProfileData = true;
289                    compilationReason = "install";
290                    break;
291                default:
292                    pw.println("Error: Unknown option: " + opt);
293                    return 1;
294            }
295        }
296
297        if (checkProfilesRaw != null) {
298            if ("true".equals(checkProfilesRaw)) {
299                checkProfiles = true;
300            } else if ("false".equals(checkProfilesRaw)) {
301                checkProfiles = false;
302            } else {
303                pw.println("Invalid value for \"--check-prof\". Expected \"true\" or \"false\".");
304                return 1;
305            }
306        }
307
308        if (compilerFilter != null && compilationReason != null) {
309            pw.println("Cannot use compilation filter (\"-m\") and compilation reason (\"-r\") " +
310                    "at the same time");
311            return 1;
312        }
313        if (compilerFilter == null && compilationReason == null) {
314            pw.println("Cannot run without any of compilation filter (\"-m\") and compilation " +
315                    "reason (\"-r\") at the same time");
316            return 1;
317        }
318
319        String targetCompilerFilter;
320        if (compilerFilter != null) {
321            if (!DexFile.isValidCompilerFilter(compilerFilter)) {
322                pw.println("Error: \"" + compilerFilter +
323                        "\" is not a valid compilation filter.");
324                return 1;
325            }
326            targetCompilerFilter = compilerFilter;
327        } else {
328            int reason = -1;
329            for (int i = 0; i < PackageManagerServiceCompilerMapping.REASON_STRINGS.length; i++) {
330                if (PackageManagerServiceCompilerMapping.REASON_STRINGS[i].equals(
331                        compilationReason)) {
332                    reason = i;
333                    break;
334                }
335            }
336            if (reason == -1) {
337                pw.println("Error: Unknown compilation reason: " + compilationReason);
338                return 1;
339            }
340            targetCompilerFilter =
341                    PackageManagerServiceCompilerMapping.getCompilerFilterForReason(reason);
342        }
343
344
345        List<String> packageNames = null;
346        if (allPackages) {
347            packageNames = mInterface.getAllPackages();
348        } else {
349            String packageName = getNextArg();
350            if (packageName == null) {
351                pw.println("Error: package name not specified");
352                return 1;
353            }
354            packageNames = Collections.singletonList(packageName);
355        }
356
357        List<String> failedPackages = new ArrayList<>();
358        for (String packageName : packageNames) {
359            if (clearProfileData) {
360                mInterface.clearApplicationProfileData(packageName);
361            }
362
363            boolean result = mInterface.performDexOptMode(packageName,
364                    checkProfiles, targetCompilerFilter, forceCompilation);
365            if (!result) {
366                failedPackages.add(packageName);
367            }
368        }
369
370        if (failedPackages.isEmpty()) {
371            pw.println("Success");
372            return 0;
373        } else if (failedPackages.size() == 1) {
374            pw.println("Failure: package " + failedPackages.get(0) + " could not be compiled");
375            return 1;
376        } else {
377            pw.print("Failure: the following packages could not be compiled: ");
378            boolean is_first = true;
379            for (String packageName : failedPackages) {
380                if (is_first) {
381                    is_first = false;
382                } else {
383                    pw.print(", ");
384                }
385                pw.print(packageName);
386            }
387            pw.println();
388            return 1;
389        }
390    }
391
392    private int runDumpProfiles() throws RemoteException {
393        String packageName = getNextArg();
394        mInterface.dumpProfiles(packageName);
395        return 0;
396    }
397
398    private int runList() throws RemoteException {
399        final PrintWriter pw = getOutPrintWriter();
400        final String type = getNextArg();
401        if (type == null) {
402            pw.println("Error: didn't specify type of data to list");
403            return -1;
404        }
405        switch(type) {
406            case "features":
407                return runListFeatures();
408            case "instrumentation":
409                return runListInstrumentation();
410            case "libraries":
411                return runListLibraries();
412            case "package":
413            case "packages":
414                return runListPackages(false /*showSourceDir*/);
415            case "permission-groups":
416                return runListPermissionGroups();
417            case "permissions":
418                return runListPermissions();
419        }
420        pw.println("Error: unknown list type '" + type + "'");
421        return -1;
422    }
423
424    private int runListFeatures() throws RemoteException {
425        final PrintWriter pw = getOutPrintWriter();
426        final List<FeatureInfo> list = mInterface.getSystemAvailableFeatures().getList();
427
428        // sort by name
429        Collections.sort(list, new Comparator<FeatureInfo>() {
430            public int compare(FeatureInfo o1, FeatureInfo o2) {
431                if (o1.name == o2.name) return 0;
432                if (o1.name == null) return -1;
433                if (o2.name == null) return 1;
434                return o1.name.compareTo(o2.name);
435            }
436        });
437
438        final int count = (list != null) ? list.size() : 0;
439        for (int p = 0; p < count; p++) {
440            FeatureInfo fi = list.get(p);
441            pw.print("feature:");
442            if (fi.name != null) {
443                pw.print(fi.name);
444                if (fi.version > 0) {
445                    pw.print("=");
446                    pw.print(fi.version);
447                }
448                pw.println();
449            } else {
450                pw.println("reqGlEsVersion=0x"
451                    + Integer.toHexString(fi.reqGlEsVersion));
452            }
453        }
454        return 0;
455    }
456
457    private int runListInstrumentation() throws RemoteException {
458        final PrintWriter pw = getOutPrintWriter();
459        boolean showSourceDir = false;
460        String targetPackage = null;
461
462        try {
463            String opt;
464            while ((opt = getNextArg()) != null) {
465                switch (opt) {
466                    case "-f":
467                        showSourceDir = true;
468                        break;
469                    default:
470                        if (opt.charAt(0) != '-') {
471                            targetPackage = opt;
472                        } else {
473                            pw.println("Error: Unknown option: " + opt);
474                            return -1;
475                        }
476                        break;
477                }
478            }
479        } catch (RuntimeException ex) {
480            pw.println("Error: " + ex.toString());
481            return -1;
482        }
483
484        final List<InstrumentationInfo> list =
485                mInterface.queryInstrumentation(targetPackage, 0 /*flags*/).getList();
486
487        // sort by target package
488        Collections.sort(list, new Comparator<InstrumentationInfo>() {
489            public int compare(InstrumentationInfo o1, InstrumentationInfo o2) {
490                return o1.targetPackage.compareTo(o2.targetPackage);
491            }
492        });
493
494        final int count = (list != null) ? list.size() : 0;
495        for (int p = 0; p < count; p++) {
496            final InstrumentationInfo ii = list.get(p);
497            pw.print("instrumentation:");
498            if (showSourceDir) {
499                pw.print(ii.sourceDir);
500                pw.print("=");
501            }
502            final ComponentName cn = new ComponentName(ii.packageName, ii.name);
503            pw.print(cn.flattenToShortString());
504            pw.print(" (target=");
505            pw.print(ii.targetPackage);
506            pw.println(")");
507        }
508        return 0;
509    }
510
511    private int runListLibraries() throws RemoteException {
512        final PrintWriter pw = getOutPrintWriter();
513        final List<String> list = new ArrayList<String>();
514        final String[] rawList = mInterface.getSystemSharedLibraryNames();
515        for (int i = 0; i < rawList.length; i++) {
516            list.add(rawList[i]);
517        }
518
519        // sort by name
520        Collections.sort(list, new Comparator<String>() {
521            public int compare(String o1, String o2) {
522                if (o1 == o2) return 0;
523                if (o1 == null) return -1;
524                if (o2 == null) return 1;
525                return o1.compareTo(o2);
526            }
527        });
528
529        final int count = (list != null) ? list.size() : 0;
530        for (int p = 0; p < count; p++) {
531            String lib = list.get(p);
532            pw.print("library:");
533            pw.println(lib);
534        }
535        return 0;
536    }
537
538    private int runListPackages(boolean showSourceDir) throws RemoteException {
539        final PrintWriter pw = getOutPrintWriter();
540        int getFlags = 0;
541        boolean listDisabled = false, listEnabled = false;
542        boolean listSystem = false, listThirdParty = false;
543        boolean listInstaller = false;
544        int userId = UserHandle.USER_SYSTEM;
545        try {
546            String opt;
547            while ((opt = getNextOption()) != null) {
548                switch (opt) {
549                    case "-d":
550                        listDisabled = true;
551                        break;
552                    case "-e":
553                        listEnabled = true;
554                        break;
555                    case "-f":
556                        showSourceDir = true;
557                        break;
558                    case "-i":
559                        listInstaller = true;
560                        break;
561                    case "-l":
562                        // old compat
563                        break;
564                    case "-lf":
565                        showSourceDir = true;
566                        break;
567                    case "-s":
568                        listSystem = true;
569                        break;
570                    case "-u":
571                        getFlags |= PackageManager.GET_UNINSTALLED_PACKAGES;
572                        break;
573                    case "-3":
574                        listThirdParty = true;
575                        break;
576                    case "--user":
577                        userId = UserHandle.parseUserArg(getNextArgRequired());
578                        break;
579                    default:
580                        pw.println("Error: Unknown option: " + opt);
581                        return -1;
582                }
583            }
584        } catch (RuntimeException ex) {
585            pw.println("Error: " + ex.toString());
586            return -1;
587        }
588
589        final String filter = getNextArg();
590
591        @SuppressWarnings("unchecked")
592        final ParceledListSlice<PackageInfo> slice =
593                mInterface.getInstalledPackages(getFlags, userId);
594        final List<PackageInfo> packages = slice.getList();
595
596        final int count = packages.size();
597        for (int p = 0; p < count; p++) {
598            final PackageInfo info = packages.get(p);
599            if (filter != null && !info.packageName.contains(filter)) {
600                continue;
601            }
602            final boolean isSystem =
603                    (info.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0;
604            if ((!listDisabled || !info.applicationInfo.enabled) &&
605                    (!listEnabled || info.applicationInfo.enabled) &&
606                    (!listSystem || isSystem) &&
607                    (!listThirdParty || !isSystem)) {
608                pw.print("package:");
609                if (showSourceDir) {
610                    pw.print(info.applicationInfo.sourceDir);
611                    pw.print("=");
612                }
613                pw.print(info.packageName);
614                if (listInstaller) {
615                    pw.print("  installer=");
616                    pw.print(mInterface.getInstallerPackageName(info.packageName));
617                }
618                pw.println();
619            }
620        }
621        return 0;
622    }
623
624    private int runListPermissionGroups() throws RemoteException {
625        final PrintWriter pw = getOutPrintWriter();
626        final List<PermissionGroupInfo> pgs = mInterface.getAllPermissionGroups(0).getList();
627
628        final int count = pgs.size();
629        for (int p = 0; p < count ; p++) {
630            final PermissionGroupInfo pgi = pgs.get(p);
631            pw.print("permission group:");
632            pw.println(pgi.name);
633        }
634        return 0;
635    }
636
637    private int runListPermissions() throws RemoteException {
638        final PrintWriter pw = getOutPrintWriter();
639        boolean labels = false;
640        boolean groups = false;
641        boolean userOnly = false;
642        boolean summary = false;
643        boolean dangerousOnly = false;
644        String opt;
645        while ((opt = getNextOption()) != null) {
646            switch (opt) {
647                case "-d":
648                    dangerousOnly = true;
649                    break;
650                case "-f":
651                    labels = true;
652                    break;
653                case "-g":
654                    groups = true;
655                    break;
656                case "-s":
657                    groups = true;
658                    labels = true;
659                    summary = true;
660                    break;
661                case "-u":
662                    userOnly = true;
663                    break;
664                default:
665                    pw.println("Error: Unknown option: " + opt);
666                    return 1;
667            }
668        }
669
670        final ArrayList<String> groupList = new ArrayList<String>();
671        if (groups) {
672            final List<PermissionGroupInfo> infos =
673                    mInterface.getAllPermissionGroups(0 /*flags*/).getList();
674            final int count = infos.size();
675            for (int i = 0; i < count; i++) {
676                groupList.add(infos.get(i).name);
677            }
678            groupList.add(null);
679        } else {
680            final String grp = getNextArg();
681            groupList.add(grp);
682        }
683
684        if (dangerousOnly) {
685            pw.println("Dangerous Permissions:");
686            pw.println("");
687            doListPermissions(groupList, groups, labels, summary,
688                    PermissionInfo.PROTECTION_DANGEROUS,
689                    PermissionInfo.PROTECTION_DANGEROUS);
690            if (userOnly) {
691                pw.println("Normal Permissions:");
692                pw.println("");
693                doListPermissions(groupList, groups, labels, summary,
694                        PermissionInfo.PROTECTION_NORMAL,
695                        PermissionInfo.PROTECTION_NORMAL);
696            }
697        } else if (userOnly) {
698            pw.println("Dangerous and Normal Permissions:");
699            pw.println("");
700            doListPermissions(groupList, groups, labels, summary,
701                    PermissionInfo.PROTECTION_NORMAL,
702                    PermissionInfo.PROTECTION_DANGEROUS);
703        } else {
704            pw.println("All Permissions:");
705            pw.println("");
706            doListPermissions(groupList, groups, labels, summary,
707                    -10000, 10000);
708        }
709        return 0;
710    }
711
712    private int runUninstall() throws RemoteException {
713        final PrintWriter pw = getOutPrintWriter();
714        int flags = 0;
715        int userId = UserHandle.USER_ALL;
716
717        String opt;
718        while ((opt = getNextOption()) != null) {
719            switch (opt) {
720                case "-k":
721                    flags |= PackageManager.DELETE_KEEP_DATA;
722                    break;
723                case "--user":
724                    userId = UserHandle.parseUserArg(getNextArgRequired());
725                    break;
726                default:
727                    pw.println("Error: Unknown option: " + opt);
728                    return 1;
729            }
730        }
731
732        final String packageName = getNextArg();
733        if (packageName == null) {
734            pw.println("Error: package name not specified");
735            return 1;
736        }
737
738        // if a split is specified, just remove it and not the whole package
739        final String splitName = getNextArg();
740        if (splitName != null) {
741            return runRemoveSplit(packageName, splitName);
742        }
743
744        userId = translateUserId(userId, "runUninstall");
745        if (userId == UserHandle.USER_ALL) {
746            userId = UserHandle.USER_SYSTEM;
747            flags |= PackageManager.DELETE_ALL_USERS;
748        } else {
749            final PackageInfo info = mInterface.getPackageInfo(packageName, 0, userId);
750            if (info == null) {
751                pw.println("Failure [not installed for " + userId + "]");
752                return 1;
753            }
754            final boolean isSystem =
755                    (info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
756            // If we are being asked to delete a system app for just one
757            // user set flag so it disables rather than reverting to system
758            // version of the app.
759            if (isSystem) {
760                flags |= PackageManager.DELETE_SYSTEM_APP;
761            }
762        }
763
764        final LocalIntentReceiver receiver = new LocalIntentReceiver();
765        mInterface.getPackageInstaller().uninstall(packageName, null /*callerPackageName*/, flags,
766                receiver.getIntentSender(), userId);
767
768        final Intent result = receiver.getResult();
769        final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
770                PackageInstaller.STATUS_FAILURE);
771        if (status == PackageInstaller.STATUS_SUCCESS) {
772            pw.println("Success");
773            return 0;
774        } else {
775            pw.println("Failure ["
776                    + result.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + "]");
777            return 1;
778        }
779    }
780
781    private int runRemoveSplit(String packageName, String splitName) throws RemoteException {
782        final PrintWriter pw = getOutPrintWriter();
783        final SessionParams sessionParams = new SessionParams(SessionParams.MODE_INHERIT_EXISTING);
784        sessionParams.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
785        sessionParams.appPackageName = packageName;
786        final int sessionId =
787                doCreateSession(sessionParams, null /*installerPackageName*/, UserHandle.USER_ALL);
788        boolean abandonSession = true;
789        try {
790            if (doRemoveSplit(sessionId, splitName, false /*logSuccess*/)
791                    != PackageInstaller.STATUS_SUCCESS) {
792                return 1;
793            }
794            if (doCommitSession(sessionId, false /*logSuccess*/)
795                    != PackageInstaller.STATUS_SUCCESS) {
796                return 1;
797            }
798            abandonSession = false;
799            pw.println("Success");
800            return 0;
801        } finally {
802            if (abandonSession) {
803                try {
804                    doAbandonSession(sessionId, false /*logSuccess*/);
805                } catch (Exception ignore) {
806                }
807            }
808        }
809    }
810
811    private Intent parseIntentAndUser() throws URISyntaxException {
812        mTargetUser = UserHandle.USER_CURRENT;
813        mBrief = false;
814        mComponents = false;
815        Intent intent = Intent.parseCommandArgs(this, new Intent.CommandOptionHandler() {
816            @Override
817            public boolean handleOption(String opt, ShellCommand cmd) {
818                if ("--user".equals(opt)) {
819                    mTargetUser = UserHandle.parseUserArg(cmd.getNextArgRequired());
820                    return true;
821                } else if ("--brief".equals(opt)) {
822                    mBrief = true;
823                    return true;
824                } else if ("--components".equals(opt)) {
825                    mComponents = true;
826                    return true;
827                }
828                return false;
829            }
830        });
831        mTargetUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
832                Binder.getCallingUid(), mTargetUser, false, false, null, null);
833        return intent;
834    }
835
836    private void printResolveInfo(PrintWriterPrinter pr, String prefix, ResolveInfo ri,
837            boolean brief, boolean components) {
838        if (brief || components) {
839            final ComponentName comp;
840            if (ri.activityInfo != null) {
841                comp = new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
842            } else if (ri.serviceInfo != null) {
843                comp = new ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name);
844            } else if (ri.providerInfo != null) {
845                comp = new ComponentName(ri.providerInfo.packageName, ri.providerInfo.name);
846            } else {
847                comp = null;
848            }
849            if (comp != null) {
850                if (!components) {
851                    pr.println(prefix + "priority=" + ri.priority
852                            + " preferredOrder=" + ri.preferredOrder
853                            + " match=0x" + Integer.toHexString(ri.match)
854                            + " specificIndex=" + ri.specificIndex
855                            + " isDefault=" + ri.isDefault);
856                }
857                pr.println(prefix + comp.flattenToShortString());
858                return;
859            }
860        }
861        ri.dump(pr, prefix);
862    }
863
864    private int runResolveActivity() {
865        Intent intent;
866        try {
867            intent = parseIntentAndUser();
868        } catch (URISyntaxException e) {
869            throw new RuntimeException(e.getMessage(), e);
870        }
871        try {
872            ResolveInfo ri = mInterface.resolveIntent(intent, null, 0, mTargetUser);
873            PrintWriter pw = getOutPrintWriter();
874            if (ri == null) {
875                pw.println("No activity found");
876            } else {
877                PrintWriterPrinter pr = new PrintWriterPrinter(pw);
878                printResolveInfo(pr, "", ri, mBrief, mComponents);
879            }
880        } catch (RemoteException e) {
881            throw new RuntimeException("Failed calling service", e);
882        }
883        return 0;
884    }
885
886    private int runQueryIntentActivities() {
887        Intent intent;
888        try {
889            intent = parseIntentAndUser();
890        } catch (URISyntaxException e) {
891            throw new RuntimeException(e.getMessage(), e);
892        }
893        try {
894            List<ResolveInfo> result = mInterface.queryIntentActivities(intent, null, 0,
895                    mTargetUser).getList();
896            PrintWriter pw = getOutPrintWriter();
897            if (result == null || result.size() <= 0) {
898                pw.println("No activities found");
899            } else {
900                if (!mComponents) {
901                    pw.print(result.size()); pw.println(" activities found:");
902                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
903                    for (int i = 0; i < result.size(); i++) {
904                        pw.print("  Activity #"); pw.print(i); pw.println(":");
905                        printResolveInfo(pr, "    ", result.get(i), mBrief, mComponents);
906                    }
907                } else {
908                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
909                    for (int i = 0; i < result.size(); i++) {
910                        printResolveInfo(pr, "", result.get(i), mBrief, mComponents);
911                    }
912                }
913            }
914        } catch (RemoteException e) {
915            throw new RuntimeException("Failed calling service", e);
916        }
917        return 0;
918    }
919
920    private int runQueryIntentServices() {
921        Intent intent;
922        try {
923            intent = parseIntentAndUser();
924        } catch (URISyntaxException e) {
925            throw new RuntimeException(e.getMessage(), e);
926        }
927        try {
928            List<ResolveInfo> result = mInterface.queryIntentServices(intent, null, 0,
929                    mTargetUser).getList();
930            PrintWriter pw = getOutPrintWriter();
931            if (result == null || result.size() <= 0) {
932                pw.println("No services found");
933            } else {
934                if (!mComponents) {
935                    pw.print(result.size()); pw.println(" services found:");
936                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
937                    for (int i = 0; i < result.size(); i++) {
938                        pw.print("  Service #"); pw.print(i); pw.println(":");
939                        printResolveInfo(pr, "    ", result.get(i), mBrief, mComponents);
940                    }
941                } else {
942                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
943                    for (int i = 0; i < result.size(); i++) {
944                        printResolveInfo(pr, "", result.get(i), mBrief, mComponents);
945                    }
946                }
947            }
948        } catch (RemoteException e) {
949            throw new RuntimeException("Failed calling service", e);
950        }
951        return 0;
952    }
953
954    private int runQueryIntentReceivers() {
955        Intent intent;
956        try {
957            intent = parseIntentAndUser();
958        } catch (URISyntaxException e) {
959            throw new RuntimeException(e.getMessage(), e);
960        }
961        try {
962            List<ResolveInfo> result = mInterface.queryIntentReceivers(intent, null, 0,
963                    mTargetUser).getList();
964            PrintWriter pw = getOutPrintWriter();
965            if (result == null || result.size() <= 0) {
966                pw.println("No receivers found");
967            } else {
968                if (!mComponents) {
969                    pw.print(result.size()); pw.println(" receivers found:");
970                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
971                    for (int i = 0; i < result.size(); i++) {
972                        pw.print("  Receiver #"); pw.print(i); pw.println(":");
973                        printResolveInfo(pr, "    ", result.get(i), mBrief, mComponents);
974                    }
975                } else {
976                    PrintWriterPrinter pr = new PrintWriterPrinter(pw);
977                    for (int i = 0; i < result.size(); i++) {
978                        printResolveInfo(pr, "", result.get(i), mBrief, mComponents);
979                    }
980                }
981            }
982        } catch (RemoteException e) {
983            throw new RuntimeException("Failed calling service", e);
984        }
985        return 0;
986    }
987
988    private static class InstallParams {
989        SessionParams sessionParams;
990        String installerPackageName;
991        int userId = UserHandle.USER_ALL;
992    }
993
994    private InstallParams makeInstallParams() {
995        final SessionParams sessionParams = new SessionParams(SessionParams.MODE_FULL_INSTALL);
996        final InstallParams params = new InstallParams();
997        params.sessionParams = sessionParams;
998        String opt;
999        while ((opt = getNextOption()) != null) {
1000            switch (opt) {
1001                case "-l":
1002                    sessionParams.installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
1003                    break;
1004                case "-r":
1005                    sessionParams.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
1006                    break;
1007                case "-i":
1008                    params.installerPackageName = getNextArg();
1009                    if (params.installerPackageName == null) {
1010                        throw new IllegalArgumentException("Missing installer package");
1011                    }
1012                    break;
1013                case "-t":
1014                    sessionParams.installFlags |= PackageManager.INSTALL_ALLOW_TEST;
1015                    break;
1016                case "-s":
1017                    sessionParams.installFlags |= PackageManager.INSTALL_EXTERNAL;
1018                    break;
1019                case "-f":
1020                    sessionParams.installFlags |= PackageManager.INSTALL_INTERNAL;
1021                    break;
1022                case "-d":
1023                    sessionParams.installFlags |= PackageManager.INSTALL_ALLOW_DOWNGRADE;
1024                    break;
1025                case "-g":
1026                    sessionParams.installFlags |= PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS;
1027                    break;
1028                case "--dont-kill":
1029                    sessionParams.installFlags |= PackageManager.INSTALL_DONT_KILL_APP;
1030                    break;
1031                case "--originating-uri":
1032                    sessionParams.originatingUri = Uri.parse(getNextArg());
1033                    break;
1034                case "--referrer":
1035                    sessionParams.referrerUri = Uri.parse(getNextArg());
1036                    break;
1037                case "-p":
1038                    sessionParams.mode = SessionParams.MODE_INHERIT_EXISTING;
1039                    sessionParams.appPackageName = getNextArg();
1040                    if (sessionParams.appPackageName == null) {
1041                        throw new IllegalArgumentException("Missing inherit package name");
1042                    }
1043                    break;
1044                case "-S":
1045                    sessionParams.setSize(Long.parseLong(getNextArg()));
1046                    break;
1047                case "--abi":
1048                    sessionParams.abiOverride = checkAbiArgument(getNextArg());
1049                    break;
1050                case "--ephemeral":
1051                    sessionParams.installFlags |= PackageManager.INSTALL_EPHEMERAL;
1052                    break;
1053                case "--user":
1054                    params.userId = UserHandle.parseUserArg(getNextArgRequired());
1055                    break;
1056                case "--install-location":
1057                    sessionParams.installLocation = Integer.parseInt(getNextArg());
1058                    break;
1059                case "--force-uuid":
1060                    sessionParams.installFlags |= PackageManager.INSTALL_FORCE_VOLUME_UUID;
1061                    sessionParams.volumeUuid = getNextArg();
1062                    if ("internal".equals(sessionParams.volumeUuid)) {
1063                        sessionParams.volumeUuid = null;
1064                    }
1065                    break;
1066                case "--force-sdk":
1067                    sessionParams.installFlags |= PackageManager.INSTALL_FORCE_SDK;
1068                    break;
1069                default:
1070                    throw new IllegalArgumentException("Unknown option " + opt);
1071            }
1072        }
1073        return params;
1074    }
1075
1076    private int runSetHomeActivity() {
1077        final PrintWriter pw = getOutPrintWriter();
1078        int userId = UserHandle.USER_SYSTEM;
1079        String opt;
1080        while ((opt = getNextOption()) != null) {
1081            switch (opt) {
1082                case "--user":
1083                    userId = UserHandle.parseUserArg(getNextArgRequired());
1084                    break;
1085                default:
1086                    pw.println("Error: Unknown option: " + opt);
1087                    return 1;
1088            }
1089        }
1090
1091        String component = getNextArg();
1092        ComponentName componentName =
1093                component != null ? ComponentName.unflattenFromString(component) : null;
1094
1095        if (componentName == null) {
1096            pw.println("Error: component name not specified or invalid");
1097            return 1;
1098        }
1099
1100        try {
1101            mInterface.setHomeActivity(componentName, userId);
1102            return 0;
1103        } catch (RemoteException e) {
1104            pw.println(e.toString());
1105            return 1;
1106        }
1107    }
1108
1109    private static String checkAbiArgument(String abi) {
1110        if (TextUtils.isEmpty(abi)) {
1111            throw new IllegalArgumentException("Missing ABI argument");
1112        }
1113
1114        if ("-".equals(abi)) {
1115            return abi;
1116        }
1117
1118        final String[] supportedAbis = Build.SUPPORTED_ABIS;
1119        for (String supportedAbi : supportedAbis) {
1120            if (supportedAbi.equals(abi)) {
1121                return abi;
1122            }
1123        }
1124
1125        throw new IllegalArgumentException("ABI " + abi + " not supported on this device");
1126    }
1127
1128    private int translateUserId(int userId, String logContext) {
1129        return ActivityManager.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1130                userId, true, true, logContext, "pm command");
1131    }
1132
1133    private int doCreateSession(SessionParams params, String installerPackageName, int userId)
1134            throws RemoteException {
1135        userId = translateUserId(userId, "runInstallCreate");
1136        if (userId == UserHandle.USER_ALL) {
1137            userId = UserHandle.USER_SYSTEM;
1138            params.installFlags |= PackageManager.INSTALL_ALL_USERS;
1139        }
1140
1141        final int sessionId = mInterface.getPackageInstaller()
1142                .createSession(params, installerPackageName, userId);
1143        return sessionId;
1144    }
1145
1146    private int doWriteSplit(int sessionId, String inPath, long sizeBytes, String splitName,
1147            boolean logSuccess) throws RemoteException {
1148        final PrintWriter pw = getOutPrintWriter();
1149        if ("-".equals(inPath)) {
1150            inPath = null;
1151        } else if (inPath != null) {
1152            final File file = new File(inPath);
1153            if (file.isFile()) {
1154                sizeBytes = file.length();
1155            }
1156        }
1157
1158        final SessionInfo info = mInterface.getPackageInstaller().getSessionInfo(sessionId);
1159
1160        PackageInstaller.Session session = null;
1161        InputStream in = null;
1162        OutputStream out = null;
1163        try {
1164            session = new PackageInstaller.Session(
1165                    mInterface.getPackageInstaller().openSession(sessionId));
1166
1167            if (inPath != null) {
1168                in = new FileInputStream(inPath);
1169            } else {
1170                in = new SizedInputStream(getRawInputStream(), sizeBytes);
1171            }
1172            out = session.openWrite(splitName, 0, sizeBytes);
1173
1174            int total = 0;
1175            byte[] buffer = new byte[65536];
1176            int c;
1177            while ((c = in.read(buffer)) != -1) {
1178                total += c;
1179                out.write(buffer, 0, c);
1180
1181                if (info.sizeBytes > 0) {
1182                    final float fraction = ((float) c / (float) info.sizeBytes);
1183                    session.addProgress(fraction);
1184                }
1185            }
1186            session.fsync(out);
1187
1188            if (logSuccess) {
1189                pw.println("Success: streamed " + total + " bytes");
1190            }
1191            return 0;
1192        } catch (IOException e) {
1193            pw.println("Error: failed to write; " + e.getMessage());
1194            return 1;
1195        } finally {
1196            IoUtils.closeQuietly(out);
1197            IoUtils.closeQuietly(in);
1198            IoUtils.closeQuietly(session);
1199        }
1200    }
1201
1202    private int doRemoveSplit(int sessionId, String splitName, boolean logSuccess)
1203            throws RemoteException {
1204        final PrintWriter pw = getOutPrintWriter();
1205        PackageInstaller.Session session = null;
1206        try {
1207            session = new PackageInstaller.Session(
1208                    mInterface.getPackageInstaller().openSession(sessionId));
1209            session.removeSplit(splitName);
1210
1211            if (logSuccess) {
1212                pw.println("Success");
1213            }
1214            return 0;
1215        } catch (IOException e) {
1216            pw.println("Error: failed to remove split; " + e.getMessage());
1217            return 1;
1218        } finally {
1219            IoUtils.closeQuietly(session);
1220        }
1221    }
1222
1223    private int doCommitSession(int sessionId, boolean logSuccess) throws RemoteException {
1224        final PrintWriter pw = getOutPrintWriter();
1225        PackageInstaller.Session session = null;
1226        try {
1227            session = new PackageInstaller.Session(
1228                    mInterface.getPackageInstaller().openSession(sessionId));
1229
1230            final LocalIntentReceiver receiver = new LocalIntentReceiver();
1231            session.commit(receiver.getIntentSender());
1232
1233            final Intent result = receiver.getResult();
1234            final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
1235                    PackageInstaller.STATUS_FAILURE);
1236            if (status == PackageInstaller.STATUS_SUCCESS) {
1237                if (logSuccess) {
1238                    System.out.println("Success");
1239                }
1240            } else {
1241                pw.println("Failure ["
1242                        + result.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + "]");
1243            }
1244            return status;
1245        } finally {
1246            IoUtils.closeQuietly(session);
1247        }
1248    }
1249
1250    private int doAbandonSession(int sessionId, boolean logSuccess) throws RemoteException {
1251        final PrintWriter pw = getOutPrintWriter();
1252        PackageInstaller.Session session = null;
1253        try {
1254            session = new PackageInstaller.Session(
1255                    mInterface.getPackageInstaller().openSession(sessionId));
1256            session.abandon();
1257            if (logSuccess) {
1258                pw.println("Success");
1259            }
1260            return 0;
1261        } finally {
1262            IoUtils.closeQuietly(session);
1263        }
1264    }
1265
1266    private void doListPermissions(ArrayList<String> groupList, boolean groups, boolean labels,
1267            boolean summary, int startProtectionLevel, int endProtectionLevel)
1268                    throws RemoteException {
1269        final PrintWriter pw = getOutPrintWriter();
1270        final int groupCount = groupList.size();
1271        for (int i = 0; i < groupCount; i++) {
1272            String groupName = groupList.get(i);
1273            String prefix = "";
1274            if (groups) {
1275                if (i > 0) {
1276                    pw.println("");
1277                }
1278                if (groupName != null) {
1279                    PermissionGroupInfo pgi =
1280                            mInterface.getPermissionGroupInfo(groupName, 0 /*flags*/);
1281                    if (summary) {
1282                        Resources res = getResources(pgi);
1283                        if (res != null) {
1284                            pw.print(loadText(pgi, pgi.labelRes, pgi.nonLocalizedLabel) + ": ");
1285                        } else {
1286                            pw.print(pgi.name + ": ");
1287
1288                        }
1289                    } else {
1290                        pw.println((labels ? "+ " : "") + "group:" + pgi.name);
1291                        if (labels) {
1292                            pw.println("  package:" + pgi.packageName);
1293                            Resources res = getResources(pgi);
1294                            if (res != null) {
1295                                pw.println("  label:"
1296                                        + loadText(pgi, pgi.labelRes, pgi.nonLocalizedLabel));
1297                                pw.println("  description:"
1298                                        + loadText(pgi, pgi.descriptionRes,
1299                                                pgi.nonLocalizedDescription));
1300                            }
1301                        }
1302                    }
1303                } else {
1304                    pw.println(((labels && !summary) ? "+ " : "") + "ungrouped:");
1305                }
1306                prefix = "  ";
1307            }
1308            List<PermissionInfo> ps =
1309                    mInterface.queryPermissionsByGroup(groupList.get(i), 0 /*flags*/).getList();
1310            final int count = ps.size();
1311            boolean first = true;
1312            for (int p = 0 ; p < count ; p++) {
1313                PermissionInfo pi = ps.get(p);
1314                if (groups && groupName == null && pi.group != null) {
1315                    continue;
1316                }
1317                final int base = pi.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
1318                if (base < startProtectionLevel
1319                        || base > endProtectionLevel) {
1320                    continue;
1321                }
1322                if (summary) {
1323                    if (first) {
1324                        first = false;
1325                    } else {
1326                        pw.print(", ");
1327                    }
1328                    Resources res = getResources(pi);
1329                    if (res != null) {
1330                        pw.print(loadText(pi, pi.labelRes,
1331                                pi.nonLocalizedLabel));
1332                    } else {
1333                        pw.print(pi.name);
1334                    }
1335                } else {
1336                    pw.println(prefix + (labels ? "+ " : "")
1337                            + "permission:" + pi.name);
1338                    if (labels) {
1339                        pw.println(prefix + "  package:" + pi.packageName);
1340                        Resources res = getResources(pi);
1341                        if (res != null) {
1342                            pw.println(prefix + "  label:"
1343                                    + loadText(pi, pi.labelRes,
1344                                            pi.nonLocalizedLabel));
1345                            pw.println(prefix + "  description:"
1346                                    + loadText(pi, pi.descriptionRes,
1347                                            pi.nonLocalizedDescription));
1348                        }
1349                        pw.println(prefix + "  protectionLevel:"
1350                                + PermissionInfo.protectionToString(pi.protectionLevel));
1351                    }
1352                }
1353            }
1354
1355            if (summary) {
1356                pw.println("");
1357            }
1358        }
1359    }
1360
1361    private String loadText(PackageItemInfo pii, int res, CharSequence nonLocalized)
1362            throws RemoteException {
1363        if (nonLocalized != null) {
1364            return nonLocalized.toString();
1365        }
1366        if (res != 0) {
1367            Resources r = getResources(pii);
1368            if (r != null) {
1369                try {
1370                    return r.getString(res);
1371                } catch (Resources.NotFoundException e) {
1372                }
1373            }
1374        }
1375        return null;
1376    }
1377
1378    private Resources getResources(PackageItemInfo pii) throws RemoteException {
1379        Resources res = mResourceCache.get(pii.packageName);
1380        if (res != null) return res;
1381
1382        ApplicationInfo ai = mInterface.getApplicationInfo(pii.packageName, 0, 0);
1383        AssetManager am = new AssetManager();
1384        am.addAssetPath(ai.publicSourceDir);
1385        res = new Resources(am, null, null);
1386        mResourceCache.put(pii.packageName, res);
1387        return res;
1388    }
1389
1390    @Override
1391    public void onHelp() {
1392        final PrintWriter pw = getOutPrintWriter();
1393        pw.println("Package manager (package) commands:");
1394        pw.println("  help");
1395        pw.println("    Print this help text.");
1396        pw.println("");
1397        pw.println("  compile [-m MODE | -r REASON] [-f] [-c]");
1398        pw.println("          [--reset] [--check-prof (true | false)] (-a | TARGET-PACKAGE)");
1399        pw.println("    Trigger compilation of TARGET-PACKAGE or all packages if \"-a\".");
1400        pw.println("    Options:");
1401        pw.println("      -a: compile all packages");
1402        pw.println("      -c: clear profile data before compiling");
1403        pw.println("      -f: force compilation even if not needed");
1404        pw.println("      -m: select compilation mode");
1405        pw.println("          MODE is one of the dex2oat compiler filters:");
1406        pw.println("            verify-none");
1407        pw.println("            verify-at-runtime");
1408        pw.println("            verify-profile");
1409        pw.println("            interpret-only");
1410        pw.println("            space-profile");
1411        pw.println("            space");
1412        pw.println("            speed-profile");
1413        pw.println("            speed");
1414        pw.println("            everything");
1415        pw.println("      -r: select compilation reason");
1416        pw.println("          REASON is one of:");
1417        for (int i = 0; i < PackageManagerServiceCompilerMapping.REASON_STRINGS.length; i++) {
1418            pw.println("            " + PackageManagerServiceCompilerMapping.REASON_STRINGS[i]);
1419        }
1420        pw.println("      --reset: restore package to its post-install state");
1421        pw.println("      --check-prof (true | false): look at profiles when doing dexopt?");
1422        pw.println("  list features");
1423        pw.println("    Prints all features of the system.");
1424        pw.println("  list instrumentation [-f] [TARGET-PACKAGE]");
1425        pw.println("    Prints all test packages; optionally only those targeting TARGET-PACKAGE");
1426        pw.println("    Options:");
1427        pw.println("      -f: dump the name of the .apk file containing the test package");
1428        pw.println("  list libraries");
1429        pw.println("    Prints all system libraries.");
1430        pw.println("  list packages [-f] [-d] [-e] [-s] [-3] [-i] [-u] [--user USER_ID] [FILTER]");
1431        pw.println("    Prints all packages; optionally only those whose name contains");
1432        pw.println("    the text in FILTER.");
1433        pw.println("    Options:");
1434        pw.println("      -f: see their associated file");
1435        pw.println("      -d: filter to only show disabled packages");
1436        pw.println("      -e: filter to only show enabled packages");
1437        pw.println("      -s: filter to only show system packages");
1438        pw.println("      -3: filter to only show third party packages");
1439        pw.println("      -i: see the installer for the packages");
1440        pw.println("      -u: also include uninstalled packages");
1441        pw.println("  list permission-groups");
1442        pw.println("    Prints all known permission groups.");
1443        pw.println("  list permissions [-g] [-f] [-d] [-u] [GROUP]");
1444        pw.println("    Prints all known permissions; optionally only those in GROUP.");
1445        pw.println("    Options:");
1446        pw.println("      -g: organize by group");
1447        pw.println("      -f: print all information");
1448        pw.println("      -s: short summary");
1449        pw.println("      -d: only list dangerous permissions");
1450        pw.println("      -u: list only the permissions users will see");
1451        pw.println("  dump-profiles TARGET-PACKAGE");
1452        pw.println("    Dumps method/class profile files to");
1453        pw.println("    /data/misc/profman/TARGET-PACKAGE.txt");
1454        pw.println("  resolve-activity [--brief] [--components] [--user USER_ID] INTENT");
1455        pw.println("    Prints the activity that resolves to the given Intent.");
1456        pw.println("  query-activities [--brief] [--components] [--user USER_ID] INTENT");
1457        pw.println("    Prints all activities that can handle the given Intent.");
1458        pw.println("  query-services [--brief] [--components] [--user USER_ID] INTENT");
1459        pw.println("    Prints all services that can handle the given Intent.");
1460        pw.println("  query-receivers [--brief] [--components] [--user USER_ID] INTENT");
1461        pw.println("    Prints all broadcast receivers that can handle the given Intent.");
1462        pw.println("  suspend [--user USER_ID] TARGET-PACKAGE");
1463        pw.println("    Suspends the specified package (as user).");
1464        pw.println("  unsuspend [--user USER_ID] TARGET-PACKAGE");
1465        pw.println("    Unsuspends the specified package (as user).");
1466        pw.println("  set-home-activity [--user USER_ID] TARGET-COMPONENT");
1467        pw.println("    set the default home activity (aka launcher).");
1468        pw.println();
1469        Intent.printIntentArgsHelp(pw , "");
1470    }
1471
1472    private static class LocalIntentReceiver {
1473        private final SynchronousQueue<Intent> mResult = new SynchronousQueue<>();
1474
1475        private IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
1476            @Override
1477            public void send(int code, Intent intent, String resolvedType,
1478                    IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
1479                try {
1480                    mResult.offer(intent, 5, TimeUnit.SECONDS);
1481                } catch (InterruptedException e) {
1482                    throw new RuntimeException(e);
1483                }
1484            }
1485        };
1486
1487        public IntentSender getIntentSender() {
1488            return new IntentSender((IIntentSender) mLocalSender);
1489        }
1490
1491        public Intent getResult() {
1492            try {
1493                return mResult.take();
1494            } catch (InterruptedException e) {
1495                throw new RuntimeException(e);
1496            }
1497        }
1498    }
1499}
1500