PackageManagerService.java revision 36070b414a710dd09a24698699f501d58c5772a4
1/*
2 * Copyright (C) 2006 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 static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
25import static com.android.internal.util.ArrayUtils.appendInt;
26import static com.android.internal.util.ArrayUtils.removeInt;
27import static libcore.io.OsConstants.S_ISLNK;
28import static libcore.io.OsConstants.S_IRWXU;
29import static libcore.io.OsConstants.S_IRGRP;
30import static libcore.io.OsConstants.S_IXGRP;
31import static libcore.io.OsConstants.S_IROTH;
32import static libcore.io.OsConstants.S_IXOTH;
33
34import com.android.internal.app.IMediaContainerService;
35import com.android.internal.app.ResolverActivity;
36import com.android.internal.content.NativeLibraryHelper;
37import com.android.internal.content.PackageHelper;
38import com.android.internal.util.FastXmlSerializer;
39import com.android.internal.util.XmlUtils;
40import com.android.server.DeviceStorageMonitorService;
41import com.android.server.EventLogTags;
42import com.android.server.IntentResolver;
43
44import org.xmlpull.v1.XmlPullParser;
45import org.xmlpull.v1.XmlPullParserException;
46import org.xmlpull.v1.XmlSerializer;
47
48import android.app.ActivityManager;
49import android.app.ActivityManagerNative;
50import android.app.IActivityManager;
51import android.app.admin.IDevicePolicyManager;
52import android.app.backup.IBackupManager;
53import android.content.BroadcastReceiver;
54import android.content.ComponentName;
55import android.content.Context;
56import android.content.IIntentReceiver;
57import android.content.Intent;
58import android.content.IntentFilter;
59import android.content.IntentSender;
60import android.content.ServiceConnection;
61import android.content.IntentSender.SendIntentException;
62import android.content.pm.ActivityInfo;
63import android.content.pm.ApplicationInfo;
64import android.content.pm.ContainerEncryptionParams;
65import android.content.pm.FeatureInfo;
66import android.content.pm.IPackageDataObserver;
67import android.content.pm.IPackageDeleteObserver;
68import android.content.pm.IPackageInstallObserver;
69import android.content.pm.IPackageManager;
70import android.content.pm.IPackageMoveObserver;
71import android.content.pm.IPackageStatsObserver;
72import android.content.pm.InstrumentationInfo;
73import android.content.pm.PackageCleanItem;
74import android.content.pm.PackageInfo;
75import android.content.pm.PackageInfoLite;
76import android.content.pm.PackageManager;
77import android.content.pm.PackageParser;
78import android.content.pm.PackageUserState;
79import android.content.pm.PackageParser.ActivityIntentInfo;
80import android.content.pm.PackageStats;
81import android.content.pm.ParceledListSlice;
82import android.content.pm.PermissionGroupInfo;
83import android.content.pm.PermissionInfo;
84import android.content.pm.ProviderInfo;
85import android.content.pm.ResolveInfo;
86import android.content.pm.ServiceInfo;
87import android.content.pm.Signature;
88import android.content.pm.ManifestDigest;
89import android.content.pm.VerificationParams;
90import android.content.pm.VerifierDeviceIdentity;
91import android.content.pm.VerifierInfo;
92import android.net.Uri;
93import android.os.Binder;
94import android.os.Build;
95import android.os.Bundle;
96import android.os.Environment;
97import android.os.FileObserver;
98import android.os.FileUtils;
99import android.os.Handler;
100import android.os.HandlerThread;
101import android.os.IBinder;
102import android.os.Looper;
103import android.os.Message;
104import android.os.Parcel;
105import android.os.ParcelFileDescriptor;
106import android.os.Process;
107import android.os.RemoteException;
108import android.os.SELinux;
109import android.os.ServiceManager;
110import android.os.SystemClock;
111import android.os.SystemProperties;
112import android.os.UserHandle;
113import android.os.Environment.UserEnvironment;
114import android.provider.Settings.Secure;
115import android.security.SystemKeyStore;
116import android.util.DisplayMetrics;
117import android.util.EventLog;
118import android.util.Log;
119import android.util.LogPrinter;
120import android.util.Slog;
121import android.util.SparseArray;
122import android.util.Xml;
123import android.view.Display;
124import android.view.WindowManager;
125
126import java.io.BufferedOutputStream;
127import java.io.File;
128import java.io.FileDescriptor;
129import java.io.FileInputStream;
130import java.io.FileNotFoundException;
131import java.io.FileOutputStream;
132import java.io.FileReader;
133import java.io.FilenameFilter;
134import java.io.IOException;
135import java.io.PrintWriter;
136import java.security.NoSuchAlgorithmException;
137import java.security.PublicKey;
138import java.security.cert.CertificateException;
139import java.text.SimpleDateFormat;
140import java.util.ArrayList;
141import java.util.Arrays;
142import java.util.Collection;
143import java.util.Collections;
144import java.util.Comparator;
145import java.util.Date;
146import java.util.HashMap;
147import java.util.HashSet;
148import java.util.Iterator;
149import java.util.List;
150import java.util.Map;
151import java.util.Map.Entry;
152import java.util.Set;
153
154import libcore.io.ErrnoException;
155import libcore.io.IoUtils;
156import libcore.io.Libcore;
157import libcore.io.OsConstants;
158import libcore.io.StructStat;
159
160/**
161 * Keep track of all those .apks everywhere.
162 *
163 * This is very central to the platform's security; please run the unit
164 * tests whenever making modifications here:
165 *
166mmm frameworks/base/tests/AndroidTests
167adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
168adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
169 *
170 * {@hide}
171 */
172public class PackageManagerService extends IPackageManager.Stub {
173    static final String TAG = "PackageManager";
174    static final boolean DEBUG_SETTINGS = false;
175    private static final boolean DEBUG_PREFERRED = false;
176    static final boolean DEBUG_UPGRADE = false;
177    private static final boolean DEBUG_INSTALL = false;
178    private static final boolean DEBUG_REMOVE = false;
179    private static final boolean DEBUG_BROADCASTS = false;
180    private static final boolean DEBUG_SHOW_INFO = false;
181    private static final boolean DEBUG_PACKAGE_INFO = false;
182    private static final boolean DEBUG_INTENT_MATCHING = false;
183    private static final boolean DEBUG_PACKAGE_SCANNING = false;
184    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
185    private static final boolean DEBUG_VERIFY = false;
186
187    private static final int RADIO_UID = Process.PHONE_UID;
188    private static final int LOG_UID = Process.LOG_UID;
189    private static final int NFC_UID = Process.NFC_UID;
190    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
191
192    private static final boolean GET_CERTIFICATES = true;
193
194    private static final int REMOVE_EVENTS =
195        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
196    private static final int ADD_EVENTS =
197        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
198
199    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
200    // Suffix used during package installation when copying/moving
201    // package apks to install directory.
202    private static final String INSTALL_PACKAGE_SUFFIX = "-";
203
204    static final int SCAN_MONITOR = 1<<0;
205    static final int SCAN_NO_DEX = 1<<1;
206    static final int SCAN_FORCE_DEX = 1<<2;
207    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
208    static final int SCAN_NEW_INSTALL = 1<<4;
209    static final int SCAN_NO_PATHS = 1<<5;
210    static final int SCAN_UPDATE_TIME = 1<<6;
211    static final int SCAN_DEFER_DEX = 1<<7;
212    static final int SCAN_BOOTING = 1<<8;
213
214    static final int REMOVE_CHATTY = 1<<16;
215
216    /**
217     * Whether verification is enabled by default.
218     */
219    private static final boolean DEFAULT_VERIFY_ENABLE = true;
220
221    /**
222     * The default maximum time to wait for the verification agent to return in
223     * milliseconds.
224     */
225    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
226
227    /**
228     * The default response for package verification timeout.
229     *
230     * This can be either PackageManager.VERIFICATION_ALLOW or
231     * PackageManager.VERIFICATION_REJECT.
232     */
233    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
234
235    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
236
237    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
238            DEFAULT_CONTAINER_PACKAGE,
239            "com.android.defcontainer.DefaultContainerService");
240
241    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
242
243    private static final String LIB_DIR_NAME = "lib";
244
245    static final String mTempContainerPrefix = "smdl2tmp";
246
247    final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
248            Process.THREAD_PRIORITY_BACKGROUND);
249    final PackageHandler mHandler;
250
251    final int mSdkVersion = Build.VERSION.SDK_INT;
252    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
253            ? null : Build.VERSION.CODENAME;
254
255    final Context mContext;
256    final boolean mFactoryTest;
257    final boolean mOnlyCore;
258    final boolean mNoDexOpt;
259    final DisplayMetrics mMetrics;
260    final int mDefParseFlags;
261    final String[] mSeparateProcesses;
262
263    // This is where all application persistent data goes.
264    final File mAppDataDir;
265
266    // This is where all application persistent data goes for secondary users.
267    final File mUserAppDataDir;
268
269    /** The location for ASEC container files on internal storage. */
270    final String mAsecInternalPath;
271
272    // This is the object monitoring the framework dir.
273    final FileObserver mFrameworkInstallObserver;
274
275    // This is the object monitoring the system app dir.
276    final FileObserver mSystemInstallObserver;
277
278    // This is the object monitoring the system app dir.
279    final FileObserver mVendorInstallObserver;
280
281    // This is the object monitoring mAppInstallDir.
282    final FileObserver mAppInstallObserver;
283
284    // This is the object monitoring mDrmAppPrivateInstallDir.
285    final FileObserver mDrmAppInstallObserver;
286
287    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
288    // LOCK HELD.  Can be called with mInstallLock held.
289    final Installer mInstaller;
290
291    final File mFrameworkDir;
292    final File mSystemAppDir;
293    final File mVendorAppDir;
294    final File mAppInstallDir;
295    final File mDalvikCacheDir;
296
297    /**
298     * Directory to which applications installed internally have native
299     * libraries copied.
300     */
301    private File mAppLibInstallDir;
302
303    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
304    // apps.
305    final File mDrmAppPrivateInstallDir;
306
307    // ----------------------------------------------------------------
308
309    // Lock for state used when installing and doing other long running
310    // operations.  Methods that must be called with this lock held have
311    // the prefix "LI".
312    final Object mInstallLock = new Object();
313
314    // These are the directories in the 3rd party applications installed dir
315    // that we have currently loaded packages from.  Keys are the application's
316    // installed zip file (absolute codePath), and values are Package.
317    final HashMap<String, PackageParser.Package> mAppDirs =
318            new HashMap<String, PackageParser.Package>();
319
320    // Information for the parser to write more useful error messages.
321    File mScanningPath;
322    int mLastScanError;
323
324    // ----------------------------------------------------------------
325
326    // Keys are String (package name), values are Package.  This also serves
327    // as the lock for the global state.  Methods that must be called with
328    // this lock held have the prefix "LP".
329    final HashMap<String, PackageParser.Package> mPackages =
330            new HashMap<String, PackageParser.Package>();
331
332    final Settings mSettings;
333    boolean mRestoredSettings;
334
335    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
336    int[] mGlobalGids;
337
338    // These are the built-in uid -> permission mappings that were read from the
339    // etc/permissions.xml file.
340    final SparseArray<HashSet<String>> mSystemPermissions =
341            new SparseArray<HashSet<String>>();
342
343    // These are the built-in shared libraries that were read from the
344    // etc/permissions.xml file.
345    final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
346
347    // Temporary for building the final shared libraries for an .apk.
348    String[] mTmpSharedLibraries = null;
349
350    // These are the features this devices supports that were read from the
351    // etc/permissions.xml file.
352    final HashMap<String, FeatureInfo> mAvailableFeatures =
353            new HashMap<String, FeatureInfo>();
354
355    // All available activities, for your resolving pleasure.
356    final ActivityIntentResolver mActivities =
357            new ActivityIntentResolver();
358
359    // All available receivers, for your resolving pleasure.
360    final ActivityIntentResolver mReceivers =
361            new ActivityIntentResolver();
362
363    // All available services, for your resolving pleasure.
364    final ServiceIntentResolver mServices = new ServiceIntentResolver();
365
366    // Keys are String (provider class name), values are Provider.
367    final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
368            new HashMap<ComponentName, PackageParser.Provider>();
369
370    // Mapping from provider base names (first directory in content URI codePath)
371    // to the provider information.
372    final HashMap<String, PackageParser.Provider> mProviders =
373            new HashMap<String, PackageParser.Provider>();
374
375    // Mapping from instrumentation class names to info about them.
376    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
377            new HashMap<ComponentName, PackageParser.Instrumentation>();
378
379    // Mapping from permission names to info about them.
380    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
381            new HashMap<String, PackageParser.PermissionGroup>();
382
383    // Packages whose data we have transfered into another package, thus
384    // should no longer exist.
385    final HashSet<String> mTransferedPackages = new HashSet<String>();
386
387    // Broadcast actions that are only available to the system.
388    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
389
390    /** List of packages waiting for verification. */
391    final SparseArray<PackageVerificationState> mPendingVerification
392            = new SparseArray<PackageVerificationState>();
393
394    final ArrayList<PackageParser.Package> mDeferredDexOpt =
395            new ArrayList<PackageParser.Package>();
396
397    /** Token for keys in mPendingVerification. */
398    private int mPendingVerificationToken = 0;
399
400    boolean mSystemReady;
401    boolean mSafeMode;
402    boolean mHasSystemUidErrors;
403
404    ApplicationInfo mAndroidApplication;
405    final ActivityInfo mResolveActivity = new ActivityInfo();
406    final ResolveInfo mResolveInfo = new ResolveInfo();
407    ComponentName mResolveComponentName;
408    PackageParser.Package mPlatformPackage;
409
410    // Set of pending broadcasts for aggregating enable/disable of components.
411    final HashMap<String, ArrayList<String>> mPendingBroadcasts
412            = new HashMap<String, ArrayList<String>>();
413    // Service Connection to remote media container service to copy
414    // package uri's from external media onto secure containers
415    // or internal storage.
416    private IMediaContainerService mContainerService = null;
417
418    static final int SEND_PENDING_BROADCAST = 1;
419    static final int MCS_BOUND = 3;
420    static final int END_COPY = 4;
421    static final int INIT_COPY = 5;
422    static final int MCS_UNBIND = 6;
423    static final int START_CLEANING_PACKAGE = 7;
424    static final int FIND_INSTALL_LOC = 8;
425    static final int POST_INSTALL = 9;
426    static final int MCS_RECONNECT = 10;
427    static final int MCS_GIVE_UP = 11;
428    static final int UPDATED_MEDIA_STATUS = 12;
429    static final int WRITE_SETTINGS = 13;
430    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
431    static final int PACKAGE_VERIFIED = 15;
432    static final int CHECK_PENDING_VERIFICATION = 16;
433
434    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
435
436    // Delay time in millisecs
437    static final int BROADCAST_DELAY = 10 * 1000;
438
439    static UserManagerService sUserManager;
440
441    // Stores a list of users whose package restrictions file needs to be updated
442    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
443
444    final private DefaultContainerConnection mDefContainerConn =
445            new DefaultContainerConnection();
446    class DefaultContainerConnection implements ServiceConnection {
447        public void onServiceConnected(ComponentName name, IBinder service) {
448            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
449            IMediaContainerService imcs =
450                IMediaContainerService.Stub.asInterface(service);
451            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
452        }
453
454        public void onServiceDisconnected(ComponentName name) {
455            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
456        }
457    };
458
459    // Recordkeeping of restore-after-install operations that are currently in flight
460    // between the Package Manager and the Backup Manager
461    class PostInstallData {
462        public InstallArgs args;
463        public PackageInstalledInfo res;
464
465        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
466            args = _a;
467            res = _r;
468        }
469    };
470    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
471    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
472
473    private final String mRequiredVerifierPackage;
474
475    class PackageHandler extends Handler {
476        private boolean mBound = false;
477        final ArrayList<HandlerParams> mPendingInstalls =
478            new ArrayList<HandlerParams>();
479
480        private boolean connectToService() {
481            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
482                    " DefaultContainerService");
483            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
484            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
485            if (mContext.bindService(service, mDefContainerConn,
486                    Context.BIND_AUTO_CREATE, UserHandle.USER_OWNER)) {
487                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
488                mBound = true;
489                return true;
490            }
491            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
492            return false;
493        }
494
495        private void disconnectService() {
496            mContainerService = null;
497            mBound = false;
498            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
499            mContext.unbindService(mDefContainerConn);
500            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
501        }
502
503        PackageHandler(Looper looper) {
504            super(looper);
505        }
506
507        public void handleMessage(Message msg) {
508            try {
509                doHandleMessage(msg);
510            } finally {
511                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
512            }
513        }
514
515        void doHandleMessage(Message msg) {
516            switch (msg.what) {
517                case INIT_COPY: {
518                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
519                    HandlerParams params = (HandlerParams) msg.obj;
520                    int idx = mPendingInstalls.size();
521                    if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
522                    // If a bind was already initiated we dont really
523                    // need to do anything. The pending install
524                    // will be processed later on.
525                    if (!mBound) {
526                        // If this is the only one pending we might
527                        // have to bind to the service again.
528                        if (!connectToService()) {
529                            Slog.e(TAG, "Failed to bind to media container service");
530                            params.serviceError();
531                            return;
532                        } else {
533                            // Once we bind to the service, the first
534                            // pending request will be processed.
535                            mPendingInstalls.add(idx, params);
536                        }
537                    } else {
538                        mPendingInstalls.add(idx, params);
539                        // Already bound to the service. Just make
540                        // sure we trigger off processing the first request.
541                        if (idx == 0) {
542                            mHandler.sendEmptyMessage(MCS_BOUND);
543                        }
544                    }
545                    break;
546                }
547                case MCS_BOUND: {
548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
549                    if (msg.obj != null) {
550                        mContainerService = (IMediaContainerService) msg.obj;
551                    }
552                    if (mContainerService == null) {
553                        // Something seriously wrong. Bail out
554                        Slog.e(TAG, "Cannot bind to media container service");
555                        for (HandlerParams params : mPendingInstalls) {
556                            // Indicate service bind error
557                            params.serviceError();
558                        }
559                        mPendingInstalls.clear();
560                    } else if (mPendingInstalls.size() > 0) {
561                        HandlerParams params = mPendingInstalls.get(0);
562                        if (params != null) {
563                            if (params.startCopy()) {
564                                // We are done...  look for more work or to
565                                // go idle.
566                                if (DEBUG_SD_INSTALL) Log.i(TAG,
567                                        "Checking for more work or unbind...");
568                                // Delete pending install
569                                if (mPendingInstalls.size() > 0) {
570                                    mPendingInstalls.remove(0);
571                                }
572                                if (mPendingInstalls.size() == 0) {
573                                    if (mBound) {
574                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
575                                                "Posting delayed MCS_UNBIND");
576                                        removeMessages(MCS_UNBIND);
577                                        Message ubmsg = obtainMessage(MCS_UNBIND);
578                                        // Unbind after a little delay, to avoid
579                                        // continual thrashing.
580                                        sendMessageDelayed(ubmsg, 10000);
581                                    }
582                                } else {
583                                    // There are more pending requests in queue.
584                                    // Just post MCS_BOUND message to trigger processing
585                                    // of next pending install.
586                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
587                                            "Posting MCS_BOUND for next woek");
588                                    mHandler.sendEmptyMessage(MCS_BOUND);
589                                }
590                            }
591                        }
592                    } else {
593                        // Should never happen ideally.
594                        Slog.w(TAG, "Empty queue");
595                    }
596                    break;
597                }
598                case MCS_RECONNECT: {
599                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
600                    if (mPendingInstalls.size() > 0) {
601                        if (mBound) {
602                            disconnectService();
603                        }
604                        if (!connectToService()) {
605                            Slog.e(TAG, "Failed to bind to media container service");
606                            for (HandlerParams params : mPendingInstalls) {
607                                // Indicate service bind error
608                                params.serviceError();
609                            }
610                            mPendingInstalls.clear();
611                        }
612                    }
613                    break;
614                }
615                case MCS_UNBIND: {
616                    // If there is no actual work left, then time to unbind.
617                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
618
619                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
620                        if (mBound) {
621                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
622
623                            disconnectService();
624                        }
625                    } else if (mPendingInstalls.size() > 0) {
626                        // There are more pending requests in queue.
627                        // Just post MCS_BOUND message to trigger processing
628                        // of next pending install.
629                        mHandler.sendEmptyMessage(MCS_BOUND);
630                    }
631
632                    break;
633                }
634                case MCS_GIVE_UP: {
635                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
636                    mPendingInstalls.remove(0);
637                    break;
638                }
639                case SEND_PENDING_BROADCAST: {
640                    String packages[];
641                    ArrayList<String> components[];
642                    int size = 0;
643                    int uids[];
644                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
645                    synchronized (mPackages) {
646                        if (mPendingBroadcasts == null) {
647                            return;
648                        }
649                        size = mPendingBroadcasts.size();
650                        if (size <= 0) {
651                            // Nothing to be done. Just return
652                            return;
653                        }
654                        packages = new String[size];
655                        components = new ArrayList[size];
656                        uids = new int[size];
657                        Iterator<Map.Entry<String, ArrayList<String>>>
658                                it = mPendingBroadcasts.entrySet().iterator();
659                        int i = 0;
660                        while (it.hasNext() && i < size) {
661                            Map.Entry<String, ArrayList<String>> ent = it.next();
662                            packages[i] = ent.getKey();
663                            components[i] = ent.getValue();
664                            PackageSetting ps = mSettings.mPackages.get(ent.getKey());
665                            uids[i] = (ps != null) ? ps.appId : -1;
666                            i++;
667                        }
668                        size = i;
669                        mPendingBroadcasts.clear();
670                    }
671                    // Send broadcasts
672                    for (int i = 0; i < size; i++) {
673                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
674                    }
675                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
676                    break;
677                }
678                case START_CLEANING_PACKAGE: {
679                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
680                    final String packageName = (String)msg.obj;
681                    final int userId = msg.arg1;
682                    final boolean andCode = msg.arg2 != 0;
683                    synchronized (mPackages) {
684                        if (userId == UserHandle.USER_ALL) {
685                            int[] users = sUserManager.getUserIds();
686                            for (int user : users) {
687                                mSettings.addPackageToCleanLPw(
688                                        new PackageCleanItem(user, packageName, andCode));
689                            }
690                        } else {
691                            mSettings.addPackageToCleanLPw(
692                                    new PackageCleanItem(userId, packageName, andCode));
693                        }
694                    }
695                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
696                    startCleaningPackages();
697                } break;
698                case POST_INSTALL: {
699                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
700                    PostInstallData data = mRunningInstalls.get(msg.arg1);
701                    mRunningInstalls.delete(msg.arg1);
702                    boolean deleteOld = false;
703
704                    if (data != null) {
705                        InstallArgs args = data.args;
706                        PackageInstalledInfo res = data.res;
707
708                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
709                            res.removedInfo.sendBroadcast(false, true, false);
710                            Bundle extras = new Bundle(1);
711                            extras.putInt(Intent.EXTRA_UID, res.uid);
712                            // Determine the set of users who are adding this
713                            // package for the first time vs. those who are seeing
714                            // an update.
715                            int[] firstUsers;
716                            int[] updateUsers = new int[0];
717                            if (res.origUsers == null || res.origUsers.length == 0) {
718                                firstUsers = res.newUsers;
719                            } else {
720                                firstUsers = new int[0];
721                                for (int i=0; i<res.newUsers.length; i++) {
722                                    int user = res.newUsers[i];
723                                    boolean isNew = true;
724                                    for (int j=0; j<res.origUsers.length; j++) {
725                                        if (res.origUsers[j] == user) {
726                                            isNew = false;
727                                            break;
728                                        }
729                                    }
730                                    if (isNew) {
731                                        int[] newFirst = new int[firstUsers.length+1];
732                                        System.arraycopy(firstUsers, 0, newFirst, 0,
733                                                firstUsers.length);
734                                        newFirst[firstUsers.length] = user;
735                                        firstUsers = newFirst;
736                                    } else {
737                                        int[] newUpdate = new int[updateUsers.length+1];
738                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
739                                                updateUsers.length);
740                                        newUpdate[updateUsers.length] = user;
741                                        updateUsers = newUpdate;
742                                    }
743                                }
744                            }
745                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
746                                    res.pkg.applicationInfo.packageName,
747                                    extras, null, null, firstUsers);
748                            final boolean update = res.removedInfo.removedPackage != null;
749                            if (update) {
750                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
751                            }
752                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
753                                    res.pkg.applicationInfo.packageName,
754                                    extras, null, null, updateUsers);
755                            if (update) {
756                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
757                                        res.pkg.applicationInfo.packageName,
758                                        extras, null, null, updateUsers);
759                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
760                                        null, null,
761                                        res.pkg.applicationInfo.packageName, null, updateUsers);
762                            }
763                            if (res.removedInfo.args != null) {
764                                // Remove the replaced package's older resources safely now
765                                deleteOld = true;
766                            }
767
768                            // Log current value of "unknown sources" setting
769                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
770                                getUnknownSourcesSettings());
771                        }
772                        // Force a gc to clear up things
773                        Runtime.getRuntime().gc();
774                        // We delete after a gc for applications  on sdcard.
775                        if (deleteOld) {
776                            synchronized (mInstallLock) {
777                                res.removedInfo.args.doPostDeleteLI(true);
778                            }
779                        }
780                        if (args.observer != null) {
781                            try {
782                                args.observer.packageInstalled(res.name, res.returnCode);
783                            } catch (RemoteException e) {
784                                Slog.i(TAG, "Observer no longer exists.");
785                            }
786                        }
787                    } else {
788                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
789                    }
790                } break;
791                case UPDATED_MEDIA_STATUS: {
792                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
793                    boolean reportStatus = msg.arg1 == 1;
794                    boolean doGc = msg.arg2 == 1;
795                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
796                    if (doGc) {
797                        // Force a gc to clear up stale containers.
798                        Runtime.getRuntime().gc();
799                    }
800                    if (msg.obj != null) {
801                        @SuppressWarnings("unchecked")
802                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
803                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
804                        // Unload containers
805                        unloadAllContainers(args);
806                    }
807                    if (reportStatus) {
808                        try {
809                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
810                            PackageHelper.getMountService().finishMediaUpdate();
811                        } catch (RemoteException e) {
812                            Log.e(TAG, "MountService not running?");
813                        }
814                    }
815                } break;
816                case WRITE_SETTINGS: {
817                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
818                    synchronized (mPackages) {
819                        removeMessages(WRITE_SETTINGS);
820                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
821                        mSettings.writeLPr();
822                        mDirtyUsers.clear();
823                    }
824                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
825                } break;
826                case WRITE_PACKAGE_RESTRICTIONS: {
827                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
828                    synchronized (mPackages) {
829                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
830                        for (int userId : mDirtyUsers) {
831                            mSettings.writePackageRestrictionsLPr(userId);
832                        }
833                        mDirtyUsers.clear();
834                    }
835                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
836                } break;
837                case CHECK_PENDING_VERIFICATION: {
838                    final int verificationId = msg.arg1;
839                    final PackageVerificationState state = mPendingVerification.get(verificationId);
840
841                    if ((state != null) && !state.timeoutExtended()) {
842                        final InstallArgs args = state.getInstallArgs();
843                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
844                        mPendingVerification.remove(verificationId);
845
846                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
847
848                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
849                            Slog.i(TAG, "Continuing with installation of "
850                                    + args.packageURI.toString());
851                            state.setVerifierResponse(Binder.getCallingUid(),
852                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
853                            broadcastPackageVerified(verificationId, args.packageURI,
854                                    PackageManager.VERIFICATION_ALLOW,
855                                    state.getInstallArgs().getUser());
856                            try {
857                                ret = args.copyApk(mContainerService, true);
858                            } catch (RemoteException e) {
859                                Slog.e(TAG, "Could not contact the ContainerService");
860                            }
861                        } else {
862                            broadcastPackageVerified(verificationId, args.packageURI,
863                                    PackageManager.VERIFICATION_REJECT,
864                                    state.getInstallArgs().getUser());
865                        }
866
867                        processPendingInstall(args, ret);
868                        mHandler.sendEmptyMessage(MCS_UNBIND);
869                    }
870                    break;
871                }
872                case PACKAGE_VERIFIED: {
873                    final int verificationId = msg.arg1;
874
875                    final PackageVerificationState state = mPendingVerification.get(verificationId);
876                    if (state == null) {
877                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
878                        break;
879                    }
880
881                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
882
883                    state.setVerifierResponse(response.callerUid, response.code);
884
885                    if (state.isVerificationComplete()) {
886                        mPendingVerification.remove(verificationId);
887
888                        final InstallArgs args = state.getInstallArgs();
889
890                        int ret;
891                        if (state.isInstallAllowed()) {
892                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
893                            broadcastPackageVerified(verificationId, args.packageURI,
894                                    response.code, state.getInstallArgs().getUser());
895                            try {
896                                ret = args.copyApk(mContainerService, true);
897                            } catch (RemoteException e) {
898                                Slog.e(TAG, "Could not contact the ContainerService");
899                            }
900                        } else {
901                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
902                        }
903
904                        processPendingInstall(args, ret);
905
906                        mHandler.sendEmptyMessage(MCS_UNBIND);
907                    }
908
909                    break;
910                }
911            }
912        }
913    }
914
915    void scheduleWriteSettingsLocked() {
916        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
917            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
918        }
919    }
920
921    void scheduleWritePackageRestrictionsLocked(int userId) {
922        if (!sUserManager.exists(userId)) return;
923        mDirtyUsers.add(userId);
924        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
925            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
926        }
927    }
928
929    public static final IPackageManager main(Context context, Installer installer,
930            boolean factoryTest, boolean onlyCore) {
931        PackageManagerService m = new PackageManagerService(context, installer,
932                factoryTest, onlyCore);
933        ServiceManager.addService("package", m);
934        return m;
935    }
936
937    static String[] splitString(String str, char sep) {
938        int count = 1;
939        int i = 0;
940        while ((i=str.indexOf(sep, i)) >= 0) {
941            count++;
942            i++;
943        }
944
945        String[] res = new String[count];
946        i=0;
947        count = 0;
948        int lastI=0;
949        while ((i=str.indexOf(sep, i)) >= 0) {
950            res[count] = str.substring(lastI, i);
951            count++;
952            i++;
953            lastI = i;
954        }
955        res[count] = str.substring(lastI, str.length());
956        return res;
957    }
958
959    public PackageManagerService(Context context, Installer installer,
960            boolean factoryTest, boolean onlyCore) {
961        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
962                SystemClock.uptimeMillis());
963
964        if (mSdkVersion <= 0) {
965            Slog.w(TAG, "**** ro.build.version.sdk not set!");
966        }
967
968        mContext = context;
969        mFactoryTest = factoryTest;
970        mOnlyCore = onlyCore;
971        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
972        mMetrics = new DisplayMetrics();
973        mSettings = new Settings(context);
974        mSettings.addSharedUserLPw("android.uid.system",
975                Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
976        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
977        mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
978        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
979        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
980
981        String separateProcesses = SystemProperties.get("debug.separate_processes");
982        if (separateProcesses != null && separateProcesses.length() > 0) {
983            if ("*".equals(separateProcesses)) {
984                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
985                mSeparateProcesses = null;
986                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
987            } else {
988                mDefParseFlags = 0;
989                mSeparateProcesses = separateProcesses.split(",");
990                Slog.w(TAG, "Running with debug.separate_processes: "
991                        + separateProcesses);
992            }
993        } else {
994            mDefParseFlags = 0;
995            mSeparateProcesses = null;
996        }
997
998        mInstaller = installer;
999
1000        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1001        Display d = wm.getDefaultDisplay();
1002        d.getMetrics(mMetrics);
1003
1004        synchronized (mInstallLock) {
1005        // writer
1006        synchronized (mPackages) {
1007            mHandlerThread.start();
1008            mHandler = new PackageHandler(mHandlerThread.getLooper());
1009
1010            File dataDir = Environment.getDataDirectory();
1011            mAppDataDir = new File(dataDir, "data");
1012            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1013            mUserAppDataDir = new File(dataDir, "user");
1014            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1015
1016            sUserManager = new UserManagerService(context, this,
1017                    mInstallLock, mPackages);
1018
1019            readPermissions();
1020
1021            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1022            long startTime = SystemClock.uptimeMillis();
1023
1024            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1025                    startTime);
1026
1027            // Set flag to monitor and not change apk file paths when
1028            // scanning install directories.
1029            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1030            if (mNoDexOpt) {
1031                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1032                scanMode |= SCAN_NO_DEX;
1033            }
1034
1035            final HashSet<String> libFiles = new HashSet<String>();
1036
1037            mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
1038            mDalvikCacheDir = new File(dataDir, "dalvik-cache");
1039
1040            boolean didDexOpt = false;
1041
1042            /**
1043             * Out of paranoia, ensure that everything in the boot class
1044             * path has been dexed.
1045             */
1046            String bootClassPath = System.getProperty("java.boot.class.path");
1047            if (bootClassPath != null) {
1048                String[] paths = splitString(bootClassPath, ':');
1049                for (int i=0; i<paths.length; i++) {
1050                    try {
1051                        if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
1052                            libFiles.add(paths[i]);
1053                            mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
1054                            didDexOpt = true;
1055                        }
1056                    } catch (FileNotFoundException e) {
1057                        Slog.w(TAG, "Boot class path not found: " + paths[i]);
1058                    } catch (IOException e) {
1059                        Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
1060                                + e.getMessage());
1061                    }
1062                }
1063            } else {
1064                Slog.w(TAG, "No BOOTCLASSPATH found!");
1065            }
1066
1067            /**
1068             * Also ensure all external libraries have had dexopt run on them.
1069             */
1070            if (mSharedLibraries.size() > 0) {
1071                Iterator<String> libs = mSharedLibraries.values().iterator();
1072                while (libs.hasNext()) {
1073                    String lib = libs.next();
1074                    try {
1075                        if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1076                            libFiles.add(lib);
1077                            mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1078                            didDexOpt = true;
1079                        }
1080                    } catch (FileNotFoundException e) {
1081                        Slog.w(TAG, "Library not found: " + lib);
1082                    } catch (IOException e) {
1083                        Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1084                                + e.getMessage());
1085                    }
1086                }
1087            }
1088
1089            // Gross hack for now: we know this file doesn't contain any
1090            // code, so don't dexopt it to avoid the resulting log spew.
1091            libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1092
1093            /**
1094             * And there are a number of commands implemented in Java, which
1095             * we currently need to do the dexopt on so that they can be
1096             * run from a non-root shell.
1097             */
1098            String[] frameworkFiles = mFrameworkDir.list();
1099            if (frameworkFiles != null) {
1100                for (int i=0; i<frameworkFiles.length; i++) {
1101                    File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1102                    String path = libPath.getPath();
1103                    // Skip the file if we alrady did it.
1104                    if (libFiles.contains(path)) {
1105                        continue;
1106                    }
1107                    // Skip the file if it is not a type we want to dexopt.
1108                    if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1109                        continue;
1110                    }
1111                    try {
1112                        if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1113                            mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1114                            didDexOpt = true;
1115                        }
1116                    } catch (FileNotFoundException e) {
1117                        Slog.w(TAG, "Jar not found: " + path);
1118                    } catch (IOException e) {
1119                        Slog.w(TAG, "Exception reading jar: " + path, e);
1120                    }
1121                }
1122            }
1123
1124            if (didDexOpt) {
1125                // If we had to do a dexopt of one of the previous
1126                // things, then something on the system has changed.
1127                // Consider this significant, and wipe away all other
1128                // existing dexopt files to ensure we don't leave any
1129                // dangling around.
1130                String[] files = mDalvikCacheDir.list();
1131                if (files != null) {
1132                    for (int i=0; i<files.length; i++) {
1133                        String fn = files[i];
1134                        if (fn.startsWith("data@app@")
1135                                || fn.startsWith("data@app-private@")) {
1136                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1137                            (new File(mDalvikCacheDir, fn)).delete();
1138                        }
1139                    }
1140                }
1141            }
1142
1143            // Find base frameworks (resource packages without code).
1144            mFrameworkInstallObserver = new AppDirObserver(
1145                mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1146            mFrameworkInstallObserver.startWatching();
1147            scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1148                    | PackageParser.PARSE_IS_SYSTEM_DIR,
1149                    scanMode | SCAN_NO_DEX, 0);
1150
1151            // Collect all system packages.
1152            mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1153            mSystemInstallObserver = new AppDirObserver(
1154                mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1155            mSystemInstallObserver.startWatching();
1156            scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
1157                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1158
1159            // Collect all vendor packages.
1160            mVendorAppDir = new File("/vendor/app");
1161            mVendorInstallObserver = new AppDirObserver(
1162                mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1163            mVendorInstallObserver.startWatching();
1164            scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
1165                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1166
1167            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1168            mInstaller.moveFiles();
1169
1170            // Prune any system packages that no longer exist.
1171            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1172            if (!mOnlyCore) {
1173                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1174                while (psit.hasNext()) {
1175                    PackageSetting ps = psit.next();
1176
1177                    /*
1178                     * If this is not a system app, it can't be a
1179                     * disable system app.
1180                     */
1181                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1182                        continue;
1183                    }
1184
1185                    /*
1186                     * If the package is scanned, it's not erased.
1187                     */
1188                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1189                    if (scannedPkg != null) {
1190                        /*
1191                         * If the system app is both scanned and in the
1192                         * disabled packages list, then it must have been
1193                         * added via OTA. Remove it from the currently
1194                         * scanned package so the previously user-installed
1195                         * application can be scanned.
1196                         */
1197                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1198                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1199                                    + "; removing system app");
1200                            removePackageLI(ps, true);
1201                        }
1202
1203                        continue;
1204                    }
1205
1206                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1207                        psit.remove();
1208                        String msg = "System package " + ps.name
1209                                + " no longer exists; wiping its data";
1210                        reportSettingsProblem(Log.WARN, msg);
1211                        removeDataDirsLI(ps.name);
1212                    } else {
1213                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1214                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1215                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1216                        }
1217                    }
1218                }
1219            }
1220
1221            mAppInstallDir = new File(dataDir, "app");
1222            mAppLibInstallDir = new File(dataDir, "app-lib");
1223            //look for any incomplete package installations
1224            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1225            //clean up list
1226            for(int i = 0; i < deletePkgsList.size(); i++) {
1227                //clean up here
1228                cleanupInstallFailedPackage(deletePkgsList.get(i));
1229            }
1230            //delete tmp files
1231            deleteTempPackageFiles();
1232
1233            if (!mOnlyCore) {
1234                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1235                        SystemClock.uptimeMillis());
1236                mAppInstallObserver = new AppDirObserver(
1237                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1238                mAppInstallObserver.startWatching();
1239                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1240
1241                mDrmAppInstallObserver = new AppDirObserver(
1242                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1243                mDrmAppInstallObserver.startWatching();
1244                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1245                        scanMode, 0);
1246
1247                /**
1248                 * Remove disable package settings for any updated system
1249                 * apps that were removed via an OTA. If they're not a
1250                 * previously-updated app, remove them completely.
1251                 * Otherwise, just revoke their system-level permissions.
1252                 */
1253                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1254                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1255                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1256
1257                    String msg;
1258                    if (deletedPkg == null) {
1259                        msg = "Updated system package " + deletedAppName
1260                                + " no longer exists; wiping its data";
1261                        removeDataDirsLI(deletedAppName);
1262                    } else {
1263                        msg = "Updated system app + " + deletedAppName
1264                                + " no longer present; removing system privileges for "
1265                                + deletedAppName;
1266
1267                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1268
1269                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1270                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1271                    }
1272                    reportSettingsProblem(Log.WARN, msg);
1273                }
1274            } else {
1275                mAppInstallObserver = null;
1276                mDrmAppInstallObserver = null;
1277            }
1278
1279            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1280                    SystemClock.uptimeMillis());
1281            Slog.i(TAG, "Time to scan packages: "
1282                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1283                    + " seconds");
1284
1285            // If the platform SDK has changed since the last time we booted,
1286            // we need to re-grant app permission to catch any new ones that
1287            // appear.  This is really a hack, and means that apps can in some
1288            // cases get permissions that the user didn't initially explicitly
1289            // allow...  it would be nice to have some better way to handle
1290            // this situation.
1291            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1292                    != mSdkVersion;
1293            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1294                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1295                    + "; regranting permissions for internal storage");
1296            mSettings.mInternalSdkPlatform = mSdkVersion;
1297
1298            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1299                    | (regrantPermissions
1300                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1301                            : 0));
1302
1303            // can downgrade to reader
1304            mSettings.writeLPr();
1305
1306            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1307                    SystemClock.uptimeMillis());
1308
1309            // Now after opening every single application zip, make sure they
1310            // are all flushed.  Not really needed, but keeps things nice and
1311            // tidy.
1312            Runtime.getRuntime().gc();
1313
1314            mRequiredVerifierPackage = getRequiredVerifierLPr();
1315        } // synchronized (mPackages)
1316        } // synchronized (mInstallLock)
1317    }
1318
1319    public boolean isFirstBoot() {
1320        return !mRestoredSettings;
1321    }
1322
1323    private String getRequiredVerifierLPr() {
1324        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1325        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1326                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1327
1328        String requiredVerifier = null;
1329
1330        final int N = receivers.size();
1331        for (int i = 0; i < N; i++) {
1332            final ResolveInfo info = receivers.get(i);
1333
1334            if (info.activityInfo == null) {
1335                continue;
1336            }
1337
1338            final String packageName = info.activityInfo.packageName;
1339
1340            final PackageSetting ps = mSettings.mPackages.get(packageName);
1341            if (ps == null) {
1342                continue;
1343            }
1344
1345            if (!ps.grantedPermissions
1346                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1347                continue;
1348            }
1349
1350            if (requiredVerifier != null) {
1351                throw new RuntimeException("There can be only one required verifier");
1352            }
1353
1354            requiredVerifier = packageName;
1355        }
1356
1357        return requiredVerifier;
1358    }
1359
1360    @Override
1361    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1362            throws RemoteException {
1363        try {
1364            return super.onTransact(code, data, reply, flags);
1365        } catch (RuntimeException e) {
1366            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1367                Slog.e(TAG, "Package Manager Crash", e);
1368            }
1369            throw e;
1370        }
1371    }
1372
1373    void cleanupInstallFailedPackage(PackageSetting ps) {
1374        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1375        removeDataDirsLI(ps.name);
1376        if (ps.codePath != null) {
1377            if (!ps.codePath.delete()) {
1378                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1379            }
1380        }
1381        if (ps.resourcePath != null) {
1382            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1383                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1384            }
1385        }
1386        mSettings.removePackageLPw(ps.name);
1387    }
1388
1389    void readPermissions() {
1390        // Read permissions from .../etc/permission directory.
1391        File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1392        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1393            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1394            return;
1395        }
1396        if (!libraryDir.canRead()) {
1397            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1398            return;
1399        }
1400
1401        // Iterate over the files in the directory and scan .xml files
1402        for (File f : libraryDir.listFiles()) {
1403            // We'll read platform.xml last
1404            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1405                continue;
1406            }
1407
1408            if (!f.getPath().endsWith(".xml")) {
1409                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1410                continue;
1411            }
1412            if (!f.canRead()) {
1413                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1414                continue;
1415            }
1416
1417            readPermissionsFromXml(f);
1418        }
1419
1420        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1421        final File permFile = new File(Environment.getRootDirectory(),
1422                "etc/permissions/platform.xml");
1423        readPermissionsFromXml(permFile);
1424    }
1425
1426    private void readPermissionsFromXml(File permFile) {
1427        FileReader permReader = null;
1428        try {
1429            permReader = new FileReader(permFile);
1430        } catch (FileNotFoundException e) {
1431            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1432            return;
1433        }
1434
1435        try {
1436            XmlPullParser parser = Xml.newPullParser();
1437            parser.setInput(permReader);
1438
1439            XmlUtils.beginDocument(parser, "permissions");
1440
1441            while (true) {
1442                XmlUtils.nextElement(parser);
1443                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1444                    break;
1445                }
1446
1447                String name = parser.getName();
1448                if ("group".equals(name)) {
1449                    String gidStr = parser.getAttributeValue(null, "gid");
1450                    if (gidStr != null) {
1451                        int gid = Integer.parseInt(gidStr);
1452                        mGlobalGids = appendInt(mGlobalGids, gid);
1453                    } else {
1454                        Slog.w(TAG, "<group> without gid at "
1455                                + parser.getPositionDescription());
1456                    }
1457
1458                    XmlUtils.skipCurrentTag(parser);
1459                    continue;
1460                } else if ("permission".equals(name)) {
1461                    String perm = parser.getAttributeValue(null, "name");
1462                    if (perm == null) {
1463                        Slog.w(TAG, "<permission> without name at "
1464                                + parser.getPositionDescription());
1465                        XmlUtils.skipCurrentTag(parser);
1466                        continue;
1467                    }
1468                    perm = perm.intern();
1469                    readPermission(parser, perm);
1470
1471                } else if ("assign-permission".equals(name)) {
1472                    String perm = parser.getAttributeValue(null, "name");
1473                    if (perm == null) {
1474                        Slog.w(TAG, "<assign-permission> without name at "
1475                                + parser.getPositionDescription());
1476                        XmlUtils.skipCurrentTag(parser);
1477                        continue;
1478                    }
1479                    String uidStr = parser.getAttributeValue(null, "uid");
1480                    if (uidStr == null) {
1481                        Slog.w(TAG, "<assign-permission> without uid at "
1482                                + parser.getPositionDescription());
1483                        XmlUtils.skipCurrentTag(parser);
1484                        continue;
1485                    }
1486                    int uid = Process.getUidForName(uidStr);
1487                    if (uid < 0) {
1488                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1489                                + uidStr + "\" at "
1490                                + parser.getPositionDescription());
1491                        XmlUtils.skipCurrentTag(parser);
1492                        continue;
1493                    }
1494                    perm = perm.intern();
1495                    HashSet<String> perms = mSystemPermissions.get(uid);
1496                    if (perms == null) {
1497                        perms = new HashSet<String>();
1498                        mSystemPermissions.put(uid, perms);
1499                    }
1500                    perms.add(perm);
1501                    XmlUtils.skipCurrentTag(parser);
1502
1503                } else if ("library".equals(name)) {
1504                    String lname = parser.getAttributeValue(null, "name");
1505                    String lfile = parser.getAttributeValue(null, "file");
1506                    if (lname == null) {
1507                        Slog.w(TAG, "<library> without name at "
1508                                + parser.getPositionDescription());
1509                    } else if (lfile == null) {
1510                        Slog.w(TAG, "<library> without file at "
1511                                + parser.getPositionDescription());
1512                    } else {
1513                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1514                        mSharedLibraries.put(lname, lfile);
1515                    }
1516                    XmlUtils.skipCurrentTag(parser);
1517                    continue;
1518
1519                } else if ("feature".equals(name)) {
1520                    String fname = parser.getAttributeValue(null, "name");
1521                    if (fname == null) {
1522                        Slog.w(TAG, "<feature> without name at "
1523                                + parser.getPositionDescription());
1524                    } else {
1525                        //Log.i(TAG, "Got feature " + fname);
1526                        FeatureInfo fi = new FeatureInfo();
1527                        fi.name = fname;
1528                        mAvailableFeatures.put(fname, fi);
1529                    }
1530                    XmlUtils.skipCurrentTag(parser);
1531                    continue;
1532
1533                } else {
1534                    XmlUtils.skipCurrentTag(parser);
1535                    continue;
1536                }
1537
1538            }
1539            permReader.close();
1540        } catch (XmlPullParserException e) {
1541            Slog.w(TAG, "Got execption parsing permissions.", e);
1542        } catch (IOException e) {
1543            Slog.w(TAG, "Got execption parsing permissions.", e);
1544        }
1545    }
1546
1547    void readPermission(XmlPullParser parser, String name)
1548            throws IOException, XmlPullParserException {
1549
1550        name = name.intern();
1551
1552        BasePermission bp = mSettings.mPermissions.get(name);
1553        if (bp == null) {
1554            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1555            mSettings.mPermissions.put(name, bp);
1556        }
1557        int outerDepth = parser.getDepth();
1558        int type;
1559        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1560               && (type != XmlPullParser.END_TAG
1561                       || parser.getDepth() > outerDepth)) {
1562            if (type == XmlPullParser.END_TAG
1563                    || type == XmlPullParser.TEXT) {
1564                continue;
1565            }
1566
1567            String tagName = parser.getName();
1568            if ("group".equals(tagName)) {
1569                String gidStr = parser.getAttributeValue(null, "gid");
1570                if (gidStr != null) {
1571                    int gid = Process.getGidForName(gidStr);
1572                    bp.gids = appendInt(bp.gids, gid);
1573                } else {
1574                    Slog.w(TAG, "<group> without gid at "
1575                            + parser.getPositionDescription());
1576                }
1577            }
1578            XmlUtils.skipCurrentTag(parser);
1579        }
1580    }
1581
1582    static int[] appendInts(int[] cur, int[] add) {
1583        if (add == null) return cur;
1584        if (cur == null) return add;
1585        final int N = add.length;
1586        for (int i=0; i<N; i++) {
1587            cur = appendInt(cur, add[i]);
1588        }
1589        return cur;
1590    }
1591
1592    static int[] removeInts(int[] cur, int[] rem) {
1593        if (rem == null) return cur;
1594        if (cur == null) return cur;
1595        final int N = rem.length;
1596        for (int i=0; i<N; i++) {
1597            cur = removeInt(cur, rem[i]);
1598        }
1599        return cur;
1600    }
1601
1602    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1603        if (!sUserManager.exists(userId)) return null;
1604        PackageInfo pi;
1605        final PackageSetting ps = (PackageSetting) p.mExtras;
1606        if (ps == null) {
1607            return null;
1608        }
1609        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1610        final PackageUserState state = ps.readUserState(userId);
1611        pi = PackageParser.generatePackageInfo(p, gp.gids, flags,
1612                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1613                state, userId);
1614        if (pi != null) {
1615            pi.applicationInfo.enabledSetting = state.enabled;
1616            pi.applicationInfo.enabled =
1617                    pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT
1618                    || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED;
1619        }
1620        return pi;
1621    }
1622
1623    @Override
1624    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1625        if (!sUserManager.exists(userId)) return null;
1626        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1627        // reader
1628        synchronized (mPackages) {
1629            PackageParser.Package p = mPackages.get(packageName);
1630            if (DEBUG_PACKAGE_INFO)
1631                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1632            if (p != null) {
1633                return generatePackageInfo(p, flags, userId);
1634            }
1635            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1636                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1637            }
1638        }
1639        return null;
1640    }
1641
1642    public String[] currentToCanonicalPackageNames(String[] names) {
1643        String[] out = new String[names.length];
1644        // reader
1645        synchronized (mPackages) {
1646            for (int i=names.length-1; i>=0; i--) {
1647                PackageSetting ps = mSettings.mPackages.get(names[i]);
1648                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1649            }
1650        }
1651        return out;
1652    }
1653
1654    public String[] canonicalToCurrentPackageNames(String[] names) {
1655        String[] out = new String[names.length];
1656        // reader
1657        synchronized (mPackages) {
1658            for (int i=names.length-1; i>=0; i--) {
1659                String cur = mSettings.mRenamedPackages.get(names[i]);
1660                out[i] = cur != null ? cur : names[i];
1661            }
1662        }
1663        return out;
1664    }
1665
1666    @Override
1667    public int getPackageUid(String packageName, int userId) {
1668        if (!sUserManager.exists(userId)) return -1;
1669        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1670        // reader
1671        synchronized (mPackages) {
1672            PackageParser.Package p = mPackages.get(packageName);
1673            if(p != null) {
1674                return UserHandle.getUid(userId, p.applicationInfo.uid);
1675            }
1676            PackageSetting ps = mSettings.mPackages.get(packageName);
1677            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1678                return -1;
1679            }
1680            p = ps.pkg;
1681            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1682        }
1683    }
1684
1685    public int[] getPackageGids(String packageName) {
1686        final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
1687        // reader
1688        synchronized (mPackages) {
1689            PackageParser.Package p = mPackages.get(packageName);
1690            if (DEBUG_PACKAGE_INFO)
1691                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1692            if (p != null) {
1693                final PackageSetting ps = (PackageSetting)p.mExtras;
1694                final SharedUserSetting suid = ps.sharedUser;
1695                int[] gids = suid != null ? suid.gids : ps.gids;
1696
1697                // include GIDs for any unenforced permissions
1698                if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
1699                    final BasePermission basePerm = mSettings.mPermissions.get(
1700                            READ_EXTERNAL_STORAGE);
1701                    gids = appendInts(gids, basePerm.gids);
1702                }
1703
1704                return gids;
1705            }
1706        }
1707        // stupid thing to indicate an error.
1708        return new int[0];
1709    }
1710
1711    static final PermissionInfo generatePermissionInfo(
1712            BasePermission bp, int flags) {
1713        if (bp.perm != null) {
1714            return PackageParser.generatePermissionInfo(bp.perm, flags);
1715        }
1716        PermissionInfo pi = new PermissionInfo();
1717        pi.name = bp.name;
1718        pi.packageName = bp.sourcePackage;
1719        pi.nonLocalizedLabel = bp.name;
1720        pi.protectionLevel = bp.protectionLevel;
1721        return pi;
1722    }
1723
1724    public PermissionInfo getPermissionInfo(String name, int flags) {
1725        // reader
1726        synchronized (mPackages) {
1727            final BasePermission p = mSettings.mPermissions.get(name);
1728            if (p != null) {
1729                return generatePermissionInfo(p, flags);
1730            }
1731            return null;
1732        }
1733    }
1734
1735    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1736        // reader
1737        synchronized (mPackages) {
1738            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1739            for (BasePermission p : mSettings.mPermissions.values()) {
1740                if (group == null) {
1741                    if (p.perm == null || p.perm.info.group == null) {
1742                        out.add(generatePermissionInfo(p, flags));
1743                    }
1744                } else {
1745                    if (p.perm != null && group.equals(p.perm.info.group)) {
1746                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1747                    }
1748                }
1749            }
1750
1751            if (out.size() > 0) {
1752                return out;
1753            }
1754            return mPermissionGroups.containsKey(group) ? out : null;
1755        }
1756    }
1757
1758    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1759        // reader
1760        synchronized (mPackages) {
1761            return PackageParser.generatePermissionGroupInfo(
1762                    mPermissionGroups.get(name), flags);
1763        }
1764    }
1765
1766    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1767        // reader
1768        synchronized (mPackages) {
1769            final int N = mPermissionGroups.size();
1770            ArrayList<PermissionGroupInfo> out
1771                    = new ArrayList<PermissionGroupInfo>(N);
1772            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1773                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1774            }
1775            return out;
1776        }
1777    }
1778
1779    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1780            int userId) {
1781        if (!sUserManager.exists(userId)) return null;
1782        PackageSetting ps = mSettings.mPackages.get(packageName);
1783        if (ps != null) {
1784            if (ps.pkg == null) {
1785                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
1786                        flags, userId);
1787                if (pInfo != null) {
1788                    return pInfo.applicationInfo;
1789                }
1790                return null;
1791            }
1792            return PackageParser.generateApplicationInfo(ps.pkg, flags,
1793                    ps.readUserState(userId), userId);
1794        }
1795        return null;
1796    }
1797
1798    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1799            int userId) {
1800        if (!sUserManager.exists(userId)) return null;
1801        PackageSetting ps = mSettings.mPackages.get(packageName);
1802        if (ps != null) {
1803            PackageParser.Package pkg = ps.pkg;
1804            if (pkg == null) {
1805                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
1806                    return null;
1807                }
1808                pkg = new PackageParser.Package(packageName);
1809                pkg.applicationInfo.packageName = packageName;
1810                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
1811                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1812                pkg.applicationInfo.sourceDir = ps.codePathString;
1813                pkg.applicationInfo.dataDir =
1814                        getDataPathForPackage(packageName, 0).getPath();
1815                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
1816            }
1817            // pkg.mSetEnabled = ps.getEnabled(userId);
1818            // pkg.mSetStopped = ps.getStopped(userId);
1819            return generatePackageInfo(pkg, flags, userId);
1820        }
1821        return null;
1822    }
1823
1824    @Override
1825    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
1826        if (!sUserManager.exists(userId)) return null;
1827        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
1828        // writer
1829        synchronized (mPackages) {
1830            PackageParser.Package p = mPackages.get(packageName);
1831            if (DEBUG_PACKAGE_INFO) Log.v(
1832                    TAG, "getApplicationInfo " + packageName
1833                    + ": " + p);
1834            if (p != null) {
1835                PackageSetting ps = mSettings.mPackages.get(packageName);
1836                if (ps == null) return null;
1837                // Note: isEnabledLP() does not apply here - always return info
1838                return PackageParser.generateApplicationInfo(p, flags, ps.readUserState(userId));
1839            }
1840            if ("android".equals(packageName)||"system".equals(packageName)) {
1841                return mAndroidApplication;
1842            }
1843            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1844                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
1845            }
1846        }
1847        return null;
1848    }
1849
1850
1851    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1852        mContext.enforceCallingOrSelfPermission(
1853                android.Manifest.permission.CLEAR_APP_CACHE, null);
1854        // Queue up an async operation since clearing cache may take a little while.
1855        mHandler.post(new Runnable() {
1856            public void run() {
1857                mHandler.removeCallbacks(this);
1858                int retCode = -1;
1859                synchronized (mInstallLock) {
1860                    retCode = mInstaller.freeCache(freeStorageSize);
1861                    if (retCode < 0) {
1862                        Slog.w(TAG, "Couldn't clear application caches");
1863                    }
1864                }
1865                if (observer != null) {
1866                    try {
1867                        observer.onRemoveCompleted(null, (retCode >= 0));
1868                    } catch (RemoteException e) {
1869                        Slog.w(TAG, "RemoveException when invoking call back");
1870                    }
1871                }
1872            }
1873        });
1874    }
1875
1876    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
1877        mContext.enforceCallingOrSelfPermission(
1878                android.Manifest.permission.CLEAR_APP_CACHE, null);
1879        // Queue up an async operation since clearing cache may take a little while.
1880        mHandler.post(new Runnable() {
1881            public void run() {
1882                mHandler.removeCallbacks(this);
1883                int retCode = -1;
1884                synchronized (mInstallLock) {
1885                    retCode = mInstaller.freeCache(freeStorageSize);
1886                    if (retCode < 0) {
1887                        Slog.w(TAG, "Couldn't clear application caches");
1888                    }
1889                }
1890                if(pi != null) {
1891                    try {
1892                        // Callback via pending intent
1893                        int code = (retCode >= 0) ? 1 : 0;
1894                        pi.sendIntent(null, code, null,
1895                                null, null);
1896                    } catch (SendIntentException e1) {
1897                        Slog.i(TAG, "Failed to send pending intent");
1898                    }
1899                }
1900            }
1901        });
1902    }
1903
1904    @Override
1905    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
1906        if (!sUserManager.exists(userId)) return null;
1907        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
1908        synchronized (mPackages) {
1909            PackageParser.Activity a = mActivities.mActivities.get(component);
1910
1911            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
1912            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
1913                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1914                if (ps == null) return null;
1915                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1916                        userId);
1917            }
1918            if (mResolveComponentName.equals(component)) {
1919                return mResolveActivity;
1920            }
1921        }
1922        return null;
1923    }
1924
1925    @Override
1926    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
1927        if (!sUserManager.exists(userId)) return null;
1928        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
1929        synchronized (mPackages) {
1930            PackageParser.Activity a = mReceivers.mActivities.get(component);
1931            if (DEBUG_PACKAGE_INFO) Log.v(
1932                TAG, "getReceiverInfo " + component + ": " + a);
1933            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
1934                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1935                if (ps == null) return null;
1936                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1937                        userId);
1938            }
1939        }
1940        return null;
1941    }
1942
1943    @Override
1944    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
1945        if (!sUserManager.exists(userId)) return null;
1946        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
1947        synchronized (mPackages) {
1948            PackageParser.Service s = mServices.mServices.get(component);
1949            if (DEBUG_PACKAGE_INFO) Log.v(
1950                TAG, "getServiceInfo " + component + ": " + s);
1951            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
1952                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1953                if (ps == null) return null;
1954                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
1955                        userId);
1956            }
1957        }
1958        return null;
1959    }
1960
1961    @Override
1962    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
1963        if (!sUserManager.exists(userId)) return null;
1964        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
1965        synchronized (mPackages) {
1966            PackageParser.Provider p = mProvidersByComponent.get(component);
1967            if (DEBUG_PACKAGE_INFO) Log.v(
1968                TAG, "getProviderInfo " + component + ": " + p);
1969            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
1970                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1971                if (ps == null) return null;
1972                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
1973                        userId);
1974            }
1975        }
1976        return null;
1977    }
1978
1979    public String[] getSystemSharedLibraryNames() {
1980        Set<String> libSet;
1981        synchronized (mPackages) {
1982            libSet = mSharedLibraries.keySet();
1983            int size = libSet.size();
1984            if (size > 0) {
1985                String[] libs = new String[size];
1986                libSet.toArray(libs);
1987                return libs;
1988            }
1989        }
1990        return null;
1991    }
1992
1993    public FeatureInfo[] getSystemAvailableFeatures() {
1994        Collection<FeatureInfo> featSet;
1995        synchronized (mPackages) {
1996            featSet = mAvailableFeatures.values();
1997            int size = featSet.size();
1998            if (size > 0) {
1999                FeatureInfo[] features = new FeatureInfo[size+1];
2000                featSet.toArray(features);
2001                FeatureInfo fi = new FeatureInfo();
2002                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2003                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2004                features[size] = fi;
2005                return features;
2006            }
2007        }
2008        return null;
2009    }
2010
2011    public boolean hasSystemFeature(String name) {
2012        synchronized (mPackages) {
2013            return mAvailableFeatures.containsKey(name);
2014        }
2015    }
2016
2017    private void checkValidCaller(int uid, int userId) {
2018        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2019            return;
2020
2021        throw new SecurityException("Caller uid=" + uid
2022                + " is not privileged to communicate with user=" + userId);
2023    }
2024
2025    public int checkPermission(String permName, String pkgName) {
2026        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
2027        synchronized (mPackages) {
2028            PackageParser.Package p = mPackages.get(pkgName);
2029            if (p != null && p.mExtras != null) {
2030                PackageSetting ps = (PackageSetting)p.mExtras;
2031                if (ps.sharedUser != null) {
2032                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2033                        return PackageManager.PERMISSION_GRANTED;
2034                    }
2035                } else if (ps.grantedPermissions.contains(permName)) {
2036                    return PackageManager.PERMISSION_GRANTED;
2037                }
2038            }
2039            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
2040                return PackageManager.PERMISSION_GRANTED;
2041            }
2042        }
2043        return PackageManager.PERMISSION_DENIED;
2044    }
2045
2046    public int checkUidPermission(String permName, int uid) {
2047        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
2048        synchronized (mPackages) {
2049            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2050            if (obj != null) {
2051                GrantedPermissions gp = (GrantedPermissions)obj;
2052                if (gp.grantedPermissions.contains(permName)) {
2053                    return PackageManager.PERMISSION_GRANTED;
2054                }
2055            } else {
2056                HashSet<String> perms = mSystemPermissions.get(uid);
2057                if (perms != null && perms.contains(permName)) {
2058                    return PackageManager.PERMISSION_GRANTED;
2059                }
2060            }
2061            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
2062                return PackageManager.PERMISSION_GRANTED;
2063            }
2064        }
2065        return PackageManager.PERMISSION_DENIED;
2066    }
2067
2068    /**
2069     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2070     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2071     * @param message the message to log on security exception
2072     * @return
2073     */
2074    private void enforceCrossUserPermission(int callingUid, int userId,
2075            boolean requireFullPermission, String message) {
2076        if (userId < 0) {
2077            throw new IllegalArgumentException("Invalid userId " + userId);
2078        }
2079        if (userId == UserHandle.getUserId(callingUid)) return;
2080        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2081            if (requireFullPermission) {
2082                mContext.enforceCallingOrSelfPermission(
2083                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2084            } else {
2085                try {
2086                    mContext.enforceCallingOrSelfPermission(
2087                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2088                } catch (SecurityException se) {
2089                    mContext.enforceCallingOrSelfPermission(
2090                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2091                }
2092            }
2093        }
2094    }
2095
2096    private BasePermission findPermissionTreeLP(String permName) {
2097        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2098            if (permName.startsWith(bp.name) &&
2099                    permName.length() > bp.name.length() &&
2100                    permName.charAt(bp.name.length()) == '.') {
2101                return bp;
2102            }
2103        }
2104        return null;
2105    }
2106
2107    private BasePermission checkPermissionTreeLP(String permName) {
2108        if (permName != null) {
2109            BasePermission bp = findPermissionTreeLP(permName);
2110            if (bp != null) {
2111                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2112                    return bp;
2113                }
2114                throw new SecurityException("Calling uid "
2115                        + Binder.getCallingUid()
2116                        + " is not allowed to add to permission tree "
2117                        + bp.name + " owned by uid " + bp.uid);
2118            }
2119        }
2120        throw new SecurityException("No permission tree found for " + permName);
2121    }
2122
2123    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2124        if (s1 == null) {
2125            return s2 == null;
2126        }
2127        if (s2 == null) {
2128            return false;
2129        }
2130        if (s1.getClass() != s2.getClass()) {
2131            return false;
2132        }
2133        return s1.equals(s2);
2134    }
2135
2136    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2137        if (pi1.icon != pi2.icon) return false;
2138        if (pi1.logo != pi2.logo) return false;
2139        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2140        if (!compareStrings(pi1.name, pi2.name)) return false;
2141        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2142        // We'll take care of setting this one.
2143        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2144        // These are not currently stored in settings.
2145        //if (!compareStrings(pi1.group, pi2.group)) return false;
2146        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2147        //if (pi1.labelRes != pi2.labelRes) return false;
2148        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2149        return true;
2150    }
2151
2152    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2153        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2154            throw new SecurityException("Label must be specified in permission");
2155        }
2156        BasePermission tree = checkPermissionTreeLP(info.name);
2157        BasePermission bp = mSettings.mPermissions.get(info.name);
2158        boolean added = bp == null;
2159        boolean changed = true;
2160        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2161        if (added) {
2162            bp = new BasePermission(info.name, tree.sourcePackage,
2163                    BasePermission.TYPE_DYNAMIC);
2164        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2165            throw new SecurityException(
2166                    "Not allowed to modify non-dynamic permission "
2167                    + info.name);
2168        } else {
2169            if (bp.protectionLevel == fixedLevel
2170                    && bp.perm.owner.equals(tree.perm.owner)
2171                    && bp.uid == tree.uid
2172                    && comparePermissionInfos(bp.perm.info, info)) {
2173                changed = false;
2174            }
2175        }
2176        bp.protectionLevel = fixedLevel;
2177        info = new PermissionInfo(info);
2178        info.protectionLevel = fixedLevel;
2179        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2180        bp.perm.info.packageName = tree.perm.info.packageName;
2181        bp.uid = tree.uid;
2182        if (added) {
2183            mSettings.mPermissions.put(info.name, bp);
2184        }
2185        if (changed) {
2186            if (!async) {
2187                mSettings.writeLPr();
2188            } else {
2189                scheduleWriteSettingsLocked();
2190            }
2191        }
2192        return added;
2193    }
2194
2195    public boolean addPermission(PermissionInfo info) {
2196        synchronized (mPackages) {
2197            return addPermissionLocked(info, false);
2198        }
2199    }
2200
2201    public boolean addPermissionAsync(PermissionInfo info) {
2202        synchronized (mPackages) {
2203            return addPermissionLocked(info, true);
2204        }
2205    }
2206
2207    public void removePermission(String name) {
2208        synchronized (mPackages) {
2209            checkPermissionTreeLP(name);
2210            BasePermission bp = mSettings.mPermissions.get(name);
2211            if (bp != null) {
2212                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2213                    throw new SecurityException(
2214                            "Not allowed to modify non-dynamic permission "
2215                            + name);
2216                }
2217                mSettings.mPermissions.remove(name);
2218                mSettings.writeLPr();
2219            }
2220        }
2221    }
2222
2223    public void grantPermission(String packageName, String permissionName) {
2224        mContext.enforceCallingOrSelfPermission(
2225                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2226        synchronized (mPackages) {
2227            final PackageParser.Package pkg = mPackages.get(packageName);
2228            if (pkg == null) {
2229                throw new IllegalArgumentException("Unknown package: " + packageName);
2230            }
2231            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2232            if (bp == null) {
2233                throw new IllegalArgumentException("Unknown permission: " + packageName);
2234            }
2235            if (!pkg.requestedPermissions.contains(permissionName)) {
2236                throw new SecurityException("Package " + packageName
2237                        + " has not requested permission " + permissionName);
2238            }
2239            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2240                throw new SecurityException("Permission " + permissionName
2241                        + " is not a development permission");
2242            }
2243            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2244            if (ps == null) {
2245                return;
2246            }
2247            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2248            if (gp.grantedPermissions.add(permissionName)) {
2249                if (ps.haveGids) {
2250                    gp.gids = appendInts(gp.gids, bp.gids);
2251                }
2252                mSettings.writeLPr();
2253            }
2254        }
2255    }
2256
2257    public void revokePermission(String packageName, String permissionName) {
2258        synchronized (mPackages) {
2259            final PackageParser.Package pkg = mPackages.get(packageName);
2260            if (pkg == null) {
2261                throw new IllegalArgumentException("Unknown package: " + packageName);
2262            }
2263            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2264                mContext.enforceCallingOrSelfPermission(
2265                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2266            }
2267            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2268            if (bp == null) {
2269                throw new IllegalArgumentException("Unknown permission: " + packageName);
2270            }
2271            if (!pkg.requestedPermissions.contains(permissionName)) {
2272                throw new SecurityException("Package " + packageName
2273                        + " has not requested permission " + permissionName);
2274            }
2275            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2276                throw new SecurityException("Permission " + permissionName
2277                        + " is not a development permission");
2278            }
2279            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2280            if (ps == null) {
2281                return;
2282            }
2283            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2284            if (gp.grantedPermissions.remove(permissionName)) {
2285                gp.grantedPermissions.remove(permissionName);
2286                if (ps.haveGids) {
2287                    gp.gids = removeInts(gp.gids, bp.gids);
2288                }
2289                mSettings.writeLPr();
2290            }
2291        }
2292    }
2293
2294    public boolean isProtectedBroadcast(String actionName) {
2295        synchronized (mPackages) {
2296            return mProtectedBroadcasts.contains(actionName);
2297        }
2298    }
2299
2300    public int checkSignatures(String pkg1, String pkg2) {
2301        synchronized (mPackages) {
2302            final PackageParser.Package p1 = mPackages.get(pkg1);
2303            final PackageParser.Package p2 = mPackages.get(pkg2);
2304            if (p1 == null || p1.mExtras == null
2305                    || p2 == null || p2.mExtras == null) {
2306                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2307            }
2308            return compareSignatures(p1.mSignatures, p2.mSignatures);
2309        }
2310    }
2311
2312    public int checkUidSignatures(int uid1, int uid2) {
2313        // Map to base uids.
2314        uid1 = UserHandle.getAppId(uid1);
2315        uid2 = UserHandle.getAppId(uid2);
2316        // reader
2317        synchronized (mPackages) {
2318            Signature[] s1;
2319            Signature[] s2;
2320            Object obj = mSettings.getUserIdLPr(uid1);
2321            if (obj != null) {
2322                if (obj instanceof SharedUserSetting) {
2323                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2324                } else if (obj instanceof PackageSetting) {
2325                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2326                } else {
2327                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2328                }
2329            } else {
2330                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2331            }
2332            obj = mSettings.getUserIdLPr(uid2);
2333            if (obj != null) {
2334                if (obj instanceof SharedUserSetting) {
2335                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2336                } else if (obj instanceof PackageSetting) {
2337                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2338                } else {
2339                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2340                }
2341            } else {
2342                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2343            }
2344            return compareSignatures(s1, s2);
2345        }
2346    }
2347
2348    static int compareSignatures(Signature[] s1, Signature[] s2) {
2349        if (s1 == null) {
2350            return s2 == null
2351                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2352                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2353        }
2354        if (s2 == null) {
2355            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2356        }
2357        HashSet<Signature> set1 = new HashSet<Signature>();
2358        for (Signature sig : s1) {
2359            set1.add(sig);
2360        }
2361        HashSet<Signature> set2 = new HashSet<Signature>();
2362        for (Signature sig : s2) {
2363            set2.add(sig);
2364        }
2365        // Make sure s2 contains all signatures in s1.
2366        if (set1.equals(set2)) {
2367            return PackageManager.SIGNATURE_MATCH;
2368        }
2369        return PackageManager.SIGNATURE_NO_MATCH;
2370    }
2371
2372    public String[] getPackagesForUid(int uid) {
2373        uid = UserHandle.getAppId(uid);
2374        // reader
2375        synchronized (mPackages) {
2376            Object obj = mSettings.getUserIdLPr(uid);
2377            if (obj instanceof SharedUserSetting) {
2378                final SharedUserSetting sus = (SharedUserSetting) obj;
2379                final int N = sus.packages.size();
2380                final String[] res = new String[N];
2381                final Iterator<PackageSetting> it = sus.packages.iterator();
2382                int i = 0;
2383                while (it.hasNext()) {
2384                    res[i++] = it.next().name;
2385                }
2386                return res;
2387            } else if (obj instanceof PackageSetting) {
2388                final PackageSetting ps = (PackageSetting) obj;
2389                return new String[] { ps.name };
2390            }
2391        }
2392        return null;
2393    }
2394
2395    public String getNameForUid(int uid) {
2396        // reader
2397        synchronized (mPackages) {
2398            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2399            if (obj instanceof SharedUserSetting) {
2400                final SharedUserSetting sus = (SharedUserSetting) obj;
2401                return sus.name + ":" + sus.userId;
2402            } else if (obj instanceof PackageSetting) {
2403                final PackageSetting ps = (PackageSetting) obj;
2404                return ps.name;
2405            }
2406        }
2407        return null;
2408    }
2409
2410    public int getUidForSharedUser(String sharedUserName) {
2411        if(sharedUserName == null) {
2412            return -1;
2413        }
2414        // reader
2415        synchronized (mPackages) {
2416            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2417            if (suid == null) {
2418                return -1;
2419            }
2420            return suid.userId;
2421        }
2422    }
2423
2424    @Override
2425    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2426            int flags, int userId) {
2427        if (!sUserManager.exists(userId)) return null;
2428        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2429        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2430        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2431    }
2432
2433    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2434            int flags, List<ResolveInfo> query, int userId) {
2435        if (query != null) {
2436            final int N = query.size();
2437            if (N == 1) {
2438                return query.get(0);
2439            } else if (N > 1) {
2440                // If there is more than one activity with the same priority,
2441                // then let the user decide between them.
2442                ResolveInfo r0 = query.get(0);
2443                ResolveInfo r1 = query.get(1);
2444                if (DEBUG_INTENT_MATCHING) {
2445                    Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2446                            + r1.activityInfo.name + "=" + r1.priority);
2447                }
2448                // If the first activity has a higher priority, or a different
2449                // default, then it is always desireable to pick it.
2450                if (r0.priority != r1.priority
2451                        || r0.preferredOrder != r1.preferredOrder
2452                        || r0.isDefault != r1.isDefault) {
2453                    return query.get(0);
2454                }
2455                // If we have saved a preference for a preferred activity for
2456                // this Intent, use that.
2457                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2458                        flags, query, r0.priority, userId);
2459                if (ri != null) {
2460                    return ri;
2461                }
2462                if (userId != 0) {
2463                    ri = new ResolveInfo(mResolveInfo);
2464                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2465                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2466                            ri.activityInfo.applicationInfo);
2467                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2468                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2469                    return ri;
2470                }
2471                return mResolveInfo;
2472            }
2473        }
2474        return null;
2475    }
2476
2477    ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
2478            int flags, List<ResolveInfo> query, int priority, int userId) {
2479        if (!sUserManager.exists(userId)) return null;
2480        // writer
2481        synchronized (mPackages) {
2482            if (intent.getSelector() != null) {
2483                intent = intent.getSelector();
2484            }
2485            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2486            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
2487            List<PreferredActivity> prefs = pir != null
2488                    ? pir.queryIntent(intent, resolvedType,
2489                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2490                    : null;
2491            if (prefs != null && prefs.size() > 0) {
2492                // First figure out how good the original match set is.
2493                // We will only allow preferred activities that came
2494                // from the same match quality.
2495                int match = 0;
2496
2497                if (DEBUG_PREFERRED) {
2498                    Log.v(TAG, "Figuring out best match...");
2499                }
2500
2501                final int N = query.size();
2502                for (int j=0; j<N; j++) {
2503                    final ResolveInfo ri = query.get(j);
2504                    if (DEBUG_PREFERRED) {
2505                        Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2506                                + Integer.toHexString(match));
2507                    }
2508                    if (ri.match > match) {
2509                        match = ri.match;
2510                    }
2511                }
2512
2513                if (DEBUG_PREFERRED) {
2514                    Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2515                }
2516
2517                match &= IntentFilter.MATCH_CATEGORY_MASK;
2518                final int M = prefs.size();
2519                for (int i=0; i<M; i++) {
2520                    final PreferredActivity pa = prefs.get(i);
2521                    if (pa.mPref.mMatch != match) {
2522                        continue;
2523                    }
2524                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId);
2525                    if (DEBUG_PREFERRED) {
2526                        Log.v(TAG, "Got preferred activity:");
2527                        if (ai != null) {
2528                            ai.dump(new LogPrinter(Log.VERBOSE, TAG), "  ");
2529                        } else {
2530                            Log.v(TAG, "  null");
2531                        }
2532                    }
2533                    if (ai == null) {
2534                        // This previously registered preferred activity
2535                        // component is no longer known.  Most likely an update
2536                        // to the app was installed and in the new version this
2537                        // component no longer exists.  Clean it up by removing
2538                        // it from the preferred activities list, and skip it.
2539                        Slog.w(TAG, "Removing dangling preferred activity: "
2540                                + pa.mPref.mComponent);
2541                        pir.removeFilter(pa);
2542                        continue;
2543                    }
2544                    for (int j=0; j<N; j++) {
2545                        final ResolveInfo ri = query.get(j);
2546                        if (!ri.activityInfo.applicationInfo.packageName
2547                                .equals(ai.applicationInfo.packageName)) {
2548                            continue;
2549                        }
2550                        if (!ri.activityInfo.name.equals(ai.name)) {
2551                            continue;
2552                        }
2553
2554                        // Okay we found a previously set preferred app.
2555                        // If the result set is different from when this
2556                        // was created, we need to clear it and re-ask the
2557                        // user their preference.
2558                        if (!pa.mPref.sameSet(query, priority)) {
2559                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
2560                                    + intent + " type " + resolvedType);
2561                            pir.removeFilter(pa);
2562                            return null;
2563                        }
2564
2565                        // Yay!
2566                        return ri;
2567                    }
2568                }
2569            }
2570        }
2571        return null;
2572    }
2573
2574    @Override
2575    public List<ResolveInfo> queryIntentActivities(Intent intent,
2576            String resolvedType, int flags, int userId) {
2577        if (!sUserManager.exists(userId)) return null;
2578        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
2579        ComponentName comp = intent.getComponent();
2580        if (comp == null) {
2581            if (intent.getSelector() != null) {
2582                intent = intent.getSelector();
2583                comp = intent.getComponent();
2584            }
2585        }
2586
2587        if (comp != null) {
2588            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2589            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
2590            if (ai != null) {
2591                final ResolveInfo ri = new ResolveInfo();
2592                ri.activityInfo = ai;
2593                list.add(ri);
2594            }
2595            return list;
2596        }
2597
2598        // reader
2599        synchronized (mPackages) {
2600            final String pkgName = intent.getPackage();
2601            if (pkgName == null) {
2602                return mActivities.queryIntent(intent, resolvedType, flags, userId);
2603            }
2604            final PackageParser.Package pkg = mPackages.get(pkgName);
2605            if (pkg != null) {
2606                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
2607                        pkg.activities, userId);
2608            }
2609            return new ArrayList<ResolveInfo>();
2610        }
2611    }
2612
2613    @Override
2614    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2615            Intent[] specifics, String[] specificTypes, Intent intent,
2616            String resolvedType, int flags, int userId) {
2617        if (!sUserManager.exists(userId)) return null;
2618        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2619                "query intent activity options");
2620        final String resultsAction = intent.getAction();
2621
2622        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
2623                | PackageManager.GET_RESOLVED_FILTER, userId);
2624
2625        if (DEBUG_INTENT_MATCHING) {
2626            Log.v(TAG, "Query " + intent + ": " + results);
2627        }
2628
2629        int specificsPos = 0;
2630        int N;
2631
2632        // todo: note that the algorithm used here is O(N^2).  This
2633        // isn't a problem in our current environment, but if we start running
2634        // into situations where we have more than 5 or 10 matches then this
2635        // should probably be changed to something smarter...
2636
2637        // First we go through and resolve each of the specific items
2638        // that were supplied, taking care of removing any corresponding
2639        // duplicate items in the generic resolve list.
2640        if (specifics != null) {
2641            for (int i=0; i<specifics.length; i++) {
2642                final Intent sintent = specifics[i];
2643                if (sintent == null) {
2644                    continue;
2645                }
2646
2647                if (DEBUG_INTENT_MATCHING) {
2648                    Log.v(TAG, "Specific #" + i + ": " + sintent);
2649                }
2650
2651                String action = sintent.getAction();
2652                if (resultsAction != null && resultsAction.equals(action)) {
2653                    // If this action was explicitly requested, then don't
2654                    // remove things that have it.
2655                    action = null;
2656                }
2657
2658                ResolveInfo ri = null;
2659                ActivityInfo ai = null;
2660
2661                ComponentName comp = sintent.getComponent();
2662                if (comp == null) {
2663                    ri = resolveIntent(
2664                        sintent,
2665                        specificTypes != null ? specificTypes[i] : null,
2666                            flags, userId);
2667                    if (ri == null) {
2668                        continue;
2669                    }
2670                    if (ri == mResolveInfo) {
2671                        // ACK!  Must do something better with this.
2672                    }
2673                    ai = ri.activityInfo;
2674                    comp = new ComponentName(ai.applicationInfo.packageName,
2675                            ai.name);
2676                } else {
2677                    ai = getActivityInfo(comp, flags, userId);
2678                    if (ai == null) {
2679                        continue;
2680                    }
2681                }
2682
2683                // Look for any generic query activities that are duplicates
2684                // of this specific one, and remove them from the results.
2685                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
2686                N = results.size();
2687                int j;
2688                for (j=specificsPos; j<N; j++) {
2689                    ResolveInfo sri = results.get(j);
2690                    if ((sri.activityInfo.name.equals(comp.getClassName())
2691                            && sri.activityInfo.applicationInfo.packageName.equals(
2692                                    comp.getPackageName()))
2693                        || (action != null && sri.filter.matchAction(action))) {
2694                        results.remove(j);
2695                        if (DEBUG_INTENT_MATCHING) Log.v(
2696                            TAG, "Removing duplicate item from " + j
2697                            + " due to specific " + specificsPos);
2698                        if (ri == null) {
2699                            ri = sri;
2700                        }
2701                        j--;
2702                        N--;
2703                    }
2704                }
2705
2706                // Add this specific item to its proper place.
2707                if (ri == null) {
2708                    ri = new ResolveInfo();
2709                    ri.activityInfo = ai;
2710                }
2711                results.add(specificsPos, ri);
2712                ri.specificIndex = i;
2713                specificsPos++;
2714            }
2715        }
2716
2717        // Now we go through the remaining generic results and remove any
2718        // duplicate actions that are found here.
2719        N = results.size();
2720        for (int i=specificsPos; i<N-1; i++) {
2721            final ResolveInfo rii = results.get(i);
2722            if (rii.filter == null) {
2723                continue;
2724            }
2725
2726            // Iterate over all of the actions of this result's intent
2727            // filter...  typically this should be just one.
2728            final Iterator<String> it = rii.filter.actionsIterator();
2729            if (it == null) {
2730                continue;
2731            }
2732            while (it.hasNext()) {
2733                final String action = it.next();
2734                if (resultsAction != null && resultsAction.equals(action)) {
2735                    // If this action was explicitly requested, then don't
2736                    // remove things that have it.
2737                    continue;
2738                }
2739                for (int j=i+1; j<N; j++) {
2740                    final ResolveInfo rij = results.get(j);
2741                    if (rij.filter != null && rij.filter.hasAction(action)) {
2742                        results.remove(j);
2743                        if (DEBUG_INTENT_MATCHING) Log.v(
2744                            TAG, "Removing duplicate item from " + j
2745                            + " due to action " + action + " at " + i);
2746                        j--;
2747                        N--;
2748                    }
2749                }
2750            }
2751
2752            // If the caller didn't request filter information, drop it now
2753            // so we don't have to marshall/unmarshall it.
2754            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2755                rii.filter = null;
2756            }
2757        }
2758
2759        // Filter out the caller activity if so requested.
2760        if (caller != null) {
2761            N = results.size();
2762            for (int i=0; i<N; i++) {
2763                ActivityInfo ainfo = results.get(i).activityInfo;
2764                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2765                        && caller.getClassName().equals(ainfo.name)) {
2766                    results.remove(i);
2767                    break;
2768                }
2769            }
2770        }
2771
2772        // If the caller didn't request filter information,
2773        // drop them now so we don't have to
2774        // marshall/unmarshall it.
2775        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2776            N = results.size();
2777            for (int i=0; i<N; i++) {
2778                results.get(i).filter = null;
2779            }
2780        }
2781
2782        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
2783        return results;
2784    }
2785
2786    @Override
2787    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2788            int userId) {
2789        if (!sUserManager.exists(userId)) return null;
2790        ComponentName comp = intent.getComponent();
2791        if (comp == null) {
2792            if (intent.getSelector() != null) {
2793                intent = intent.getSelector();
2794                comp = intent.getComponent();
2795            }
2796        }
2797        if (comp != null) {
2798            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2799            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
2800            if (ai != null) {
2801                ResolveInfo ri = new ResolveInfo();
2802                ri.activityInfo = ai;
2803                list.add(ri);
2804            }
2805            return list;
2806        }
2807
2808        // reader
2809        synchronized (mPackages) {
2810            String pkgName = intent.getPackage();
2811            if (pkgName == null) {
2812                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
2813            }
2814            final PackageParser.Package pkg = mPackages.get(pkgName);
2815            if (pkg != null) {
2816                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2817                        userId);
2818            }
2819            return null;
2820        }
2821    }
2822
2823    @Override
2824    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2825        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
2826        if (!sUserManager.exists(userId)) return null;
2827        if (query != null) {
2828            if (query.size() >= 1) {
2829                // If there is more than one service with the same priority,
2830                // just arbitrarily pick the first one.
2831                return query.get(0);
2832            }
2833        }
2834        return null;
2835    }
2836
2837    @Override
2838    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2839            int userId) {
2840        if (!sUserManager.exists(userId)) return null;
2841        ComponentName comp = intent.getComponent();
2842        if (comp == null) {
2843            if (intent.getSelector() != null) {
2844                intent = intent.getSelector();
2845                comp = intent.getComponent();
2846            }
2847        }
2848        if (comp != null) {
2849            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2850            final ServiceInfo si = getServiceInfo(comp, flags, userId);
2851            if (si != null) {
2852                final ResolveInfo ri = new ResolveInfo();
2853                ri.serviceInfo = si;
2854                list.add(ri);
2855            }
2856            return list;
2857        }
2858
2859        // reader
2860        synchronized (mPackages) {
2861            String pkgName = intent.getPackage();
2862            if (pkgName == null) {
2863                return mServices.queryIntent(intent, resolvedType, flags, userId);
2864            }
2865            final PackageParser.Package pkg = mPackages.get(pkgName);
2866            if (pkg != null) {
2867                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
2868                        userId);
2869            }
2870            return null;
2871        }
2872    }
2873
2874    private static final int getContinuationPoint(final String[] keys, final String key) {
2875        final int index;
2876        if (key == null) {
2877            index = 0;
2878        } else {
2879            final int insertPoint = Arrays.binarySearch(keys, key);
2880            if (insertPoint < 0) {
2881                index = -insertPoint;
2882            } else {
2883                index = insertPoint + 1;
2884            }
2885        }
2886        return index;
2887    }
2888
2889    @Override
2890    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead,
2891            int userId) {
2892        final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2893        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2894        final String[] keys;
2895
2896        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
2897
2898        // writer
2899        synchronized (mPackages) {
2900            if (listUninstalled) {
2901                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2902            } else {
2903                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2904            }
2905
2906            Arrays.sort(keys);
2907            int i = getContinuationPoint(keys, lastRead);
2908            final int N = keys.length;
2909
2910            while (i < N) {
2911                final String packageName = keys[i++];
2912
2913                PackageInfo pi = null;
2914                if (listUninstalled) {
2915                    final PackageSetting ps = mSettings.mPackages.get(packageName);
2916                    if (ps != null) {
2917                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
2918                    }
2919                } else {
2920                    final PackageParser.Package p = mPackages.get(packageName);
2921                    if (p != null) {
2922                        pi = generatePackageInfo(p, flags, userId);
2923                    }
2924                }
2925
2926                if (pi != null && list.append(pi)) {
2927                    break;
2928                }
2929            }
2930
2931            if (i == N) {
2932                list.setLastSlice(true);
2933            }
2934        }
2935
2936        return list;
2937    }
2938
2939    @Override
2940    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
2941            String lastRead, int userId) {
2942        if (!sUserManager.exists(userId)) return null;
2943        final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2944        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2945        final String[] keys;
2946
2947        // writer
2948        synchronized (mPackages) {
2949            if (listUninstalled) {
2950                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2951            } else {
2952                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2953            }
2954
2955            Arrays.sort(keys);
2956            int i = getContinuationPoint(keys, lastRead);
2957            final int N = keys.length;
2958
2959            while (i < N) {
2960                final String packageName = keys[i++];
2961
2962                ApplicationInfo ai = null;
2963                final PackageSetting ps = mSettings.mPackages.get(packageName);
2964                if (listUninstalled) {
2965                    if (ps != null) {
2966                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
2967                    }
2968                } else {
2969                    final PackageParser.Package p = mPackages.get(packageName);
2970                    if (p != null && ps != null) {
2971                        ai = PackageParser.generateApplicationInfo(p, flags,
2972                                ps.readUserState(userId), userId);
2973                    }
2974                }
2975
2976                if (ai != null && list.append(ai)) {
2977                    break;
2978                }
2979            }
2980
2981            if (i == N) {
2982                list.setLastSlice(true);
2983            }
2984        }
2985
2986        return list;
2987    }
2988
2989    public List<ApplicationInfo> getPersistentApplications(int flags) {
2990        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2991
2992        // reader
2993        synchronized (mPackages) {
2994            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
2995            final int userId = UserHandle.getCallingUserId();
2996            while (i.hasNext()) {
2997                final PackageParser.Package p = i.next();
2998                if (p.applicationInfo != null
2999                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3000                        && (!mSafeMode || isSystemApp(p))) {
3001                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3002                    if (ps != null) {
3003                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3004                                ps.readUserState(userId), userId);
3005                        if (ai != null) {
3006                            finalList.add(ai);
3007                        }
3008                    }
3009                }
3010            }
3011        }
3012
3013        return finalList;
3014    }
3015
3016    @Override
3017    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3018        if (!sUserManager.exists(userId)) return null;
3019        // reader
3020        synchronized (mPackages) {
3021            final PackageParser.Provider provider = mProviders.get(name);
3022            PackageSetting ps = provider != null
3023                    ? mSettings.mPackages.get(provider.owner.packageName)
3024                    : null;
3025            return ps != null
3026                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3027                    && (!mSafeMode || (provider.info.applicationInfo.flags
3028                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3029                    ? PackageParser.generateProviderInfo(provider, flags,
3030                            ps.readUserState(userId), userId)
3031                    : null;
3032        }
3033    }
3034
3035    /**
3036     * @deprecated
3037     */
3038    @Deprecated
3039    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3040        // reader
3041        synchronized (mPackages) {
3042            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3043                    .iterator();
3044            final int userId = UserHandle.getCallingUserId();
3045            while (i.hasNext()) {
3046                Map.Entry<String, PackageParser.Provider> entry = i.next();
3047                PackageParser.Provider p = entry.getValue();
3048                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3049
3050                if (ps != null && p.syncable
3051                        && (!mSafeMode || (p.info.applicationInfo.flags
3052                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3053                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3054                            ps.readUserState(userId), userId);
3055                    if (info != null) {
3056                        outNames.add(entry.getKey());
3057                        outInfo.add(info);
3058                    }
3059                }
3060            }
3061        }
3062    }
3063
3064    public List<ProviderInfo> queryContentProviders(String processName,
3065            int uid, int flags) {
3066        ArrayList<ProviderInfo> finalList = null;
3067
3068        // reader
3069        synchronized (mPackages) {
3070            final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
3071            final int userId = processName != null ?
3072                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3073            while (i.hasNext()) {
3074                final PackageParser.Provider p = i.next();
3075                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3076                if (ps != null && p.info.authority != null
3077                        && (processName == null
3078                                || (p.info.processName.equals(processName)
3079                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3080                        && mSettings.isEnabledLPr(p.info, flags, userId)
3081                        && (!mSafeMode
3082                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3083                    if (finalList == null) {
3084                        finalList = new ArrayList<ProviderInfo>(3);
3085                    }
3086                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3087                            ps.readUserState(userId), userId);
3088                    if (info != null) {
3089                        finalList.add(info);
3090                    }
3091                }
3092            }
3093        }
3094
3095        if (finalList != null) {
3096            Collections.sort(finalList, mProviderInitOrderSorter);
3097        }
3098
3099        return finalList;
3100    }
3101
3102    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3103            int flags) {
3104        // reader
3105        synchronized (mPackages) {
3106            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3107            return PackageParser.generateInstrumentationInfo(i, flags);
3108        }
3109    }
3110
3111    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3112            int flags) {
3113        ArrayList<InstrumentationInfo> finalList =
3114            new ArrayList<InstrumentationInfo>();
3115
3116        // reader
3117        synchronized (mPackages) {
3118            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3119            while (i.hasNext()) {
3120                final PackageParser.Instrumentation p = i.next();
3121                if (targetPackage == null
3122                        || targetPackage.equals(p.info.targetPackage)) {
3123                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3124                            flags);
3125                    if (ii != null) {
3126                        finalList.add(ii);
3127                    }
3128                }
3129            }
3130        }
3131
3132        return finalList;
3133    }
3134
3135    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3136        String[] files = dir.list();
3137        if (files == null) {
3138            Log.d(TAG, "No files in app dir " + dir);
3139            return;
3140        }
3141
3142        if (DEBUG_PACKAGE_SCANNING) {
3143            Log.d(TAG, "Scanning app dir " + dir);
3144        }
3145
3146        int i;
3147        for (i=0; i<files.length; i++) {
3148            File file = new File(dir, files[i]);
3149            if (!isPackageFilename(files[i])) {
3150                // Ignore entries which are not apk's
3151                continue;
3152            }
3153            PackageParser.Package pkg = scanPackageLI(file,
3154                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3155            // Don't mess around with apps in system partition.
3156            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3157                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3158                // Delete the apk
3159                Slog.w(TAG, "Cleaning up failed install of " + file);
3160                file.delete();
3161            }
3162        }
3163    }
3164
3165    private static File getSettingsProblemFile() {
3166        File dataDir = Environment.getDataDirectory();
3167        File systemDir = new File(dataDir, "system");
3168        File fname = new File(systemDir, "uiderrors.txt");
3169        return fname;
3170    }
3171
3172    static void reportSettingsProblem(int priority, String msg) {
3173        try {
3174            File fname = getSettingsProblemFile();
3175            FileOutputStream out = new FileOutputStream(fname, true);
3176            PrintWriter pw = new PrintWriter(out);
3177            SimpleDateFormat formatter = new SimpleDateFormat();
3178            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3179            pw.println(dateString + ": " + msg);
3180            pw.close();
3181            FileUtils.setPermissions(
3182                    fname.toString(),
3183                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3184                    -1, -1);
3185        } catch (java.io.IOException e) {
3186        }
3187        Slog.println(priority, TAG, msg);
3188    }
3189
3190    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3191            PackageParser.Package pkg, File srcFile, int parseFlags) {
3192        if (GET_CERTIFICATES) {
3193            if (ps != null
3194                    && ps.codePath.equals(srcFile)
3195                    && ps.timeStamp == srcFile.lastModified()) {
3196                if (ps.signatures.mSignatures != null
3197                        && ps.signatures.mSignatures.length != 0) {
3198                    // Optimization: reuse the existing cached certificates
3199                    // if the package appears to be unchanged.
3200                    pkg.mSignatures = ps.signatures.mSignatures;
3201                    return true;
3202                }
3203
3204                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3205            } else {
3206                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3207            }
3208
3209            if (!pp.collectCertificates(pkg, parseFlags)) {
3210                mLastScanError = pp.getParseError();
3211                return false;
3212            }
3213        }
3214        return true;
3215    }
3216
3217    /*
3218     *  Scan a package and return the newly parsed package.
3219     *  Returns null in case of errors and the error code is stored in mLastScanError
3220     */
3221    private PackageParser.Package scanPackageLI(File scanFile,
3222            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3223        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3224        String scanPath = scanFile.getPath();
3225        parseFlags |= mDefParseFlags;
3226        PackageParser pp = new PackageParser(scanPath);
3227        pp.setSeparateProcesses(mSeparateProcesses);
3228        pp.setOnlyCoreApps(mOnlyCore);
3229        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3230                scanPath, mMetrics, parseFlags);
3231        if (pkg == null) {
3232            mLastScanError = pp.getParseError();
3233            return null;
3234        }
3235        PackageSetting ps = null;
3236        PackageSetting updatedPkg;
3237        // reader
3238        synchronized (mPackages) {
3239            // Look to see if we already know about this package.
3240            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3241            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3242                // This package has been renamed to its original name.  Let's
3243                // use that.
3244                ps = mSettings.peekPackageLPr(oldName);
3245            }
3246            // If there was no original package, see one for the real package name.
3247            if (ps == null) {
3248                ps = mSettings.peekPackageLPr(pkg.packageName);
3249            }
3250            // Check to see if this package could be hiding/updating a system
3251            // package.  Must look for it either under the original or real
3252            // package name depending on our state.
3253            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3254        }
3255        // First check if this is a system package that may involve an update
3256        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3257            if (ps != null && !ps.codePath.equals(scanFile)) {
3258                // The path has changed from what was last scanned...  check the
3259                // version of the new path against what we have stored to determine
3260                // what to do.
3261                if (pkg.mVersionCode < ps.versionCode) {
3262                    // The system package has been updated and the code path does not match
3263                    // Ignore entry. Skip it.
3264                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3265                            + " ignored: updated version " + ps.versionCode
3266                            + " better than this " + pkg.mVersionCode);
3267                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3268                    return null;
3269                } else {
3270                    // The current app on the system partion is better than
3271                    // what we have updated to on the data partition; switch
3272                    // back to the system partition version.
3273                    // At this point, its safely assumed that package installation for
3274                    // apps in system partition will go through. If not there won't be a working
3275                    // version of the app
3276                    // writer
3277                    synchronized (mPackages) {
3278                        // Just remove the loaded entries from package lists.
3279                        mPackages.remove(ps.name);
3280                    }
3281                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3282                            + "reverting from " + ps.codePathString
3283                            + ": new version " + pkg.mVersionCode
3284                            + " better than installed " + ps.versionCode);
3285
3286                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3287                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3288                    synchronized (mInstallLock) {
3289                        args.cleanUpResourcesLI();
3290                    }
3291                    synchronized (mPackages) {
3292                        mSettings.enableSystemPackageLPw(ps.name);
3293                    }
3294                }
3295            }
3296        }
3297
3298        if (updatedPkg != null) {
3299            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3300            // initially
3301            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3302        }
3303        // Verify certificates against what was last scanned
3304        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3305            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3306            return null;
3307        }
3308
3309        /*
3310         * A new system app appeared, but we already had a non-system one of the
3311         * same name installed earlier.
3312         */
3313        boolean shouldHideSystemApp = false;
3314        if (updatedPkg == null && ps != null
3315                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3316            /*
3317             * Check to make sure the signatures match first. If they don't,
3318             * wipe the installed application and its data.
3319             */
3320            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3321                    != PackageManager.SIGNATURE_MATCH) {
3322                deletePackageLI(pkg.packageName, null, true, 0, null, false);
3323                ps = null;
3324            } else {
3325                /*
3326                 * If the newly-added system app is an older version than the
3327                 * already installed version, hide it. It will be scanned later
3328                 * and re-added like an update.
3329                 */
3330                if (pkg.mVersionCode < ps.versionCode) {
3331                    shouldHideSystemApp = true;
3332                } else {
3333                    /*
3334                     * The newly found system app is a newer version that the
3335                     * one previously installed. Simply remove the
3336                     * already-installed application and replace it with our own
3337                     * while keeping the application data.
3338                     */
3339                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3340                            + ps.codePathString + ": new version " + pkg.mVersionCode
3341                            + " better than installed " + ps.versionCode);
3342                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3343                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3344                    synchronized (mInstallLock) {
3345                        args.cleanUpResourcesLI();
3346                    }
3347                }
3348            }
3349        }
3350
3351        // The apk is forward locked (not public) if its code and resources
3352        // are kept in different files.
3353        // TODO grab this value from PackageSettings
3354        if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3355            parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3356        }
3357
3358        String codePath = null;
3359        String resPath = null;
3360        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3361            if (ps != null && ps.resourcePathString != null) {
3362                resPath = ps.resourcePathString;
3363            } else {
3364                // Should not happen at all. Just log an error.
3365                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3366            }
3367        } else {
3368            resPath = pkg.mScanPath;
3369        }
3370        codePath = pkg.mScanPath;
3371        // Set application objects path explicitly.
3372        setApplicationInfoPaths(pkg, codePath, resPath);
3373        // Note that we invoke the following method only if we are about to unpack an application
3374        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3375                | SCAN_UPDATE_SIGNATURE, currentTime, user);
3376
3377        /*
3378         * If the system app should be overridden by a previously installed
3379         * data, hide the system app now and let the /data/app scan pick it up
3380         * again.
3381         */
3382        if (shouldHideSystemApp) {
3383            synchronized (mPackages) {
3384                /*
3385                 * We have to grant systems permissions before we hide, because
3386                 * grantPermissions will assume the package update is trying to
3387                 * expand its permissions.
3388                 */
3389                grantPermissionsLPw(pkg, true);
3390                mSettings.disableSystemPackageLPw(pkg.packageName);
3391            }
3392        }
3393
3394        return scannedPkg;
3395    }
3396
3397    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3398            String destResPath) {
3399        pkg.mPath = pkg.mScanPath = destCodePath;
3400        pkg.applicationInfo.sourceDir = destCodePath;
3401        pkg.applicationInfo.publicSourceDir = destResPath;
3402    }
3403
3404    private static String fixProcessName(String defProcessName,
3405            String processName, int uid) {
3406        if (processName == null) {
3407            return defProcessName;
3408        }
3409        return processName;
3410    }
3411
3412    private boolean verifySignaturesLP(PackageSetting pkgSetting,
3413            PackageParser.Package pkg) {
3414        if (pkgSetting.signatures.mSignatures != null) {
3415            // Already existing package. Make sure signatures match
3416            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
3417                PackageManager.SIGNATURE_MATCH) {
3418                    Slog.e(TAG, "Package " + pkg.packageName
3419                            + " signatures do not match the previously installed version; ignoring!");
3420                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3421                    return false;
3422                }
3423        }
3424        // Check for shared user signatures
3425        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
3426            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3427                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3428                Slog.e(TAG, "Package " + pkg.packageName
3429                        + " has no signatures that match those in shared user "
3430                        + pkgSetting.sharedUser.name + "; ignoring!");
3431                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3432                return false;
3433            }
3434        }
3435        return true;
3436    }
3437
3438    /**
3439     * Enforces that only the system UID or root's UID can call a method exposed
3440     * via Binder.
3441     *
3442     * @param message used as message if SecurityException is thrown
3443     * @throws SecurityException if the caller is not system or root
3444     */
3445    private static final void enforceSystemOrRoot(String message) {
3446        final int uid = Binder.getCallingUid();
3447        if (uid != Process.SYSTEM_UID && uid != 0) {
3448            throw new SecurityException(message);
3449        }
3450    }
3451
3452    public void performBootDexOpt() {
3453        ArrayList<PackageParser.Package> pkgs = null;
3454        synchronized (mPackages) {
3455            if (mDeferredDexOpt.size() > 0) {
3456                pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3457                mDeferredDexOpt.clear();
3458            }
3459        }
3460        if (pkgs != null) {
3461            for (int i=0; i<pkgs.size(); i++) {
3462                if (!isFirstBoot()) {
3463                    try {
3464                        ActivityManagerNative.getDefault().showBootMessage(
3465                                mContext.getResources().getString(
3466                                        com.android.internal.R.string.android_upgrading_apk,
3467                                        i+1, pkgs.size()), true);
3468                    } catch (RemoteException e) {
3469                    }
3470                }
3471                PackageParser.Package p = pkgs.get(i);
3472                synchronized (mInstallLock) {
3473                    if (!p.mDidDexOpt) {
3474                        performDexOptLI(p, false, false);
3475                    }
3476                }
3477            }
3478        }
3479    }
3480
3481    public boolean performDexOpt(String packageName) {
3482        enforceSystemOrRoot("Only the system can request dexopt be performed");
3483
3484        if (!mNoDexOpt) {
3485            return false;
3486        }
3487
3488        PackageParser.Package p;
3489        synchronized (mPackages) {
3490            p = mPackages.get(packageName);
3491            if (p == null || p.mDidDexOpt) {
3492                return false;
3493            }
3494        }
3495        synchronized (mInstallLock) {
3496            return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
3497        }
3498    }
3499
3500    static final int DEX_OPT_SKIPPED = 0;
3501    static final int DEX_OPT_PERFORMED = 1;
3502    static final int DEX_OPT_DEFERRED = 2;
3503    static final int DEX_OPT_FAILED = -1;
3504
3505    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
3506        boolean performed = false;
3507        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3508            String path = pkg.mScanPath;
3509            int ret = 0;
3510            try {
3511                if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
3512                    if (!forceDex && defer) {
3513                        mDeferredDexOpt.add(pkg);
3514                        return DEX_OPT_DEFERRED;
3515                    } else {
3516                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3517                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3518                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
3519                        pkg.mDidDexOpt = true;
3520                        performed = true;
3521                    }
3522                }
3523            } catch (FileNotFoundException e) {
3524                Slog.w(TAG, "Apk not found for dexopt: " + path);
3525                ret = -1;
3526            } catch (IOException e) {
3527                Slog.w(TAG, "IOException reading apk: " + path, e);
3528                ret = -1;
3529            } catch (dalvik.system.StaleDexCacheError e) {
3530                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3531                ret = -1;
3532            } catch (Exception e) {
3533                Slog.w(TAG, "Exception when doing dexopt : ", e);
3534                ret = -1;
3535            }
3536            if (ret < 0) {
3537                //error from installer
3538                return DEX_OPT_FAILED;
3539            }
3540        }
3541
3542        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3543    }
3544
3545    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
3546        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
3547            Slog.w(TAG, "Unable to update from " + oldPkg.name
3548                    + " to " + newPkg.packageName
3549                    + ": old package not in system partition");
3550            return false;
3551        } else if (mPackages.get(oldPkg.name) != null) {
3552            Slog.w(TAG, "Unable to update from " + oldPkg.name
3553                    + " to " + newPkg.packageName
3554                    + ": old package still exists");
3555            return false;
3556        }
3557        return true;
3558    }
3559
3560    File getDataPathForUser(int userId) {
3561        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
3562    }
3563
3564    private File getDataPathForPackage(String packageName, int userId) {
3565        /*
3566         * Until we fully support multiple users, return the directory we
3567         * previously would have. The PackageManagerTests will need to be
3568         * revised when this is changed back..
3569         */
3570        if (userId == 0) {
3571            return new File(mAppDataDir, packageName);
3572        } else {
3573            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
3574                + File.separator + packageName);
3575        }
3576    }
3577
3578    private int createDataDirsLI(String packageName, int uid) {
3579        int[] users = sUserManager.getUserIds();
3580        int res = mInstaller.install(packageName, uid, uid);
3581        if (res < 0) {
3582            return res;
3583        }
3584        for (int user : users) {
3585            if (user != 0) {
3586                res = mInstaller.createUserData(packageName,
3587                        UserHandle.getUid(user, uid), user);
3588                if (res < 0) {
3589                    return res;
3590                }
3591            }
3592        }
3593        return res;
3594    }
3595
3596    private int removeDataDirsLI(String packageName) {
3597        int[] users = sUserManager.getUserIds();
3598        int res = 0;
3599        for (int user : users) {
3600            int resInner = mInstaller.remove(packageName, user);
3601            if (resInner < 0) {
3602                res = resInner;
3603            }
3604        }
3605
3606        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
3607        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
3608        if (!nativeLibraryFile.delete()) {
3609            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
3610        }
3611
3612        return res;
3613    }
3614
3615    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
3616            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3617        File scanFile = new File(pkg.mScanPath);
3618        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3619                pkg.applicationInfo.publicSourceDir == null) {
3620            // Bail out. The resource and code paths haven't been set.
3621            Slog.w(TAG, " Code and resource paths haven't been set correctly");
3622            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3623            return null;
3624        }
3625        mScanningPath = scanFile;
3626
3627        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3628            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3629        }
3630
3631        if (pkg.packageName.equals("android")) {
3632            synchronized (mPackages) {
3633                if (mAndroidApplication != null) {
3634                    Slog.w(TAG, "*************************************************");
3635                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
3636                    Slog.w(TAG, " file=" + mScanningPath);
3637                    Slog.w(TAG, "*************************************************");
3638                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3639                    return null;
3640                }
3641
3642                // Set up information for our fall-back user intent resolution
3643                // activity.
3644                mPlatformPackage = pkg;
3645                pkg.mVersionCode = mSdkVersion;
3646                mAndroidApplication = pkg.applicationInfo;
3647                mResolveActivity.applicationInfo = mAndroidApplication;
3648                mResolveActivity.name = ResolverActivity.class.getName();
3649                mResolveActivity.packageName = mAndroidApplication.packageName;
3650                mResolveActivity.processName = "system:ui";
3651                mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3652                mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
3653                mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
3654                mResolveActivity.exported = true;
3655                mResolveActivity.enabled = true;
3656                mResolveInfo.activityInfo = mResolveActivity;
3657                mResolveInfo.priority = 0;
3658                mResolveInfo.preferredOrder = 0;
3659                mResolveInfo.match = 0;
3660                mResolveComponentName = new ComponentName(
3661                        mAndroidApplication.packageName, mResolveActivity.name);
3662            }
3663        }
3664
3665        if (DEBUG_PACKAGE_SCANNING) {
3666            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3667                Log.d(TAG, "Scanning package " + pkg.packageName);
3668        }
3669
3670        if (mPackages.containsKey(pkg.packageName)
3671                || mSharedLibraries.containsKey(pkg.packageName)) {
3672            Slog.w(TAG, "Application package " + pkg.packageName
3673                    + " already installed.  Skipping duplicate.");
3674            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3675            return null;
3676        }
3677
3678        // Initialize package source and resource directories
3679        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3680        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
3681
3682        SharedUserSetting suid = null;
3683        PackageSetting pkgSetting = null;
3684
3685        if (!isSystemApp(pkg)) {
3686            // Only system apps can use these features.
3687            pkg.mOriginalPackages = null;
3688            pkg.mRealPackage = null;
3689            pkg.mAdoptPermissions = null;
3690        }
3691
3692        // writer
3693        synchronized (mPackages) {
3694            // Check all shared libraries and map to their actual file path.
3695            if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3696                if (mTmpSharedLibraries == null ||
3697                        mTmpSharedLibraries.length < mSharedLibraries.size()) {
3698                    mTmpSharedLibraries = new String[mSharedLibraries.size()];
3699                }
3700                int num = 0;
3701                int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3702                for (int i=0; i<N; i++) {
3703                    final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
3704                    if (file == null) {
3705                        Slog.e(TAG, "Package " + pkg.packageName
3706                                + " requires unavailable shared library "
3707                                + pkg.usesLibraries.get(i) + "; failing!");
3708                        mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3709                        return null;
3710                    }
3711                    mTmpSharedLibraries[num] = file;
3712                    num++;
3713                }
3714                N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3715                for (int i=0; i<N; i++) {
3716                    final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
3717                    if (file == null) {
3718                        Slog.w(TAG, "Package " + pkg.packageName
3719                                + " desires unavailable shared library "
3720                                + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3721                    } else {
3722                        mTmpSharedLibraries[num] = file;
3723                        num++;
3724                    }
3725                }
3726                if (num > 0) {
3727                    pkg.usesLibraryFiles = new String[num];
3728                    System.arraycopy(mTmpSharedLibraries, 0,
3729                            pkg.usesLibraryFiles, 0, num);
3730                }
3731            }
3732
3733            if (pkg.mSharedUserId != null) {
3734                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
3735                        pkg.applicationInfo.flags, true);
3736                if (suid == null) {
3737                    Slog.w(TAG, "Creating application package " + pkg.packageName
3738                            + " for shared user failed");
3739                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3740                    return null;
3741                }
3742                if (DEBUG_PACKAGE_SCANNING) {
3743                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3744                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3745                                + "): packages=" + suid.packages);
3746                }
3747            }
3748
3749            // Check if we are renaming from an original package name.
3750            PackageSetting origPackage = null;
3751            String realName = null;
3752            if (pkg.mOriginalPackages != null) {
3753                // This package may need to be renamed to a previously
3754                // installed name.  Let's check on that...
3755                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
3756                if (pkg.mOriginalPackages.contains(renamed)) {
3757                    // This package had originally been installed as the
3758                    // original name, and we have already taken care of
3759                    // transitioning to the new one.  Just update the new
3760                    // one to continue using the old name.
3761                    realName = pkg.mRealPackage;
3762                    if (!pkg.packageName.equals(renamed)) {
3763                        // Callers into this function may have already taken
3764                        // care of renaming the package; only do it here if
3765                        // it is not already done.
3766                        pkg.setPackageName(renamed);
3767                    }
3768
3769                } else {
3770                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
3771                        if ((origPackage = mSettings.peekPackageLPr(
3772                                pkg.mOriginalPackages.get(i))) != null) {
3773                            // We do have the package already installed under its
3774                            // original name...  should we use it?
3775                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
3776                                // New package is not compatible with original.
3777                                origPackage = null;
3778                                continue;
3779                            } else if (origPackage.sharedUser != null) {
3780                                // Make sure uid is compatible between packages.
3781                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
3782                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
3783                                            + " to " + pkg.packageName + ": old uid "
3784                                            + origPackage.sharedUser.name
3785                                            + " differs from " + pkg.mSharedUserId);
3786                                    origPackage = null;
3787                                    continue;
3788                                }
3789                            } else {
3790                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3791                                        + pkg.packageName + " to old name " + origPackage.name);
3792                            }
3793                            break;
3794                        }
3795                    }
3796                }
3797            }
3798
3799            if (mTransferedPackages.contains(pkg.packageName)) {
3800                Slog.w(TAG, "Package " + pkg.packageName
3801                        + " was transferred to another, but its .apk remains");
3802            }
3803
3804            // Just create the setting, don't add it yet. For already existing packages
3805            // the PkgSetting exists already and doesn't have to be created.
3806            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
3807                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3808                    pkg.applicationInfo.flags, user, false);
3809            if (pkgSetting == null) {
3810                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
3811                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3812                return null;
3813            }
3814
3815            if (pkgSetting.origPackage != null) {
3816                // If we are first transitioning from an original package,
3817                // fix up the new package's name now.  We need to do this after
3818                // looking up the package under its new name, so getPackageLP
3819                // can take care of fiddling things correctly.
3820                pkg.setPackageName(origPackage.name);
3821
3822                // File a report about this.
3823                String msg = "New package " + pkgSetting.realName
3824                        + " renamed to replace old package " + pkgSetting.name;
3825                reportSettingsProblem(Log.WARN, msg);
3826
3827                // Make a note of it.
3828                mTransferedPackages.add(origPackage.name);
3829
3830                // No longer need to retain this.
3831                pkgSetting.origPackage = null;
3832            }
3833
3834            if (realName != null) {
3835                // Make a note of it.
3836                mTransferedPackages.add(pkg.packageName);
3837            }
3838
3839            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
3840                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3841            }
3842
3843            pkg.applicationInfo.uid = pkgSetting.appId;
3844            pkg.mExtras = pkgSetting;
3845
3846            if (!verifySignaturesLP(pkgSetting, pkg)) {
3847                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3848                    return null;
3849                }
3850                // The signature has changed, but this package is in the system
3851                // image...  let's recover!
3852                pkgSetting.signatures.mSignatures = pkg.mSignatures;
3853                // However...  if this package is part of a shared user, but it
3854                // doesn't match the signature of the shared user, let's fail.
3855                // What this means is that you can't change the signatures
3856                // associated with an overall shared user, which doesn't seem all
3857                // that unreasonable.
3858                if (pkgSetting.sharedUser != null) {
3859                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3860                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3861                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
3862                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3863                        return null;
3864                    }
3865                }
3866                // File a report about this.
3867                String msg = "System package " + pkg.packageName
3868                        + " signature changed; retaining data.";
3869                reportSettingsProblem(Log.WARN, msg);
3870            }
3871
3872            // Verify that this new package doesn't have any content providers
3873            // that conflict with existing packages.  Only do this if the
3874            // package isn't already installed, since we don't want to break
3875            // things that are installed.
3876            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3877                final int N = pkg.providers.size();
3878                int i;
3879                for (i=0; i<N; i++) {
3880                    PackageParser.Provider p = pkg.providers.get(i);
3881                    if (p.info.authority != null) {
3882                        String names[] = p.info.authority.split(";");
3883                        for (int j = 0; j < names.length; j++) {
3884                            if (mProviders.containsKey(names[j])) {
3885                                PackageParser.Provider other = mProviders.get(names[j]);
3886                                Slog.w(TAG, "Can't install because provider name " + names[j] +
3887                                        " (in package " + pkg.applicationInfo.packageName +
3888                                        ") is already used by "
3889                                        + ((other != null && other.getComponentName() != null)
3890                                                ? other.getComponentName().getPackageName() : "?"));
3891                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3892                                return null;
3893                            }
3894                        }
3895                    }
3896                }
3897            }
3898
3899            if (pkg.mAdoptPermissions != null) {
3900                // This package wants to adopt ownership of permissions from
3901                // another package.
3902                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3903                    final String origName = pkg.mAdoptPermissions.get(i);
3904                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
3905                    if (orig != null) {
3906                        if (verifyPackageUpdateLPr(orig, pkg)) {
3907                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
3908                                    + pkg.packageName);
3909                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
3910                        }
3911                    }
3912                }
3913            }
3914        }
3915
3916        final String pkgName = pkg.packageName;
3917
3918        final long scanFileTime = scanFile.lastModified();
3919        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3920        pkg.applicationInfo.processName = fixProcessName(
3921                pkg.applicationInfo.packageName,
3922                pkg.applicationInfo.processName,
3923                pkg.applicationInfo.uid);
3924
3925        File dataPath;
3926        if (mPlatformPackage == pkg) {
3927            // The system package is special.
3928            dataPath = new File (Environment.getDataDirectory(), "system");
3929            pkg.applicationInfo.dataDir = dataPath.getPath();
3930        } else {
3931            // This is a normal package, need to make its data directory.
3932            dataPath = getDataPathForPackage(pkg.packageName, 0);
3933
3934            boolean uidError = false;
3935
3936            if (dataPath.exists()) {
3937                int currentUid = 0;
3938                try {
3939                    StructStat stat = Libcore.os.stat(dataPath.getPath());
3940                    currentUid = stat.st_uid;
3941                } catch (ErrnoException e) {
3942                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
3943                }
3944
3945                // If we have mismatched owners for the data path, we have a problem.
3946                if (currentUid != pkg.applicationInfo.uid) {
3947                    boolean recovered = false;
3948                    if (currentUid == 0) {
3949                        // The directory somehow became owned by root.  Wow.
3950                        // This is probably because the system was stopped while
3951                        // installd was in the middle of messing with its libs
3952                        // directory.  Ask installd to fix that.
3953                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3954                                pkg.applicationInfo.uid);
3955                        if (ret >= 0) {
3956                            recovered = true;
3957                            String msg = "Package " + pkg.packageName
3958                                    + " unexpectedly changed to uid 0; recovered to " +
3959                                    + pkg.applicationInfo.uid;
3960                            reportSettingsProblem(Log.WARN, msg);
3961                        }
3962                    }
3963                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3964                            || (scanMode&SCAN_BOOTING) != 0)) {
3965                        // If this is a system app, we can at least delete its
3966                        // current data so the application will still work.
3967                        int ret = removeDataDirsLI(pkgName);
3968                        if (ret >= 0) {
3969                            // TODO: Kill the processes first
3970                            // Old data gone!
3971                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3972                                    ? "System package " : "Third party package ";
3973                            String msg = prefix + pkg.packageName
3974                                    + " has changed from uid: "
3975                                    + currentUid + " to "
3976                                    + pkg.applicationInfo.uid + "; old data erased";
3977                            reportSettingsProblem(Log.WARN, msg);
3978                            recovered = true;
3979
3980                            // And now re-install the app.
3981                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
3982                            if (ret == -1) {
3983                                // Ack should not happen!
3984                                msg = prefix + pkg.packageName
3985                                        + " could not have data directory re-created after delete.";
3986                                reportSettingsProblem(Log.WARN, msg);
3987                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3988                                return null;
3989                            }
3990                        }
3991                        if (!recovered) {
3992                            mHasSystemUidErrors = true;
3993                        }
3994                    } else if (!recovered) {
3995                        // If we allow this install to proceed, we will be broken.
3996                        // Abort, abort!
3997                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
3998                        return null;
3999                    }
4000                    if (!recovered) {
4001                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4002                            + pkg.applicationInfo.uid + "/fs_"
4003                            + currentUid;
4004                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4005                        String msg = "Package " + pkg.packageName
4006                                + " has mismatched uid: "
4007                                + currentUid + " on disk, "
4008                                + pkg.applicationInfo.uid + " in settings";
4009                        // writer
4010                        synchronized (mPackages) {
4011                            mSettings.mReadMessages.append(msg);
4012                            mSettings.mReadMessages.append('\n');
4013                            uidError = true;
4014                            if (!pkgSetting.uidError) {
4015                                reportSettingsProblem(Log.ERROR, msg);
4016                            }
4017                        }
4018                    }
4019                }
4020                pkg.applicationInfo.dataDir = dataPath.getPath();
4021            } else {
4022                if (DEBUG_PACKAGE_SCANNING) {
4023                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4024                        Log.v(TAG, "Want this data dir: " + dataPath);
4025                }
4026                //invoke installer to do the actual installation
4027                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
4028                if (ret < 0) {
4029                    // Error from installer
4030                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4031                    return null;
4032                }
4033
4034                if (dataPath.exists()) {
4035                    pkg.applicationInfo.dataDir = dataPath.getPath();
4036                } else {
4037                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4038                    pkg.applicationInfo.dataDir = null;
4039                }
4040            }
4041
4042            /*
4043             * Set the data dir to the default "/data/data/<package name>/lib"
4044             * if we got here without anyone telling us different (e.g., apps
4045             * stored on SD card have their native libraries stored in the ASEC
4046             * container with the APK).
4047             *
4048             * This happens during an upgrade from a package settings file that
4049             * doesn't have a native library path attribute at all.
4050             */
4051            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4052                if (pkgSetting.nativeLibraryPathString == null) {
4053                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4054                } else {
4055                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4056                }
4057            }
4058
4059            pkgSetting.uidError = uidError;
4060        }
4061
4062        String path = scanFile.getPath();
4063        /* Note: We don't want to unpack the native binaries for
4064         *        system applications, unless they have been updated
4065         *        (the binaries are already under /system/lib).
4066         *        Also, don't unpack libs for apps on the external card
4067         *        since they should have their libraries in the ASEC
4068         *        container already.
4069         *
4070         *        In other words, we're going to unpack the binaries
4071         *        only for non-system apps and system app upgrades.
4072         */
4073        if (pkg.applicationInfo.nativeLibraryDir != null) {
4074            try {
4075                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4076                final String dataPathString = dataPath.getCanonicalPath();
4077
4078                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4079                    /*
4080                     * Upgrading from a previous version of the OS sometimes
4081                     * leaves native libraries in the /data/data/<app>/lib
4082                     * directory for system apps even when they shouldn't be.
4083                     * Recent changes in the JNI library search path
4084                     * necessitates we remove those to match previous behavior.
4085                     */
4086                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4087                        Log.i(TAG, "removed obsolete native libraries for system package "
4088                                + path);
4089                    }
4090                } else if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4091                    // Update native library dir if it starts with /data/data
4092                    if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4093                        setInternalAppNativeLibraryPath(pkg, pkgSetting);
4094                        nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4095                    }
4096
4097                    try {
4098                        if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4099                            Slog.e(TAG, "Unable to copy native libraries");
4100                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4101                            return null;
4102                        }
4103                    } catch (IOException e) {
4104                        Slog.e(TAG, "Unable to copy native libraries", e);
4105                        mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4106                        return null;
4107                    }
4108
4109                    if (mInstaller.linkNativeLibraryDirectory(dataPathString,
4110                            pkg.applicationInfo.nativeLibraryDir) == -1) {
4111                        Slog.e(TAG, "Unable to link native library directory");
4112                        mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4113                        return null;
4114                    }
4115                } else {
4116                    Slog.i(TAG, "Linking native library dir for " + path);
4117                    int ret = mInstaller.linkNativeLibraryDirectory(dataPathString,
4118                            pkg.applicationInfo.nativeLibraryDir);
4119                    if (ret < 0) {
4120                        Slog.w(TAG, "Failed linking native library dir for " + path);
4121                        mLastScanError = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4122                        return null;
4123                    }
4124                }
4125            } catch (IOException ioe) {
4126                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4127            }
4128        }
4129        pkg.mScanPath = path;
4130
4131        if ((scanMode&SCAN_NO_DEX) == 0) {
4132            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
4133                    == DEX_OPT_FAILED) {
4134                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4135                return null;
4136            }
4137        }
4138
4139        if (mFactoryTest && pkg.requestedPermissions.contains(
4140                android.Manifest.permission.FACTORY_TEST)) {
4141            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4142        }
4143
4144        // Request the ActivityManager to kill the process(only for existing packages)
4145        // so that we do not end up in a confused state while the user is still using the older
4146        // version of the application while the new one gets installed.
4147        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4148            killApplication(pkg.applicationInfo.packageName,
4149                        pkg.applicationInfo.uid);
4150        }
4151
4152        // writer
4153        synchronized (mPackages) {
4154            // We don't expect installation to fail beyond this point,
4155            if ((scanMode&SCAN_MONITOR) != 0) {
4156                mAppDirs.put(pkg.mPath, pkg);
4157            }
4158            // Add the new setting to mSettings
4159            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
4160            // Add the new setting to mPackages
4161            mPackages.put(pkg.applicationInfo.packageName, pkg);
4162            // Make sure we don't accidentally delete its data.
4163            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4164            while (iter.hasNext()) {
4165                PackageCleanItem item = iter.next();
4166                if (pkgName.equals(item.packageName)) {
4167                    iter.remove();
4168                }
4169            }
4170
4171            // Take care of first install / last update times.
4172            if (currentTime != 0) {
4173                if (pkgSetting.firstInstallTime == 0) {
4174                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4175                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4176                    pkgSetting.lastUpdateTime = currentTime;
4177                }
4178            } else if (pkgSetting.firstInstallTime == 0) {
4179                // We need *something*.  Take time time stamp of the file.
4180                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4181            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4182                if (scanFileTime != pkgSetting.timeStamp) {
4183                    // A package on the system image has changed; consider this
4184                    // to be an update.
4185                    pkgSetting.lastUpdateTime = scanFileTime;
4186                }
4187            }
4188
4189            int N = pkg.providers.size();
4190            StringBuilder r = null;
4191            int i;
4192            for (i=0; i<N; i++) {
4193                PackageParser.Provider p = pkg.providers.get(i);
4194                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4195                        p.info.processName, pkg.applicationInfo.uid);
4196                mProvidersByComponent.put(new ComponentName(p.info.packageName,
4197                        p.info.name), p);
4198                p.syncable = p.info.isSyncable;
4199                if (p.info.authority != null) {
4200                    String names[] = p.info.authority.split(";");
4201                    p.info.authority = null;
4202                    for (int j = 0; j < names.length; j++) {
4203                        if (j == 1 && p.syncable) {
4204                            // We only want the first authority for a provider to possibly be
4205                            // syncable, so if we already added this provider using a different
4206                            // authority clear the syncable flag. We copy the provider before
4207                            // changing it because the mProviders object contains a reference
4208                            // to a provider that we don't want to change.
4209                            // Only do this for the second authority since the resulting provider
4210                            // object can be the same for all future authorities for this provider.
4211                            p = new PackageParser.Provider(p);
4212                            p.syncable = false;
4213                        }
4214                        if (!mProviders.containsKey(names[j])) {
4215                            mProviders.put(names[j], p);
4216                            if (p.info.authority == null) {
4217                                p.info.authority = names[j];
4218                            } else {
4219                                p.info.authority = p.info.authority + ";" + names[j];
4220                            }
4221                            if (DEBUG_PACKAGE_SCANNING) {
4222                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4223                                    Log.d(TAG, "Registered content provider: " + names[j]
4224                                            + ", className = " + p.info.name + ", isSyncable = "
4225                                            + p.info.isSyncable);
4226                            }
4227                        } else {
4228                            PackageParser.Provider other = mProviders.get(names[j]);
4229                            Slog.w(TAG, "Skipping provider name " + names[j] +
4230                                    " (in package " + pkg.applicationInfo.packageName +
4231                                    "): name already used by "
4232                                    + ((other != null && other.getComponentName() != null)
4233                                            ? other.getComponentName().getPackageName() : "?"));
4234                        }
4235                    }
4236                }
4237                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4238                    if (r == null) {
4239                        r = new StringBuilder(256);
4240                    } else {
4241                        r.append(' ');
4242                    }
4243                    r.append(p.info.name);
4244                }
4245            }
4246            if (r != null) {
4247                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
4248            }
4249
4250            N = pkg.services.size();
4251            r = null;
4252            for (i=0; i<N; i++) {
4253                PackageParser.Service s = pkg.services.get(i);
4254                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4255                        s.info.processName, pkg.applicationInfo.uid);
4256                mServices.addService(s);
4257                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4258                    if (r == null) {
4259                        r = new StringBuilder(256);
4260                    } else {
4261                        r.append(' ');
4262                    }
4263                    r.append(s.info.name);
4264                }
4265            }
4266            if (r != null) {
4267                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
4268            }
4269
4270            N = pkg.receivers.size();
4271            r = null;
4272            for (i=0; i<N; i++) {
4273                PackageParser.Activity a = pkg.receivers.get(i);
4274                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4275                        a.info.processName, pkg.applicationInfo.uid);
4276                mReceivers.addActivity(a, "receiver");
4277                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4278                    if (r == null) {
4279                        r = new StringBuilder(256);
4280                    } else {
4281                        r.append(' ');
4282                    }
4283                    r.append(a.info.name);
4284                }
4285            }
4286            if (r != null) {
4287                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
4288            }
4289
4290            N = pkg.activities.size();
4291            r = null;
4292            for (i=0; i<N; i++) {
4293                PackageParser.Activity a = pkg.activities.get(i);
4294                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4295                        a.info.processName, pkg.applicationInfo.uid);
4296                mActivities.addActivity(a, "activity");
4297                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4298                    if (r == null) {
4299                        r = new StringBuilder(256);
4300                    } else {
4301                        r.append(' ');
4302                    }
4303                    r.append(a.info.name);
4304                }
4305            }
4306            if (r != null) {
4307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
4308            }
4309
4310            N = pkg.permissionGroups.size();
4311            r = null;
4312            for (i=0; i<N; i++) {
4313                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4314                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4315                if (cur == null) {
4316                    mPermissionGroups.put(pg.info.name, pg);
4317                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4318                        if (r == null) {
4319                            r = new StringBuilder(256);
4320                        } else {
4321                            r.append(' ');
4322                        }
4323                        r.append(pg.info.name);
4324                    }
4325                } else {
4326                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
4327                            + pg.info.packageName + " ignored: original from "
4328                            + cur.info.packageName);
4329                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4330                        if (r == null) {
4331                            r = new StringBuilder(256);
4332                        } else {
4333                            r.append(' ');
4334                        }
4335                        r.append("DUP:");
4336                        r.append(pg.info.name);
4337                    }
4338                }
4339            }
4340            if (r != null) {
4341                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
4342            }
4343
4344            N = pkg.permissions.size();
4345            r = null;
4346            for (i=0; i<N; i++) {
4347                PackageParser.Permission p = pkg.permissions.get(i);
4348                HashMap<String, BasePermission> permissionMap =
4349                        p.tree ? mSettings.mPermissionTrees
4350                        : mSettings.mPermissions;
4351                p.group = mPermissionGroups.get(p.info.group);
4352                if (p.info.group == null || p.group != null) {
4353                    BasePermission bp = permissionMap.get(p.info.name);
4354                    if (bp == null) {
4355                        bp = new BasePermission(p.info.name, p.info.packageName,
4356                                BasePermission.TYPE_NORMAL);
4357                        permissionMap.put(p.info.name, bp);
4358                    }
4359                    if (bp.perm == null) {
4360                        if (bp.sourcePackage == null
4361                                || bp.sourcePackage.equals(p.info.packageName)) {
4362                            BasePermission tree = findPermissionTreeLP(p.info.name);
4363                            if (tree == null
4364                                    || tree.sourcePackage.equals(p.info.packageName)) {
4365                                bp.packageSetting = pkgSetting;
4366                                bp.perm = p;
4367                                bp.uid = pkg.applicationInfo.uid;
4368                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4369                                    if (r == null) {
4370                                        r = new StringBuilder(256);
4371                                    } else {
4372                                        r.append(' ');
4373                                    }
4374                                    r.append(p.info.name);
4375                                }
4376                            } else {
4377                                Slog.w(TAG, "Permission " + p.info.name + " from package "
4378                                        + p.info.packageName + " ignored: base tree "
4379                                        + tree.name + " is from package "
4380                                        + tree.sourcePackage);
4381                            }
4382                        } else {
4383                            Slog.w(TAG, "Permission " + p.info.name + " from package "
4384                                    + p.info.packageName + " ignored: original from "
4385                                    + bp.sourcePackage);
4386                        }
4387                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4388                        if (r == null) {
4389                            r = new StringBuilder(256);
4390                        } else {
4391                            r.append(' ');
4392                        }
4393                        r.append("DUP:");
4394                        r.append(p.info.name);
4395                    }
4396                    if (bp.perm == p) {
4397                        bp.protectionLevel = p.info.protectionLevel;
4398                    }
4399                } else {
4400                    Slog.w(TAG, "Permission " + p.info.name + " from package "
4401                            + p.info.packageName + " ignored: no group "
4402                            + p.group);
4403                }
4404            }
4405            if (r != null) {
4406                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
4407            }
4408
4409            N = pkg.instrumentation.size();
4410            r = null;
4411            for (i=0; i<N; i++) {
4412                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4413                a.info.packageName = pkg.applicationInfo.packageName;
4414                a.info.sourceDir = pkg.applicationInfo.sourceDir;
4415                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4416                a.info.dataDir = pkg.applicationInfo.dataDir;
4417                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
4418                mInstrumentation.put(a.getComponentName(), a);
4419                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4420                    if (r == null) {
4421                        r = new StringBuilder(256);
4422                    } else {
4423                        r.append(' ');
4424                    }
4425                    r.append(a.info.name);
4426                }
4427            }
4428            if (r != null) {
4429                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
4430            }
4431
4432            if (pkg.protectedBroadcasts != null) {
4433                N = pkg.protectedBroadcasts.size();
4434                for (i=0; i<N; i++) {
4435                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4436                }
4437            }
4438
4439            pkgSetting.setTimeStamp(scanFileTime);
4440        }
4441
4442        return pkg;
4443    }
4444
4445    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
4446            PackageSetting pkgSetting) {
4447        final String apkLibPath = getApkName(pkgSetting.codePathString);
4448        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
4449        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4450        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4451    }
4452
4453    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
4454            throws IOException {
4455        if (!nativeLibraryDir.isDirectory()) {
4456            nativeLibraryDir.delete();
4457
4458            if (!nativeLibraryDir.mkdir()) {
4459                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
4460            }
4461
4462            try {
4463                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
4464                        | S_IXOTH);
4465            } catch (ErrnoException e) {
4466                throw new IOException("Cannot chmod native library directory "
4467                        + nativeLibraryDir.getPath(), e);
4468            }
4469        } else if (!SELinux.restorecon(nativeLibraryDir)) {
4470            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
4471        }
4472
4473        /*
4474         * If this is an internal application or our nativeLibraryPath points to
4475         * the app-lib directory, unpack the libraries if necessary.
4476         */
4477        return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
4478    }
4479
4480    private void killApplication(String pkgName, int appId) {
4481        // Request the ActivityManager to kill the process(only for existing packages)
4482        // so that we do not end up in a confused state while the user is still using the older
4483        // version of the application while the new one gets installed.
4484        IActivityManager am = ActivityManagerNative.getDefault();
4485        if (am != null) {
4486            try {
4487                am.killApplicationWithAppId(pkgName, appId);
4488            } catch (RemoteException e) {
4489            }
4490        }
4491    }
4492
4493    void removePackageLI(PackageSetting ps, boolean chatty) {
4494        if (DEBUG_INSTALL) {
4495            if (chatty)
4496                Log.d(TAG, "Removing package " + ps.name);
4497        }
4498
4499        // writer
4500        synchronized (mPackages) {
4501            mPackages.remove(ps.name);
4502            if (ps.codePathString != null) {
4503                mAppDirs.remove(ps.codePathString);
4504            }
4505
4506            final PackageParser.Package pkg = ps.pkg;
4507            if (pkg != null) {
4508                cleanPackageDataStructuresLILPw(pkg, chatty);
4509            }
4510        }
4511    }
4512
4513    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
4514        if (DEBUG_INSTALL) {
4515            if (chatty)
4516                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4517        }
4518
4519        // writer
4520        synchronized (mPackages) {
4521            mPackages.remove(pkg.applicationInfo.packageName);
4522            if (pkg.mPath != null) {
4523                mAppDirs.remove(pkg.mPath);
4524            }
4525            cleanPackageDataStructuresLILPw(pkg, chatty);
4526        }
4527    }
4528
4529    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
4530        int N = pkg.providers.size();
4531        StringBuilder r = null;
4532        int i;
4533        for (i=0; i<N; i++) {
4534            PackageParser.Provider p = pkg.providers.get(i);
4535            mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4536                    p.info.name));
4537            if (p.info.authority == null) {
4538
4539                /* There was another ContentProvider with this authority when
4540                 * this app was installed so this authority is null,
4541                 * Ignore it as we don't have to unregister the provider.
4542                 */
4543                continue;
4544            }
4545            String names[] = p.info.authority.split(";");
4546            for (int j = 0; j < names.length; j++) {
4547                if (mProviders.get(names[j]) == p) {
4548                    mProviders.remove(names[j]);
4549                    if (DEBUG_REMOVE) {
4550                        if (chatty)
4551                            Log.d(TAG, "Unregistered content provider: " + names[j]
4552                                    + ", className = " + p.info.name + ", isSyncable = "
4553                                    + p.info.isSyncable);
4554                    }
4555                }
4556            }
4557            if (chatty) {
4558                if (r == null) {
4559                    r = new StringBuilder(256);
4560                } else {
4561                    r.append(' ');
4562                }
4563                r.append(p.info.name);
4564            }
4565        }
4566        if (r != null) {
4567            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
4568        }
4569
4570        N = pkg.services.size();
4571        r = null;
4572        for (i=0; i<N; i++) {
4573            PackageParser.Service s = pkg.services.get(i);
4574            mServices.removeService(s);
4575            if (chatty) {
4576                if (r == null) {
4577                    r = new StringBuilder(256);
4578                } else {
4579                    r.append(' ');
4580                }
4581                r.append(s.info.name);
4582            }
4583        }
4584        if (r != null) {
4585            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
4586        }
4587
4588        N = pkg.receivers.size();
4589        r = null;
4590        for (i=0; i<N; i++) {
4591            PackageParser.Activity a = pkg.receivers.get(i);
4592            mReceivers.removeActivity(a, "receiver");
4593            if (chatty) {
4594                if (r == null) {
4595                    r = new StringBuilder(256);
4596                } else {
4597                    r.append(' ');
4598                }
4599                r.append(a.info.name);
4600            }
4601        }
4602        if (r != null) {
4603            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
4604        }
4605
4606        N = pkg.activities.size();
4607        r = null;
4608        for (i=0; i<N; i++) {
4609            PackageParser.Activity a = pkg.activities.get(i);
4610            mActivities.removeActivity(a, "activity");
4611            if (chatty) {
4612                if (r == null) {
4613                    r = new StringBuilder(256);
4614                } else {
4615                    r.append(' ');
4616                }
4617                r.append(a.info.name);
4618            }
4619        }
4620        if (r != null) {
4621            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
4622        }
4623
4624        N = pkg.permissions.size();
4625        r = null;
4626        for (i=0; i<N; i++) {
4627            PackageParser.Permission p = pkg.permissions.get(i);
4628            BasePermission bp = mSettings.mPermissions.get(p.info.name);
4629            if (bp == null) {
4630                bp = mSettings.mPermissionTrees.get(p.info.name);
4631            }
4632            if (bp != null && bp.perm == p) {
4633                bp.perm = null;
4634                if (chatty) {
4635                    if (r == null) {
4636                        r = new StringBuilder(256);
4637                    } else {
4638                        r.append(' ');
4639                    }
4640                    r.append(p.info.name);
4641                }
4642            }
4643        }
4644        if (r != null) {
4645            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
4646        }
4647
4648        N = pkg.instrumentation.size();
4649        r = null;
4650        for (i=0; i<N; i++) {
4651            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4652            mInstrumentation.remove(a.getComponentName());
4653            if (chatty) {
4654                if (r == null) {
4655                    r = new StringBuilder(256);
4656                } else {
4657                    r.append(' ');
4658                }
4659                r.append(a.info.name);
4660            }
4661        }
4662        if (r != null) {
4663            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
4664        }
4665    }
4666
4667    private static final boolean isPackageFilename(String name) {
4668        return name != null && name.endsWith(".apk");
4669    }
4670
4671    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4672        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4673            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4674                return true;
4675            }
4676        }
4677        return false;
4678    }
4679
4680    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4681    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4682    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4683
4684    private void updatePermissionsLPw(String changingPkg,
4685            PackageParser.Package pkgInfo, int flags) {
4686        // Make sure there are no dangling permission trees.
4687        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
4688        while (it.hasNext()) {
4689            final BasePermission bp = it.next();
4690            if (bp.packageSetting == null) {
4691                // We may not yet have parsed the package, so just see if
4692                // we still know about its settings.
4693                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4694            }
4695            if (bp.packageSetting == null) {
4696                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
4697                        + " from package " + bp.sourcePackage);
4698                it.remove();
4699            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4700                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4701                    Slog.i(TAG, "Removing old permission tree: " + bp.name
4702                            + " from package " + bp.sourcePackage);
4703                    flags |= UPDATE_PERMISSIONS_ALL;
4704                    it.remove();
4705                }
4706            }
4707        }
4708
4709        // Make sure all dynamic permissions have been assigned to a package,
4710        // and make sure there are no dangling permissions.
4711        it = mSettings.mPermissions.values().iterator();
4712        while (it.hasNext()) {
4713            final BasePermission bp = it.next();
4714            if (bp.type == BasePermission.TYPE_DYNAMIC) {
4715                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4716                        + bp.name + " pkg=" + bp.sourcePackage
4717                        + " info=" + bp.pendingInfo);
4718                if (bp.packageSetting == null && bp.pendingInfo != null) {
4719                    final BasePermission tree = findPermissionTreeLP(bp.name);
4720                    if (tree != null && tree.perm != null) {
4721                        bp.packageSetting = tree.packageSetting;
4722                        bp.perm = new PackageParser.Permission(tree.perm.owner,
4723                                new PermissionInfo(bp.pendingInfo));
4724                        bp.perm.info.packageName = tree.perm.info.packageName;
4725                        bp.perm.info.name = bp.name;
4726                        bp.uid = tree.uid;
4727                    }
4728                }
4729            }
4730            if (bp.packageSetting == null) {
4731                // We may not yet have parsed the package, so just see if
4732                // we still know about its settings.
4733                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4734            }
4735            if (bp.packageSetting == null) {
4736                Slog.w(TAG, "Removing dangling permission: " + bp.name
4737                        + " from package " + bp.sourcePackage);
4738                it.remove();
4739            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4740                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4741                    Slog.i(TAG, "Removing old permission: " + bp.name
4742                            + " from package " + bp.sourcePackage);
4743                    flags |= UPDATE_PERMISSIONS_ALL;
4744                    it.remove();
4745                }
4746            }
4747        }
4748
4749        // Now update the permissions for all packages, in particular
4750        // replace the granted permissions of the system packages.
4751        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
4752            for (PackageParser.Package pkg : mPackages.values()) {
4753                if (pkg != pkgInfo) {
4754                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
4755                }
4756            }
4757        }
4758
4759        if (pkgInfo != null) {
4760            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
4761        }
4762    }
4763
4764    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4765        final PackageSetting ps = (PackageSetting) pkg.mExtras;
4766        if (ps == null) {
4767            return;
4768        }
4769        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
4770        HashSet<String> origPermissions = gp.grantedPermissions;
4771        boolean changedPermission = false;
4772
4773        if (replace) {
4774            ps.permissionsFixed = false;
4775            if (gp == ps) {
4776                origPermissions = new HashSet<String>(gp.grantedPermissions);
4777                gp.grantedPermissions.clear();
4778                gp.gids = mGlobalGids;
4779            }
4780        }
4781
4782        if (gp.gids == null) {
4783            gp.gids = mGlobalGids;
4784        }
4785
4786        final int N = pkg.requestedPermissions.size();
4787        for (int i=0; i<N; i++) {
4788            final String name = pkg.requestedPermissions.get(i);
4789            //final boolean required = pkg.requestedPermssionsRequired.get(i);
4790            final BasePermission bp = mSettings.mPermissions.get(name);
4791            if (DEBUG_INSTALL) {
4792                if (gp != ps) {
4793                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
4794                }
4795            }
4796            if (bp != null && bp.packageSetting != null) {
4797                final String perm = bp.name;
4798                boolean allowed;
4799                boolean allowedSig = false;
4800                final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4801                if (level == PermissionInfo.PROTECTION_NORMAL
4802                        || level == PermissionInfo.PROTECTION_DANGEROUS) {
4803                    allowed = true;
4804                } else if (bp.packageSetting == null) {
4805                    // This permission is invalid; skip it.
4806                    allowed = false;
4807                } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
4808                    allowed = (compareSignatures(
4809                            bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
4810                                    == PackageManager.SIGNATURE_MATCH)
4811                            || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
4812                                    == PackageManager.SIGNATURE_MATCH);
4813                    if (!allowed && (bp.protectionLevel
4814                            & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
4815                        if (isSystemApp(pkg)) {
4816                            // For updated system applications, a system permission
4817                            // is granted only if it had been defined by the original application.
4818                            if (isUpdatedSystemApp(pkg)) {
4819                                final PackageSetting sysPs = mSettings
4820                                        .getDisabledSystemPkgLPr(pkg.packageName);
4821                                final GrantedPermissions origGp = sysPs.sharedUser != null
4822                                        ? sysPs.sharedUser : sysPs;
4823                                if (origGp.grantedPermissions.contains(perm)) {
4824                                    allowed = true;
4825                                } else {
4826                                    allowed = false;
4827                                }
4828                            } else {
4829                                allowed = true;
4830                            }
4831                        }
4832                    }
4833                    if (!allowed && (bp.protectionLevel
4834                            & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4835                        // For development permissions, a development permission
4836                        // is granted only if it was already granted.
4837                        if (origPermissions.contains(perm)) {
4838                            allowed = true;
4839                        } else {
4840                            allowed = false;
4841                        }
4842                    }
4843                    if (allowed) {
4844                        allowedSig = true;
4845                    }
4846                } else {
4847                    allowed = false;
4848                }
4849                if (DEBUG_INSTALL) {
4850                    if (gp != ps) {
4851                        Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4852                    }
4853                }
4854                if (allowed) {
4855                    if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4856                            && ps.permissionsFixed) {
4857                        // If this is an existing, non-system package, then
4858                        // we can't add any new permissions to it.
4859                        if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
4860                            allowed = false;
4861                            // Except...  if this is a permission that was added
4862                            // to the platform (note: need to only do this when
4863                            // updating the platform).
4864                            final int NP = PackageParser.NEW_PERMISSIONS.length;
4865                            for (int ip=0; ip<NP; ip++) {
4866                                final PackageParser.NewPermissionInfo npi
4867                                        = PackageParser.NEW_PERMISSIONS[ip];
4868                                if (npi.name.equals(perm)
4869                                        && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4870                                    allowed = true;
4871                                    Log.i(TAG, "Auto-granting " + perm + " to old pkg "
4872                                            + pkg.packageName);
4873                                    break;
4874                                }
4875                            }
4876                        }
4877                    }
4878                    if (allowed) {
4879                        if (!gp.grantedPermissions.contains(perm)) {
4880                            changedPermission = true;
4881                            gp.grantedPermissions.add(perm);
4882                            gp.gids = appendInts(gp.gids, bp.gids);
4883                        } else if (!ps.haveGids) {
4884                            gp.gids = appendInts(gp.gids, bp.gids);
4885                        }
4886                    } else {
4887                        Slog.w(TAG, "Not granting permission " + perm
4888                                + " to package " + pkg.packageName
4889                                + " because it was previously installed without");
4890                    }
4891                } else {
4892                    if (gp.grantedPermissions.remove(perm)) {
4893                        changedPermission = true;
4894                        gp.gids = removeInts(gp.gids, bp.gids);
4895                        Slog.i(TAG, "Un-granting permission " + perm
4896                                + " from package " + pkg.packageName
4897                                + " (protectionLevel=" + bp.protectionLevel
4898                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4899                                + ")");
4900                    } else {
4901                        Slog.w(TAG, "Not granting permission " + perm
4902                                + " to package " + pkg.packageName
4903                                + " (protectionLevel=" + bp.protectionLevel
4904                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4905                                + ")");
4906                    }
4907                }
4908            } else {
4909                Slog.w(TAG, "Unknown permission " + name
4910                        + " in package " + pkg.packageName);
4911            }
4912        }
4913
4914        if ((changedPermission || replace) && !ps.permissionsFixed &&
4915                ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4916                ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
4917            // This is the first that we have heard about this package, so the
4918            // permissions we have now selected are fixed until explicitly
4919            // changed.
4920            ps.permissionsFixed = true;
4921        }
4922        ps.haveGids = true;
4923    }
4924
4925    private final class ActivityIntentResolver
4926            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
4927        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
4928                boolean defaultOnly, int userId) {
4929            if (!sUserManager.exists(userId)) return null;
4930            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
4931            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
4932        }
4933
4934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4935                int userId) {
4936            if (!sUserManager.exists(userId)) return null;
4937            mFlags = flags;
4938            return super.queryIntent(intent, resolvedType,
4939                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
4940        }
4941
4942        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
4943                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
4944            if (!sUserManager.exists(userId)) return null;
4945            if (packageActivities == null) {
4946                return null;
4947            }
4948            mFlags = flags;
4949            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4950            final int N = packageActivities.size();
4951            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4952                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
4953
4954            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
4955            for (int i = 0; i < N; ++i) {
4956                intentFilters = packageActivities.get(i).intents;
4957                if (intentFilters != null && intentFilters.size() > 0) {
4958                    PackageParser.ActivityIntentInfo[] array =
4959                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
4960                    intentFilters.toArray(array);
4961                    listCut.add(array);
4962                }
4963            }
4964            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
4965        }
4966
4967        public final void addActivity(PackageParser.Activity a, String type) {
4968            final boolean systemApp = isSystemApp(a.info.applicationInfo);
4969            mActivities.put(a.getComponentName(), a);
4970            if (DEBUG_SHOW_INFO)
4971                Log.v(
4972                TAG, "  " + type + " " +
4973                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4974            if (DEBUG_SHOW_INFO)
4975                Log.v(TAG, "    Class=" + a.info.name);
4976            final int NI = a.intents.size();
4977            for (int j=0; j<NI; j++) {
4978                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4979                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4980                    intent.setPriority(0);
4981                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4982                            + a.className + " with priority > 0, forcing to 0");
4983                }
4984                if (DEBUG_SHOW_INFO) {
4985                    Log.v(TAG, "    IntentFilter:");
4986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
4987                }
4988                if (!intent.debugCheck()) {
4989                    Log.w(TAG, "==> For Activity " + a.info.name);
4990                }
4991                addFilter(intent);
4992            }
4993        }
4994
4995        public final void removeActivity(PackageParser.Activity a, String type) {
4996            mActivities.remove(a.getComponentName());
4997            if (DEBUG_SHOW_INFO) {
4998                Log.v(TAG, "  " + type + " "
4999                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5000                                : a.info.name) + ":");
5001                Log.v(TAG, "    Class=" + a.info.name);
5002            }
5003            final int NI = a.intents.size();
5004            for (int j=0; j<NI; j++) {
5005                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5006                if (DEBUG_SHOW_INFO) {
5007                    Log.v(TAG, "    IntentFilter:");
5008                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5009                }
5010                removeFilter(intent);
5011            }
5012        }
5013
5014        @Override
5015        protected boolean allowFilterResult(
5016                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5017            ActivityInfo filterAi = filter.activity.info;
5018            for (int i=dest.size()-1; i>=0; i--) {
5019                ActivityInfo destAi = dest.get(i).activityInfo;
5020                if (destAi.name == filterAi.name
5021                        && destAi.packageName == filterAi.packageName) {
5022                    return false;
5023                }
5024            }
5025            return true;
5026        }
5027
5028        @Override
5029        protected ActivityIntentInfo[] newArray(int size) {
5030            return new ActivityIntentInfo[size];
5031        }
5032
5033        @Override
5034        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
5035            if (!sUserManager.exists(userId)) return true;
5036            PackageParser.Package p = filter.activity.owner;
5037            if (p != null) {
5038                PackageSetting ps = (PackageSetting)p.mExtras;
5039                if (ps != null) {
5040                    // System apps are never considered stopped for purposes of
5041                    // filtering, because there may be no way for the user to
5042                    // actually re-launch them.
5043                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5044                            && ps.getStopped(userId);
5045                }
5046            }
5047            return false;
5048        }
5049
5050        @Override
5051        protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
5052            return info.activity.owner.packageName;
5053        }
5054
5055        @Override
5056        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
5057                int match, int userId) {
5058            if (!sUserManager.exists(userId)) return null;
5059            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
5060                return null;
5061            }
5062            final PackageParser.Activity activity = info.activity;
5063            if (mSafeMode && (activity.info.applicationInfo.flags
5064                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5065                return null;
5066            }
5067            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
5068            if (ps == null) {
5069                return null;
5070            }
5071            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5072                    ps.readUserState(userId), userId);
5073            if (ai == null) {
5074                return null;
5075            }
5076            final ResolveInfo res = new ResolveInfo();
5077            res.activityInfo = ai;
5078            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5079                res.filter = info;
5080            }
5081            res.priority = info.getPriority();
5082            res.preferredOrder = activity.owner.mPreferredOrder;
5083            //System.out.println("Result: " + res.activityInfo.className +
5084            //                   " = " + res.priority);
5085            res.match = match;
5086            res.isDefault = info.hasDefault;
5087            res.labelRes = info.labelRes;
5088            res.nonLocalizedLabel = info.nonLocalizedLabel;
5089            res.icon = info.icon;
5090            res.system = isSystemApp(res.activityInfo.applicationInfo);
5091            return res;
5092        }
5093
5094        @Override
5095        protected void sortResults(List<ResolveInfo> results) {
5096            Collections.sort(results, mResolvePrioritySorter);
5097        }
5098
5099        @Override
5100        protected void dumpFilter(PrintWriter out, String prefix,
5101                PackageParser.ActivityIntentInfo filter) {
5102            out.print(prefix); out.print(
5103                    Integer.toHexString(System.identityHashCode(filter.activity)));
5104                    out.print(' ');
5105                    out.print(filter.activity.getComponentShortName());
5106                    out.print(" filter ");
5107                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5108        }
5109
5110//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5111//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5112//            final List<ResolveInfo> retList = Lists.newArrayList();
5113//            while (i.hasNext()) {
5114//                final ResolveInfo resolveInfo = i.next();
5115//                if (isEnabledLP(resolveInfo.activityInfo)) {
5116//                    retList.add(resolveInfo);
5117//                }
5118//            }
5119//            return retList;
5120//        }
5121
5122        // Keys are String (activity class name), values are Activity.
5123        private final HashMap<ComponentName, PackageParser.Activity> mActivities
5124                = new HashMap<ComponentName, PackageParser.Activity>();
5125        private int mFlags;
5126    }
5127
5128    private final class ServiceIntentResolver
5129            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
5130        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5131                boolean defaultOnly, int userId) {
5132            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5133            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5134        }
5135
5136        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5137                int userId) {
5138            if (!sUserManager.exists(userId)) return null;
5139            mFlags = flags;
5140            return super.queryIntent(intent, resolvedType,
5141                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5142        }
5143
5144        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5145                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
5146            if (!sUserManager.exists(userId)) return null;
5147            if (packageServices == null) {
5148                return null;
5149            }
5150            mFlags = flags;
5151            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5152            final int N = packageServices.size();
5153            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5154                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
5155
5156            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5157            for (int i = 0; i < N; ++i) {
5158                intentFilters = packageServices.get(i).intents;
5159                if (intentFilters != null && intentFilters.size() > 0) {
5160                    PackageParser.ServiceIntentInfo[] array =
5161                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
5162                    intentFilters.toArray(array);
5163                    listCut.add(array);
5164                }
5165            }
5166            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5167        }
5168
5169        public final void addService(PackageParser.Service s) {
5170            mServices.put(s.getComponentName(), s);
5171            if (DEBUG_SHOW_INFO) {
5172                Log.v(TAG, "  "
5173                        + (s.info.nonLocalizedLabel != null
5174                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5175                Log.v(TAG, "    Class=" + s.info.name);
5176            }
5177            final int NI = s.intents.size();
5178            int j;
5179            for (j=0; j<NI; j++) {
5180                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5181                if (DEBUG_SHOW_INFO) {
5182                    Log.v(TAG, "    IntentFilter:");
5183                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5184                }
5185                if (!intent.debugCheck()) {
5186                    Log.w(TAG, "==> For Service " + s.info.name);
5187                }
5188                addFilter(intent);
5189            }
5190        }
5191
5192        public final void removeService(PackageParser.Service s) {
5193            mServices.remove(s.getComponentName());
5194            if (DEBUG_SHOW_INFO) {
5195                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
5196                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5197                Log.v(TAG, "    Class=" + s.info.name);
5198            }
5199            final int NI = s.intents.size();
5200            int j;
5201            for (j=0; j<NI; j++) {
5202                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5203                if (DEBUG_SHOW_INFO) {
5204                    Log.v(TAG, "    IntentFilter:");
5205                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5206                }
5207                removeFilter(intent);
5208            }
5209        }
5210
5211        @Override
5212        protected boolean allowFilterResult(
5213                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5214            ServiceInfo filterSi = filter.service.info;
5215            for (int i=dest.size()-1; i>=0; i--) {
5216                ServiceInfo destAi = dest.get(i).serviceInfo;
5217                if (destAi.name == filterSi.name
5218                        && destAi.packageName == filterSi.packageName) {
5219                    return false;
5220                }
5221            }
5222            return true;
5223        }
5224
5225        @Override
5226        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5227            return new PackageParser.ServiceIntentInfo[size];
5228        }
5229
5230        @Override
5231        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
5232            if (!sUserManager.exists(userId)) return true;
5233            PackageParser.Package p = filter.service.owner;
5234            if (p != null) {
5235                PackageSetting ps = (PackageSetting)p.mExtras;
5236                if (ps != null) {
5237                    // System apps are never considered stopped for purposes of
5238                    // filtering, because there may be no way for the user to
5239                    // actually re-launch them.
5240                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5241                            && ps.getStopped(userId);
5242                }
5243            }
5244            return false;
5245        }
5246
5247        @Override
5248        protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5249            return info.service.owner.packageName;
5250        }
5251
5252        @Override
5253        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
5254                int match, int userId) {
5255            if (!sUserManager.exists(userId)) return null;
5256            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
5257            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
5258                return null;
5259            }
5260            final PackageParser.Service service = info.service;
5261            if (mSafeMode && (service.info.applicationInfo.flags
5262                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5263                return null;
5264            }
5265            PackageSetting ps = (PackageSetting) service.owner.mExtras;
5266            if (ps == null) {
5267                return null;
5268            }
5269            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5270                    ps.readUserState(userId), userId);
5271            if (si == null) {
5272                return null;
5273            }
5274            final ResolveInfo res = new ResolveInfo();
5275            res.serviceInfo = si;
5276            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5277                res.filter = filter;
5278            }
5279            res.priority = info.getPriority();
5280            res.preferredOrder = service.owner.mPreferredOrder;
5281            //System.out.println("Result: " + res.activityInfo.className +
5282            //                   " = " + res.priority);
5283            res.match = match;
5284            res.isDefault = info.hasDefault;
5285            res.labelRes = info.labelRes;
5286            res.nonLocalizedLabel = info.nonLocalizedLabel;
5287            res.icon = info.icon;
5288            res.system = isSystemApp(res.serviceInfo.applicationInfo);
5289            return res;
5290        }
5291
5292        @Override
5293        protected void sortResults(List<ResolveInfo> results) {
5294            Collections.sort(results, mResolvePrioritySorter);
5295        }
5296
5297        @Override
5298        protected void dumpFilter(PrintWriter out, String prefix,
5299                PackageParser.ServiceIntentInfo filter) {
5300            out.print(prefix); out.print(
5301                    Integer.toHexString(System.identityHashCode(filter.service)));
5302                    out.print(' ');
5303                    out.print(filter.service.getComponentShortName());
5304                    out.print(" filter ");
5305                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5306        }
5307
5308//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5309//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5310//            final List<ResolveInfo> retList = Lists.newArrayList();
5311//            while (i.hasNext()) {
5312//                final ResolveInfo resolveInfo = (ResolveInfo) i;
5313//                if (isEnabledLP(resolveInfo.serviceInfo)) {
5314//                    retList.add(resolveInfo);
5315//                }
5316//            }
5317//            return retList;
5318//        }
5319
5320        // Keys are String (activity class name), values are Activity.
5321        private final HashMap<ComponentName, PackageParser.Service> mServices
5322                = new HashMap<ComponentName, PackageParser.Service>();
5323        private int mFlags;
5324    };
5325
5326    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5327            new Comparator<ResolveInfo>() {
5328        public int compare(ResolveInfo r1, ResolveInfo r2) {
5329            int v1 = r1.priority;
5330            int v2 = r2.priority;
5331            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5332            if (v1 != v2) {
5333                return (v1 > v2) ? -1 : 1;
5334            }
5335            v1 = r1.preferredOrder;
5336            v2 = r2.preferredOrder;
5337            if (v1 != v2) {
5338                return (v1 > v2) ? -1 : 1;
5339            }
5340            if (r1.isDefault != r2.isDefault) {
5341                return r1.isDefault ? -1 : 1;
5342            }
5343            v1 = r1.match;
5344            v2 = r2.match;
5345            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
5346            if (v1 != v2) {
5347                return (v1 > v2) ? -1 : 1;
5348            }
5349            if (r1.system != r2.system) {
5350                return r1.system ? -1 : 1;
5351            }
5352            return 0;
5353        }
5354    };
5355
5356    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5357            new Comparator<ProviderInfo>() {
5358        public int compare(ProviderInfo p1, ProviderInfo p2) {
5359            final int v1 = p1.initOrder;
5360            final int v2 = p2.initOrder;
5361            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5362        }
5363    };
5364
5365    static final void sendPackageBroadcast(String action, String pkg,
5366            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5367            int[] userIds) {
5368        IActivityManager am = ActivityManagerNative.getDefault();
5369        if (am != null) {
5370            try {
5371                if (userIds == null) {
5372                    userIds = am.getRunningUserIds();
5373                }
5374                for (int id : userIds) {
5375                    final Intent intent = new Intent(action,
5376                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
5377                    if (extras != null) {
5378                        intent.putExtras(extras);
5379                    }
5380                    if (targetPkg != null) {
5381                        intent.setPackage(targetPkg);
5382                    }
5383                    // Modify the UID when posting to other users
5384                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
5385                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
5386                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
5387                        intent.putExtra(Intent.EXTRA_UID, uid);
5388                    }
5389                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
5390                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5391                    if (DEBUG_BROADCASTS) {
5392                        RuntimeException here = new RuntimeException("here");
5393                        here.fillInStackTrace();
5394                        Slog.d(TAG, "Sending to user " + id + ": "
5395                                + intent.toShortString(false, true, false, false)
5396                                + " " + intent.getExtras(), here);
5397                    }
5398                    am.broadcastIntent(null, intent, null, finishedReceiver,
5399                            0, null, null, null, finishedReceiver != null, false, id);
5400                }
5401            } catch (RemoteException ex) {
5402            }
5403        }
5404    }
5405
5406    /**
5407     * Check if the external storage media is available. This is true if there
5408     * is a mounted external storage medium or if the external storage is
5409     * emulated.
5410     */
5411    private boolean isExternalMediaAvailable() {
5412        return mMediaMounted || Environment.isExternalStorageEmulated();
5413    }
5414
5415    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
5416        // writer
5417        synchronized (mPackages) {
5418            if (!isExternalMediaAvailable()) {
5419                // If the external storage is no longer mounted at this point,
5420                // the caller may not have been able to delete all of this
5421                // packages files and can not delete any more.  Bail.
5422                return null;
5423            }
5424            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
5425            if (lastPackage != null) {
5426                pkgs.remove(lastPackage);
5427            }
5428            if (pkgs.size() > 0) {
5429                return pkgs.get(0);
5430            }
5431        }
5432        return null;
5433    }
5434
5435    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5436        if (false) {
5437            RuntimeException here = new RuntimeException("here");
5438            here.fillInStackTrace();
5439            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5440                    + " andCode=" + andCode, here);
5441        }
5442        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5443                userId, andCode ? 1 : 0, packageName));
5444    }
5445
5446    void startCleaningPackages() {
5447        // reader
5448        synchronized (mPackages) {
5449            if (!isExternalMediaAvailable()) {
5450                return;
5451            }
5452            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
5453                return;
5454            }
5455        }
5456        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5457        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5458        IActivityManager am = ActivityManagerNative.getDefault();
5459        if (am != null) {
5460            try {
5461                am.startService(null, intent, null, UserHandle.USER_OWNER);
5462            } catch (RemoteException e) {
5463            }
5464        }
5465    }
5466
5467    private final class AppDirObserver extends FileObserver {
5468        public AppDirObserver(String path, int mask, boolean isrom) {
5469            super(path, mask);
5470            mRootDir = path;
5471            mIsRom = isrom;
5472        }
5473
5474        public void onEvent(int event, String path) {
5475            String removedPackage = null;
5476            int removedAppId = -1;
5477            int[] removedUsers = null;
5478            String addedPackage = null;
5479            int addedAppId = -1;
5480            int[] addedUsers = null;
5481
5482            // TODO post a message to the handler to obtain serial ordering
5483            synchronized (mInstallLock) {
5484                String fullPathStr = null;
5485                File fullPath = null;
5486                if (path != null) {
5487                    fullPath = new File(mRootDir, path);
5488                    fullPathStr = fullPath.getPath();
5489                }
5490
5491                if (DEBUG_APP_DIR_OBSERVER)
5492                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
5493
5494                if (!isPackageFilename(path)) {
5495                    if (DEBUG_APP_DIR_OBSERVER)
5496                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
5497                    return;
5498                }
5499
5500                // Ignore packages that are being installed or
5501                // have just been installed.
5502                if (ignoreCodePath(fullPathStr)) {
5503                    return;
5504                }
5505                PackageParser.Package p = null;
5506                PackageSetting ps = null;
5507                // reader
5508                synchronized (mPackages) {
5509                    p = mAppDirs.get(fullPathStr);
5510                    if (p != null) {
5511                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
5512                        if (ps != null) {
5513                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5514                        } else {
5515                            removedUsers = sUserManager.getUserIds();
5516                        }
5517                    }
5518                    addedUsers = sUserManager.getUserIds();
5519                }
5520                if ((event&REMOVE_EVENTS) != 0) {
5521                    if (ps != null) {
5522                        removePackageLI(ps, true);
5523                        removedPackage = ps.name;
5524                        removedAppId = ps.appId;
5525                    }
5526                }
5527
5528                if ((event&ADD_EVENTS) != 0) {
5529                    if (p == null) {
5530                        p = scanPackageLI(fullPath,
5531                                (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5532                                        | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
5533                                PackageParser.PARSE_CHATTY |
5534                                PackageParser.PARSE_MUST_BE_APK,
5535                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
5536                                System.currentTimeMillis(), UserHandle.ALL);
5537                        if (p != null) {
5538                            /*
5539                             * TODO this seems dangerous as the package may have
5540                             * changed since we last acquired the mPackages
5541                             * lock.
5542                             */
5543                            // writer
5544                            synchronized (mPackages) {
5545                                updatePermissionsLPw(p.packageName, p,
5546                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
5547                            }
5548                            addedPackage = p.applicationInfo.packageName;
5549                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
5550                        }
5551                    }
5552                }
5553
5554                // reader
5555                synchronized (mPackages) {
5556                    mSettings.writeLPr();
5557                }
5558            }
5559
5560            if (removedPackage != null) {
5561                Bundle extras = new Bundle(1);
5562                extras.putInt(Intent.EXTRA_UID, removedAppId);
5563                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
5564                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
5565                        extras, null, null, removedUsers);
5566            }
5567            if (addedPackage != null) {
5568                Bundle extras = new Bundle(1);
5569                extras.putInt(Intent.EXTRA_UID, addedAppId);
5570                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
5571                        extras, null, null, addedUsers);
5572            }
5573        }
5574
5575        private final String mRootDir;
5576        private final boolean mIsRom;
5577    }
5578
5579    /* Called when a downloaded package installation has been confirmed by the user */
5580    public void installPackage(
5581            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
5582        installPackage(packageURI, observer, flags, null);
5583    }
5584
5585    /* Called when a downloaded package installation has been confirmed by the user */
5586    public void installPackage(
5587            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5588            final String installerPackageName) {
5589        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
5590                null, null);
5591    }
5592
5593    @Override
5594    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5595            int flags, String installerPackageName, Uri verificationURI,
5596            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
5597        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
5598                VerificationParams.NO_UID, manifestDigest);
5599        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
5600                installerPackageName, verificationParams, encryptionParams);
5601    }
5602
5603    public void installPackageWithVerificationAndEncryption(Uri packageURI,
5604            IPackageInstallObserver observer, int flags, String installerPackageName,
5605            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
5606        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5607                null);
5608
5609        final int uid = Binder.getCallingUid();
5610        UserHandle user;
5611        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
5612            user = UserHandle.ALL;
5613        } else {
5614            user = new UserHandle(UserHandle.getUserId(uid));
5615        }
5616
5617        final int filteredFlags;
5618
5619        if (uid == Process.SHELL_UID || uid == 0) {
5620            if (DEBUG_INSTALL) {
5621                Slog.v(TAG, "Install from ADB");
5622            }
5623            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5624        } else {
5625            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5626        }
5627
5628        verificationParams.setInstallerUid(uid);
5629
5630        final Message msg = mHandler.obtainMessage(INIT_COPY);
5631        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
5632                verificationParams, encryptionParams, user);
5633        mHandler.sendMessage(msg);
5634    }
5635
5636    /**
5637     * @hide
5638     */
5639    @Override
5640    public int installExistingPackage(String packageName) {
5641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5642                null);
5643        PackageSetting pkgSetting;
5644        final int uid = Binder.getCallingUid();
5645        final int userId = UserHandle.getUserId(uid);
5646
5647        long callingId = Binder.clearCallingIdentity();
5648        try {
5649            boolean sendAdded = false;
5650            Bundle extras = new Bundle(1);
5651
5652            // writer
5653            synchronized (mPackages) {
5654                pkgSetting = mSettings.mPackages.get(packageName);
5655                if (pkgSetting == null) {
5656                    return PackageManager.INSTALL_FAILED_INVALID_URI;
5657                }
5658                if (!pkgSetting.getInstalled(userId)) {
5659                    pkgSetting.setInstalled(true, userId);
5660                    mSettings.writePackageRestrictionsLPr(userId);
5661                    extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
5662                    sendAdded = true;
5663                }
5664            }
5665
5666            if (sendAdded) {
5667                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
5668                        packageName, extras, null, null, new int[] {userId});
5669            }
5670        } finally {
5671            Binder.restoreCallingIdentity(callingId);
5672        }
5673
5674        return PackageManager.INSTALL_SUCCEEDED;
5675    }
5676
5677    @Override
5678    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
5679        mContext.enforceCallingOrSelfPermission(
5680                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5681                "Only package verification agents can verify applications");
5682
5683        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5684        final PackageVerificationResponse response = new PackageVerificationResponse(
5685                verificationCode, Binder.getCallingUid());
5686        msg.arg1 = id;
5687        msg.obj = response;
5688        mHandler.sendMessage(msg);
5689    }
5690
5691    @Override
5692    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
5693            long millisecondsToDelay) {
5694        mContext.enforceCallingOrSelfPermission(
5695                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5696                "Only package verification agents can extend verification timeouts");
5697
5698        final PackageVerificationState state = mPendingVerification.get(id);
5699        final PackageVerificationResponse response = new PackageVerificationResponse(
5700                verificationCodeAtTimeout, Binder.getCallingUid());
5701
5702        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
5703            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
5704        }
5705        if (millisecondsToDelay < 0) {
5706            millisecondsToDelay = 0;
5707        }
5708        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
5709                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
5710            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
5711        }
5712
5713        if ((state != null) && !state.timeoutExtended()) {
5714            state.extendTimeout();
5715
5716            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5717            msg.arg1 = id;
5718            msg.obj = response;
5719            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
5720        }
5721    }
5722
5723    private void broadcastPackageVerified(int verificationId, Uri packageUri,
5724            int verificationCode, UserHandle user) {
5725        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
5726        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
5727        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5728        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
5729        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
5730
5731        mContext.sendBroadcastAsUser(intent, user,
5732                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
5733    }
5734
5735    private ComponentName matchComponentForVerifier(String packageName,
5736            List<ResolveInfo> receivers) {
5737        ActivityInfo targetReceiver = null;
5738
5739        final int NR = receivers.size();
5740        for (int i = 0; i < NR; i++) {
5741            final ResolveInfo info = receivers.get(i);
5742            if (info.activityInfo == null) {
5743                continue;
5744            }
5745
5746            if (packageName.equals(info.activityInfo.packageName)) {
5747                targetReceiver = info.activityInfo;
5748                break;
5749            }
5750        }
5751
5752        if (targetReceiver == null) {
5753            return null;
5754        }
5755
5756        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5757    }
5758
5759    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5760            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5761        if (pkgInfo.verifiers.length == 0) {
5762            return null;
5763        }
5764
5765        final int N = pkgInfo.verifiers.length;
5766        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5767        for (int i = 0; i < N; i++) {
5768            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5769
5770            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5771                    receivers);
5772            if (comp == null) {
5773                continue;
5774            }
5775
5776            final int verifierUid = getUidForVerifier(verifierInfo);
5777            if (verifierUid == -1) {
5778                continue;
5779            }
5780
5781            if (DEBUG_VERIFY) {
5782                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5783                        + " with the correct signature");
5784            }
5785            sufficientVerifiers.add(comp);
5786            verificationState.addSufficientVerifier(verifierUid);
5787        }
5788
5789        return sufficientVerifiers;
5790    }
5791
5792    private int getUidForVerifier(VerifierInfo verifierInfo) {
5793        synchronized (mPackages) {
5794            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5795            if (pkg == null) {
5796                return -1;
5797            } else if (pkg.mSignatures.length != 1) {
5798                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5799                        + " has more than one signature; ignoring");
5800                return -1;
5801            }
5802
5803            /*
5804             * If the public key of the package's signature does not match
5805             * our expected public key, then this is a different package and
5806             * we should skip.
5807             */
5808
5809            final byte[] expectedPublicKey;
5810            try {
5811                final Signature verifierSig = pkg.mSignatures[0];
5812                final PublicKey publicKey = verifierSig.getPublicKey();
5813                expectedPublicKey = publicKey.getEncoded();
5814            } catch (CertificateException e) {
5815                return -1;
5816            }
5817
5818            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5819
5820            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5821                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5822                        + " does not have the expected public key; ignoring");
5823                return -1;
5824            }
5825
5826            return pkg.applicationInfo.uid;
5827        }
5828    }
5829
5830    public void finishPackageInstall(int token) {
5831        enforceSystemOrRoot("Only the system is allowed to finish installs");
5832
5833        if (DEBUG_INSTALL) {
5834            Slog.v(TAG, "BM finishing package install for " + token);
5835        }
5836
5837        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5838        mHandler.sendMessage(msg);
5839    }
5840
5841    /**
5842     * Get the verification agent timeout.
5843     *
5844     * @return verification timeout in milliseconds
5845     */
5846    private long getVerificationTimeout() {
5847        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
5848                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
5849                DEFAULT_VERIFICATION_TIMEOUT);
5850    }
5851
5852    /**
5853     * Get the default verification agent response code.
5854     *
5855     * @return default verification response code
5856     */
5857    private int getDefaultVerificationResponse() {
5858        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5859                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
5860                DEFAULT_VERIFICATION_RESPONSE);
5861    }
5862
5863    /**
5864     * Check whether or not package verification has been enabled.
5865     *
5866     * @return true if verification should be performed
5867     */
5868    private boolean isVerificationEnabled(int flags) {
5869        if (!DEFAULT_VERIFY_ENABLE) {
5870            return false;
5871        }
5872
5873        // Check if installing from ADB
5874        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
5875            // Do not run verification in a test harness environment
5876            if (ActivityManager.isRunningInTestHarness()) {
5877                return false;
5878            }
5879            // Check if the developer does not want package verification for ADB installs
5880            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5881                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
5882                return false;
5883            }
5884        }
5885
5886        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5887                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
5888    }
5889
5890    /**
5891     * Get the "allow unknown sources" setting.
5892     *
5893     * @return the current "allow unknown sources" setting
5894     */
5895    private int getUnknownSourcesSettings() {
5896        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5897                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
5898                -1);
5899    }
5900
5901    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
5902        final int uid = Binder.getCallingUid();
5903        // writer
5904        synchronized (mPackages) {
5905            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5906            if (targetPackageSetting == null) {
5907                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5908            }
5909
5910            PackageSetting installerPackageSetting;
5911            if (installerPackageName != null) {
5912                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5913                if (installerPackageSetting == null) {
5914                    throw new IllegalArgumentException("Unknown installer package: "
5915                            + installerPackageName);
5916                }
5917            } else {
5918                installerPackageSetting = null;
5919            }
5920
5921            Signature[] callerSignature;
5922            Object obj = mSettings.getUserIdLPr(uid);
5923            if (obj != null) {
5924                if (obj instanceof SharedUserSetting) {
5925                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5926                } else if (obj instanceof PackageSetting) {
5927                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5928                } else {
5929                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
5930                }
5931            } else {
5932                throw new SecurityException("Unknown calling uid " + uid);
5933            }
5934
5935            // Verify: can't set installerPackageName to a package that is
5936            // not signed with the same cert as the caller.
5937            if (installerPackageSetting != null) {
5938                if (compareSignatures(callerSignature,
5939                        installerPackageSetting.signatures.mSignatures)
5940                        != PackageManager.SIGNATURE_MATCH) {
5941                    throw new SecurityException(
5942                            "Caller does not have same cert as new installer package "
5943                            + installerPackageName);
5944                }
5945            }
5946
5947            // Verify: if target already has an installer package, it must
5948            // be signed with the same cert as the caller.
5949            if (targetPackageSetting.installerPackageName != null) {
5950                PackageSetting setting = mSettings.mPackages.get(
5951                        targetPackageSetting.installerPackageName);
5952                // If the currently set package isn't valid, then it's always
5953                // okay to change it.
5954                if (setting != null) {
5955                    if (compareSignatures(callerSignature,
5956                            setting.signatures.mSignatures)
5957                            != PackageManager.SIGNATURE_MATCH) {
5958                        throw new SecurityException(
5959                                "Caller does not have same cert as old installer package "
5960                                + targetPackageSetting.installerPackageName);
5961                    }
5962                }
5963            }
5964
5965            // Okay!
5966            targetPackageSetting.installerPackageName = installerPackageName;
5967            scheduleWriteSettingsLocked();
5968        }
5969    }
5970
5971    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
5972        // Queue up an async operation since the package installation may take a little while.
5973        mHandler.post(new Runnable() {
5974            public void run() {
5975                mHandler.removeCallbacks(this);
5976                 // Result object to be returned
5977                PackageInstalledInfo res = new PackageInstalledInfo();
5978                res.returnCode = currentStatus;
5979                res.uid = -1;
5980                res.pkg = null;
5981                res.removedInfo = new PackageRemovedInfo();
5982                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5983                    args.doPreInstall(res.returnCode);
5984                    synchronized (mInstallLock) {
5985                        installPackageLI(args, true, res);
5986                    }
5987                    args.doPostInstall(res.returnCode, res.uid);
5988                }
5989
5990                // A restore should be performed at this point if (a) the install
5991                // succeeded, (b) the operation is not an update, and (c) the new
5992                // package has a backupAgent defined.
5993                final boolean update = res.removedInfo.removedPackage != null;
5994                boolean doRestore = (!update
5995                        && res.pkg != null
5996                        && res.pkg.applicationInfo.backupAgentName != null);
5997
5998                // Set up the post-install work request bookkeeping.  This will be used
5999                // and cleaned up by the post-install event handling regardless of whether
6000                // there's a restore pass performed.  Token values are >= 1.
6001                int token;
6002                if (mNextInstallToken < 0) mNextInstallToken = 1;
6003                token = mNextInstallToken++;
6004
6005                PostInstallData data = new PostInstallData(args, res);
6006                mRunningInstalls.put(token, data);
6007                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
6008
6009                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
6010                    // Pass responsibility to the Backup Manager.  It will perform a
6011                    // restore if appropriate, then pass responsibility back to the
6012                    // Package Manager to run the post-install observer callbacks
6013                    // and broadcasts.
6014                    IBackupManager bm = IBackupManager.Stub.asInterface(
6015                            ServiceManager.getService(Context.BACKUP_SERVICE));
6016                    if (bm != null) {
6017                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
6018                                + " to BM for possible restore");
6019                        try {
6020                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
6021                        } catch (RemoteException e) {
6022                            // can't happen; the backup manager is local
6023                        } catch (Exception e) {
6024                            Slog.e(TAG, "Exception trying to enqueue restore", e);
6025                            doRestore = false;
6026                        }
6027                    } else {
6028                        Slog.e(TAG, "Backup Manager not found!");
6029                        doRestore = false;
6030                    }
6031                }
6032
6033                if (!doRestore) {
6034                    // No restore possible, or the Backup Manager was mysteriously not
6035                    // available -- just fire the post-install work request directly.
6036                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
6037                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6038                    mHandler.sendMessage(msg);
6039                }
6040            }
6041        });
6042    }
6043
6044    private abstract class HandlerParams {
6045        private static final int MAX_RETRIES = 4;
6046
6047        /**
6048         * Number of times startCopy() has been attempted and had a non-fatal
6049         * error.
6050         */
6051        private int mRetries = 0;
6052
6053        /** User handle for the user requesting the information or installation. */
6054        private final UserHandle mUser;
6055
6056        HandlerParams(UserHandle user) {
6057            mUser = user;
6058        }
6059
6060        UserHandle getUser() {
6061            return mUser;
6062        }
6063
6064        final boolean startCopy() {
6065            boolean res;
6066            try {
6067                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
6068
6069                if (++mRetries > MAX_RETRIES) {
6070                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
6071                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
6072                    handleServiceError();
6073                    return false;
6074                } else {
6075                    handleStartCopy();
6076                    res = true;
6077                }
6078            } catch (RemoteException e) {
6079                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
6080                mHandler.sendEmptyMessage(MCS_RECONNECT);
6081                res = false;
6082            }
6083            handleReturnCode();
6084            return res;
6085        }
6086
6087        final void serviceError() {
6088            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
6089            handleServiceError();
6090            handleReturnCode();
6091        }
6092
6093        abstract void handleStartCopy() throws RemoteException;
6094        abstract void handleServiceError();
6095        abstract void handleReturnCode();
6096    }
6097
6098    class MeasureParams extends HandlerParams {
6099        private final PackageStats mStats;
6100        private boolean mSuccess;
6101
6102        private final IPackageStatsObserver mObserver;
6103
6104        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
6105            super(new UserHandle(stats.userHandle));
6106            mObserver = observer;
6107            mStats = stats;
6108        }
6109
6110        @Override
6111        void handleStartCopy() throws RemoteException {
6112            synchronized (mInstallLock) {
6113                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
6114            }
6115
6116            final boolean mounted;
6117            if (Environment.isExternalStorageEmulated()) {
6118                mounted = true;
6119            } else {
6120                final String status = Environment.getExternalStorageState();
6121                mounted = (Environment.MEDIA_MOUNTED.equals(status)
6122                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
6123            }
6124
6125            if (mounted) {
6126                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
6127
6128                final File externalCacheDir = userEnv
6129                        .getExternalStorageAppCacheDirectory(mStats.packageName);
6130                final long externalCacheSize = mContainerService
6131                        .calculateDirectorySize(externalCacheDir.getPath());
6132                mStats.externalCacheSize = externalCacheSize;
6133
6134                final File externalDataDir = userEnv
6135                        .getExternalStorageAppDataDirectory(mStats.packageName);
6136                long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6137                        .getPath());
6138
6139                if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6140                    externalDataSize -= externalCacheSize;
6141                }
6142                mStats.externalDataSize = externalDataSize;
6143
6144                final File externalMediaDir = userEnv
6145                        .getExternalStorageAppMediaDirectory(mStats.packageName);
6146                mStats.externalMediaSize = mContainerService
6147                        .calculateDirectorySize(externalMediaDir.getPath());
6148
6149                final File externalObbDir = userEnv
6150                        .getExternalStorageAppObbDirectory(mStats.packageName);
6151                mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6152                        .getPath());
6153            }
6154        }
6155
6156        @Override
6157        void handleReturnCode() {
6158            if (mObserver != null) {
6159                try {
6160                    mObserver.onGetStatsCompleted(mStats, mSuccess);
6161                } catch (RemoteException e) {
6162                    Slog.i(TAG, "Observer no longer exists.");
6163                }
6164            }
6165        }
6166
6167        @Override
6168        void handleServiceError() {
6169            Slog.e(TAG, "Could not measure application " + mStats.packageName
6170                            + " external storage");
6171        }
6172    }
6173
6174    class InstallParams extends HandlerParams {
6175        final IPackageInstallObserver observer;
6176        int flags;
6177
6178        private final Uri mPackageURI;
6179        final String installerPackageName;
6180        final VerificationParams verificationParams;
6181        private InstallArgs mArgs;
6182        private int mRet;
6183        private File mTempPackage;
6184        final ContainerEncryptionParams encryptionParams;
6185
6186        InstallParams(Uri packageURI,
6187                IPackageInstallObserver observer, int flags,
6188                String installerPackageName, VerificationParams verificationParams,
6189                ContainerEncryptionParams encryptionParams, UserHandle user) {
6190            super(user);
6191            this.mPackageURI = packageURI;
6192            this.flags = flags;
6193            this.observer = observer;
6194            this.installerPackageName = installerPackageName;
6195            this.verificationParams = verificationParams;
6196            this.encryptionParams = encryptionParams;
6197        }
6198
6199        public ManifestDigest getManifestDigest() {
6200            if (verificationParams == null) {
6201                return null;
6202            }
6203            return verificationParams.getManifestDigest();
6204        }
6205
6206        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6207            String packageName = pkgLite.packageName;
6208            int installLocation = pkgLite.installLocation;
6209            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6210            // reader
6211            synchronized (mPackages) {
6212                PackageParser.Package pkg = mPackages.get(packageName);
6213                if (pkg != null) {
6214                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
6215                        // Check for downgrading.
6216                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6217                            if (pkgLite.versionCode < pkg.mVersionCode) {
6218                                Slog.w(TAG, "Can't install update of " + packageName
6219                                        + " update version " + pkgLite.versionCode
6220                                        + " is older than installed version "
6221                                        + pkg.mVersionCode);
6222                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6223                            }
6224                        }
6225                        // Check for updated system application.
6226                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6227                            if (onSd) {
6228                                Slog.w(TAG, "Cannot install update to system app on sdcard");
6229                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6230                            }
6231                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6232                        } else {
6233                            if (onSd) {
6234                                // Install flag overrides everything.
6235                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6236                            }
6237                            // If current upgrade specifies particular preference
6238                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6239                                // Application explicitly specified internal.
6240                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6241                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6242                                // App explictly prefers external. Let policy decide
6243                            } else {
6244                                // Prefer previous location
6245                                if (isExternal(pkg)) {
6246                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6247                                }
6248                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6249                            }
6250                        }
6251                    } else {
6252                        // Invalid install. Return error code
6253                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6254                    }
6255                }
6256            }
6257            // All the special cases have been taken care of.
6258            // Return result based on recommended install location.
6259            if (onSd) {
6260                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6261            }
6262            return pkgLite.recommendedInstallLocation;
6263        }
6264
6265        /*
6266         * Invoke remote method to get package information and install
6267         * location values. Override install location based on default
6268         * policy if needed and then create install arguments based
6269         * on the install location.
6270         */
6271        public void handleStartCopy() throws RemoteException {
6272            int ret = PackageManager.INSTALL_SUCCEEDED;
6273            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6274            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6275            PackageInfoLite pkgLite = null;
6276
6277            if (onInt && onSd) {
6278                // Check if both bits are set.
6279                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6280                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6281            } else {
6282                final long lowThreshold;
6283
6284                final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6285                        .getService(DeviceStorageMonitorService.SERVICE);
6286                if (dsm == null) {
6287                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6288                    lowThreshold = 0L;
6289                } else {
6290                    lowThreshold = dsm.getMemoryLowThreshold();
6291                }
6292
6293                try {
6294                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
6295                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6296
6297                    final File packageFile;
6298                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
6299                        ParcelFileDescriptor out = null;
6300
6301                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6302                        if (mTempPackage != null) {
6303                            try {
6304                                out = ParcelFileDescriptor.open(mTempPackage,
6305                                        ParcelFileDescriptor.MODE_READ_WRITE);
6306                            } catch (FileNotFoundException e) {
6307                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6308                            }
6309
6310                            // Make a temporary file for decryption.
6311                            ret = mContainerService
6312                                    .copyResource(mPackageURI, encryptionParams, out);
6313
6314                            packageFile = mTempPackage;
6315
6316                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
6317                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
6318                                            | FileUtils.S_IROTH,
6319                                    -1, -1);
6320                        } else {
6321                            packageFile = null;
6322                        }
6323                    } else {
6324                        packageFile = new File(mPackageURI.getPath());
6325                    }
6326
6327                    if (packageFile != null) {
6328                        // Remote call to find out default install location
6329                        pkgLite = mContainerService.getMinimalPackageInfo(
6330                                packageFile.getAbsolutePath(), flags, lowThreshold);
6331                    }
6332                } finally {
6333                    mContext.revokeUriPermission(mPackageURI,
6334                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6335                }
6336            }
6337
6338            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6339                int loc = pkgLite.recommendedInstallLocation;
6340                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
6341                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6342                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
6343                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
6344                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
6345                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6346                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6347                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
6348                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6349                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
6350                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
6351                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
6352                } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6353                    ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
6354                } else {
6355                    // Override with defaults if needed.
6356                    loc = installLocationPolicy(pkgLite, flags);
6357                    if (!onSd && !onInt) {
6358                        // Override install location with flags
6359                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6360                            // Set the flag to install on external media.
6361                            flags |= PackageManager.INSTALL_EXTERNAL;
6362                            flags &= ~PackageManager.INSTALL_INTERNAL;
6363                        } else {
6364                            // Make sure the flag for installing on external
6365                            // media is unset
6366                            flags |= PackageManager.INSTALL_INTERNAL;
6367                            flags &= ~PackageManager.INSTALL_EXTERNAL;
6368                        }
6369                    }
6370                }
6371            }
6372
6373            final InstallArgs args = createInstallArgs(this);
6374            mArgs = args;
6375
6376            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6377                 /*
6378                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
6379                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
6380                 */
6381                int userIdentifier = getUser().getIdentifier();
6382                if (userIdentifier == UserHandle.USER_ALL
6383                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
6384                    userIdentifier = UserHandle.USER_OWNER;
6385                }
6386
6387                /*
6388                 * Determine if we have any installed package verifiers. If we
6389                 * do, then we'll defer to them to verify the packages.
6390                 */
6391                final int requiredUid = mRequiredVerifierPackage == null ? -1
6392                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
6393                if (requiredUid != -1 && isVerificationEnabled(flags)) {
6394                    final Intent verification = new Intent(
6395                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6396                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
6397                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6398
6399                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6400                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6401                            0 /* TODO: Which userId? */);
6402
6403                    if (DEBUG_VERIFY) {
6404                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
6405                                + verification.toString() + " with " + pkgLite.verifiers.length
6406                                + " optional verifiers");
6407                    }
6408
6409                    final int verificationId = mPendingVerificationToken++;
6410
6411                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6412
6413                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6414                            installerPackageName);
6415
6416                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6417
6418                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
6419                            pkgLite.packageName);
6420
6421                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
6422                            pkgLite.versionCode);
6423
6424                    if (verificationParams != null) {
6425                        if (verificationParams.getVerificationURI() != null) {
6426                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6427                                 verificationParams.getVerificationURI());
6428                        }
6429                        if (verificationParams.getOriginatingURI() != null) {
6430                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6431                                  verificationParams.getOriginatingURI());
6432                        }
6433                        if (verificationParams.getReferrer() != null) {
6434                            verification.putExtra(Intent.EXTRA_REFERRER,
6435                                  verificationParams.getReferrer());
6436                        }
6437                        if (verificationParams.getOriginatingUid() >= 0) {
6438                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
6439                                  verificationParams.getOriginatingUid());
6440                        }
6441                        if (verificationParams.getInstallerUid() >= 0) {
6442                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
6443                                  verificationParams.getInstallerUid());
6444                        }
6445                    }
6446
6447                    final PackageVerificationState verificationState = new PackageVerificationState(
6448                            requiredUid, args);
6449
6450                    mPendingVerification.append(verificationId, verificationState);
6451
6452                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6453                            receivers, verificationState);
6454
6455                    /*
6456                     * If any sufficient verifiers were listed in the package
6457                     * manifest, attempt to ask them.
6458                     */
6459                    if (sufficientVerifiers != null) {
6460                        final int N = sufficientVerifiers.size();
6461                        if (N == 0) {
6462                            Slog.i(TAG, "Additional verifiers required, but none installed.");
6463                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6464                        } else {
6465                            for (int i = 0; i < N; i++) {
6466                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
6467
6468                                final Intent sufficientIntent = new Intent(verification);
6469                                sufficientIntent.setComponent(verifierComponent);
6470
6471                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
6472                            }
6473                        }
6474                    }
6475
6476                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6477                            mRequiredVerifierPackage, receivers);
6478                    if (ret == PackageManager.INSTALL_SUCCEEDED
6479                            && mRequiredVerifierPackage != null) {
6480                        /*
6481                         * Send the intent to the required verification agent,
6482                         * but only start the verification timeout after the
6483                         * target BroadcastReceivers have run.
6484                         */
6485                        verification.setComponent(requiredVerifierComponent);
6486                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
6487                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6488                                new BroadcastReceiver() {
6489                                    @Override
6490                                    public void onReceive(Context context, Intent intent) {
6491                                        final Message msg = mHandler
6492                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
6493                                        msg.arg1 = verificationId;
6494                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6495                                    }
6496                                }, null, 0, null, null);
6497
6498                        /*
6499                         * We don't want the copy to proceed until verification
6500                         * succeeds, so null out this field.
6501                         */
6502                        mArgs = null;
6503                    }
6504                } else {
6505                    /*
6506                     * No package verification is enabled, so immediately start
6507                     * the remote call to initiate copy using temporary file.
6508                     */
6509                    ret = args.copyApk(mContainerService, true);
6510                }
6511            }
6512
6513            mRet = ret;
6514        }
6515
6516        @Override
6517        void handleReturnCode() {
6518            // If mArgs is null, then MCS couldn't be reached. When it
6519            // reconnects, it will try again to install. At that point, this
6520            // will succeed.
6521            if (mArgs != null) {
6522                processPendingInstall(mArgs, mRet);
6523
6524                if (mTempPackage != null) {
6525                    if (!mTempPackage.delete()) {
6526                        Slog.w(TAG, "Couldn't delete temporary file: " +
6527                                mTempPackage.getAbsolutePath());
6528                    }
6529                }
6530            }
6531        }
6532
6533        @Override
6534        void handleServiceError() {
6535            mArgs = createInstallArgs(this);
6536            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6537        }
6538
6539        public boolean isForwardLocked() {
6540            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6541        }
6542
6543        public Uri getPackageUri() {
6544            if (mTempPackage != null) {
6545                return Uri.fromFile(mTempPackage);
6546            } else {
6547                return mPackageURI;
6548            }
6549        }
6550    }
6551
6552    /*
6553     * Utility class used in movePackage api.
6554     * srcArgs and targetArgs are not set for invalid flags and make
6555     * sure to do null checks when invoking methods on them.
6556     * We probably want to return ErrorPrams for both failed installs
6557     * and moves.
6558     */
6559    class MoveParams extends HandlerParams {
6560        final IPackageMoveObserver observer;
6561        final int flags;
6562        final String packageName;
6563        final InstallArgs srcArgs;
6564        final InstallArgs targetArgs;
6565        int uid;
6566        int mRet;
6567
6568        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
6569                String packageName, String dataDir, int uid, UserHandle user) {
6570            super(user);
6571            this.srcArgs = srcArgs;
6572            this.observer = observer;
6573            this.flags = flags;
6574            this.packageName = packageName;
6575            this.uid = uid;
6576            if (srcArgs != null) {
6577                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
6578                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
6579            } else {
6580                targetArgs = null;
6581            }
6582        }
6583
6584        public void handleStartCopy() throws RemoteException {
6585            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6586            // Check for storage space on target medium
6587            if (!targetArgs.checkFreeStorage(mContainerService)) {
6588                Log.w(TAG, "Insufficient storage to install");
6589                return;
6590            }
6591
6592            mRet = srcArgs.doPreCopy();
6593            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6594                return;
6595            }
6596
6597            mRet = targetArgs.copyApk(mContainerService, false);
6598            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6599                srcArgs.doPostCopy(uid);
6600                return;
6601            }
6602
6603            mRet = srcArgs.doPostCopy(uid);
6604            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6605                return;
6606            }
6607
6608            mRet = targetArgs.doPreInstall(mRet);
6609            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6610                return;
6611            }
6612
6613            if (DEBUG_SD_INSTALL) {
6614                StringBuilder builder = new StringBuilder();
6615                if (srcArgs != null) {
6616                    builder.append("src: ");
6617                    builder.append(srcArgs.getCodePath());
6618                }
6619                if (targetArgs != null) {
6620                    builder.append(" target : ");
6621                    builder.append(targetArgs.getCodePath());
6622                }
6623                Log.i(TAG, builder.toString());
6624            }
6625        }
6626
6627        @Override
6628        void handleReturnCode() {
6629            targetArgs.doPostInstall(mRet, uid);
6630            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6631            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6632                currentStatus = PackageManager.MOVE_SUCCEEDED;
6633            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6634                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6635            }
6636            processPendingMove(this, currentStatus);
6637        }
6638
6639        @Override
6640        void handleServiceError() {
6641            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6642        }
6643    }
6644
6645    /**
6646     * Used during creation of InstallArgs
6647     *
6648     * @param flags package installation flags
6649     * @return true if should be installed on external storage
6650     */
6651    private static boolean installOnSd(int flags) {
6652        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6653            return false;
6654        }
6655        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6656            return true;
6657        }
6658        return false;
6659    }
6660
6661    /**
6662     * Used during creation of InstallArgs
6663     *
6664     * @param flags package installation flags
6665     * @return true if should be installed as forward locked
6666     */
6667    private static boolean installForwardLocked(int flags) {
6668        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6669    }
6670
6671    private InstallArgs createInstallArgs(InstallParams params) {
6672        if (installOnSd(params.flags) || params.isForwardLocked()) {
6673            return new AsecInstallArgs(params);
6674        } else {
6675            return new FileInstallArgs(params);
6676        }
6677    }
6678
6679    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6680            String nativeLibraryPath) {
6681        final boolean isInAsec;
6682        if (installOnSd(flags)) {
6683            /* Apps on SD card are always in ASEC containers. */
6684            isInAsec = true;
6685        } else if (installForwardLocked(flags)
6686                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6687            /*
6688             * Forward-locked apps are only in ASEC containers if they're the
6689             * new style
6690             */
6691            isInAsec = true;
6692        } else {
6693            isInAsec = false;
6694        }
6695
6696        if (isInAsec) {
6697            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
6698                    installOnSd(flags), installForwardLocked(flags));
6699        } else {
6700            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
6701        }
6702    }
6703
6704    // Used by package mover
6705    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
6706        if (installOnSd(flags) || installForwardLocked(flags)) {
6707            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6708                    + AsecInstallArgs.RES_FILE_NAME);
6709            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6710                    installForwardLocked(flags));
6711        } else {
6712            return new FileInstallArgs(packageURI, pkgName, dataDir);
6713        }
6714    }
6715
6716    static abstract class InstallArgs {
6717        final IPackageInstallObserver observer;
6718        // Always refers to PackageManager flags only
6719        final int flags;
6720        final Uri packageURI;
6721        final String installerPackageName;
6722        final ManifestDigest manifestDigest;
6723        final UserHandle user;
6724
6725        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
6726                String installerPackageName, ManifestDigest manifestDigest,
6727                UserHandle user) {
6728            this.packageURI = packageURI;
6729            this.flags = flags;
6730            this.observer = observer;
6731            this.installerPackageName = installerPackageName;
6732            this.manifestDigest = manifestDigest;
6733            this.user = user;
6734        }
6735
6736        abstract void createCopyFile();
6737        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
6738        abstract int doPreInstall(int status);
6739        abstract boolean doRename(int status, String pkgName, String oldCodePath);
6740
6741        abstract int doPostInstall(int status, int uid);
6742        abstract String getCodePath();
6743        abstract String getResourcePath();
6744        abstract String getNativeLibraryPath();
6745        // Need installer lock especially for dex file removal.
6746        abstract void cleanUpResourcesLI();
6747        abstract boolean doPostDeleteLI(boolean delete);
6748        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
6749
6750        /**
6751         * Called before the source arguments are copied. This is used mostly
6752         * for MoveParams when it needs to read the source file to put it in the
6753         * destination.
6754         */
6755        int doPreCopy() {
6756            return PackageManager.INSTALL_SUCCEEDED;
6757        }
6758
6759        /**
6760         * Called after the source arguments are copied. This is used mostly for
6761         * MoveParams when it needs to read the source file to put it in the
6762         * destination.
6763         *
6764         * @return
6765         */
6766        int doPostCopy(int uid) {
6767            return PackageManager.INSTALL_SUCCEEDED;
6768        }
6769
6770        protected boolean isFwdLocked() {
6771            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6772        }
6773
6774        UserHandle getUser() {
6775            return user;
6776        }
6777    }
6778
6779    class FileInstallArgs extends InstallArgs {
6780        File installDir;
6781        String codeFileName;
6782        String resourceFileName;
6783        String libraryPath;
6784        boolean created = false;
6785
6786        FileInstallArgs(InstallParams params) {
6787            super(params.getPackageUri(), params.observer, params.flags,
6788                    params.installerPackageName, params.getManifestDigest(),
6789                    params.getUser());
6790        }
6791
6792        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
6793            super(null, null, 0, null, null, null);
6794            File codeFile = new File(fullCodePath);
6795            installDir = codeFile.getParentFile();
6796            codeFileName = fullCodePath;
6797            resourceFileName = fullResourcePath;
6798            libraryPath = nativeLibraryPath;
6799        }
6800
6801        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
6802            super(packageURI, null, 0, null, null, null);
6803            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6804            String apkName = getNextCodePath(null, pkgName, ".apk");
6805            codeFileName = new File(installDir, apkName + ".apk").getPath();
6806            resourceFileName = getResourcePathFromCodePath();
6807            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
6808        }
6809
6810        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6811            final long lowThreshold;
6812
6813            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6814                    .getService(DeviceStorageMonitorService.SERVICE);
6815            if (dsm == null) {
6816                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6817                lowThreshold = 0L;
6818            } else {
6819                if (dsm.isMemoryLow()) {
6820                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
6821                    return false;
6822                }
6823
6824                lowThreshold = dsm.getMemoryLowThreshold();
6825            }
6826
6827            try {
6828                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6829                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6830                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
6831            } finally {
6832                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6833            }
6834        }
6835
6836        String getCodePath() {
6837            return codeFileName;
6838        }
6839
6840        void createCopyFile() {
6841            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6842            codeFileName = createTempPackageFile(installDir).getPath();
6843            resourceFileName = getResourcePathFromCodePath();
6844            libraryPath = getLibraryPathFromCodePath();
6845            created = true;
6846        }
6847
6848        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
6849            if (temp) {
6850                // Generate temp file name
6851                createCopyFile();
6852            }
6853            // Get a ParcelFileDescriptor to write to the output file
6854            File codeFile = new File(codeFileName);
6855            if (!created) {
6856                try {
6857                    codeFile.createNewFile();
6858                    // Set permissions
6859                    if (!setPermissions()) {
6860                        // Failed setting permissions.
6861                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6862                    }
6863                } catch (IOException e) {
6864                   Slog.w(TAG, "Failed to create file " + codeFile);
6865                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6866                }
6867            }
6868            ParcelFileDescriptor out = null;
6869            try {
6870                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
6871            } catch (FileNotFoundException e) {
6872                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
6873                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6874            }
6875            // Copy the resource now
6876            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6877            try {
6878                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6879                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6880                ret = imcs.copyResource(packageURI, null, out);
6881            } finally {
6882                IoUtils.closeQuietly(out);
6883                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6884            }
6885
6886            if (isFwdLocked()) {
6887                final File destResourceFile = new File(getResourcePath());
6888
6889                // Copy the public files
6890                try {
6891                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6892                } catch (IOException e) {
6893                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6894                            + " forward-locked app.");
6895                    destResourceFile.delete();
6896                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6897                }
6898            }
6899
6900            final File nativeLibraryFile = new File(getNativeLibraryPath());
6901            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
6902            if (nativeLibraryFile.exists()) {
6903                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
6904                nativeLibraryFile.delete();
6905            }
6906            try {
6907                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
6908                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6909                    return copyRet;
6910                }
6911            } catch (IOException e) {
6912                Slog.e(TAG, "Copying native libraries failed", e);
6913                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6914            }
6915
6916            return ret;
6917        }
6918
6919        int doPreInstall(int status) {
6920            if (status != PackageManager.INSTALL_SUCCEEDED) {
6921                cleanUp();
6922            }
6923            return status;
6924        }
6925
6926        boolean doRename(int status, final String pkgName, String oldCodePath) {
6927            if (status != PackageManager.INSTALL_SUCCEEDED) {
6928                cleanUp();
6929                return false;
6930            } else {
6931                final File oldCodeFile = new File(getCodePath());
6932                final File oldResourceFile = new File(getResourcePath());
6933                final File oldLibraryFile = new File(getNativeLibraryPath());
6934
6935                // Rename APK file based on packageName
6936                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
6937                final File newCodeFile = new File(installDir, apkName + ".apk");
6938                if (!oldCodeFile.renameTo(newCodeFile)) {
6939                    return false;
6940                }
6941                codeFileName = newCodeFile.getPath();
6942
6943                // Rename public resource file if it's forward-locked.
6944                final File newResFile = new File(getResourcePathFromCodePath());
6945                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
6946                    return false;
6947                }
6948                resourceFileName = newResFile.getPath();
6949
6950                // Rename library path
6951                final File newLibraryFile = new File(getLibraryPathFromCodePath());
6952                if (newLibraryFile.exists()) {
6953                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
6954                    newLibraryFile.delete();
6955                }
6956                if (!oldLibraryFile.renameTo(newLibraryFile)) {
6957                    Slog.e(TAG, "Cannot rename native library directory "
6958                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
6959                    return false;
6960                }
6961                libraryPath = newLibraryFile.getPath();
6962
6963                // Attempt to set permissions
6964                if (!setPermissions()) {
6965                    return false;
6966                }
6967
6968                if (!SELinux.restorecon(newCodeFile)) {
6969                    return false;
6970                }
6971
6972                return true;
6973            }
6974        }
6975
6976        int doPostInstall(int status, int uid) {
6977            if (status != PackageManager.INSTALL_SUCCEEDED) {
6978                cleanUp();
6979            }
6980            return status;
6981        }
6982
6983        String getResourcePath() {
6984            return resourceFileName;
6985        }
6986
6987        private String getResourcePathFromCodePath() {
6988            final String codePath = getCodePath();
6989            if (isFwdLocked()) {
6990                final StringBuilder sb = new StringBuilder();
6991
6992                sb.append(mAppInstallDir.getPath());
6993                sb.append('/');
6994                sb.append(getApkName(codePath));
6995                sb.append(".zip");
6996
6997                /*
6998                 * If our APK is a temporary file, mark the resource as a
6999                 * temporary file as well so it can be cleaned up after
7000                 * catastrophic failure.
7001                 */
7002                if (codePath.endsWith(".tmp")) {
7003                    sb.append(".tmp");
7004                }
7005
7006                return sb.toString();
7007            } else {
7008                return codePath;
7009            }
7010        }
7011
7012        private String getLibraryPathFromCodePath() {
7013            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
7014        }
7015
7016        @Override
7017        String getNativeLibraryPath() {
7018            if (libraryPath == null) {
7019                libraryPath = getLibraryPathFromCodePath();
7020            }
7021            return libraryPath;
7022        }
7023
7024        private boolean cleanUp() {
7025            boolean ret = true;
7026            String sourceDir = getCodePath();
7027            String publicSourceDir = getResourcePath();
7028            if (sourceDir != null) {
7029                File sourceFile = new File(sourceDir);
7030                if (!sourceFile.exists()) {
7031                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
7032                    ret = false;
7033                }
7034                // Delete application's code and resources
7035                sourceFile.delete();
7036            }
7037            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
7038                final File publicSourceFile = new File(publicSourceDir);
7039                if (!publicSourceFile.exists()) {
7040                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
7041                }
7042                if (publicSourceFile.exists()) {
7043                    publicSourceFile.delete();
7044                }
7045            }
7046
7047            if (libraryPath != null) {
7048                File nativeLibraryFile = new File(libraryPath);
7049                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
7050                if (!nativeLibraryFile.delete()) {
7051                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
7052                }
7053            }
7054
7055            return ret;
7056        }
7057
7058        void cleanUpResourcesLI() {
7059            String sourceDir = getCodePath();
7060            if (cleanUp()) {
7061                int retCode = mInstaller.rmdex(sourceDir);
7062                if (retCode < 0) {
7063                    Slog.w(TAG, "Couldn't remove dex file for package: "
7064                            +  " at location "
7065                            + sourceDir + ", retcode=" + retCode);
7066                    // we don't consider this to be a failure of the core package deletion
7067                }
7068            }
7069        }
7070
7071        private boolean setPermissions() {
7072            // TODO Do this in a more elegant way later on. for now just a hack
7073            if (!isFwdLocked()) {
7074                final int filePermissions =
7075                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
7076                    |FileUtils.S_IROTH;
7077                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
7078                if (retCode != 0) {
7079                    Slog.e(TAG, "Couldn't set new package file permissions for " +
7080                            getCodePath()
7081                            + ". The return code was: " + retCode);
7082                    // TODO Define new internal error
7083                    return false;
7084                }
7085                return true;
7086            }
7087            return true;
7088        }
7089
7090        boolean doPostDeleteLI(boolean delete) {
7091            // XXX err, shouldn't we respect the delete flag?
7092            cleanUpResourcesLI();
7093            return true;
7094        }
7095    }
7096
7097    private boolean isAsecExternal(String cid) {
7098        final String asecPath = PackageHelper.getSdFilesystem(cid);
7099        return !asecPath.startsWith(mAsecInternalPath);
7100    }
7101
7102    /**
7103     * Extract the MountService "container ID" from the full code path of an
7104     * .apk.
7105     */
7106    static String cidFromCodePath(String fullCodePath) {
7107        int eidx = fullCodePath.lastIndexOf("/");
7108        String subStr1 = fullCodePath.substring(0, eidx);
7109        int sidx = subStr1.lastIndexOf("/");
7110        return subStr1.substring(sidx+1, eidx);
7111    }
7112
7113    class AsecInstallArgs extends InstallArgs {
7114        static final String RES_FILE_NAME = "pkg.apk";
7115        static final String PUBLIC_RES_FILE_NAME = "res.zip";
7116
7117        String cid;
7118        String packagePath;
7119        String resourcePath;
7120        String libraryPath;
7121
7122        AsecInstallArgs(InstallParams params) {
7123            super(params.getPackageUri(), params.observer, params.flags,
7124                    params.installerPackageName, params.getManifestDigest(),
7125                    params.getUser());
7126        }
7127
7128        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
7129                boolean isExternal, boolean isForwardLocked) {
7130            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7131                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7132                    null, null, null);
7133            // Extract cid from fullCodePath
7134            int eidx = fullCodePath.lastIndexOf("/");
7135            String subStr1 = fullCodePath.substring(0, eidx);
7136            int sidx = subStr1.lastIndexOf("/");
7137            cid = subStr1.substring(sidx+1, eidx);
7138            setCachePath(subStr1);
7139        }
7140
7141        AsecInstallArgs(String cid, boolean isForwardLocked) {
7142            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
7143                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7144                    null, null, null);
7145            this.cid = cid;
7146            setCachePath(PackageHelper.getSdDir(cid));
7147        }
7148
7149        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
7150            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7151                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7152                    null, null, null);
7153            this.cid = cid;
7154        }
7155
7156        void createCopyFile() {
7157            cid = getTempContainerId();
7158        }
7159
7160        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7161            try {
7162                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7163                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7164                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
7165            } finally {
7166                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7167            }
7168        }
7169
7170        private final boolean isExternal() {
7171            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7172        }
7173
7174        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
7175            if (temp) {
7176                createCopyFile();
7177            } else {
7178                /*
7179                 * Pre-emptively destroy the container since it's destroyed if
7180                 * copying fails due to it existing anyway.
7181                 */
7182                PackageHelper.destroySdDir(cid);
7183            }
7184
7185            final String newCachePath;
7186            try {
7187                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7188                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7189                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7190                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
7191            } finally {
7192                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7193            }
7194
7195            if (newCachePath != null) {
7196                setCachePath(newCachePath);
7197                return PackageManager.INSTALL_SUCCEEDED;
7198            } else {
7199                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7200            }
7201        }
7202
7203        @Override
7204        String getCodePath() {
7205            return packagePath;
7206        }
7207
7208        @Override
7209        String getResourcePath() {
7210            return resourcePath;
7211        }
7212
7213        @Override
7214        String getNativeLibraryPath() {
7215            return libraryPath;
7216        }
7217
7218        int doPreInstall(int status) {
7219            if (status != PackageManager.INSTALL_SUCCEEDED) {
7220                // Destroy container
7221                PackageHelper.destroySdDir(cid);
7222            } else {
7223                boolean mounted = PackageHelper.isContainerMounted(cid);
7224                if (!mounted) {
7225                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7226                            Process.SYSTEM_UID);
7227                    if (newCachePath != null) {
7228                        setCachePath(newCachePath);
7229                    } else {
7230                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7231                    }
7232                }
7233            }
7234            return status;
7235        }
7236
7237        boolean doRename(int status, final String pkgName,
7238                String oldCodePath) {
7239            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
7240            String newCachePath = null;
7241            if (PackageHelper.isContainerMounted(cid)) {
7242                // Unmount the container
7243                if (!PackageHelper.unMountSdDir(cid)) {
7244                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
7245                    return false;
7246                }
7247            }
7248            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7249                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7250                        " which might be stale. Will try to clean up.");
7251                // Clean up the stale container and proceed to recreate.
7252                if (!PackageHelper.destroySdDir(newCacheId)) {
7253                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7254                    return false;
7255                }
7256                // Successfully cleaned up stale container. Try to rename again.
7257                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7258                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7259                            + " inspite of cleaning it up.");
7260                    return false;
7261                }
7262            }
7263            if (!PackageHelper.isContainerMounted(newCacheId)) {
7264                Slog.w(TAG, "Mounting container " + newCacheId);
7265                newCachePath = PackageHelper.mountSdDir(newCacheId,
7266                        getEncryptKey(), Process.SYSTEM_UID);
7267            } else {
7268                newCachePath = PackageHelper.getSdDir(newCacheId);
7269            }
7270            if (newCachePath == null) {
7271                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
7272                return false;
7273            }
7274            Log.i(TAG, "Succesfully renamed " + cid +
7275                    " to " + newCacheId +
7276                    " at new path: " + newCachePath);
7277            cid = newCacheId;
7278            setCachePath(newCachePath);
7279            return true;
7280        }
7281
7282        private void setCachePath(String newCachePath) {
7283            File cachePath = new File(newCachePath);
7284            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7285            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
7286
7287            if (isFwdLocked()) {
7288                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7289            } else {
7290                resourcePath = packagePath;
7291            }
7292        }
7293
7294        int doPostInstall(int status, int uid) {
7295            if (status != PackageManager.INSTALL_SUCCEEDED) {
7296                cleanUp();
7297            } else {
7298                final int groupOwner;
7299                final String protectedFile;
7300                if (isFwdLocked()) {
7301                    groupOwner = UserHandle.getSharedAppGid(uid);
7302                    protectedFile = RES_FILE_NAME;
7303                } else {
7304                    groupOwner = -1;
7305                    protectedFile = null;
7306                }
7307
7308                if (uid < Process.FIRST_APPLICATION_UID
7309                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
7310                    Slog.e(TAG, "Failed to finalize " + cid);
7311                    PackageHelper.destroySdDir(cid);
7312                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7313                }
7314
7315                boolean mounted = PackageHelper.isContainerMounted(cid);
7316                if (!mounted) {
7317                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
7318                }
7319            }
7320            return status;
7321        }
7322
7323        private void cleanUp() {
7324            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7325
7326            // Destroy secure container
7327            PackageHelper.destroySdDir(cid);
7328        }
7329
7330        void cleanUpResourcesLI() {
7331            String sourceFile = getCodePath();
7332            // Remove dex file
7333            int retCode = mInstaller.rmdex(sourceFile);
7334            if (retCode < 0) {
7335                Slog.w(TAG, "Couldn't remove dex file for package: "
7336                        + " at location "
7337                        + sourceFile.toString() + ", retcode=" + retCode);
7338                // we don't consider this to be a failure of the core package deletion
7339            }
7340            cleanUp();
7341        }
7342
7343        boolean matchContainer(String app) {
7344            if (cid.startsWith(app)) {
7345                return true;
7346            }
7347            return false;
7348        }
7349
7350        String getPackageName() {
7351            return getAsecPackageName(cid);
7352        }
7353
7354        boolean doPostDeleteLI(boolean delete) {
7355            boolean ret = false;
7356            boolean mounted = PackageHelper.isContainerMounted(cid);
7357            if (mounted) {
7358                // Unmount first
7359                ret = PackageHelper.unMountSdDir(cid);
7360            }
7361            if (ret && delete) {
7362                cleanUpResourcesLI();
7363            }
7364            return ret;
7365        }
7366
7367        @Override
7368        int doPreCopy() {
7369            if (isFwdLocked()) {
7370                if (!PackageHelper.fixSdPermissions(cid,
7371                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7372                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7373                }
7374            }
7375
7376            return PackageManager.INSTALL_SUCCEEDED;
7377        }
7378
7379        @Override
7380        int doPostCopy(int uid) {
7381            if (isFwdLocked()) {
7382                if (uid < Process.FIRST_APPLICATION_UID
7383                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
7384                                RES_FILE_NAME)) {
7385                    Slog.e(TAG, "Failed to finalize " + cid);
7386                    PackageHelper.destroySdDir(cid);
7387                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7388                }
7389            }
7390
7391            return PackageManager.INSTALL_SUCCEEDED;
7392        }
7393    };
7394
7395    static String getAsecPackageName(String packageCid) {
7396        int idx = packageCid.lastIndexOf("-");
7397        if (idx == -1) {
7398            return packageCid;
7399        }
7400        return packageCid.substring(0, idx);
7401    }
7402
7403    // Utility method used to create code paths based on package name and available index.
7404    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7405        String idxStr = "";
7406        int idx = 1;
7407        // Fall back to default value of idx=1 if prefix is not
7408        // part of oldCodePath
7409        if (oldCodePath != null) {
7410            String subStr = oldCodePath;
7411            // Drop the suffix right away
7412            if (subStr.endsWith(suffix)) {
7413                subStr = subStr.substring(0, subStr.length() - suffix.length());
7414            }
7415            // If oldCodePath already contains prefix find out the
7416            // ending index to either increment or decrement.
7417            int sidx = subStr.lastIndexOf(prefix);
7418            if (sidx != -1) {
7419                subStr = subStr.substring(sidx + prefix.length());
7420                if (subStr != null) {
7421                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7422                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
7423                    }
7424                    try {
7425                        idx = Integer.parseInt(subStr);
7426                        if (idx <= 1) {
7427                            idx++;
7428                        } else {
7429                            idx--;
7430                        }
7431                    } catch(NumberFormatException e) {
7432                    }
7433                }
7434            }
7435        }
7436        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
7437        return prefix + idxStr;
7438    }
7439
7440    // Utility method used to ignore ADD/REMOVE events
7441    // by directory observer.
7442    private static boolean ignoreCodePath(String fullPathStr) {
7443        String apkName = getApkName(fullPathStr);
7444        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
7445        if (idx != -1 && ((idx+1) < apkName.length())) {
7446            // Make sure the package ends with a numeral
7447            String version = apkName.substring(idx+1);
7448            try {
7449                Integer.parseInt(version);
7450                return true;
7451            } catch (NumberFormatException e) {}
7452        }
7453        return false;
7454    }
7455
7456    // Utility method that returns the relative package path with respect
7457    // to the installation directory. Like say for /data/data/com.test-1.apk
7458    // string com.test-1 is returned.
7459    static String getApkName(String codePath) {
7460        if (codePath == null) {
7461            return null;
7462        }
7463        int sidx = codePath.lastIndexOf("/");
7464        int eidx = codePath.lastIndexOf(".");
7465        if (eidx == -1) {
7466            eidx = codePath.length();
7467        } else if (eidx == 0) {
7468            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
7469            return null;
7470        }
7471        return codePath.substring(sidx+1, eidx);
7472    }
7473
7474    class PackageInstalledInfo {
7475        String name;
7476        int uid;
7477        // The set of users that originally had this package installed.
7478        int[] origUsers;
7479        // The set of users that now have this package installed.
7480        int[] newUsers;
7481        PackageParser.Package pkg;
7482        int returnCode;
7483        PackageRemovedInfo removedInfo;
7484    }
7485
7486    /*
7487     * Install a non-existing package.
7488     */
7489    private void installNewPackageLI(PackageParser.Package pkg,
7490            int parseFlags, int scanMode, UserHandle user,
7491            String installerPackageName, PackageInstalledInfo res) {
7492        // Remember this for later, in case we need to rollback this install
7493        String pkgName = pkg.packageName;
7494
7495        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
7496        synchronized(mPackages) {
7497            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7498                // A package with the same name is already installed, though
7499                // it has been renamed to an older name.  The package we
7500                // are trying to install should be installed as an update to
7501                // the existing one, but that has not been requested, so bail.
7502                Slog.w(TAG, "Attempt to re-install " + pkgName
7503                        + " without first uninstalling package running as "
7504                        + mSettings.mRenamedPackages.get(pkgName));
7505                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7506                return;
7507            }
7508            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
7509                // Don't allow installation over an existing package with the same name.
7510                Slog.w(TAG, "Attempt to re-install " + pkgName
7511                        + " without first uninstalling.");
7512                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7513                return;
7514            }
7515        }
7516        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7517        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
7518                System.currentTimeMillis(), user);
7519        if (newPackage == null) {
7520            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7521            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7522                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7523            }
7524        } else {
7525            updateSettingsLI(newPackage,
7526                    installerPackageName,
7527                    res);
7528            // delete the partially installed application. the data directory will have to be
7529            // restored if it was already existing
7530            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7531                // remove package from internal structures.  Note that we want deletePackageX to
7532                // delete the package data and cache directories that it created in
7533                // scanPackageLocked, unless those directories existed before we even tried to
7534                // install.
7535                deletePackageLI(pkgName, UserHandle.ALL, false,
7536                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
7537                                res.removedInfo, true);
7538            }
7539        }
7540    }
7541
7542    private void replacePackageLI(PackageParser.Package pkg,
7543            int parseFlags, int scanMode, UserHandle user,
7544            String installerPackageName, PackageInstalledInfo res) {
7545
7546        PackageParser.Package oldPackage;
7547        String pkgName = pkg.packageName;
7548        // First find the old package info and check signatures
7549        synchronized(mPackages) {
7550            oldPackage = mPackages.get(pkgName);
7551            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
7552                    != PackageManager.SIGNATURE_MATCH) {
7553                Slog.w(TAG, "New package has a different signature: " + pkgName);
7554                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7555                return;
7556            }
7557        }
7558        boolean sysPkg = (isSystemApp(oldPackage));
7559        if (sysPkg) {
7560            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7561                    user, installerPackageName, res);
7562        } else {
7563            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7564                    user, installerPackageName, res);
7565        }
7566    }
7567
7568    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
7569            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7570            String installerPackageName, PackageInstalledInfo res) {
7571        PackageParser.Package newPackage = null;
7572        String pkgName = deletedPackage.packageName;
7573        boolean deletedPkg = true;
7574        boolean updatedSettings = false;
7575
7576        long origUpdateTime;
7577        if (pkg.mExtras != null) {
7578            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7579        } else {
7580            origUpdateTime = 0;
7581        }
7582
7583        // First delete the existing package while retaining the data directory
7584        if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA,
7585                res.removedInfo, true)) {
7586            // If the existing package wasn't successfully deleted
7587            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7588            deletedPkg = false;
7589        } else {
7590            // Successfully deleted the old package. Now proceed with re-installation
7591            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7592            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
7593                    System.currentTimeMillis(), user);
7594            if (newPackage == null) {
7595                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7596                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7597                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7598                }
7599            } else {
7600                updateSettingsLI(newPackage,
7601                        installerPackageName,
7602                        res);
7603                updatedSettings = true;
7604            }
7605        }
7606
7607        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7608            // remove package from internal structures.  Note that we want deletePackageX to
7609            // delete the package data and cache directories that it created in
7610            // scanPackageLocked, unless those directories existed before we even tried to
7611            // install.
7612            if(updatedSettings) {
7613                deletePackageLI(
7614                        pkgName, null, true,
7615                        PackageManager.DELETE_KEEP_DATA,
7616                                res.removedInfo, true);
7617            }
7618            // Since we failed to install the new package we need to restore the old
7619            // package that we deleted.
7620            if(deletedPkg) {
7621                File restoreFile = new File(deletedPackage.mPath);
7622                // Parse old package
7623                boolean oldOnSd = isExternal(deletedPackage);
7624                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
7625                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7626                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
7627                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7628                        | SCAN_UPDATE_TIME;
7629                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
7630                        origUpdateTime, null) == null) {
7631                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7632                    return;
7633                }
7634                // Restore of old package succeeded. Update permissions.
7635                // writer
7636                synchronized (mPackages) {
7637                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
7638                            UPDATE_PERMISSIONS_ALL);
7639                    // can downgrade to reader
7640                    mSettings.writeLPr();
7641                }
7642                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
7643            }
7644        }
7645    }
7646
7647    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
7648            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7649            String installerPackageName, PackageInstalledInfo res) {
7650        PackageParser.Package newPackage = null;
7651        boolean updatedSettings = false;
7652        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
7653                PackageParser.PARSE_IS_SYSTEM;
7654        String packageName = deletedPackage.packageName;
7655        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7656        if (packageName == null) {
7657            Slog.w(TAG, "Attempt to delete null packageName.");
7658            return;
7659        }
7660        PackageParser.Package oldPkg;
7661        PackageSetting oldPkgSetting;
7662        // reader
7663        synchronized (mPackages) {
7664            oldPkg = mPackages.get(packageName);
7665            oldPkgSetting = mSettings.mPackages.get(packageName);
7666            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7667                    (oldPkgSetting == null)) {
7668                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
7669                return;
7670            }
7671        }
7672
7673        killApplication(packageName, oldPkg.applicationInfo.uid);
7674
7675        res.removedInfo.uid = oldPkg.applicationInfo.uid;
7676        res.removedInfo.removedPackage = packageName;
7677        // Remove existing system package
7678        removePackageLI(oldPkgSetting, true);
7679        // writer
7680        synchronized (mPackages) {
7681            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
7682                // We didn't need to disable the .apk as a current system package,
7683                // which means we are replacing another update that is already
7684                // installed.  We need to make sure to delete the older one's .apk.
7685                res.removedInfo.args = createInstallArgs(0,
7686                        deletedPackage.applicationInfo.sourceDir,
7687                        deletedPackage.applicationInfo.publicSourceDir,
7688                        deletedPackage.applicationInfo.nativeLibraryDir);
7689            } else {
7690                res.removedInfo.args = null;
7691            }
7692        }
7693
7694        // Successfully disabled the old package. Now proceed with re-installation
7695        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7696        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7697        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
7698        if (newPackage == null) {
7699            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7700            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7701                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7702            }
7703        } else {
7704            if (newPackage.mExtras != null) {
7705                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7706                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7707                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7708            }
7709            updateSettingsLI(newPackage, installerPackageName, res);
7710            updatedSettings = true;
7711        }
7712
7713        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7714            // Re installation failed. Restore old information
7715            // Remove new pkg information
7716            if (newPackage != null) {
7717                removeInstalledPackageLI(newPackage, true);
7718            }
7719            // Add back the old system package
7720            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
7721            // Restore the old system information in Settings
7722            synchronized(mPackages) {
7723                if (updatedSettings) {
7724                    mSettings.enableSystemPackageLPw(packageName);
7725                    mSettings.setInstallerPackageName(packageName,
7726                            oldPkgSetting.installerPackageName);
7727                }
7728                mSettings.writeLPr();
7729            }
7730        }
7731    }
7732
7733    // Utility method used to move dex files during install.
7734    private int moveDexFilesLI(PackageParser.Package newPackage) {
7735        int retCode;
7736        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7737            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7738            if (retCode != 0) {
7739                if (mNoDexOpt) {
7740                    /*
7741                     * If we're in an engineering build, programs are lazily run
7742                     * through dexopt. If the .dex file doesn't exist yet, it
7743                     * will be created when the program is run next.
7744                     */
7745                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7746                } else {
7747                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7748                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7749                }
7750            }
7751        }
7752        return PackageManager.INSTALL_SUCCEEDED;
7753    }
7754
7755    private void updateSettingsLI(PackageParser.Package newPackage,
7756            String installerPackageName, PackageInstalledInfo res) {
7757        String pkgName = newPackage.packageName;
7758        synchronized (mPackages) {
7759            //write settings. the installStatus will be incomplete at this stage.
7760            //note that the new package setting would have already been
7761            //added to mPackages. It hasn't been persisted yet.
7762            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
7763            mSettings.writeLPr();
7764        }
7765
7766        if ((res.returnCode = moveDexFilesLI(newPackage))
7767                != PackageManager.INSTALL_SUCCEEDED) {
7768            // Discontinue if moving dex files failed.
7769            return;
7770        }
7771
7772        Log.d(TAG, "New package installed in " + newPackage.mPath);
7773
7774        synchronized (mPackages) {
7775            updatePermissionsLPw(newPackage.packageName, newPackage,
7776                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7777                            ? UPDATE_PERMISSIONS_ALL : 0));
7778            res.name = pkgName;
7779            res.uid = newPackage.applicationInfo.uid;
7780            res.pkg = newPackage;
7781            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
7782            mSettings.setInstallerPackageName(pkgName, installerPackageName);
7783            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7784            //to update install status
7785            mSettings.writeLPr();
7786        }
7787    }
7788
7789    private void installPackageLI(InstallArgs args,
7790            boolean newInstall, PackageInstalledInfo res) {
7791        int pFlags = args.flags;
7792        String installerPackageName = args.installerPackageName;
7793        File tmpPackageFile = new File(args.getCodePath());
7794        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
7795        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
7796        boolean replace = false;
7797        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
7798                | (newInstall ? SCAN_NEW_INSTALL : 0);
7799        // Result object to be returned
7800        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7801
7802        // Retrieve PackageSettings and parse package
7803        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7804                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7805                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
7806        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7807        pp.setSeparateProcesses(mSeparateProcesses);
7808        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7809                null, mMetrics, parseFlags);
7810        if (pkg == null) {
7811            res.returnCode = pp.getParseError();
7812            return;
7813        }
7814        String pkgName = res.name = pkg.packageName;
7815        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7816            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7817                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7818                return;
7819            }
7820        }
7821        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7822            res.returnCode = pp.getParseError();
7823            return;
7824        }
7825
7826        /* If the installer passed in a manifest digest, compare it now. */
7827        if (args.manifestDigest != null) {
7828            if (DEBUG_INSTALL) {
7829                final String parsedManifest = pkg.manifestDigest == null ? "null"
7830                        : pkg.manifestDigest.toString();
7831                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7832                        + parsedManifest);
7833            }
7834
7835            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7836                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7837                return;
7838            }
7839        } else if (DEBUG_INSTALL) {
7840            final String parsedManifest = pkg.manifestDigest == null
7841                    ? "null" : pkg.manifestDigest.toString();
7842            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7843        }
7844
7845        // Get rid of all references to package scan path via parser.
7846        pp = null;
7847        String oldCodePath = null;
7848        boolean systemApp = false;
7849        synchronized (mPackages) {
7850            // Check if installing already existing package
7851            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7852                String oldName = mSettings.mRenamedPackages.get(pkgName);
7853                if (pkg.mOriginalPackages != null
7854                        && pkg.mOriginalPackages.contains(oldName)
7855                        && mPackages.containsKey(oldName)) {
7856                    // This package is derived from an original package,
7857                    // and this device has been updating from that original
7858                    // name.  We must continue using the original name, so
7859                    // rename the new package here.
7860                    pkg.setPackageName(oldName);
7861                    pkgName = pkg.packageName;
7862                    replace = true;
7863                } else if (mPackages.containsKey(pkgName)) {
7864                    // This package, under its official name, already exists
7865                    // on the device; we should replace it.
7866                    replace = true;
7867                }
7868            }
7869            PackageSetting ps = mSettings.mPackages.get(pkgName);
7870            if (ps != null) {
7871                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7872                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7873                    systemApp = (ps.pkg.applicationInfo.flags &
7874                            ApplicationInfo.FLAG_SYSTEM) != 0;
7875                }
7876                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7877            }
7878        }
7879
7880        if (systemApp && onSd) {
7881            // Disable updates to system apps on sdcard
7882            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
7883            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7884            return;
7885        }
7886
7887        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7888            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7889            return;
7890        }
7891        // Set application objects path explicitly after the rename
7892        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
7893        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
7894        if (replace) {
7895            replacePackageLI(pkg, parseFlags, scanMode, args.user,
7896                    installerPackageName, res);
7897        } else {
7898            installNewPackageLI(pkg, parseFlags, scanMode, args.user,
7899                    installerPackageName, res);
7900        }
7901        synchronized (mPackages) {
7902            final PackageSetting ps = mSettings.mPackages.get(pkgName);
7903            if (ps != null) {
7904                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7905            }
7906        }
7907    }
7908
7909    private static boolean isForwardLocked(PackageParser.Package pkg) {
7910        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7911    }
7912
7913
7914    private boolean isForwardLocked(PackageSetting ps) {
7915        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7916    }
7917
7918    private static boolean isExternal(PackageParser.Package pkg) {
7919        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7920    }
7921
7922    private static boolean isExternal(PackageSetting ps) {
7923        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7924    }
7925
7926    private static boolean isSystemApp(PackageParser.Package pkg) {
7927        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7928    }
7929
7930    private static boolean isSystemApp(ApplicationInfo info) {
7931        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7932    }
7933
7934    private static boolean isSystemApp(PackageSetting ps) {
7935        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
7936    }
7937
7938    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
7939        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
7940    }
7941
7942    private int packageFlagsToInstallFlags(PackageSetting ps) {
7943        int installFlags = 0;
7944        if (isExternal(ps)) {
7945            installFlags |= PackageManager.INSTALL_EXTERNAL;
7946        }
7947        if (isForwardLocked(ps)) {
7948            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
7949        }
7950        return installFlags;
7951    }
7952
7953    private void deleteTempPackageFiles() {
7954        final FilenameFilter filter = new FilenameFilter() {
7955            public boolean accept(File dir, String name) {
7956                return name.startsWith("vmdl") && name.endsWith(".tmp");
7957            }
7958        };
7959        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
7960        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
7961    }
7962
7963    private static final void deleteTempPackageFilesInDirectory(File directory,
7964            FilenameFilter filter) {
7965        final String[] tmpFilesList = directory.list(filter);
7966        if (tmpFilesList == null) {
7967            return;
7968        }
7969        for (int i = 0; i < tmpFilesList.length; i++) {
7970            final File tmpFile = new File(directory, tmpFilesList[i]);
7971            tmpFile.delete();
7972        }
7973    }
7974
7975    private File createTempPackageFile(File installDir) {
7976        File tmpPackageFile;
7977        try {
7978            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
7979        } catch (IOException e) {
7980            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
7981            return null;
7982        }
7983        try {
7984            FileUtils.setPermissions(
7985                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
7986                    -1, -1);
7987            if (!SELinux.restorecon(tmpPackageFile)) {
7988                return null;
7989            }
7990        } catch (IOException e) {
7991            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
7992            return null;
7993        }
7994        return tmpPackageFile;
7995    }
7996
7997    public void deletePackage(final String packageName,
7998                              final IPackageDeleteObserver observer,
7999                              final int flags) {
8000        mContext.enforceCallingOrSelfPermission(
8001                android.Manifest.permission.DELETE_PACKAGES, null);
8002        // Queue up an async operation since the package deletion may take a little while.
8003        final int uid = Binder.getCallingUid();
8004        mHandler.post(new Runnable() {
8005            public void run() {
8006                mHandler.removeCallbacks(this);
8007                final int returnCode = deletePackageX(packageName, uid, flags);
8008                if (observer != null) {
8009                    try {
8010                        observer.packageDeleted(packageName, returnCode);
8011                    } catch (RemoteException e) {
8012                        Log.i(TAG, "Observer no longer exists.");
8013                    } //end catch
8014                } //end if
8015            } //end run
8016        });
8017    }
8018
8019    /**
8020     *  This method is an internal method that could be get invoked either
8021     *  to delete an installed package or to clean up a failed installation.
8022     *  After deleting an installed package, a broadcast is sent to notify any
8023     *  listeners that the package has been installed. For cleaning up a failed
8024     *  installation, the broadcast is not necessary since the package's
8025     *  installation wouldn't have sent the initial broadcast either
8026     *  The key steps in deleting a package are
8027     *  deleting the package information in internal structures like mPackages,
8028     *  deleting the packages base directories through installd
8029     *  updating mSettings to reflect current status
8030     *  persisting settings for later use
8031     *  sending a broadcast if necessary
8032     */
8033    private int deletePackageX(String packageName, int uid, int flags) {
8034        final PackageRemovedInfo info = new PackageRemovedInfo();
8035        final boolean res;
8036
8037        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
8038                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
8039        try {
8040            if (dpm != null && dpm.packageHasActiveAdmins(packageName, UserHandle.getUserId(uid))) {
8041                Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
8042                return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
8043            }
8044        } catch (RemoteException e) {
8045        }
8046
8047        boolean removedForAllUsers = false;
8048        boolean systemUpdate = false;
8049        synchronized (mInstallLock) {
8050            res = deletePackageLI(packageName,
8051                    (flags & PackageManager.DELETE_ALL_USERS) != 0
8052                            ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)),
8053                    true, flags | REMOVE_CHATTY, info, true);
8054            systemUpdate = info.isRemovedPackageSystemUpdate;
8055            if (res && !systemUpdate && mPackages.get(packageName) == null) {
8056                removedForAllUsers = true;
8057            }
8058        }
8059
8060        if (res) {
8061            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
8062
8063            // If the removed package was a system update, the old system package
8064            // was re-enabled; we need to broadcast this information
8065            if (systemUpdate) {
8066                Bundle extras = new Bundle(1);
8067                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
8068                        ? info.removedAppId : info.uid);
8069                extras.putBoolean(Intent.EXTRA_REPLACING, true);
8070
8071                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
8072                        extras, null, null, null);
8073                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
8074                        extras, null, null, null);
8075                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
8076                        null, packageName, null, null);
8077            }
8078        }
8079        // Force a gc here.
8080        Runtime.getRuntime().gc();
8081        // Delete the resources here after sending the broadcast to let
8082        // other processes clean up before deleting resources.
8083        if (info.args != null) {
8084            synchronized (mInstallLock) {
8085                info.args.doPostDeleteLI(true);
8086            }
8087        }
8088
8089        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
8090    }
8091
8092    static class PackageRemovedInfo {
8093        String removedPackage;
8094        int uid = -1;
8095        int removedAppId = -1;
8096        int[] removedUsers = null;
8097        boolean isRemovedPackageSystemUpdate = false;
8098        // Clean up resources deleted packages.
8099        InstallArgs args = null;
8100
8101        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
8102            Bundle extras = new Bundle(1);
8103            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
8104            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
8105            if (replacing) {
8106                extras.putBoolean(Intent.EXTRA_REPLACING, true);
8107            }
8108            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
8109            if (removedPackage != null) {
8110                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
8111                        extras, null, null, removedUsers);
8112                if (fullRemove && !replacing) {
8113                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
8114                            extras, null, null, removedUsers);
8115                }
8116            }
8117            if (removedAppId >= 0) {
8118                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
8119                        removedUsers);
8120            }
8121        }
8122    }
8123
8124    /*
8125     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
8126     * flag is not set, the data directory is removed as well.
8127     * make sure this flag is set for partially installed apps. If not its meaningless to
8128     * delete a partially installed application.
8129     */
8130    private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo,
8131            int flags, boolean writeSettings) {
8132        String packageName = ps.name;
8133        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
8134        // Retrieve object to delete permissions for shared user later on
8135        final PackageSetting deletedPs;
8136        // reader
8137        synchronized (mPackages) {
8138            deletedPs = mSettings.mPackages.get(packageName);
8139            if (outInfo != null) {
8140                outInfo.removedPackage = packageName;
8141                outInfo.removedUsers = deletedPs != null
8142                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
8143                        : null;
8144            }
8145        }
8146        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8147            removeDataDirsLI(packageName);
8148            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
8149        }
8150        // writer
8151        synchronized (mPackages) {
8152            if (deletedPs != null) {
8153                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8154                    if (outInfo != null) {
8155                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
8156                    }
8157                    if (deletedPs != null) {
8158                        updatePermissionsLPw(deletedPs.name, null, 0);
8159                        if (deletedPs.sharedUser != null) {
8160                            // remove permissions associated with package
8161                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
8162                        }
8163                    }
8164                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
8165                }
8166            }
8167            // can downgrade to reader
8168            if (writeSettings) {
8169                // Save settings now
8170                mSettings.writeLPr();
8171            }
8172        }
8173    }
8174
8175    /*
8176     * Tries to delete system package.
8177     */
8178    private boolean deleteSystemPackageLI(PackageSetting newPs,
8179            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
8180        PackageSetting disabledPs = null;
8181        // Confirm if the system package has been updated
8182        // An updated system app can be deleted. This will also have to restore
8183        // the system pkg from system partition
8184        // reader
8185        synchronized (mPackages) {
8186            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
8187        }
8188        if (disabledPs == null) {
8189            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
8190            return false;
8191        } else {
8192            Log.i(TAG, "Deleting system pkg from data partition");
8193        }
8194        // Delete the updated package
8195        outInfo.isRemovedPackageSystemUpdate = true;
8196        if (disabledPs.versionCode < newPs.versionCode) {
8197            // Delete data for downgrades
8198            flags &= ~PackageManager.DELETE_KEEP_DATA;
8199        } else {
8200            // Preserve data by setting flag
8201            flags |= PackageManager.DELETE_KEEP_DATA;
8202        }
8203        boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo,
8204                writeSettings);
8205        if (!ret) {
8206            return false;
8207        }
8208        // writer
8209        synchronized (mPackages) {
8210            // Reinstate the old system package
8211            mSettings.enableSystemPackageLPw(newPs.name);
8212            // Remove any native libraries from the upgraded package.
8213            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
8214        }
8215        // Install the system package
8216        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
8217                PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
8218                SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
8219
8220        if (newPkg == null) {
8221            Slog.w(TAG, "Failed to restore system package:" + newPs.name
8222                    + " with error:" + mLastScanError);
8223            return false;
8224        }
8225        // writer
8226        synchronized (mPackages) {
8227            updatePermissionsLPw(newPkg.packageName, newPkg,
8228                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
8229            // can downgrade to reader here
8230            if (writeSettings) {
8231                mSettings.writeLPr();
8232            }
8233        }
8234        return true;
8235    }
8236
8237    private boolean deleteInstalledPackageLI(PackageSetting ps,
8238            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8239            boolean writeSettings) {
8240        if (outInfo != null) {
8241            outInfo.uid = ps.appId;
8242        }
8243
8244        // Delete package data from internal structures and also remove data if flag is set
8245        removePackageDataLI(ps, outInfo, flags, writeSettings);
8246
8247        // Delete application code and resources
8248        if (deleteCodeAndResources) {
8249            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
8250                    ps.resourcePathString, ps.nativeLibraryPathString);
8251        }
8252        return true;
8253    }
8254
8255    /*
8256     * This method handles package deletion in general
8257     */
8258    private boolean deletePackageLI(String packageName, UserHandle user,
8259            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8260            boolean writeSettings) {
8261        if (packageName == null) {
8262            Slog.w(TAG, "Attempt to delete null packageName.");
8263            return false;
8264        }
8265        PackageSetting ps;
8266        boolean dataOnly = false;
8267        int removeUser = -1;
8268        int appId = -1;
8269        synchronized (mPackages) {
8270            ps = mSettings.mPackages.get(packageName);
8271            if (ps == null) {
8272                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8273                return false;
8274            }
8275            if (!isSystemApp(ps) && user != null
8276                    && user.getIdentifier() != UserHandle.USER_ALL) {
8277                // The caller is asking that the package only be deleted for a single
8278                // user.  To do this, we just mark its uninstalled state and delete
8279                // its data.
8280                ps.setUserState(user.getIdentifier(),
8281                        COMPONENT_ENABLED_STATE_DEFAULT,
8282                        false, //installed
8283                        true,  //stopped
8284                        true,  //notLaunched
8285                        null, null);
8286                if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8287                    // Other user still have this package installed, so all
8288                    // we need to do is clear this user's data and save that
8289                    // it is uninstalled.
8290                    removeUser = user.getIdentifier();
8291                    appId = ps.appId;
8292                    mSettings.writePackageRestrictionsLPr(removeUser);
8293                } else {
8294                    // We need to set it back to 'installed' so the uninstall
8295                    // broadcasts will be sent correctly.
8296                    ps.setInstalled(true, user.getIdentifier());
8297                }
8298            }
8299        }
8300
8301        if (removeUser >= 0) {
8302            // From above, we determined that we are deleting this only
8303            // for a single user.  Continue the work here.
8304            if (outInfo != null) {
8305                outInfo.removedPackage = packageName;
8306                outInfo.removedAppId = appId;
8307                outInfo.removedUsers = new int[] {removeUser};
8308            }
8309            mInstaller.clearUserData(packageName, removeUser);
8310            schedulePackageCleaning(packageName, removeUser, false);
8311            return true;
8312        }
8313
8314        if (dataOnly) {
8315            // Delete application data first
8316            removePackageDataLI(ps, outInfo, flags, writeSettings);
8317            return true;
8318        }
8319        boolean ret = false;
8320        if (isSystemApp(ps)) {
8321            Log.i(TAG, "Removing system package:" + ps.name);
8322            // When an updated system application is deleted we delete the existing resources as well and
8323            // fall back to existing code in system partition
8324            ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings);
8325        } else {
8326            Log.i(TAG, "Removing non-system package:" + ps.name);
8327            // Kill application pre-emptively especially for apps on sd.
8328            killApplication(packageName, ps.appId);
8329            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo,
8330                    writeSettings);
8331        }
8332        return ret;
8333    }
8334
8335    private final class ClearStorageConnection implements ServiceConnection {
8336        IMediaContainerService mContainerService;
8337
8338        @Override
8339        public void onServiceConnected(ComponentName name, IBinder service) {
8340            synchronized (this) {
8341                mContainerService = IMediaContainerService.Stub.asInterface(service);
8342                notifyAll();
8343            }
8344        }
8345
8346        @Override
8347        public void onServiceDisconnected(ComponentName name) {
8348        }
8349    }
8350
8351    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
8352        final boolean mounted;
8353        if (Environment.isExternalStorageEmulated()) {
8354            mounted = true;
8355        } else {
8356            final String status = Environment.getExternalStorageState();
8357
8358            mounted = status.equals(Environment.MEDIA_MOUNTED)
8359                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
8360        }
8361
8362        if (!mounted) {
8363            return;
8364        }
8365
8366        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
8367        int[] users;
8368        if (userId == UserHandle.USER_ALL) {
8369            users = sUserManager.getUserIds();
8370        } else {
8371            users = new int[] { userId };
8372        }
8373        final ClearStorageConnection conn = new ClearStorageConnection();
8374        if (mContext.bindService(
8375                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_OWNER)) {
8376            try {
8377                for (int curUser : users) {
8378                    long timeout = SystemClock.uptimeMillis() + 5000;
8379                    synchronized (conn) {
8380                        long now = SystemClock.uptimeMillis();
8381                        while (conn.mContainerService == null && now < timeout) {
8382                            try {
8383                                conn.wait(timeout - now);
8384                            } catch (InterruptedException e) {
8385                            }
8386                        }
8387                    }
8388                    if (conn.mContainerService == null) {
8389                        return;
8390                    }
8391
8392                    final UserEnvironment userEnv = new UserEnvironment(curUser);
8393                    final File externalCacheDir = userEnv
8394                            .getExternalStorageAppCacheDirectory(packageName);
8395                    try {
8396                        conn.mContainerService.clearDirectory(externalCacheDir.toString());
8397                    } catch (RemoteException e) {
8398                    }
8399                    if (allData) {
8400                        final File externalDataDir = userEnv
8401                                .getExternalStorageAppDataDirectory(packageName);
8402                        try {
8403                            conn.mContainerService.clearDirectory(externalDataDir.toString());
8404                        } catch (RemoteException e) {
8405                        }
8406                        final File externalMediaDir = userEnv
8407                                .getExternalStorageAppMediaDirectory(packageName);
8408                        try {
8409                            conn.mContainerService.clearDirectory(externalMediaDir.toString());
8410                        } catch (RemoteException e) {
8411                        }
8412                    }
8413                }
8414            } finally {
8415                mContext.unbindService(conn);
8416            }
8417        }
8418    }
8419
8420    @Override
8421    public void clearApplicationUserData(final String packageName,
8422            final IPackageDataObserver observer, final int userId) {
8423        mContext.enforceCallingOrSelfPermission(
8424                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
8425        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
8426        // Queue up an async operation since the package deletion may take a little while.
8427        mHandler.post(new Runnable() {
8428            public void run() {
8429                mHandler.removeCallbacks(this);
8430                final boolean succeeded;
8431                synchronized (mInstallLock) {
8432                    succeeded = clearApplicationUserDataLI(packageName, userId);
8433                }
8434                clearExternalStorageDataSync(packageName, userId, true);
8435                if (succeeded) {
8436                    // invoke DeviceStorageMonitor's update method to clear any notifications
8437                    DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
8438                            ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
8439                    if (dsm != null) {
8440                        dsm.updateMemory();
8441                    }
8442                }
8443                if(observer != null) {
8444                    try {
8445                        observer.onRemoveCompleted(packageName, succeeded);
8446                    } catch (RemoteException e) {
8447                        Log.i(TAG, "Observer no longer exists.");
8448                    }
8449                } //end if observer
8450            } //end run
8451        });
8452    }
8453
8454    private boolean clearApplicationUserDataLI(String packageName, int userId) {
8455        if (packageName == null) {
8456            Slog.w(TAG, "Attempt to delete null packageName.");
8457            return false;
8458        }
8459        PackageParser.Package p;
8460        boolean dataOnly = false;
8461        synchronized (mPackages) {
8462            p = mPackages.get(packageName);
8463            if(p == null) {
8464                dataOnly = true;
8465                PackageSetting ps = mSettings.mPackages.get(packageName);
8466                if((ps == null) || (ps.pkg == null)) {
8467                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8468                    return false;
8469                }
8470                p = ps.pkg;
8471            }
8472        }
8473
8474        if (!dataOnly) {
8475            //need to check this only for fully installed applications
8476            if (p == null) {
8477                Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8478                return false;
8479            }
8480            final ApplicationInfo applicationInfo = p.applicationInfo;
8481            if (applicationInfo == null) {
8482                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8483                return false;
8484            }
8485        }
8486        int retCode = mInstaller.clearUserData(packageName, userId);
8487        if (retCode < 0) {
8488            Slog.w(TAG, "Couldn't remove cache files for package: "
8489                    + packageName);
8490            return false;
8491        }
8492        return true;
8493    }
8494
8495    public void deleteApplicationCacheFiles(final String packageName,
8496            final IPackageDataObserver observer) {
8497        mContext.enforceCallingOrSelfPermission(
8498                android.Manifest.permission.DELETE_CACHE_FILES, null);
8499        // Queue up an async operation since the package deletion may take a little while.
8500        final int userId = UserHandle.getCallingUserId();
8501        mHandler.post(new Runnable() {
8502            public void run() {
8503                mHandler.removeCallbacks(this);
8504                final boolean succeded;
8505                synchronized (mInstallLock) {
8506                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
8507                }
8508                clearExternalStorageDataSync(packageName, userId, false);
8509                if(observer != null) {
8510                    try {
8511                        observer.onRemoveCompleted(packageName, succeded);
8512                    } catch (RemoteException e) {
8513                        Log.i(TAG, "Observer no longer exists.");
8514                    }
8515                } //end if observer
8516            } //end run
8517        });
8518    }
8519
8520    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
8521        if (packageName == null) {
8522            Slog.w(TAG, "Attempt to delete null packageName.");
8523            return false;
8524        }
8525        PackageParser.Package p;
8526        synchronized (mPackages) {
8527            p = mPackages.get(packageName);
8528        }
8529        if (p == null) {
8530            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8531            return false;
8532        }
8533        final ApplicationInfo applicationInfo = p.applicationInfo;
8534        if (applicationInfo == null) {
8535            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8536            return false;
8537        }
8538        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
8539        if (retCode < 0) {
8540            Slog.w(TAG, "Couldn't remove cache files for package: "
8541                       + packageName + " u" + userId);
8542            return false;
8543        }
8544        return true;
8545    }
8546
8547    public void getPackageSizeInfo(final String packageName, int userHandle,
8548            final IPackageStatsObserver observer) {
8549        mContext.enforceCallingOrSelfPermission(
8550                android.Manifest.permission.GET_PACKAGE_SIZE, null);
8551
8552        PackageStats stats = new PackageStats(packageName, userHandle);
8553
8554        /*
8555         * Queue up an async operation since the package measurement may take a
8556         * little while.
8557         */
8558        Message msg = mHandler.obtainMessage(INIT_COPY);
8559        msg.obj = new MeasureParams(stats, observer);
8560        mHandler.sendMessage(msg);
8561    }
8562
8563    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
8564            PackageStats pStats) {
8565        if (packageName == null) {
8566            Slog.w(TAG, "Attempt to get size of null packageName.");
8567            return false;
8568        }
8569        PackageParser.Package p;
8570        boolean dataOnly = false;
8571        String asecPath = null;
8572        synchronized (mPackages) {
8573            p = mPackages.get(packageName);
8574            if(p == null) {
8575                dataOnly = true;
8576                PackageSetting ps = mSettings.mPackages.get(packageName);
8577                if((ps == null) || (ps.pkg == null)) {
8578                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8579                    return false;
8580                }
8581                p = ps.pkg;
8582            }
8583            if (p != null && (isExternal(p) || isForwardLocked(p))) {
8584                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8585                if (secureContainerId != null) {
8586                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8587                }
8588            }
8589        }
8590        String publicSrcDir = null;
8591        if(!dataOnly) {
8592            final ApplicationInfo applicationInfo = p.applicationInfo;
8593            if (applicationInfo == null) {
8594                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8595                return false;
8596            }
8597            if (isForwardLocked(p)) {
8598                publicSrcDir = applicationInfo.publicSourceDir;
8599            }
8600        }
8601        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir,
8602                asecPath, pStats);
8603        if (res < 0) {
8604            return false;
8605        }
8606
8607        // Fix-up for forward-locked applications in ASEC containers.
8608        if (!isExternal(p)) {
8609            pStats.codeSize += pStats.externalCodeSize;
8610            pStats.externalCodeSize = 0L;
8611        }
8612
8613        return true;
8614    }
8615
8616
8617    public void addPackageToPreferred(String packageName) {
8618        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
8619    }
8620
8621    public void removePackageFromPreferred(String packageName) {
8622        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
8623    }
8624
8625    public List<PackageInfo> getPreferredPackages(int flags) {
8626        return new ArrayList<PackageInfo>();
8627    }
8628
8629    private int getUidTargetSdkVersionLockedLPr(int uid) {
8630        Object obj = mSettings.getUserIdLPr(uid);
8631        if (obj instanceof SharedUserSetting) {
8632            final SharedUserSetting sus = (SharedUserSetting) obj;
8633            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
8634            final Iterator<PackageSetting> it = sus.packages.iterator();
8635            while (it.hasNext()) {
8636                final PackageSetting ps = it.next();
8637                if (ps.pkg != null) {
8638                    int v = ps.pkg.applicationInfo.targetSdkVersion;
8639                    if (v < vers) vers = v;
8640                }
8641            }
8642            return vers;
8643        } else if (obj instanceof PackageSetting) {
8644            final PackageSetting ps = (PackageSetting) obj;
8645            if (ps.pkg != null) {
8646                return ps.pkg.applicationInfo.targetSdkVersion;
8647            }
8648        }
8649        return Build.VERSION_CODES.CUR_DEVELOPMENT;
8650    }
8651
8652    public void addPreferredActivity(IntentFilter filter, int match,
8653            ComponentName[] set, ComponentName activity, int userId) {
8654        // writer
8655        int callingUid = Binder.getCallingUid();
8656        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
8657        synchronized (mPackages) {
8658            if (mContext.checkCallingOrSelfPermission(
8659                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8660                    != PackageManager.PERMISSION_GRANTED) {
8661                if (getUidTargetSdkVersionLockedLPr(callingUid)
8662                        < Build.VERSION_CODES.FROYO) {
8663                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
8664                            + callingUid);
8665                    return;
8666                }
8667                mContext.enforceCallingOrSelfPermission(
8668                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8669            }
8670
8671            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
8672            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8673            mSettings.editPreferredActivitiesLPw(userId).addFilter(
8674                    new PreferredActivity(filter, match, set, activity));
8675            mSettings.writePackageRestrictionsLPr(userId);
8676        }
8677    }
8678
8679    public void replacePreferredActivity(IntentFilter filter, int match,
8680            ComponentName[] set, ComponentName activity) {
8681        if (filter.countActions() != 1) {
8682            throw new IllegalArgumentException(
8683                    "replacePreferredActivity expects filter to have only 1 action.");
8684        }
8685        if (filter.countCategories() != 1) {
8686            throw new IllegalArgumentException(
8687                    "replacePreferredActivity expects filter to have only 1 category.");
8688        }
8689        if (filter.countDataAuthorities() != 0
8690                || filter.countDataPaths() != 0
8691                || filter.countDataSchemes() != 0
8692                || filter.countDataTypes() != 0) {
8693            throw new IllegalArgumentException(
8694                    "replacePreferredActivity expects filter to have no data authorities, " +
8695                    "paths, schemes or types.");
8696        }
8697        synchronized (mPackages) {
8698            if (mContext.checkCallingOrSelfPermission(
8699                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8700                    != PackageManager.PERMISSION_GRANTED) {
8701                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8702                        < Build.VERSION_CODES.FROYO) {
8703                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8704                            + Binder.getCallingUid());
8705                    return;
8706                }
8707                mContext.enforceCallingOrSelfPermission(
8708                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8709            }
8710
8711            final int callingUserId = UserHandle.getCallingUserId();
8712            ArrayList<PreferredActivity> removed = null;
8713            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
8714            if (pir != null) {
8715                Iterator<PreferredActivity> it = pir.filterIterator();
8716                String action = filter.getAction(0);
8717                String category = filter.getCategory(0);
8718                while (it.hasNext()) {
8719                    PreferredActivity pa = it.next();
8720                    if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
8721                        if (removed == null) {
8722                            removed = new ArrayList<PreferredActivity>();
8723                        }
8724                        removed.add(pa);
8725                        Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
8726                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8727                    }
8728                }
8729                if (removed != null) {
8730                    for (int i=0; i<removed.size(); i++) {
8731                        PreferredActivity pa = removed.get(i);
8732                        pir.removeFilter(pa);
8733                    }
8734                }
8735            }
8736            addPreferredActivity(filter, match, set, activity, callingUserId);
8737        }
8738    }
8739
8740    public void clearPackagePreferredActivities(String packageName) {
8741        final int uid = Binder.getCallingUid();
8742        // writer
8743        synchronized (mPackages) {
8744            PackageParser.Package pkg = mPackages.get(packageName);
8745            if (pkg == null || pkg.applicationInfo.uid != uid) {
8746                if (mContext.checkCallingOrSelfPermission(
8747                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8748                        != PackageManager.PERMISSION_GRANTED) {
8749                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8750                            < Build.VERSION_CODES.FROYO) {
8751                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8752                                + Binder.getCallingUid());
8753                        return;
8754                    }
8755                    mContext.enforceCallingOrSelfPermission(
8756                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8757                }
8758            }
8759
8760            if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
8761                scheduleWriteSettingsLocked();
8762            }
8763        }
8764    }
8765
8766    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8767    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
8768        ArrayList<PreferredActivity> removed = null;
8769        boolean changed = false;
8770        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
8771            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
8772            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
8773            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
8774                continue;
8775            }
8776            Iterator<PreferredActivity> it = pir.filterIterator();
8777            while (it.hasNext()) {
8778                PreferredActivity pa = it.next();
8779                if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
8780                    if (removed == null) {
8781                        removed = new ArrayList<PreferredActivity>();
8782                    }
8783                    removed.add(pa);
8784                }
8785            }
8786            if (removed != null) {
8787                for (int j=0; j<removed.size(); j++) {
8788                    PreferredActivity pa = removed.get(j);
8789                    pir.removeFilter(pa);
8790                }
8791                changed = true;
8792                mSettings.writePackageRestrictionsLPr(thisUserId);
8793            }
8794        }
8795        return changed;
8796    }
8797
8798    public int getPreferredActivities(List<IntentFilter> outFilters,
8799            List<ComponentName> outActivities, String packageName) {
8800
8801        int num = 0;
8802        final int userId = UserHandle.getCallingUserId();
8803        // reader
8804        synchronized (mPackages) {
8805            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
8806            if (pir != null) {
8807                final Iterator<PreferredActivity> it = pir.filterIterator();
8808                while (it.hasNext()) {
8809                    final PreferredActivity pa = it.next();
8810                    if (packageName == null
8811                            || pa.mPref.mComponent.getPackageName().equals(packageName)) {
8812                        if (outFilters != null) {
8813                            outFilters.add(new IntentFilter(pa));
8814                        }
8815                        if (outActivities != null) {
8816                            outActivities.add(pa.mPref.mComponent);
8817                        }
8818                    }
8819                }
8820            }
8821        }
8822
8823        return num;
8824    }
8825
8826    @Override
8827    public void setApplicationEnabledSetting(String appPackageName,
8828            int newState, int flags, int userId) {
8829        if (!sUserManager.exists(userId)) return;
8830        setEnabledSetting(appPackageName, null, newState, flags, userId);
8831    }
8832
8833    @Override
8834    public void setComponentEnabledSetting(ComponentName componentName,
8835            int newState, int flags, int userId) {
8836        if (!sUserManager.exists(userId)) return;
8837        setEnabledSetting(componentName.getPackageName(),
8838                componentName.getClassName(), newState, flags, userId);
8839    }
8840
8841    private void setEnabledSetting(
8842            final String packageName, String className, int newState, final int flags, int userId) {
8843        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8844              || newState == COMPONENT_ENABLED_STATE_ENABLED
8845              || newState == COMPONENT_ENABLED_STATE_DISABLED
8846              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
8847            throw new IllegalArgumentException("Invalid new component state: "
8848                    + newState);
8849        }
8850        PackageSetting pkgSetting;
8851        final int uid = Binder.getCallingUid();
8852        final int permission = mContext.checkCallingPermission(
8853                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8854        enforceCrossUserPermission(uid, userId, false, "set enabled");
8855        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8856        boolean sendNow = false;
8857        boolean isApp = (className == null);
8858        String componentName = isApp ? packageName : className;
8859        int packageUid = -1;
8860        ArrayList<String> components;
8861
8862        // writer
8863        synchronized (mPackages) {
8864            pkgSetting = mSettings.mPackages.get(packageName);
8865            if (pkgSetting == null) {
8866                if (className == null) {
8867                    throw new IllegalArgumentException(
8868                            "Unknown package: " + packageName);
8869                }
8870                throw new IllegalArgumentException(
8871                        "Unknown component: " + packageName
8872                        + "/" + className);
8873            }
8874            // Allow root and verify that userId is not being specified by a different user
8875            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
8876                throw new SecurityException(
8877                        "Permission Denial: attempt to change component state from pid="
8878                        + Binder.getCallingPid()
8879                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
8880            }
8881            if (className == null) {
8882                // We're dealing with an application/package level state change
8883                if (pkgSetting.getEnabled(userId) == newState) {
8884                    // Nothing to do
8885                    return;
8886                }
8887                pkgSetting.setEnabled(newState, userId);
8888                // pkgSetting.pkg.mSetEnabled = newState;
8889            } else {
8890                // We're dealing with a component level state change
8891                // First, verify that this is a valid class name.
8892                PackageParser.Package pkg = pkgSetting.pkg;
8893                if (pkg == null || !pkg.hasComponentClassName(className)) {
8894                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8895                        throw new IllegalArgumentException("Component class " + className
8896                                + " does not exist in " + packageName);
8897                    } else {
8898                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8899                                + className + " does not exist in " + packageName);
8900                    }
8901                }
8902                switch (newState) {
8903                case COMPONENT_ENABLED_STATE_ENABLED:
8904                    if (!pkgSetting.enableComponentLPw(className, userId)) {
8905                        return;
8906                    }
8907                    break;
8908                case COMPONENT_ENABLED_STATE_DISABLED:
8909                    if (!pkgSetting.disableComponentLPw(className, userId)) {
8910                        return;
8911                    }
8912                    break;
8913                case COMPONENT_ENABLED_STATE_DEFAULT:
8914                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
8915                        return;
8916                    }
8917                    break;
8918                default:
8919                    Slog.e(TAG, "Invalid new component state: " + newState);
8920                    return;
8921                }
8922            }
8923            mSettings.writePackageRestrictionsLPr(userId);
8924            packageUid = UserHandle.getUid(userId, pkgSetting.appId);
8925            components = mPendingBroadcasts.get(packageName);
8926            final boolean newPackage = components == null;
8927            if (newPackage) {
8928                components = new ArrayList<String>();
8929            }
8930            if (!components.contains(componentName)) {
8931                components.add(componentName);
8932            }
8933            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
8934                sendNow = true;
8935                // Purge entry from pending broadcast list if another one exists already
8936                // since we are sending one right away.
8937                mPendingBroadcasts.remove(packageName);
8938            } else {
8939                if (newPackage) {
8940                    mPendingBroadcasts.put(packageName, components);
8941                }
8942                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
8943                    // Schedule a message
8944                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
8945                }
8946            }
8947        }
8948
8949        long callingId = Binder.clearCallingIdentity();
8950        try {
8951            if (sendNow) {
8952                sendPackageChangedBroadcast(packageName,
8953                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
8954            }
8955        } finally {
8956            Binder.restoreCallingIdentity(callingId);
8957        }
8958    }
8959
8960    private void sendPackageChangedBroadcast(String packageName,
8961            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
8962        if (DEBUG_INSTALL)
8963            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
8964                    + componentNames);
8965        Bundle extras = new Bundle(4);
8966        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
8967        String nameList[] = new String[componentNames.size()];
8968        componentNames.toArray(nameList);
8969        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
8970        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
8971        extras.putInt(Intent.EXTRA_UID, packageUid);
8972        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
8973                new int[] {UserHandle.getUserId(packageUid)});
8974    }
8975
8976    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
8977        if (!sUserManager.exists(userId)) return;
8978        final int uid = Binder.getCallingUid();
8979        final int permission = mContext.checkCallingOrSelfPermission(
8980                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8981        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8982        enforceCrossUserPermission(uid, userId, true, "stop package");
8983        // writer
8984        synchronized (mPackages) {
8985            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
8986                    uid, userId)) {
8987                scheduleWritePackageRestrictionsLocked(userId);
8988            }
8989        }
8990    }
8991
8992    public String getInstallerPackageName(String packageName) {
8993        // reader
8994        synchronized (mPackages) {
8995            return mSettings.getInstallerPackageNameLPr(packageName);
8996        }
8997    }
8998
8999    @Override
9000    public int getApplicationEnabledSetting(String packageName, int userId) {
9001        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
9002        int uid = Binder.getCallingUid();
9003        enforceCrossUserPermission(uid, userId, false, "get enabled");
9004        // reader
9005        synchronized (mPackages) {
9006            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
9007        }
9008    }
9009
9010    @Override
9011    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
9012        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
9013        int uid = Binder.getCallingUid();
9014        enforceCrossUserPermission(uid, userId, false, "get component enabled");
9015        // reader
9016        synchronized (mPackages) {
9017            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
9018        }
9019    }
9020
9021    public void enterSafeMode() {
9022        enforceSystemOrRoot("Only the system can request entering safe mode");
9023
9024        if (!mSystemReady) {
9025            mSafeMode = true;
9026        }
9027    }
9028
9029    public void systemReady() {
9030        mSystemReady = true;
9031
9032        // Read the compatibilty setting when the system is ready.
9033        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
9034                mContext.getContentResolver(),
9035                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
9036        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
9037        if (DEBUG_SETTINGS) {
9038            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
9039        }
9040
9041        synchronized (mPackages) {
9042            // Verify that all of the preferred activity components actually
9043            // exist.  It is possible for applications to be updated and at
9044            // that point remove a previously declared activity component that
9045            // had been set as a preferred activity.  We try to clean this up
9046            // the next time we encounter that preferred activity, but it is
9047            // possible for the user flow to never be able to return to that
9048            // situation so here we do a sanity check to make sure we haven't
9049            // left any junk around.
9050            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
9051            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9052                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9053                removed.clear();
9054                for (PreferredActivity pa : pir.filterSet()) {
9055                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
9056                        removed.add(pa);
9057                    }
9058                }
9059                if (removed.size() > 0) {
9060                    for (int j=0; j<removed.size(); j++) {
9061                        PreferredActivity pa = removed.get(i);
9062                        RuntimeException here = new RuntimeException("here");
9063                        here.fillInStackTrace();
9064                        Slog.w(TAG, "Removing dangling preferred activity: "
9065                                + pa.mPref.mComponent, here);
9066                        pir.removeFilter(pa);
9067                    }
9068                    mSettings.writePackageRestrictionsLPr(
9069                            mSettings.mPreferredActivities.keyAt(i));
9070                }
9071            }
9072        }
9073    }
9074
9075    public boolean isSafeMode() {
9076        return mSafeMode;
9077    }
9078
9079    public boolean hasSystemUidErrors() {
9080        return mHasSystemUidErrors;
9081    }
9082
9083    static String arrayToString(int[] array) {
9084        StringBuffer buf = new StringBuffer(128);
9085        buf.append('[');
9086        if (array != null) {
9087            for (int i=0; i<array.length; i++) {
9088                if (i > 0) buf.append(", ");
9089                buf.append(array[i]);
9090            }
9091        }
9092        buf.append(']');
9093        return buf.toString();
9094    }
9095
9096    static class DumpState {
9097        public static final int DUMP_LIBS = 1 << 0;
9098
9099        public static final int DUMP_FEATURES = 1 << 1;
9100
9101        public static final int DUMP_RESOLVERS = 1 << 2;
9102
9103        public static final int DUMP_PERMISSIONS = 1 << 3;
9104
9105        public static final int DUMP_PACKAGES = 1 << 4;
9106
9107        public static final int DUMP_SHARED_USERS = 1 << 5;
9108
9109        public static final int DUMP_MESSAGES = 1 << 6;
9110
9111        public static final int DUMP_PROVIDERS = 1 << 7;
9112
9113        public static final int DUMP_VERIFIERS = 1 << 8;
9114
9115        public static final int DUMP_PREFERRED = 1 << 9;
9116
9117        public static final int DUMP_PREFERRED_XML = 1 << 10;
9118
9119        public static final int OPTION_SHOW_FILTERS = 1 << 0;
9120
9121        private int mTypes;
9122
9123        private int mOptions;
9124
9125        private boolean mTitlePrinted;
9126
9127        private SharedUserSetting mSharedUser;
9128
9129        public boolean isDumping(int type) {
9130            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
9131                return true;
9132            }
9133
9134            return (mTypes & type) != 0;
9135        }
9136
9137        public void setDump(int type) {
9138            mTypes |= type;
9139        }
9140
9141        public boolean isOptionEnabled(int option) {
9142            return (mOptions & option) != 0;
9143        }
9144
9145        public void setOptionEnabled(int option) {
9146            mOptions |= option;
9147        }
9148
9149        public boolean onTitlePrinted() {
9150            final boolean printed = mTitlePrinted;
9151            mTitlePrinted = true;
9152            return printed;
9153        }
9154
9155        public boolean getTitlePrinted() {
9156            return mTitlePrinted;
9157        }
9158
9159        public void setTitlePrinted(boolean enabled) {
9160            mTitlePrinted = enabled;
9161        }
9162
9163        public SharedUserSetting getSharedUser() {
9164            return mSharedUser;
9165        }
9166
9167        public void setSharedUser(SharedUserSetting user) {
9168            mSharedUser = user;
9169        }
9170    }
9171
9172    @Override
9173    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9174        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
9175                != PackageManager.PERMISSION_GRANTED) {
9176            pw.println("Permission Denial: can't dump ActivityManager from from pid="
9177                    + Binder.getCallingPid()
9178                    + ", uid=" + Binder.getCallingUid()
9179                    + " without permission "
9180                    + android.Manifest.permission.DUMP);
9181            return;
9182        }
9183
9184        DumpState dumpState = new DumpState();
9185
9186        String packageName = null;
9187
9188        int opti = 0;
9189        while (opti < args.length) {
9190            String opt = args[opti];
9191            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9192                break;
9193            }
9194            opti++;
9195            if ("-a".equals(opt)) {
9196                // Right now we only know how to print all.
9197            } else if ("-h".equals(opt)) {
9198                pw.println("Package manager dump options:");
9199                pw.println("  [-h] [-f] [cmd] ...");
9200                pw.println("    -f: print details of intent filters");
9201                pw.println("    -h: print this help");
9202                pw.println("  cmd may be one of:");
9203                pw.println("    l[ibraries]: list known shared libraries");
9204                pw.println("    f[ibraries]: list device features");
9205                pw.println("    r[esolvers]: dump intent resolvers");
9206                pw.println("    perm[issions]: dump permissions");
9207                pw.println("    pref[erred]: print preferred package settings");
9208                pw.println("    preferred-xml: print preferred package settings as xml");
9209                pw.println("    prov[iders]: dump content providers");
9210                pw.println("    p[ackages]: dump installed packages");
9211                pw.println("    s[hared-users]: dump shared user IDs");
9212                pw.println("    m[essages]: print collected runtime messages");
9213                pw.println("    v[erifiers]: print package verifier info");
9214                pw.println("    <package.name>: info about given package");
9215                return;
9216            } else if ("-f".equals(opt)) {
9217                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
9218            } else {
9219                pw.println("Unknown argument: " + opt + "; use -h for help");
9220            }
9221        }
9222
9223        // Is the caller requesting to dump a particular piece of data?
9224        if (opti < args.length) {
9225            String cmd = args[opti];
9226            opti++;
9227            // Is this a package name?
9228            if ("android".equals(cmd) || cmd.contains(".")) {
9229                packageName = cmd;
9230            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
9231                dumpState.setDump(DumpState.DUMP_LIBS);
9232            } else if ("f".equals(cmd) || "features".equals(cmd)) {
9233                dumpState.setDump(DumpState.DUMP_FEATURES);
9234            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
9235                dumpState.setDump(DumpState.DUMP_RESOLVERS);
9236            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
9237                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
9238            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
9239                dumpState.setDump(DumpState.DUMP_PREFERRED);
9240            } else if ("preferred-xml".equals(cmd)) {
9241                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
9242            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
9243                dumpState.setDump(DumpState.DUMP_PACKAGES);
9244            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
9245                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
9246            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
9247                dumpState.setDump(DumpState.DUMP_PROVIDERS);
9248            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
9249                dumpState.setDump(DumpState.DUMP_MESSAGES);
9250            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
9251                dumpState.setDump(DumpState.DUMP_VERIFIERS);
9252            }
9253        }
9254
9255        // reader
9256        synchronized (mPackages) {
9257            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
9258                if (dumpState.onTitlePrinted())
9259                    pw.println(" ");
9260                pw.println("Verifiers:");
9261                pw.print("  Required: ");
9262                pw.print(mRequiredVerifierPackage);
9263                pw.print(" (uid=");
9264                pw.print(getPackageUid(mRequiredVerifierPackage, 0));
9265                pw.println(")");
9266            }
9267
9268            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
9269                if (dumpState.onTitlePrinted())
9270                    pw.println(" ");
9271                pw.println("Libraries:");
9272                final Iterator<String> it = mSharedLibraries.keySet().iterator();
9273                while (it.hasNext()) {
9274                    String name = it.next();
9275                    pw.print("  ");
9276                    pw.print(name);
9277                    pw.print(" -> ");
9278                    pw.println(mSharedLibraries.get(name));
9279                }
9280            }
9281
9282            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
9283                if (dumpState.onTitlePrinted())
9284                    pw.println(" ");
9285                pw.println("Features:");
9286                Iterator<String> it = mAvailableFeatures.keySet().iterator();
9287                while (it.hasNext()) {
9288                    String name = it.next();
9289                    pw.print("  ");
9290                    pw.println(name);
9291                }
9292            }
9293
9294            if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
9295                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
9296                        : "Activity Resolver Table:", "  ", packageName,
9297                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9298                    dumpState.setTitlePrinted(true);
9299                }
9300                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
9301                        : "Receiver Resolver Table:", "  ", packageName,
9302                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9303                    dumpState.setTitlePrinted(true);
9304                }
9305                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
9306                        : "Service Resolver Table:", "  ", packageName,
9307                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9308                    dumpState.setTitlePrinted(true);
9309                }
9310            }
9311
9312            if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
9313                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
9314                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
9315                    int user = mSettings.mPreferredActivities.keyAt(i);
9316                    if (pir.dump(pw,
9317                            dumpState.getTitlePrinted()
9318                                ? "\nPreferred Activities User " + user + ":"
9319                                : "Preferred Activities User " + user + ":", "  ",
9320                            packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9321                        dumpState.setTitlePrinted(true);
9322                    }
9323                }
9324            }
9325
9326            if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
9327                pw.flush();
9328                FileOutputStream fout = new FileOutputStream(fd);
9329                BufferedOutputStream str = new BufferedOutputStream(fout);
9330                XmlSerializer serializer = new FastXmlSerializer();
9331                try {
9332                    serializer.setOutput(str, "utf-8");
9333                    serializer.startDocument(null, true);
9334                    serializer.setFeature(
9335                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
9336                    mSettings.writePreferredActivitiesLPr(serializer, 0);
9337                    serializer.endDocument();
9338                    serializer.flush();
9339                } catch (IllegalArgumentException e) {
9340                    pw.println("Failed writing: " + e);
9341                } catch (IllegalStateException e) {
9342                    pw.println("Failed writing: " + e);
9343                } catch (IOException e) {
9344                    pw.println("Failed writing: " + e);
9345                }
9346            }
9347
9348            if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
9349                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
9350            }
9351
9352            if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
9353                boolean printedSomething = false;
9354                for (PackageParser.Provider p : mProvidersByComponent.values()) {
9355                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9356                        continue;
9357                    }
9358                    if (!printedSomething) {
9359                        if (dumpState.onTitlePrinted())
9360                            pw.println(" ");
9361                        pw.println("Registered ContentProviders:");
9362                        printedSomething = true;
9363                    }
9364                    pw.print("  "); pw.print(p.getComponentShortName()); pw.println(":");
9365                    pw.print("    "); pw.println(p.toString());
9366                }
9367                printedSomething = false;
9368                for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
9369                    PackageParser.Provider p = entry.getValue();
9370                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9371                        continue;
9372                    }
9373                    if (!printedSomething) {
9374                        if (dumpState.onTitlePrinted())
9375                            pw.println(" ");
9376                        pw.println("ContentProvider Authorities:");
9377                        printedSomething = true;
9378                    }
9379                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
9380                    pw.print("    "); pw.println(p.toString());
9381                    if (p.info != null && p.info.applicationInfo != null) {
9382                        final String appInfo = p.info.applicationInfo.toString();
9383                        pw.print("      applicationInfo="); pw.println(appInfo);
9384                    }
9385                }
9386            }
9387
9388            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
9389                mSettings.dumpPackagesLPr(pw, packageName, dumpState);
9390            }
9391
9392            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
9393                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
9394            }
9395
9396            if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
9397                if (dumpState.onTitlePrinted())
9398                    pw.println(" ");
9399                mSettings.dumpReadMessagesLPr(pw, dumpState);
9400
9401                pw.println(" ");
9402                pw.println("Package warning messages:");
9403                final File fname = getSettingsProblemFile();
9404                FileInputStream in = null;
9405                try {
9406                    in = new FileInputStream(fname);
9407                    final int avail = in.available();
9408                    final byte[] data = new byte[avail];
9409                    in.read(data);
9410                    pw.print(new String(data));
9411                } catch (FileNotFoundException e) {
9412                } catch (IOException e) {
9413                } finally {
9414                    if (in != null) {
9415                        try {
9416                            in.close();
9417                        } catch (IOException e) {
9418                        }
9419                    }
9420                }
9421            }
9422        }
9423    }
9424
9425    // ------- apps on sdcard specific code -------
9426    static final boolean DEBUG_SD_INSTALL = false;
9427
9428    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9429
9430    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9431
9432    private boolean mMediaMounted = false;
9433
9434    private String getEncryptKey() {
9435        try {
9436            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9437                    SD_ENCRYPTION_KEYSTORE_NAME);
9438            if (sdEncKey == null) {
9439                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9440                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
9441                if (sdEncKey == null) {
9442                    Slog.e(TAG, "Failed to create encryption keys");
9443                    return null;
9444                }
9445            }
9446            return sdEncKey;
9447        } catch (NoSuchAlgorithmException nsae) {
9448            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
9449            return null;
9450        } catch (IOException ioe) {
9451            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
9452            return null;
9453        }
9454
9455    }
9456
9457    /* package */static String getTempContainerId() {
9458        int tmpIdx = 1;
9459        String list[] = PackageHelper.getSecureContainerList();
9460        if (list != null) {
9461            for (final String name : list) {
9462                // Ignore null and non-temporary container entries
9463                if (name == null || !name.startsWith(mTempContainerPrefix)) {
9464                    continue;
9465                }
9466
9467                String subStr = name.substring(mTempContainerPrefix.length());
9468                try {
9469                    int cid = Integer.parseInt(subStr);
9470                    if (cid >= tmpIdx) {
9471                        tmpIdx = cid + 1;
9472                    }
9473                } catch (NumberFormatException e) {
9474                }
9475            }
9476        }
9477        return mTempContainerPrefix + tmpIdx;
9478    }
9479
9480    /*
9481     * Update media status on PackageManager.
9482     */
9483    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9484        int callingUid = Binder.getCallingUid();
9485        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
9486            throw new SecurityException("Media status can only be updated by the system");
9487        }
9488        // reader; this apparently protects mMediaMounted, but should probably
9489        // be a different lock in that case.
9490        synchronized (mPackages) {
9491            Log.i(TAG, "Updating external media status from "
9492                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
9493                    + (mediaStatus ? "mounted" : "unmounted"));
9494            if (DEBUG_SD_INSTALL)
9495                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
9496                        + ", mMediaMounted=" + mMediaMounted);
9497            if (mediaStatus == mMediaMounted) {
9498                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
9499                        : 0, -1);
9500                mHandler.sendMessage(msg);
9501                return;
9502            }
9503            mMediaMounted = mediaStatus;
9504        }
9505        // Queue up an async operation since the package installation may take a
9506        // little while.
9507        mHandler.post(new Runnable() {
9508            public void run() {
9509                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
9510            }
9511        });
9512    }
9513
9514    /**
9515     * Called by MountService when the initial ASECs to scan are available.
9516     * Should block until all the ASEC containers are finished being scanned.
9517     */
9518    public void scanAvailableAsecs() {
9519        updateExternalMediaStatusInner(true, false, false);
9520    }
9521
9522    /*
9523     * Collect information of applications on external media, map them against
9524     * existing containers and update information based on current mount status.
9525     * Please note that we always have to report status if reportStatus has been
9526     * set to true especially when unloading packages.
9527     */
9528    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
9529            boolean externalStorage) {
9530        // Collection of uids
9531        int uidArr[] = null;
9532        // Collection of stale containers
9533        HashSet<String> removeCids = new HashSet<String>();
9534        // Collection of packages on external media with valid containers.
9535        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
9536        // Get list of secure containers.
9537        final String list[] = PackageHelper.getSecureContainerList();
9538        if (list == null || list.length == 0) {
9539            Log.i(TAG, "No secure containers on sdcard");
9540        } else {
9541            // Process list of secure containers and categorize them
9542            // as active or stale based on their package internal state.
9543            int uidList[] = new int[list.length];
9544            int num = 0;
9545            // reader
9546            synchronized (mPackages) {
9547                for (String cid : list) {
9548                    if (DEBUG_SD_INSTALL)
9549                        Log.i(TAG, "Processing container " + cid);
9550                    String pkgName = getAsecPackageName(cid);
9551                    if (pkgName == null) {
9552                        if (DEBUG_SD_INSTALL)
9553                            Log.i(TAG, "Container : " + cid + " stale");
9554                        removeCids.add(cid);
9555                        continue;
9556                    }
9557                    if (DEBUG_SD_INSTALL)
9558                        Log.i(TAG, "Looking for pkg : " + pkgName);
9559
9560                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
9561                    if (ps == null) {
9562                        Log.i(TAG, "Deleting container with no matching settings " + cid);
9563                        removeCids.add(cid);
9564                        continue;
9565                    }
9566
9567                    /*
9568                     * Skip packages that are not external if we're unmounting
9569                     * external storage.
9570                     */
9571                    if (externalStorage && !isMounted && !isExternal(ps)) {
9572                        continue;
9573                    }
9574
9575                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
9576                    // The package status is changed only if the code path
9577                    // matches between settings and the container id.
9578                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
9579                        if (DEBUG_SD_INSTALL) {
9580                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9581                                    + " at code path: " + ps.codePathString);
9582                        }
9583
9584                        // We do have a valid package installed on sdcard
9585                        processCids.put(args, ps.codePathString);
9586                        final int uid = ps.appId;
9587                        if (uid != -1) {
9588                            uidList[num++] = uid;
9589                        }
9590                    } else {
9591                        Log.i(TAG, "Deleting stale container for " + cid);
9592                        removeCids.add(cid);
9593                    }
9594                }
9595            }
9596
9597            if (num > 0) {
9598                // Sort uid list
9599                Arrays.sort(uidList, 0, num);
9600                // Throw away duplicates
9601                uidArr = new int[num];
9602                uidArr[0] = uidList[0];
9603                int di = 0;
9604                for (int i = 1; i < num; i++) {
9605                    if (uidList[i - 1] != uidList[i]) {
9606                        uidArr[di++] = uidList[i];
9607                    }
9608                }
9609            }
9610        }
9611        // Process packages with valid entries.
9612        if (isMounted) {
9613            if (DEBUG_SD_INSTALL)
9614                Log.i(TAG, "Loading packages");
9615            loadMediaPackages(processCids, uidArr, removeCids);
9616            startCleaningPackages();
9617        } else {
9618            if (DEBUG_SD_INSTALL)
9619                Log.i(TAG, "Unloading packages");
9620            unloadMediaPackages(processCids, uidArr, reportStatus);
9621        }
9622    }
9623
9624   private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9625            int uidArr[], IIntentReceiver finishedReceiver) {
9626        int size = pkgList.size();
9627        if (size > 0) {
9628            // Send broadcasts here
9629            Bundle extras = new Bundle();
9630            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9631                    .toArray(new String[size]));
9632            if (uidArr != null) {
9633                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9634            }
9635            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9636                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
9637            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
9638        }
9639    }
9640
9641   /*
9642     * Look at potentially valid container ids from processCids If package
9643     * information doesn't match the one on record or package scanning fails,
9644     * the cid is added to list of removeCids. We currently don't delete stale
9645     * containers.
9646     */
9647   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9648            HashSet<String> removeCids) {
9649        ArrayList<String> pkgList = new ArrayList<String>();
9650        Set<AsecInstallArgs> keys = processCids.keySet();
9651        boolean doGc = false;
9652        for (AsecInstallArgs args : keys) {
9653            String codePath = processCids.get(args);
9654            if (DEBUG_SD_INSTALL)
9655                Log.i(TAG, "Loading container : " + args.cid);
9656            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9657            try {
9658                // Make sure there are no container errors first.
9659                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9660                    Slog.e(TAG, "Failed to mount cid : " + args.cid
9661                            + " when installing from sdcard");
9662                    continue;
9663                }
9664                // Check code path here.
9665                if (codePath == null || !codePath.equals(args.getCodePath())) {
9666                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9667                            + " does not match one in settings " + codePath);
9668                    continue;
9669                }
9670                // Parse package
9671                int parseFlags = mDefParseFlags;
9672                if (args.isExternal()) {
9673                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
9674                }
9675                if (args.isFwdLocked()) {
9676                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9677                }
9678
9679                doGc = true;
9680                synchronized (mInstallLock) {
9681                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
9682                            0, 0, null);
9683                    // Scan the package
9684                    if (pkg != null) {
9685                        /*
9686                         * TODO why is the lock being held? doPostInstall is
9687                         * called in other places without the lock. This needs
9688                         * to be straightened out.
9689                         */
9690                        // writer
9691                        synchronized (mPackages) {
9692                            retCode = PackageManager.INSTALL_SUCCEEDED;
9693                            pkgList.add(pkg.packageName);
9694                            // Post process args
9695                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9696                                    pkg.applicationInfo.uid);
9697                        }
9698                    } else {
9699                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
9700                    }
9701                }
9702
9703            } finally {
9704                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9705                    // Don't destroy container here. Wait till gc clears things
9706                    // up.
9707                    removeCids.add(args.cid);
9708                }
9709            }
9710        }
9711        // writer
9712        synchronized (mPackages) {
9713            // If the platform SDK has changed since the last time we booted,
9714            // we need to re-grant app permission to catch any new ones that
9715            // appear. This is really a hack, and means that apps can in some
9716            // cases get permissions that the user didn't initially explicitly
9717            // allow... it would be nice to have some better way to handle
9718            // this situation.
9719            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9720            if (regrantPermissions)
9721                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9722                        + mSdkVersion + "; regranting permissions for external storage");
9723            mSettings.mExternalSdkPlatform = mSdkVersion;
9724
9725            // Make sure group IDs have been assigned, and any permission
9726            // changes in other apps are accounted for
9727            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9728                    | (regrantPermissions
9729                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9730                            : 0));
9731            // can downgrade to reader
9732            // Persist settings
9733            mSettings.writeLPr();
9734        }
9735        // Send a broadcast to let everyone know we are done processing
9736        if (pkgList.size() > 0) {
9737            sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9738        }
9739        // Force gc to avoid any stale parser references that we might have.
9740        if (doGc) {
9741            Runtime.getRuntime().gc();
9742        }
9743        // List stale containers and destroy stale temporary containers.
9744        if (removeCids != null) {
9745            for (String cid : removeCids) {
9746                if (cid.startsWith(mTempContainerPrefix)) {
9747                    Log.i(TAG, "Destroying stale temporary container " + cid);
9748                    PackageHelper.destroySdDir(cid);
9749                } else {
9750                    Log.w(TAG, "Container " + cid + " is stale");
9751               }
9752           }
9753        }
9754    }
9755
9756   /*
9757     * Utility method to unload a list of specified containers
9758     */
9759    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
9760        // Just unmount all valid containers.
9761        for (AsecInstallArgs arg : cidArgs) {
9762            synchronized (mInstallLock) {
9763                arg.doPostDeleteLI(false);
9764           }
9765       }
9766   }
9767
9768    /*
9769     * Unload packages mounted on external media. This involves deleting package
9770     * data from internal structures, sending broadcasts about diabled packages,
9771     * gc'ing to free up references, unmounting all secure containers
9772     * corresponding to packages on external media, and posting a
9773     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9774     * that we always have to post this message if status has been requested no
9775     * matter what.
9776     */
9777    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9778            final boolean reportStatus) {
9779        if (DEBUG_SD_INSTALL)
9780            Log.i(TAG, "unloading media packages");
9781        ArrayList<String> pkgList = new ArrayList<String>();
9782        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9783        final Set<AsecInstallArgs> keys = processCids.keySet();
9784        for (AsecInstallArgs args : keys) {
9785            String pkgName = args.getPackageName();
9786            if (DEBUG_SD_INSTALL)
9787                Log.i(TAG, "Trying to unload pkg : " + pkgName);
9788            // Delete package internally
9789            PackageRemovedInfo outInfo = new PackageRemovedInfo();
9790            synchronized (mInstallLock) {
9791                boolean res = deletePackageLI(pkgName, null, false,
9792                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
9793                if (res) {
9794                    pkgList.add(pkgName);
9795                } else {
9796                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9797                    failedList.add(args);
9798                }
9799            }
9800        }
9801
9802        // reader
9803        synchronized (mPackages) {
9804            // We didn't update the settings after removing each package;
9805            // write them now for all packages.
9806            mSettings.writeLPr();
9807        }
9808
9809        // We have to absolutely send UPDATED_MEDIA_STATUS only
9810        // after confirming that all the receivers processed the ordered
9811        // broadcast when packages get disabled, force a gc to clean things up.
9812        // and unload all the containers.
9813        if (pkgList.size() > 0) {
9814            sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9815                public void performReceive(Intent intent, int resultCode, String data,
9816                        Bundle extras, boolean ordered, boolean sticky,
9817                        int sendingUser) throws RemoteException {
9818                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9819                            reportStatus ? 1 : 0, 1, keys);
9820                    mHandler.sendMessage(msg);
9821                }
9822            });
9823        } else {
9824            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9825                    keys);
9826            mHandler.sendMessage(msg);
9827        }
9828    }
9829
9830    /** Binder call */
9831    @Override
9832    public void movePackage(final String packageName, final IPackageMoveObserver observer,
9833            final int flags) {
9834        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
9835        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
9836        int returnCode = PackageManager.MOVE_SUCCEEDED;
9837        int currFlags = 0;
9838        int newFlags = 0;
9839        // reader
9840        synchronized (mPackages) {
9841            PackageParser.Package pkg = mPackages.get(packageName);
9842            if (pkg == null) {
9843                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9844            } else {
9845                // Disable moving fwd locked apps and system packages
9846                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9847                    Slog.w(TAG, "Cannot move system application");
9848                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9849                } else if (pkg.mOperationPending) {
9850                    Slog.w(TAG, "Attempt to move package which has pending operations");
9851                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9852                } else {
9853                    // Find install location first
9854                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9855                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9856                        Slog.w(TAG, "Ambigous flags specified for move location.");
9857                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9858                    } else {
9859                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9860                                : PackageManager.INSTALL_INTERNAL;
9861                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9862                                : PackageManager.INSTALL_INTERNAL;
9863
9864                        if (newFlags == currFlags) {
9865                            Slog.w(TAG, "No move required. Trying to move to same location");
9866                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9867                        } else {
9868                            if (isForwardLocked(pkg)) {
9869                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9870                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9871                            }
9872                        }
9873                    }
9874                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9875                        pkg.mOperationPending = true;
9876                    }
9877                }
9878            }
9879
9880            /*
9881             * TODO this next block probably shouldn't be inside the lock. We
9882             * can't guarantee these won't change after this is fired off
9883             * anyway.
9884             */
9885            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9886                processPendingMove(new MoveParams(null, observer, 0, packageName,
9887                        null, -1, user),
9888                        returnCode);
9889            } else {
9890                Message msg = mHandler.obtainMessage(INIT_COPY);
9891                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9892                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9893                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9894                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
9895                msg.obj = mp;
9896                mHandler.sendMessage(msg);
9897            }
9898        }
9899    }
9900
9901    private void processPendingMove(final MoveParams mp, final int currentStatus) {
9902        // Queue up an async operation since the package deletion may take a
9903        // little while.
9904        mHandler.post(new Runnable() {
9905            public void run() {
9906                // TODO fix this; this does nothing.
9907                mHandler.removeCallbacks(this);
9908                int returnCode = currentStatus;
9909                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9910                    int uidArr[] = null;
9911                    ArrayList<String> pkgList = null;
9912                    synchronized (mPackages) {
9913                        PackageParser.Package pkg = mPackages.get(mp.packageName);
9914                        if (pkg == null) {
9915                            Slog.w(TAG, " Package " + mp.packageName
9916                                    + " doesn't exist. Aborting move");
9917                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9918                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9919                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
9920                                    + mp.srcArgs.getCodePath() + " to "
9921                                    + pkg.applicationInfo.sourceDir
9922                                    + " Aborting move and returning error");
9923                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9924                        } else {
9925                            uidArr = new int[] {
9926                                pkg.applicationInfo.uid
9927                            };
9928                            pkgList = new ArrayList<String>();
9929                            pkgList.add(mp.packageName);
9930                        }
9931                    }
9932                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9933                        // Send resources unavailable broadcast
9934                        sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
9935                        // Update package code and resource paths
9936                        synchronized (mInstallLock) {
9937                            synchronized (mPackages) {
9938                                PackageParser.Package pkg = mPackages.get(mp.packageName);
9939                                // Recheck for package again.
9940                                if (pkg == null) {
9941                                    Slog.w(TAG, " Package " + mp.packageName
9942                                            + " doesn't exist. Aborting move");
9943                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9944                                } else if (!mp.srcArgs.getCodePath().equals(
9945                                        pkg.applicationInfo.sourceDir)) {
9946                                    Slog.w(TAG, "Package " + mp.packageName
9947                                            + " code path changed from " + mp.srcArgs.getCodePath()
9948                                            + " to " + pkg.applicationInfo.sourceDir
9949                                            + " Aborting move and returning error");
9950                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9951                                } else {
9952                                    final String oldCodePath = pkg.mPath;
9953                                    final String newCodePath = mp.targetArgs.getCodePath();
9954                                    final String newResPath = mp.targetArgs.getResourcePath();
9955                                    final String newNativePath = mp.targetArgs
9956                                            .getNativeLibraryPath();
9957
9958                                    final File newNativeDir = new File(newNativePath);
9959
9960                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
9961                                        synchronized (mInstallLock) {
9962                                            if (mInstaller.linkNativeLibraryDirectory(
9963                                                    pkg.applicationInfo.dataDir, newNativePath) < 0) {
9964                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9965                                            }
9966                                        }
9967                                        NativeLibraryHelper.copyNativeBinariesIfNeededLI(new File(
9968                                                newCodePath), newNativeDir);
9969                                    } else {
9970                                        synchronized (mInstallLock) {
9971                                            if (mInstaller.linkNativeLibraryDirectory(
9972                                                    pkg.applicationInfo.dataDir, newNativePath) < 0) {
9973                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9974                                            }
9975                                        }
9976                                    }
9977
9978                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9979                                        pkg.mPath = newCodePath;
9980                                        // Move dex files around
9981                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
9982                                            // Moving of dex files failed. Set
9983                                            // error code and abort move.
9984                                            pkg.mPath = pkg.mScanPath;
9985                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9986                                        }
9987                                    }
9988
9989                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9990                                        pkg.mScanPath = newCodePath;
9991                                        pkg.applicationInfo.sourceDir = newCodePath;
9992                                        pkg.applicationInfo.publicSourceDir = newResPath;
9993                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
9994                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
9995                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
9996                                        ps.codePathString = ps.codePath.getPath();
9997                                        ps.resourcePath = new File(
9998                                                pkg.applicationInfo.publicSourceDir);
9999                                        ps.resourcePathString = ps.resourcePath.getPath();
10000                                        ps.nativeLibraryPathString = newNativePath;
10001                                        // Set the application info flag
10002                                        // correctly.
10003                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10004                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10005                                        } else {
10006                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10007                                        }
10008                                        ps.setFlags(pkg.applicationInfo.flags);
10009                                        mAppDirs.remove(oldCodePath);
10010                                        mAppDirs.put(newCodePath, pkg);
10011                                        // Persist settings
10012                                        mSettings.writeLPr();
10013                                    }
10014                                }
10015                            }
10016                        }
10017                        // Send resources available broadcast
10018                        sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
10019                    }
10020                }
10021                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
10022                    // Clean up failed installation
10023                    if (mp.targetArgs != null) {
10024                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
10025                                -1);
10026                    }
10027                } else {
10028                    // Force a gc to clear things up.
10029                    Runtime.getRuntime().gc();
10030                    // Delete older code
10031                    synchronized (mInstallLock) {
10032                        mp.srcArgs.doPostDeleteLI(true);
10033                    }
10034                }
10035
10036                // Allow more operations on this file if we didn't fail because
10037                // an operation was already pending for this package.
10038                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10039                    synchronized (mPackages) {
10040                        PackageParser.Package pkg = mPackages.get(mp.packageName);
10041                        if (pkg != null) {
10042                            pkg.mOperationPending = false;
10043                       }
10044                   }
10045                }
10046
10047                IPackageMoveObserver observer = mp.observer;
10048                if (observer != null) {
10049                    try {
10050                        observer.packageMoved(mp.packageName, returnCode);
10051                    } catch (RemoteException e) {
10052                        Log.i(TAG, "Observer no longer exists.");
10053                    }
10054                }
10055            }
10056        });
10057    }
10058
10059    public boolean setInstallLocation(int loc) {
10060        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
10061                null);
10062        if (getInstallLocation() == loc) {
10063            return true;
10064        }
10065        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
10066                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10067            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
10068                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
10069            return true;
10070        }
10071        return false;
10072   }
10073
10074    public int getInstallLocation() {
10075        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10076                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
10077                PackageHelper.APP_INSTALL_AUTO);
10078    }
10079
10080    /** Called by UserManagerService */
10081    void cleanUpUserLILPw(int userHandle) {
10082        if (mDirtyUsers.remove(userHandle));
10083        mSettings.removeUserLPr(userHandle);
10084        if (mInstaller != null) {
10085            // Technically, we shouldn't be doing this with the package lock
10086            // held.  However, this is very rare, and there is already so much
10087            // other disk I/O going on, that we'll let it slide for now.
10088            mInstaller.removeUserDataDirs(userHandle);
10089        }
10090    }
10091
10092    /** Called by UserManagerService */
10093    void createNewUserLILPw(int userHandle, File path) {
10094        if (mInstaller != null) {
10095            mSettings.createNewUserLILPw(mInstaller, userHandle, path);
10096        }
10097    }
10098
10099    @Override
10100    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
10101        mContext.enforceCallingOrSelfPermission(
10102                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10103                "Only package verification agents can read the verifier device identity");
10104
10105        synchronized (mPackages) {
10106            return mSettings.getVerifierDeviceIdentityLPw();
10107        }
10108    }
10109
10110    @Override
10111    public void setPermissionEnforced(String permission, boolean enforced) {
10112        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
10113        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10114            synchronized (mPackages) {
10115                if (mSettings.mReadExternalStorageEnforced == null
10116                        || mSettings.mReadExternalStorageEnforced != enforced) {
10117                    mSettings.mReadExternalStorageEnforced = enforced;
10118                    mSettings.writeLPr();
10119
10120                    // kill any non-foreground processes so we restart them and
10121                    // grant/revoke the GID.
10122                    final IActivityManager am = ActivityManagerNative.getDefault();
10123                    if (am != null) {
10124                        final long token = Binder.clearCallingIdentity();
10125                        try {
10126                            am.killProcessesBelowForeground("setPermissionEnforcement");
10127                        } catch (RemoteException e) {
10128                        } finally {
10129                            Binder.restoreCallingIdentity(token);
10130                        }
10131                    }
10132                }
10133            }
10134        } else {
10135            throw new IllegalArgumentException("No selective enforcement for " + permission);
10136        }
10137    }
10138
10139    @Override
10140    public boolean isPermissionEnforced(String permission) {
10141        final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
10142        synchronized (mPackages) {
10143            return isPermissionEnforcedLocked(permission, enforcedDefault);
10144        }
10145    }
10146
10147    /**
10148     * Check if given permission should be enforced by default. Should always be
10149     * called outside of {@link #mPackages} lock.
10150     */
10151    private boolean isPermissionEnforcedDefault(String permission) {
10152        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10153            return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10154                    android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
10155                    != 0;
10156        } else {
10157            return true;
10158        }
10159    }
10160
10161    /**
10162     * Check if user has requested that given permission be enforced, using
10163     * given default if undefined.
10164     */
10165    private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
10166        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10167            if (mSettings.mReadExternalStorageEnforced != null) {
10168                return mSettings.mReadExternalStorageEnforced;
10169            } else {
10170                // User hasn't defined; fall back to secure default
10171                return enforcedDefault;
10172            }
10173        } else {
10174            return true;
10175        }
10176    }
10177
10178    public boolean isStorageLow() {
10179        final long token = Binder.clearCallingIdentity();
10180        try {
10181            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
10182                    .getService(DeviceStorageMonitorService.SERVICE);
10183            return dsm.isMemoryLow();
10184        } finally {
10185            Binder.restoreCallingIdentity(token);
10186        }
10187    }
10188}
10189