1/*
2 * Copyright (C) 2007 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.commands.pm;
18
19import com.android.internal.content.PackageHelper;
20
21import android.content.ComponentName;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.FeatureInfo;
24import android.content.pm.IPackageDeleteObserver;
25import android.content.pm.IPackageInstallObserver;
26import android.content.pm.IPackageManager;
27import android.content.pm.InstrumentationInfo;
28import android.content.pm.PackageInfo;
29import android.content.pm.PackageItemInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PermissionGroupInfo;
32import android.content.pm.PermissionInfo;
33import android.content.res.AssetManager;
34import android.content.res.Resources;
35import android.net.Uri;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.provider.Settings;
39
40import java.io.File;
41import java.lang.reflect.Field;
42import java.lang.reflect.Modifier;
43import java.util.ArrayList;
44import java.util.Collections;
45import java.util.Comparator;
46import java.util.List;
47import java.util.WeakHashMap;
48
49public final class Pm {
50    IPackageManager mPm;
51
52    private WeakHashMap<String, Resources> mResourceCache
53            = new WeakHashMap<String, Resources>();
54
55    private String[] mArgs;
56    private int mNextArg;
57    private String mCurArgData;
58
59    private static final String PM_NOT_RUNNING_ERR =
60        "Error: Could not access the Package Manager.  Is the system running?";
61
62    public static void main(String[] args) {
63        new Pm().run(args);
64    }
65
66    public void run(String[] args) {
67        boolean validCommand = false;
68        if (args.length < 1) {
69            showUsage();
70            return;
71        }
72
73        mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
74        if (mPm == null) {
75            System.err.println(PM_NOT_RUNNING_ERR);
76            return;
77        }
78
79        mArgs = args;
80        String op = args[0];
81        mNextArg = 1;
82
83        if ("list".equals(op)) {
84            runList();
85            return;
86        }
87
88        if ("path".equals(op)) {
89            runPath();
90            return;
91        }
92
93        if ("install".equals(op)) {
94            runInstall();
95            return;
96        }
97
98        if ("uninstall".equals(op)) {
99            runUninstall();
100            return;
101        }
102
103        if ("enable".equals(op)) {
104            runSetEnabledSetting(PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
105            return;
106        }
107
108        if ("disable".equals(op)) {
109            runSetEnabledSetting(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
110            return;
111        }
112
113        if ("setInstallLocation".equals(op)) {
114            runSetInstallLocation();
115            return;
116        }
117
118        if ("getInstallLocation".equals(op)) {
119            runGetInstallLocation();
120            return;
121        }
122
123        try {
124            if (args.length == 1) {
125                if (args[0].equalsIgnoreCase("-l")) {
126                    validCommand = true;
127                    runListPackages(false);
128                } else if (args[0].equalsIgnoreCase("-lf")){
129                    validCommand = true;
130                    runListPackages(true);
131                }
132            } else if (args.length == 2) {
133                if (args[0].equalsIgnoreCase("-p")) {
134                    validCommand = true;
135                    displayPackageFilePath(args[1]);
136                }
137            }
138        } finally {
139            if (validCommand == false) {
140                if (op != null) {
141                    System.err.println("Error: unknown command '" + op + "'");
142                }
143                showUsage();
144            }
145        }
146    }
147
148    /**
149     * Execute the list sub-command.
150     *
151     * pm list [package | packages]
152     * pm list permission-groups
153     * pm list permissions
154     * pm list features
155     * pm list instrumentation
156     */
157    private void runList() {
158        String type = nextArg();
159        if (type == null) {
160            System.err.println("Error: didn't specify type of data to list");
161            showUsage();
162            return;
163        }
164        if ("package".equals(type) || "packages".equals(type)) {
165            runListPackages(false);
166        } else if ("permission-groups".equals(type)) {
167            runListPermissionGroups();
168        } else if ("permissions".equals(type)) {
169            runListPermissions();
170        } else if ("features".equals(type)) {
171            runListFeatures();
172        } else if ("instrumentation".equals(type)) {
173            runListInstrumentation();
174        } else {
175            System.err.println("Error: unknown list type '" + type + "'");
176            showUsage();
177        }
178    }
179
180    /**
181     * Lists all the installed packages.
182     */
183    private void runListPackages(boolean showApplicationPackage) {
184        try {
185            String opt;
186            while ((opt=nextOption()) != null) {
187                if (opt.equals("-l")) {
188                    // old compat
189                } else if (opt.equals("-lf")) {
190                    showApplicationPackage = true;
191                } else if (opt.equals("-f")) {
192                    showApplicationPackage = true;
193                } else {
194                    System.err.println("Error: Unknown option: " + opt);
195                    showUsage();
196                    return;
197                }
198            }
199        } catch (RuntimeException ex) {
200            System.err.println("Error: " + ex.toString());
201            showUsage();
202            return;
203        }
204
205        try {
206            List<PackageInfo> packages = mPm.getInstalledPackages(0 /* all */);
207
208            int count = packages.size();
209            for (int p = 0 ; p < count ; p++) {
210                PackageInfo info = packages.get(p);
211                System.out.print("package:");
212                if (showApplicationPackage) {
213                    System.out.print(info.applicationInfo.sourceDir);
214                    System.out.print("=");
215                }
216                System.out.println(info.packageName);
217            }
218        } catch (RemoteException e) {
219            System.err.println(e.toString());
220            System.err.println(PM_NOT_RUNNING_ERR);
221        }
222    }
223
224    /**
225     * Lists all of the features supported by the current device.
226     *
227     * pm list features
228     */
229    private void runListFeatures() {
230        try {
231            List<FeatureInfo> list = new ArrayList<FeatureInfo>();
232            FeatureInfo[] rawList = mPm.getSystemAvailableFeatures();
233            for (int i=0; i<rawList.length; i++) {
234                list.add(rawList[i]);
235            }
236
237
238            // Sort by name
239            Collections.sort(list, new Comparator<FeatureInfo>() {
240                public int compare(FeatureInfo o1, FeatureInfo o2) {
241                    if (o1.name == o2.name) return 0;
242                    if (o1.name == null) return -1;
243                    if (o2.name == null) return 1;
244                    return o1.name.compareTo(o2.name);
245                }
246            });
247
248            int count = (list != null) ? list.size() : 0;
249            for (int p = 0; p < count; p++) {
250                FeatureInfo fi = list.get(p);
251                System.out.print("feature:");
252                if (fi.name != null) System.out.println(fi.name);
253                else System.out.println("reqGlEsVersion=0x"
254                        + Integer.toHexString(fi.reqGlEsVersion));
255            }
256        } catch (RemoteException e) {
257            System.err.println(e.toString());
258            System.err.println(PM_NOT_RUNNING_ERR);
259        }
260    }
261
262    /**
263     * Lists all of the installed instrumentation, or all for a given package
264     *
265     * pm list instrumentation [package] [-f]
266     */
267    private void runListInstrumentation() {
268        int flags = 0;      // flags != 0 is only used to request meta-data
269        boolean showPackage = false;
270        String targetPackage = null;
271
272        try {
273            String opt;
274            while ((opt=nextArg()) != null) {
275                if (opt.equals("-f")) {
276                    showPackage = true;
277                } else if (opt.charAt(0) != '-') {
278                    targetPackage = opt;
279                } else {
280                    System.err.println("Error: Unknown option: " + opt);
281                    showUsage();
282                    return;
283                }
284            }
285        } catch (RuntimeException ex) {
286            System.err.println("Error: " + ex.toString());
287            showUsage();
288            return;
289        }
290
291        try {
292            List<InstrumentationInfo> list = mPm.queryInstrumentation(targetPackage, flags);
293
294            // Sort by target package
295            Collections.sort(list, new Comparator<InstrumentationInfo>() {
296                public int compare(InstrumentationInfo o1, InstrumentationInfo o2) {
297                    return o1.targetPackage.compareTo(o2.targetPackage);
298                }
299            });
300
301            int count = (list != null) ? list.size() : 0;
302            for (int p = 0; p < count; p++) {
303                InstrumentationInfo ii = list.get(p);
304                System.out.print("instrumentation:");
305                if (showPackage) {
306                    System.out.print(ii.sourceDir);
307                    System.out.print("=");
308                }
309                ComponentName cn = new ComponentName(ii.packageName, ii.name);
310                System.out.print(cn.flattenToShortString());
311                System.out.print(" (target=");
312                System.out.print(ii.targetPackage);
313                System.out.println(")");
314            }
315        } catch (RemoteException e) {
316            System.err.println(e.toString());
317            System.err.println(PM_NOT_RUNNING_ERR);
318        }
319    }
320
321    /**
322     * Lists all the known permission groups.
323     */
324    private void runListPermissionGroups() {
325        try {
326            List<PermissionGroupInfo> pgs = mPm.getAllPermissionGroups(0);
327
328            int count = pgs.size();
329            for (int p = 0 ; p < count ; p++) {
330                PermissionGroupInfo pgi = pgs.get(p);
331                System.out.print("permission group:");
332                System.out.println(pgi.name);
333            }
334        } catch (RemoteException e) {
335            System.err.println(e.toString());
336            System.err.println(PM_NOT_RUNNING_ERR);
337        }
338    }
339
340    private String loadText(PackageItemInfo pii, int res, CharSequence nonLocalized) {
341        if (nonLocalized != null) {
342            return nonLocalized.toString();
343        }
344        Resources r = getResources(pii);
345        if (r != null) {
346            return r.getString(res);
347        }
348        return null;
349    }
350
351    /**
352     * Lists all the permissions in a group.
353     */
354    private void runListPermissions() {
355        try {
356            boolean labels = false;
357            boolean groups = false;
358            boolean userOnly = false;
359            boolean summary = false;
360            boolean dangerousOnly = false;
361            String opt;
362            while ((opt=nextOption()) != null) {
363                if (opt.equals("-f")) {
364                    labels = true;
365                } else if (opt.equals("-g")) {
366                    groups = true;
367                } else if (opt.equals("-s")) {
368                    groups = true;
369                    labels = true;
370                    summary = true;
371                } else if (opt.equals("-u")) {
372                    userOnly = true;
373                } else if (opt.equals("-d")) {
374                    dangerousOnly = true;
375                } else {
376                    System.err.println("Error: Unknown option: " + opt);
377                    showUsage();
378                    return;
379                }
380            }
381
382            String grp = nextOption();
383            ArrayList<String> groupList = new ArrayList<String>();
384            if (groups) {
385                List<PermissionGroupInfo> infos =
386                        mPm.getAllPermissionGroups(0);
387                for (int i=0; i<infos.size(); i++) {
388                    groupList.add(infos.get(i).name);
389                }
390                groupList.add(null);
391            } else {
392                groupList.add(grp);
393            }
394
395            if (dangerousOnly) {
396                System.out.println("Dangerous Permissions:");
397                System.out.println("");
398                doListPermissions(groupList, groups, labels, summary,
399                        PermissionInfo.PROTECTION_DANGEROUS,
400                        PermissionInfo.PROTECTION_DANGEROUS);
401                if (userOnly) {
402                    System.out.println("Normal Permissions:");
403                    System.out.println("");
404                    doListPermissions(groupList, groups, labels, summary,
405                            PermissionInfo.PROTECTION_NORMAL,
406                            PermissionInfo.PROTECTION_NORMAL);
407                }
408            } else if (userOnly) {
409                System.out.println("Dangerous and Normal Permissions:");
410                System.out.println("");
411                doListPermissions(groupList, groups, labels, summary,
412                        PermissionInfo.PROTECTION_NORMAL,
413                        PermissionInfo.PROTECTION_DANGEROUS);
414            } else {
415                System.out.println("All Permissions:");
416                System.out.println("");
417                doListPermissions(groupList, groups, labels, summary,
418                        -10000, 10000);
419            }
420        } catch (RemoteException e) {
421            System.err.println(e.toString());
422            System.err.println(PM_NOT_RUNNING_ERR);
423        }
424    }
425
426    private void doListPermissions(ArrayList<String> groupList,
427            boolean groups, boolean labels, boolean summary,
428            int startProtectionLevel, int endProtectionLevel)
429            throws RemoteException {
430        for (int i=0; i<groupList.size(); i++) {
431            String groupName = groupList.get(i);
432            String prefix = "";
433            if (groups) {
434                if (i > 0) System.out.println("");
435                if (groupName != null) {
436                    PermissionGroupInfo pgi = mPm.getPermissionGroupInfo(
437                            groupName, 0);
438                    if (summary) {
439                        Resources res = getResources(pgi);
440                        if (res != null) {
441                            System.out.print(loadText(pgi, pgi.labelRes,
442                                    pgi.nonLocalizedLabel) + ": ");
443                        } else {
444                            System.out.print(pgi.name + ": ");
445
446                        }
447                    } else {
448                        System.out.println((labels ? "+ " : "")
449                                + "group:" + pgi.name);
450                        if (labels) {
451                            System.out.println("  package:" + pgi.packageName);
452                            Resources res = getResources(pgi);
453                            if (res != null) {
454                                System.out.println("  label:"
455                                        + loadText(pgi, pgi.labelRes,
456                                                pgi.nonLocalizedLabel));
457                                System.out.println("  description:"
458                                        + loadText(pgi, pgi.descriptionRes,
459                                                pgi.nonLocalizedDescription));
460                            }
461                        }
462                    }
463                } else {
464                    System.out.println(((labels && !summary)
465                            ? "+ " : "") + "ungrouped:");
466                }
467                prefix = "  ";
468            }
469            List<PermissionInfo> ps = mPm.queryPermissionsByGroup(
470                    groupList.get(i), 0);
471            int count = ps.size();
472            boolean first = true;
473            for (int p = 0 ; p < count ; p++) {
474                PermissionInfo pi = ps.get(p);
475                if (groups && groupName == null && pi.group != null) {
476                    continue;
477                }
478                if (pi.protectionLevel < startProtectionLevel
479                        || pi.protectionLevel > endProtectionLevel) {
480                    continue;
481                }
482                if (summary) {
483                    if (first) {
484                        first = false;
485                    } else {
486                        System.out.print(", ");
487                    }
488                    Resources res = getResources(pi);
489                    if (res != null) {
490                        System.out.print(loadText(pi, pi.labelRes,
491                                pi.nonLocalizedLabel));
492                    } else {
493                        System.out.print(pi.name);
494                    }
495                } else {
496                    System.out.println(prefix + (labels ? "+ " : "")
497                            + "permission:" + pi.name);
498                    if (labels) {
499                        System.out.println(prefix + "  package:" + pi.packageName);
500                        Resources res = getResources(pi);
501                        if (res != null) {
502                            System.out.println(prefix + "  label:"
503                                    + loadText(pi, pi.labelRes,
504                                            pi.nonLocalizedLabel));
505                            System.out.println(prefix + "  description:"
506                                    + loadText(pi, pi.descriptionRes,
507                                            pi.nonLocalizedDescription));
508                        }
509                        String protLevel = "unknown";
510                        switch(pi.protectionLevel) {
511                            case PermissionInfo.PROTECTION_DANGEROUS:
512                                protLevel = "dangerous";
513                                break;
514                            case PermissionInfo.PROTECTION_NORMAL:
515                                protLevel = "normal";
516                                break;
517                            case PermissionInfo.PROTECTION_SIGNATURE:
518                                protLevel = "signature";
519                                break;
520                            case PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM:
521                                protLevel = "signatureOrSystem";
522                                break;
523                        }
524                        System.out.println(prefix + "  protectionLevel:" + protLevel);
525                    }
526                }
527            }
528
529            if (summary) {
530                System.out.println("");
531            }
532        }
533    }
534
535    private void runPath() {
536        String pkg = nextArg();
537        if (pkg == null) {
538            System.err.println("Error: no package specified");
539            showUsage();
540            return;
541        }
542        displayPackageFilePath(pkg);
543    }
544
545    class PackageInstallObserver extends IPackageInstallObserver.Stub {
546        boolean finished;
547        int result;
548
549        public void packageInstalled(String name, int status) {
550            synchronized( this) {
551                finished = true;
552                result = status;
553                notifyAll();
554            }
555        }
556    }
557
558    /**
559     * Converts a failure code into a string by using reflection to find a matching constant
560     * in PackageManager.
561     */
562    private String installFailureToString(int result) {
563        Field[] fields = PackageManager.class.getFields();
564        for (Field f: fields) {
565            if (f.getType() == int.class) {
566                int modifiers = f.getModifiers();
567                // only look at public final static fields.
568                if (((modifiers & Modifier.FINAL) != 0) &&
569                        ((modifiers & Modifier.PUBLIC) != 0) &&
570                        ((modifiers & Modifier.STATIC) != 0)) {
571                    String fieldName = f.getName();
572                    if (fieldName.startsWith("INSTALL_FAILED_") ||
573                            fieldName.startsWith("INSTALL_PARSE_FAILED_")) {
574                        // get the int value and compare it to result.
575                        try {
576                            if (result == f.getInt(null)) {
577                                return fieldName;
578                            }
579                        } catch (IllegalAccessException e) {
580                            // this shouldn't happen since we only look for public static fields.
581                        }
582                    }
583                }
584            }
585        }
586
587        // couldn't find a matching constant? return the value
588        return Integer.toString(result);
589    }
590
591    private void runSetInstallLocation() {
592        int loc;
593
594        String arg = nextArg();
595        if (arg == null) {
596            System.err.println("Error: no install location specified.");
597            showUsage();
598            return;
599        }
600        try {
601            loc = Integer.parseInt(arg);
602        } catch (NumberFormatException e) {
603            System.err.println("Error: install location has to be a number.");
604            showUsage();
605            return;
606        }
607        try {
608            if (!mPm.setInstallLocation(loc)) {
609                System.err.println("Error: install location has to be a number.");
610                showUsage();
611            }
612        } catch (RemoteException e) {
613            System.err.println(e.toString());
614            System.err.println(PM_NOT_RUNNING_ERR);
615        }
616    }
617
618    private void runGetInstallLocation() {
619        try {
620            int loc = mPm.getInstallLocation();
621            String locStr = "invalid";
622            if (loc == PackageHelper.APP_INSTALL_AUTO) {
623                locStr = "auto";
624            } else if (loc == PackageHelper.APP_INSTALL_INTERNAL) {
625                locStr = "internal";
626            } else if (loc == PackageHelper.APP_INSTALL_EXTERNAL) {
627                locStr = "external";
628            }
629            System.out.println(loc + "[" + locStr + "]");
630        } catch (RemoteException e) {
631            System.err.println(e.toString());
632            System.err.println(PM_NOT_RUNNING_ERR);
633        }
634    }
635
636    private void runInstall() {
637        int installFlags = 0;
638        String installerPackageName = null;
639
640        String opt;
641        while ((opt=nextOption()) != null) {
642            if (opt.equals("-l")) {
643                installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
644            } else if (opt.equals("-r")) {
645                installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
646            } else if (opt.equals("-i")) {
647                installerPackageName = nextOptionData();
648                if (installerPackageName == null) {
649                    System.err.println("Error: no value specified for -i");
650                    showUsage();
651                    return;
652                }
653            } else if (opt.equals("-t")) {
654                installFlags |= PackageManager.INSTALL_ALLOW_TEST;
655            } else if (opt.equals("-s")) {
656                // Override if -s option is specified.
657                installFlags |= PackageManager.INSTALL_EXTERNAL;
658            } else if (opt.equals("-f")) {
659                // Override if -s option is specified.
660                installFlags |= PackageManager.INSTALL_INTERNAL;
661            } else {
662                System.err.println("Error: Unknown option: " + opt);
663                showUsage();
664                return;
665            }
666        }
667
668        String apkFilePath = nextArg();
669        System.err.println("\tpkg: " + apkFilePath);
670        if (apkFilePath == null) {
671            System.err.println("Error: no package specified");
672            showUsage();
673            return;
674        }
675
676        PackageInstallObserver obs = new PackageInstallObserver();
677        try {
678            mPm.installPackage(Uri.fromFile(new File(apkFilePath)), obs, installFlags,
679                    installerPackageName);
680
681            synchronized (obs) {
682                while (!obs.finished) {
683                    try {
684                        obs.wait();
685                    } catch (InterruptedException e) {
686                    }
687                }
688                if (obs.result == PackageManager.INSTALL_SUCCEEDED) {
689                    System.out.println("Success");
690                } else {
691                    System.err.println("Failure ["
692                            + installFailureToString(obs.result)
693                            + "]");
694                }
695            }
696        } catch (RemoteException e) {
697            System.err.println(e.toString());
698            System.err.println(PM_NOT_RUNNING_ERR);
699        }
700    }
701
702    class PackageDeleteObserver extends IPackageDeleteObserver.Stub {
703        boolean finished;
704        boolean result;
705
706        public void packageDeleted(boolean succeeded) {
707            synchronized (this) {
708                finished = true;
709                result = succeeded;
710                notifyAll();
711            }
712        }
713    }
714
715    private void runUninstall() {
716        int unInstallFlags = 0;
717
718        String opt = nextOption();
719        if (opt != null && opt.equals("-k")) {
720            unInstallFlags = PackageManager.DONT_DELETE_DATA;
721        }
722
723        String pkg = nextArg();
724        if (pkg == null) {
725            System.err.println("Error: no package specified");
726            showUsage();
727            return;
728        }
729        boolean result = deletePackage(pkg, unInstallFlags);
730        if (result) {
731            System.out.println("Success");
732        } else {
733            System.out.println("Failure");
734        }
735    }
736
737    private boolean deletePackage(String pkg, int unInstallFlags) {
738        PackageDeleteObserver obs = new PackageDeleteObserver();
739        try {
740            mPm.deletePackage(pkg, obs, unInstallFlags);
741
742            synchronized (obs) {
743                while (!obs.finished) {
744                    try {
745                        obs.wait();
746                    } catch (InterruptedException e) {
747                    }
748                }
749            }
750        } catch (RemoteException e) {
751            System.err.println(e.toString());
752            System.err.println(PM_NOT_RUNNING_ERR);
753        }
754        return obs.result;
755    }
756
757    private static String enabledSettingToString(int state) {
758        switch (state) {
759            case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
760                return "default";
761            case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
762                return "enabled";
763            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
764                return "disabled";
765        }
766        return "unknown";
767    }
768
769    private void runSetEnabledSetting(int state) {
770        String pkg = nextArg();
771        if (pkg == null) {
772            System.err.println("Error: no package or component specified");
773            showUsage();
774            return;
775        }
776        ComponentName cn = ComponentName.unflattenFromString(pkg);
777        if (cn == null) {
778            try {
779                mPm.setApplicationEnabledSetting(pkg, state, 0);
780                System.err.println("Package " + pkg + " new state: "
781                        + enabledSettingToString(
782                                mPm.getApplicationEnabledSetting(pkg)));
783            } catch (RemoteException e) {
784                System.err.println(e.toString());
785                System.err.println(PM_NOT_RUNNING_ERR);
786            }
787        } else {
788            try {
789                mPm.setComponentEnabledSetting(cn, state, 0);
790                System.err.println("Component " + cn.toShortString() + " new state: "
791                        + enabledSettingToString(
792                                mPm.getComponentEnabledSetting(cn)));
793            } catch (RemoteException e) {
794                System.err.println(e.toString());
795                System.err.println(PM_NOT_RUNNING_ERR);
796            }
797        }
798    }
799
800    /**
801     * Displays the package file for a package.
802     * @param pckg
803     */
804    private void displayPackageFilePath(String pckg) {
805        try {
806            PackageInfo info = mPm.getPackageInfo(pckg, 0);
807            if (info != null && info.applicationInfo != null) {
808                System.out.print("package:");
809                System.out.println(info.applicationInfo.sourceDir);
810            }
811        } catch (RemoteException e) {
812            System.err.println(e.toString());
813            System.err.println(PM_NOT_RUNNING_ERR);
814        }
815    }
816
817    private Resources getResources(PackageItemInfo pii) {
818        Resources res = mResourceCache.get(pii.packageName);
819        if (res != null) return res;
820
821        try {
822            ApplicationInfo ai = mPm.getApplicationInfo(pii.packageName, 0);
823            AssetManager am = new AssetManager();
824            am.addAssetPath(ai.publicSourceDir);
825            res = new Resources(am, null, null);
826            mResourceCache.put(pii.packageName, res);
827            return res;
828        } catch (RemoteException e) {
829            System.err.println(e.toString());
830            System.err.println(PM_NOT_RUNNING_ERR);
831            return null;
832        }
833    }
834
835    private String nextOption() {
836        if (mNextArg >= mArgs.length) {
837            return null;
838        }
839        String arg = mArgs[mNextArg];
840        if (!arg.startsWith("-")) {
841            return null;
842        }
843        mNextArg++;
844        if (arg.equals("--")) {
845            return null;
846        }
847        if (arg.length() > 1 && arg.charAt(1) != '-') {
848            if (arg.length() > 2) {
849                mCurArgData = arg.substring(2);
850                return arg.substring(0, 2);
851            } else {
852                mCurArgData = null;
853                return arg;
854            }
855        }
856        mCurArgData = null;
857        return arg;
858    }
859
860    private String nextOptionData() {
861        if (mCurArgData != null) {
862            return mCurArgData;
863        }
864        if (mNextArg >= mArgs.length) {
865            return null;
866        }
867        String data = mArgs[mNextArg];
868        mNextArg++;
869        return data;
870    }
871
872    private String nextArg() {
873        if (mNextArg >= mArgs.length) {
874            return null;
875        }
876        String arg = mArgs[mNextArg];
877        mNextArg++;
878        return arg;
879    }
880
881    private static void showUsage() {
882        System.err.println("usage: pm [list|path|install|uninstall]");
883        System.err.println("       pm list packages [-f]");
884        System.err.println("       pm list permission-groups");
885        System.err.println("       pm list permissions [-g] [-f] [-d] [-u] [GROUP]");
886        System.err.println("       pm list instrumentation [-f] [TARGET-PACKAGE]");
887        System.err.println("       pm list features");
888        System.err.println("       pm path PACKAGE");
889        System.err.println("       pm install [-l] [-r] [-t] [-i INSTALLER_PACKAGE_NAME] [-s] [-f] PATH");
890        System.err.println("       pm uninstall [-k] PACKAGE");
891        System.err.println("       pm enable PACKAGE_OR_COMPONENT");
892        System.err.println("       pm disable PACKAGE_OR_COMPONENT");
893        System.err.println("       pm setInstallLocation [0/auto] [1/internal] [2/external]");
894        System.err.println("");
895        System.err.println("The list packages command prints all packages.  Options:");
896        System.err.println("  -f: see their associated file.");
897        System.err.println("");
898        System.err.println("The list permission-groups command prints all known");
899        System.err.println("permission groups.");
900        System.err.println("");
901        System.err.println("The list permissions command prints all known");
902        System.err.println("permissions, optionally only those in GROUP.  Options:");
903        System.err.println("  -g: organize by group.");
904        System.err.println("  -f: print all information.");
905        System.err.println("  -s: short summary.");
906        System.err.println("  -d: only list dangerous permissions.");
907        System.err.println("  -u: list only the permissions users will see.");
908        System.err.println("");
909        System.err.println("The list instrumentation command prints all instrumentations,");
910        System.err.println("or only those that target a specified package.  Options:");
911        System.err.println("  -f: see their associated file.");
912        System.err.println("");
913        System.err.println("The list features command prints all features of the system.");
914        System.err.println("");
915        System.err.println("The path command prints the path to the .apk of a package.");
916        System.err.println("");
917        System.err.println("The install command installs a package to the system.  Options:");
918        System.err.println("  -l: install the package with FORWARD_LOCK.");
919        System.err.println("  -r: reinstall an exisiting app, keeping its data.");
920        System.err.println("  -t: allow test .apks to be installed.");
921        System.err.println("  -i: specify the installer package name.");
922        System.err.println("  -s: install package on sdcard.");
923        System.err.println("  -f: install package on internal flash.");
924        System.err.println("");
925        System.err.println("The uninstall command removes a package from the system. Options:");
926        System.err.println("  -k: keep the data and cache directories around.");
927        System.err.println("after the package removal.");
928        System.err.println("");
929        System.err.println("The enable and disable commands change the enabled state of");
930        System.err.println("a given package or component (written as \"package/class\").");
931        System.err.println("");
932        System.err.println("The getInstallLocation command gets the current install location");
933        System.err.println("  0 [auto]: Let system decide the best location");
934        System.err.println("  1 [internal]: Install on internal device storage");
935        System.err.println("  2 [external]: Install on external media");
936        System.err.println("");
937        System.err.println("The setInstallLocation command changes the default install location");
938        System.err.println("  0 [auto]: Let system decide the best location");
939        System.err.println("  1 [internal]: Install on internal device storage");
940        System.err.println("  2 [external]: Install on external media");
941    }
942}
943