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