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