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