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