PackageManagerService.java revision 151ec4c9f8ca34625733730a4551a23eb97cda23
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(ps, 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 | ApplicationInfo.FLAG_IS_DATA_ONLY;
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    @Override
2895    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead,
2896            int userId) {
2897        final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2898        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2899        final String[] keys;
2900
2901        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
2902
2903        // writer
2904        synchronized (mPackages) {
2905            if (listUninstalled) {
2906                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2907            } else {
2908                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2909            }
2910
2911            Arrays.sort(keys);
2912            int i = getContinuationPoint(keys, lastRead);
2913            final int N = keys.length;
2914
2915            while (i < N) {
2916                final String packageName = keys[i++];
2917
2918                PackageInfo pi = null;
2919                if (listUninstalled) {
2920                    final PackageSetting ps = mSettings.mPackages.get(packageName);
2921                    if (ps != null) {
2922                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
2923                    }
2924                } else {
2925                    final PackageParser.Package p = mPackages.get(packageName);
2926                    if (p != null) {
2927                        pi = generatePackageInfo(p, flags, userId);
2928                    }
2929                }
2930
2931                if (pi != null && list.append(pi)) {
2932                    break;
2933                }
2934            }
2935
2936            if (i == N) {
2937                list.setLastSlice(true);
2938            }
2939        }
2940
2941        return list;
2942    }
2943
2944    @Override
2945    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
2946            String lastRead, int userId) {
2947        if (!sUserManager.exists(userId)) return null;
2948        final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2949        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2950        final String[] keys;
2951
2952        // writer
2953        synchronized (mPackages) {
2954            if (listUninstalled) {
2955                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2956            } else {
2957                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2958            }
2959
2960            Arrays.sort(keys);
2961            int i = getContinuationPoint(keys, lastRead);
2962            final int N = keys.length;
2963
2964            while (i < N) {
2965                final String packageName = keys[i++];
2966
2967                ApplicationInfo ai = null;
2968                final PackageSetting ps = mSettings.mPackages.get(packageName);
2969                if (listUninstalled) {
2970                    if (ps != null) {
2971                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
2972                    }
2973                } else {
2974                    final PackageParser.Package p = mPackages.get(packageName);
2975                    if (p != null && ps != null) {
2976                        ai = PackageParser.generateApplicationInfo(p, flags,
2977                                ps.readUserState(userId), userId);
2978                    }
2979                }
2980
2981                if (ai != null && list.append(ai)) {
2982                    break;
2983                }
2984            }
2985
2986            if (i == N) {
2987                list.setLastSlice(true);
2988            }
2989        }
2990
2991        return list;
2992    }
2993
2994    public List<ApplicationInfo> getPersistentApplications(int flags) {
2995        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2996
2997        // reader
2998        synchronized (mPackages) {
2999            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3000            final int userId = UserHandle.getCallingUserId();
3001            while (i.hasNext()) {
3002                final PackageParser.Package p = i.next();
3003                if (p.applicationInfo != null
3004                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3005                        && (!mSafeMode || isSystemApp(p))) {
3006                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3007                    if (ps != null) {
3008                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3009                                ps.readUserState(userId), userId);
3010                        if (ai != null) {
3011                            finalList.add(ai);
3012                        }
3013                    }
3014                }
3015            }
3016        }
3017
3018        return finalList;
3019    }
3020
3021    @Override
3022    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3023        if (!sUserManager.exists(userId)) return null;
3024        // reader
3025        synchronized (mPackages) {
3026            final PackageParser.Provider provider = mProviders.get(name);
3027            PackageSetting ps = provider != null
3028                    ? mSettings.mPackages.get(provider.owner.packageName)
3029                    : null;
3030            return ps != null
3031                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3032                    && (!mSafeMode || (provider.info.applicationInfo.flags
3033                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3034                    ? PackageParser.generateProviderInfo(provider, flags,
3035                            ps.readUserState(userId), userId)
3036                    : null;
3037        }
3038    }
3039
3040    /**
3041     * @deprecated
3042     */
3043    @Deprecated
3044    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3045        // reader
3046        synchronized (mPackages) {
3047            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3048                    .iterator();
3049            final int userId = UserHandle.getCallingUserId();
3050            while (i.hasNext()) {
3051                Map.Entry<String, PackageParser.Provider> entry = i.next();
3052                PackageParser.Provider p = entry.getValue();
3053                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3054
3055                if (ps != null && p.syncable
3056                        && (!mSafeMode || (p.info.applicationInfo.flags
3057                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3058                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3059                            ps.readUserState(userId), userId);
3060                    if (info != null) {
3061                        outNames.add(entry.getKey());
3062                        outInfo.add(info);
3063                    }
3064                }
3065            }
3066        }
3067    }
3068
3069    public List<ProviderInfo> queryContentProviders(String processName,
3070            int uid, int flags) {
3071        ArrayList<ProviderInfo> finalList = null;
3072
3073        // reader
3074        synchronized (mPackages) {
3075            final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
3076            final int userId = processName != null ?
3077                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3078            while (i.hasNext()) {
3079                final PackageParser.Provider p = i.next();
3080                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3081                if (ps != null && p.info.authority != null
3082                        && (processName == null
3083                                || (p.info.processName.equals(processName)
3084                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3085                        && mSettings.isEnabledLPr(p.info, flags, userId)
3086                        && (!mSafeMode
3087                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3088                    if (finalList == null) {
3089                        finalList = new ArrayList<ProviderInfo>(3);
3090                    }
3091                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3092                            ps.readUserState(userId), userId);
3093                    if (info != null) {
3094                        finalList.add(info);
3095                    }
3096                }
3097            }
3098        }
3099
3100        if (finalList != null) {
3101            Collections.sort(finalList, mProviderInitOrderSorter);
3102        }
3103
3104        return finalList;
3105    }
3106
3107    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3108            int flags) {
3109        // reader
3110        synchronized (mPackages) {
3111            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3112            return PackageParser.generateInstrumentationInfo(i, flags);
3113        }
3114    }
3115
3116    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3117            int flags) {
3118        ArrayList<InstrumentationInfo> finalList =
3119            new ArrayList<InstrumentationInfo>();
3120
3121        // reader
3122        synchronized (mPackages) {
3123            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3124            while (i.hasNext()) {
3125                final PackageParser.Instrumentation p = i.next();
3126                if (targetPackage == null
3127                        || targetPackage.equals(p.info.targetPackage)) {
3128                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3129                            flags);
3130                    if (ii != null) {
3131                        finalList.add(ii);
3132                    }
3133                }
3134            }
3135        }
3136
3137        return finalList;
3138    }
3139
3140    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3141        String[] files = dir.list();
3142        if (files == null) {
3143            Log.d(TAG, "No files in app dir " + dir);
3144            return;
3145        }
3146
3147        if (DEBUG_PACKAGE_SCANNING) {
3148            Log.d(TAG, "Scanning app dir " + dir);
3149        }
3150
3151        int i;
3152        for (i=0; i<files.length; i++) {
3153            File file = new File(dir, files[i]);
3154            if (!isPackageFilename(files[i])) {
3155                // Ignore entries which are not apk's
3156                continue;
3157            }
3158            PackageParser.Package pkg = scanPackageLI(file,
3159                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3160            // Don't mess around with apps in system partition.
3161            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3162                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3163                // Delete the apk
3164                Slog.w(TAG, "Cleaning up failed install of " + file);
3165                file.delete();
3166            }
3167        }
3168    }
3169
3170    private static File getSettingsProblemFile() {
3171        File dataDir = Environment.getDataDirectory();
3172        File systemDir = new File(dataDir, "system");
3173        File fname = new File(systemDir, "uiderrors.txt");
3174        return fname;
3175    }
3176
3177    static void reportSettingsProblem(int priority, String msg) {
3178        try {
3179            File fname = getSettingsProblemFile();
3180            FileOutputStream out = new FileOutputStream(fname, true);
3181            PrintWriter pw = new PrintWriter(out);
3182            SimpleDateFormat formatter = new SimpleDateFormat();
3183            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3184            pw.println(dateString + ": " + msg);
3185            pw.close();
3186            FileUtils.setPermissions(
3187                    fname.toString(),
3188                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3189                    -1, -1);
3190        } catch (java.io.IOException e) {
3191        }
3192        Slog.println(priority, TAG, msg);
3193    }
3194
3195    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3196            PackageParser.Package pkg, File srcFile, int parseFlags) {
3197        if (GET_CERTIFICATES) {
3198            if (ps != null
3199                    && ps.codePath.equals(srcFile)
3200                    && ps.timeStamp == srcFile.lastModified()) {
3201                if (ps.signatures.mSignatures != null
3202                        && ps.signatures.mSignatures.length != 0) {
3203                    // Optimization: reuse the existing cached certificates
3204                    // if the package appears to be unchanged.
3205                    pkg.mSignatures = ps.signatures.mSignatures;
3206                    return true;
3207                }
3208
3209                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3210            } else {
3211                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3212            }
3213
3214            if (!pp.collectCertificates(pkg, parseFlags)) {
3215                mLastScanError = pp.getParseError();
3216                return false;
3217            }
3218        }
3219        return true;
3220    }
3221
3222    /*
3223     *  Scan a package and return the newly parsed package.
3224     *  Returns null in case of errors and the error code is stored in mLastScanError
3225     */
3226    private PackageParser.Package scanPackageLI(File scanFile,
3227            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3228        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3229        String scanPath = scanFile.getPath();
3230        parseFlags |= mDefParseFlags;
3231        PackageParser pp = new PackageParser(scanPath);
3232        pp.setSeparateProcesses(mSeparateProcesses);
3233        pp.setOnlyCoreApps(mOnlyCore);
3234        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3235                scanPath, mMetrics, parseFlags);
3236        if (pkg == null) {
3237            mLastScanError = pp.getParseError();
3238            return null;
3239        }
3240        PackageSetting ps = null;
3241        PackageSetting updatedPkg;
3242        // reader
3243        synchronized (mPackages) {
3244            // Look to see if we already know about this package.
3245            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3246            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3247                // This package has been renamed to its original name.  Let's
3248                // use that.
3249                ps = mSettings.peekPackageLPr(oldName);
3250            }
3251            // If there was no original package, see one for the real package name.
3252            if (ps == null) {
3253                ps = mSettings.peekPackageLPr(pkg.packageName);
3254            }
3255            // Check to see if this package could be hiding/updating a system
3256            // package.  Must look for it either under the original or real
3257            // package name depending on our state.
3258            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3259        }
3260        // First check if this is a system package that may involve an update
3261        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3262            if (ps != null && !ps.codePath.equals(scanFile)) {
3263                // The path has changed from what was last scanned...  check the
3264                // version of the new path against what we have stored to determine
3265                // what to do.
3266                if (pkg.mVersionCode < ps.versionCode) {
3267                    // The system package has been updated and the code path does not match
3268                    // Ignore entry. Skip it.
3269                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3270                            + " ignored: updated version " + ps.versionCode
3271                            + " better than this " + pkg.mVersionCode);
3272                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3273                    return null;
3274                } else {
3275                    // The current app on the system partion is better than
3276                    // what we have updated to on the data partition; switch
3277                    // back to the system partition version.
3278                    // At this point, its safely assumed that package installation for
3279                    // apps in system partition will go through. If not there won't be a working
3280                    // version of the app
3281                    // writer
3282                    synchronized (mPackages) {
3283                        // Just remove the loaded entries from package lists.
3284                        mPackages.remove(ps.name);
3285                    }
3286                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3287                            + "reverting from " + ps.codePathString
3288                            + ": new version " + pkg.mVersionCode
3289                            + " better than installed " + ps.versionCode);
3290
3291                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3292                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3293                    synchronized (mInstallLock) {
3294                        args.cleanUpResourcesLI();
3295                    }
3296                    synchronized (mPackages) {
3297                        mSettings.enableSystemPackageLPw(ps.name);
3298                    }
3299                }
3300            }
3301        }
3302
3303        if (updatedPkg != null) {
3304            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3305            // initially
3306            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3307        }
3308        // Verify certificates against what was last scanned
3309        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3310            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3311            return null;
3312        }
3313
3314        /*
3315         * A new system app appeared, but we already had a non-system one of the
3316         * same name installed earlier.
3317         */
3318        boolean shouldHideSystemApp = false;
3319        if (updatedPkg == null && ps != null
3320                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3321            /*
3322             * Check to make sure the signatures match first. If they don't,
3323             * wipe the installed application and its data.
3324             */
3325            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3326                    != PackageManager.SIGNATURE_MATCH) {
3327                deletePackageLI(pkg.packageName, null, true, 0, null, false);
3328                ps = null;
3329            } else {
3330                /*
3331                 * If the newly-added system app is an older version than the
3332                 * already installed version, hide it. It will be scanned later
3333                 * and re-added like an update.
3334                 */
3335                if (pkg.mVersionCode < ps.versionCode) {
3336                    shouldHideSystemApp = true;
3337                } else {
3338                    /*
3339                     * The newly found system app is a newer version that the
3340                     * one previously installed. Simply remove the
3341                     * already-installed application and replace it with our own
3342                     * while keeping the application data.
3343                     */
3344                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3345                            + ps.codePathString + ": new version " + pkg.mVersionCode
3346                            + " better than installed " + ps.versionCode);
3347                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3348                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3349                    synchronized (mInstallLock) {
3350                        args.cleanUpResourcesLI();
3351                    }
3352                }
3353            }
3354        }
3355
3356        // The apk is forward locked (not public) if its code and resources
3357        // are kept in different files.
3358        // TODO grab this value from PackageSettings
3359        if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3360            parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3361        }
3362
3363        String codePath = null;
3364        String resPath = null;
3365        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3366            if (ps != null && ps.resourcePathString != null) {
3367                resPath = ps.resourcePathString;
3368            } else {
3369                // Should not happen at all. Just log an error.
3370                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3371            }
3372        } else {
3373            resPath = pkg.mScanPath;
3374        }
3375        codePath = pkg.mScanPath;
3376        // Set application objects path explicitly.
3377        setApplicationInfoPaths(pkg, codePath, resPath);
3378        // Note that we invoke the following method only if we are about to unpack an application
3379        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3380                | SCAN_UPDATE_SIGNATURE, currentTime, user);
3381
3382        /*
3383         * If the system app should be overridden by a previously installed
3384         * data, hide the system app now and let the /data/app scan pick it up
3385         * again.
3386         */
3387        if (shouldHideSystemApp) {
3388            synchronized (mPackages) {
3389                /*
3390                 * We have to grant systems permissions before we hide, because
3391                 * grantPermissions will assume the package update is trying to
3392                 * expand its permissions.
3393                 */
3394                grantPermissionsLPw(pkg, true);
3395                mSettings.disableSystemPackageLPw(pkg.packageName);
3396            }
3397        }
3398
3399        return scannedPkg;
3400    }
3401
3402    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3403            String destResPath) {
3404        pkg.mPath = pkg.mScanPath = destCodePath;
3405        pkg.applicationInfo.sourceDir = destCodePath;
3406        pkg.applicationInfo.publicSourceDir = destResPath;
3407    }
3408
3409    private static String fixProcessName(String defProcessName,
3410            String processName, int uid) {
3411        if (processName == null) {
3412            return defProcessName;
3413        }
3414        return processName;
3415    }
3416
3417    private boolean verifySignaturesLP(PackageSetting pkgSetting,
3418            PackageParser.Package pkg) {
3419        if (pkgSetting.signatures.mSignatures != null) {
3420            // Already existing package. Make sure signatures match
3421            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
3422                PackageManager.SIGNATURE_MATCH) {
3423                    Slog.e(TAG, "Package " + pkg.packageName
3424                            + " signatures do not match the previously installed version; ignoring!");
3425                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3426                    return false;
3427                }
3428        }
3429        // Check for shared user signatures
3430        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
3431            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3432                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3433                Slog.e(TAG, "Package " + pkg.packageName
3434                        + " has no signatures that match those in shared user "
3435                        + pkgSetting.sharedUser.name + "; ignoring!");
3436                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3437                return false;
3438            }
3439        }
3440        return true;
3441    }
3442
3443    /**
3444     * Enforces that only the system UID or root's UID can call a method exposed
3445     * via Binder.
3446     *
3447     * @param message used as message if SecurityException is thrown
3448     * @throws SecurityException if the caller is not system or root
3449     */
3450    private static final void enforceSystemOrRoot(String message) {
3451        final int uid = Binder.getCallingUid();
3452        if (uid != Process.SYSTEM_UID && uid != 0) {
3453            throw new SecurityException(message);
3454        }
3455    }
3456
3457    public void performBootDexOpt() {
3458        ArrayList<PackageParser.Package> pkgs = null;
3459        synchronized (mPackages) {
3460            if (mDeferredDexOpt.size() > 0) {
3461                pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3462                mDeferredDexOpt.clear();
3463            }
3464        }
3465        if (pkgs != null) {
3466            for (int i=0; i<pkgs.size(); i++) {
3467                if (!isFirstBoot()) {
3468                    try {
3469                        ActivityManagerNative.getDefault().showBootMessage(
3470                                mContext.getResources().getString(
3471                                        com.android.internal.R.string.android_upgrading_apk,
3472                                        i+1, pkgs.size()), true);
3473                    } catch (RemoteException e) {
3474                    }
3475                }
3476                PackageParser.Package p = pkgs.get(i);
3477                synchronized (mInstallLock) {
3478                    if (!p.mDidDexOpt) {
3479                        performDexOptLI(p, false, false);
3480                    }
3481                }
3482            }
3483        }
3484    }
3485
3486    public boolean performDexOpt(String packageName) {
3487        enforceSystemOrRoot("Only the system can request dexopt be performed");
3488
3489        if (!mNoDexOpt) {
3490            return false;
3491        }
3492
3493        PackageParser.Package p;
3494        synchronized (mPackages) {
3495            p = mPackages.get(packageName);
3496            if (p == null || p.mDidDexOpt) {
3497                return false;
3498            }
3499        }
3500        synchronized (mInstallLock) {
3501            return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
3502        }
3503    }
3504
3505    static final int DEX_OPT_SKIPPED = 0;
3506    static final int DEX_OPT_PERFORMED = 1;
3507    static final int DEX_OPT_DEFERRED = 2;
3508    static final int DEX_OPT_FAILED = -1;
3509
3510    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
3511        boolean performed = false;
3512        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3513            String path = pkg.mScanPath;
3514            int ret = 0;
3515            try {
3516                if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
3517                    if (!forceDex && defer) {
3518                        mDeferredDexOpt.add(pkg);
3519                        return DEX_OPT_DEFERRED;
3520                    } else {
3521                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3522                        ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
3523                                !isForwardLocked(pkg));
3524                        pkg.mDidDexOpt = true;
3525                        performed = true;
3526                    }
3527                }
3528            } catch (FileNotFoundException e) {
3529                Slog.w(TAG, "Apk not found for dexopt: " + path);
3530                ret = -1;
3531            } catch (IOException e) {
3532                Slog.w(TAG, "IOException reading apk: " + path, e);
3533                ret = -1;
3534            } catch (dalvik.system.StaleDexCacheError e) {
3535                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3536                ret = -1;
3537            } catch (Exception e) {
3538                Slog.w(TAG, "Exception when doing dexopt : ", e);
3539                ret = -1;
3540            }
3541            if (ret < 0) {
3542                //error from installer
3543                return DEX_OPT_FAILED;
3544            }
3545        }
3546
3547        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3548    }
3549
3550    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
3551        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
3552            Slog.w(TAG, "Unable to update from " + oldPkg.name
3553                    + " to " + newPkg.packageName
3554                    + ": old package not in system partition");
3555            return false;
3556        } else if (mPackages.get(oldPkg.name) != null) {
3557            Slog.w(TAG, "Unable to update from " + oldPkg.name
3558                    + " to " + newPkg.packageName
3559                    + ": old package still exists");
3560            return false;
3561        }
3562        return true;
3563    }
3564
3565    File getDataPathForUser(int userId) {
3566        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
3567    }
3568
3569    private File getDataPathForPackage(String packageName, int userId) {
3570        /*
3571         * Until we fully support multiple users, return the directory we
3572         * previously would have. The PackageManagerTests will need to be
3573         * revised when this is changed back..
3574         */
3575        if (userId == 0) {
3576            return new File(mAppDataDir, packageName);
3577        } else {
3578            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
3579                + File.separator + packageName);
3580        }
3581    }
3582
3583    private int createDataDirsLI(String packageName, int uid) {
3584        int[] users = sUserManager.getUserIds();
3585        int res = mInstaller.install(packageName, uid, uid);
3586        if (res < 0) {
3587            return res;
3588        }
3589        for (int user : users) {
3590            if (user != 0) {
3591                res = mInstaller.createUserData(packageName,
3592                        UserHandle.getUid(user, uid), user);
3593                if (res < 0) {
3594                    return res;
3595                }
3596            }
3597        }
3598        return res;
3599    }
3600
3601    private int removeDataDirsLI(String packageName) {
3602        int[] users = sUserManager.getUserIds();
3603        int res = 0;
3604        for (int user : users) {
3605            int resInner = mInstaller.remove(packageName, user);
3606            if (resInner < 0) {
3607                res = resInner;
3608            }
3609        }
3610        return res;
3611    }
3612
3613    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
3614            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3615        File scanFile = new File(pkg.mScanPath);
3616        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3617                pkg.applicationInfo.publicSourceDir == null) {
3618            // Bail out. The resource and code paths haven't been set.
3619            Slog.w(TAG, " Code and resource paths haven't been set correctly");
3620            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3621            return null;
3622        }
3623        mScanningPath = scanFile;
3624
3625        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3626            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3627        }
3628
3629        if (pkg.packageName.equals("android")) {
3630            synchronized (mPackages) {
3631                if (mAndroidApplication != null) {
3632                    Slog.w(TAG, "*************************************************");
3633                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
3634                    Slog.w(TAG, " file=" + mScanningPath);
3635                    Slog.w(TAG, "*************************************************");
3636                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3637                    return null;
3638                }
3639
3640                // Set up information for our fall-back user intent resolution
3641                // activity.
3642                mPlatformPackage = pkg;
3643                pkg.mVersionCode = mSdkVersion;
3644                mAndroidApplication = pkg.applicationInfo;
3645                mResolveActivity.applicationInfo = mAndroidApplication;
3646                mResolveActivity.name = ResolverActivity.class.getName();
3647                mResolveActivity.packageName = mAndroidApplication.packageName;
3648                mResolveActivity.processName = mAndroidApplication.processName;
3649                mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3650                mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
3651                mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
3652                mResolveActivity.exported = true;
3653                mResolveActivity.enabled = true;
3654                mResolveInfo.activityInfo = mResolveActivity;
3655                mResolveInfo.priority = 0;
3656                mResolveInfo.preferredOrder = 0;
3657                mResolveInfo.match = 0;
3658                mResolveComponentName = new ComponentName(
3659                        mAndroidApplication.packageName, mResolveActivity.name);
3660            }
3661        }
3662
3663        if (DEBUG_PACKAGE_SCANNING) {
3664            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3665                Log.d(TAG, "Scanning package " + pkg.packageName);
3666        }
3667
3668        if (mPackages.containsKey(pkg.packageName)
3669                || mSharedLibraries.containsKey(pkg.packageName)) {
3670            Slog.w(TAG, "Application package " + pkg.packageName
3671                    + " already installed.  Skipping duplicate.");
3672            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3673            return null;
3674        }
3675
3676        // Initialize package source and resource directories
3677        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3678        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
3679
3680        SharedUserSetting suid = null;
3681        PackageSetting pkgSetting = null;
3682
3683        if (!isSystemApp(pkg)) {
3684            // Only system apps can use these features.
3685            pkg.mOriginalPackages = null;
3686            pkg.mRealPackage = null;
3687            pkg.mAdoptPermissions = null;
3688        }
3689
3690        // writer
3691        synchronized (mPackages) {
3692            // Check all shared libraries and map to their actual file path.
3693            if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3694                if (mTmpSharedLibraries == null ||
3695                        mTmpSharedLibraries.length < mSharedLibraries.size()) {
3696                    mTmpSharedLibraries = new String[mSharedLibraries.size()];
3697                }
3698                int num = 0;
3699                int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3700                for (int i=0; i<N; i++) {
3701                    final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
3702                    if (file == null) {
3703                        Slog.e(TAG, "Package " + pkg.packageName
3704                                + " requires unavailable shared library "
3705                                + pkg.usesLibraries.get(i) + "; failing!");
3706                        mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3707                        return null;
3708                    }
3709                    mTmpSharedLibraries[num] = file;
3710                    num++;
3711                }
3712                N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3713                for (int i=0; i<N; i++) {
3714                    final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
3715                    if (file == null) {
3716                        Slog.w(TAG, "Package " + pkg.packageName
3717                                + " desires unavailable shared library "
3718                                + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3719                    } else {
3720                        mTmpSharedLibraries[num] = file;
3721                        num++;
3722                    }
3723                }
3724                if (num > 0) {
3725                    pkg.usesLibraryFiles = new String[num];
3726                    System.arraycopy(mTmpSharedLibraries, 0,
3727                            pkg.usesLibraryFiles, 0, num);
3728                }
3729            }
3730
3731            if (pkg.mSharedUserId != null) {
3732                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
3733                        pkg.applicationInfo.flags, true);
3734                if (suid == null) {
3735                    Slog.w(TAG, "Creating application package " + pkg.packageName
3736                            + " for shared user failed");
3737                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3738                    return null;
3739                }
3740                if (DEBUG_PACKAGE_SCANNING) {
3741                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3742                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3743                                + "): packages=" + suid.packages);
3744                }
3745            }
3746
3747            // Check if we are renaming from an original package name.
3748            PackageSetting origPackage = null;
3749            String realName = null;
3750            if (pkg.mOriginalPackages != null) {
3751                // This package may need to be renamed to a previously
3752                // installed name.  Let's check on that...
3753                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
3754                if (pkg.mOriginalPackages.contains(renamed)) {
3755                    // This package had originally been installed as the
3756                    // original name, and we have already taken care of
3757                    // transitioning to the new one.  Just update the new
3758                    // one to continue using the old name.
3759                    realName = pkg.mRealPackage;
3760                    if (!pkg.packageName.equals(renamed)) {
3761                        // Callers into this function may have already taken
3762                        // care of renaming the package; only do it here if
3763                        // it is not already done.
3764                        pkg.setPackageName(renamed);
3765                    }
3766
3767                } else {
3768                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
3769                        if ((origPackage = mSettings.peekPackageLPr(
3770                                pkg.mOriginalPackages.get(i))) != null) {
3771                            // We do have the package already installed under its
3772                            // original name...  should we use it?
3773                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
3774                                // New package is not compatible with original.
3775                                origPackage = null;
3776                                continue;
3777                            } else if (origPackage.sharedUser != null) {
3778                                // Make sure uid is compatible between packages.
3779                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
3780                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
3781                                            + " to " + pkg.packageName + ": old uid "
3782                                            + origPackage.sharedUser.name
3783                                            + " differs from " + pkg.mSharedUserId);
3784                                    origPackage = null;
3785                                    continue;
3786                                }
3787                            } else {
3788                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3789                                        + pkg.packageName + " to old name " + origPackage.name);
3790                            }
3791                            break;
3792                        }
3793                    }
3794                }
3795            }
3796
3797            if (mTransferedPackages.contains(pkg.packageName)) {
3798                Slog.w(TAG, "Package " + pkg.packageName
3799                        + " was transferred to another, but its .apk remains");
3800            }
3801
3802            // Just create the setting, don't add it yet. For already existing packages
3803            // the PkgSetting exists already and doesn't have to be created.
3804            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
3805                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3806                    pkg.applicationInfo.flags, user, false);
3807            if (pkgSetting == null) {
3808                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
3809                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3810                return null;
3811            }
3812
3813            if (pkgSetting.origPackage != null) {
3814                // If we are first transitioning from an original package,
3815                // fix up the new package's name now.  We need to do this after
3816                // looking up the package under its new name, so getPackageLP
3817                // can take care of fiddling things correctly.
3818                pkg.setPackageName(origPackage.name);
3819
3820                // File a report about this.
3821                String msg = "New package " + pkgSetting.realName
3822                        + " renamed to replace old package " + pkgSetting.name;
3823                reportSettingsProblem(Log.WARN, msg);
3824
3825                // Make a note of it.
3826                mTransferedPackages.add(origPackage.name);
3827
3828                // No longer need to retain this.
3829                pkgSetting.origPackage = null;
3830            }
3831
3832            if (realName != null) {
3833                // Make a note of it.
3834                mTransferedPackages.add(pkg.packageName);
3835            }
3836
3837            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
3838                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3839            }
3840
3841            pkg.applicationInfo.uid = pkgSetting.appId;
3842            pkg.mExtras = pkgSetting;
3843
3844            if (!verifySignaturesLP(pkgSetting, pkg)) {
3845                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3846                    return null;
3847                }
3848                // The signature has changed, but this package is in the system
3849                // image...  let's recover!
3850                pkgSetting.signatures.mSignatures = pkg.mSignatures;
3851                // However...  if this package is part of a shared user, but it
3852                // doesn't match the signature of the shared user, let's fail.
3853                // What this means is that you can't change the signatures
3854                // associated with an overall shared user, which doesn't seem all
3855                // that unreasonable.
3856                if (pkgSetting.sharedUser != null) {
3857                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3858                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3859                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
3860                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3861                        return null;
3862                    }
3863                }
3864                // File a report about this.
3865                String msg = "System package " + pkg.packageName
3866                        + " signature changed; retaining data.";
3867                reportSettingsProblem(Log.WARN, msg);
3868            }
3869
3870            // Verify that this new package doesn't have any content providers
3871            // that conflict with existing packages.  Only do this if the
3872            // package isn't already installed, since we don't want to break
3873            // things that are installed.
3874            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3875                final int N = pkg.providers.size();
3876                int i;
3877                for (i=0; i<N; i++) {
3878                    PackageParser.Provider p = pkg.providers.get(i);
3879                    if (p.info.authority != null) {
3880                        String names[] = p.info.authority.split(";");
3881                        for (int j = 0; j < names.length; j++) {
3882                            if (mProviders.containsKey(names[j])) {
3883                                PackageParser.Provider other = mProviders.get(names[j]);
3884                                Slog.w(TAG, "Can't install because provider name " + names[j] +
3885                                        " (in package " + pkg.applicationInfo.packageName +
3886                                        ") is already used by "
3887                                        + ((other != null && other.getComponentName() != null)
3888                                                ? other.getComponentName().getPackageName() : "?"));
3889                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3890                                return null;
3891                            }
3892                        }
3893                    }
3894                }
3895            }
3896
3897            if (pkg.mAdoptPermissions != null) {
3898                // This package wants to adopt ownership of permissions from
3899                // another package.
3900                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3901                    final String origName = pkg.mAdoptPermissions.get(i);
3902                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
3903                    if (orig != null) {
3904                        if (verifyPackageUpdateLPr(orig, pkg)) {
3905                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
3906                                    + pkg.packageName);
3907                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
3908                        }
3909                    }
3910                }
3911            }
3912        }
3913
3914        final String pkgName = pkg.packageName;
3915
3916        final long scanFileTime = scanFile.lastModified();
3917        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3918        pkg.applicationInfo.processName = fixProcessName(
3919                pkg.applicationInfo.packageName,
3920                pkg.applicationInfo.processName,
3921                pkg.applicationInfo.uid);
3922
3923        File dataPath;
3924        if (mPlatformPackage == pkg) {
3925            // The system package is special.
3926            dataPath = new File (Environment.getDataDirectory(), "system");
3927            pkg.applicationInfo.dataDir = dataPath.getPath();
3928        } else {
3929            // This is a normal package, need to make its data directory.
3930            dataPath = getDataPathForPackage(pkg.packageName, 0);
3931
3932            boolean uidError = false;
3933
3934            if (dataPath.exists()) {
3935                int currentUid = 0;
3936                try {
3937                    StructStat stat = Libcore.os.stat(dataPath.getPath());
3938                    currentUid = stat.st_uid;
3939                } catch (ErrnoException e) {
3940                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
3941                }
3942
3943                // If we have mismatched owners for the data path, we have a problem.
3944                if (currentUid != pkg.applicationInfo.uid) {
3945                    boolean recovered = false;
3946                    if (currentUid == 0) {
3947                        // The directory somehow became owned by root.  Wow.
3948                        // This is probably because the system was stopped while
3949                        // installd was in the middle of messing with its libs
3950                        // directory.  Ask installd to fix that.
3951                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3952                                pkg.applicationInfo.uid);
3953                        if (ret >= 0) {
3954                            recovered = true;
3955                            String msg = "Package " + pkg.packageName
3956                                    + " unexpectedly changed to uid 0; recovered to " +
3957                                    + pkg.applicationInfo.uid;
3958                            reportSettingsProblem(Log.WARN, msg);
3959                        }
3960                    }
3961                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3962                            || (scanMode&SCAN_BOOTING) != 0)) {
3963                        // If this is a system app, we can at least delete its
3964                        // current data so the application will still work.
3965                        int ret = removeDataDirsLI(pkgName);
3966                        if (ret >= 0) {
3967                            // TODO: Kill the processes first
3968                            // Old data gone!
3969                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3970                                    ? "System package " : "Third party package ";
3971                            String msg = prefix + pkg.packageName
3972                                    + " has changed from uid: "
3973                                    + currentUid + " to "
3974                                    + pkg.applicationInfo.uid + "; old data erased";
3975                            reportSettingsProblem(Log.WARN, msg);
3976                            recovered = true;
3977
3978                            // And now re-install the app.
3979                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
3980                            if (ret == -1) {
3981                                // Ack should not happen!
3982                                msg = prefix + pkg.packageName
3983                                        + " could not have data directory re-created after delete.";
3984                                reportSettingsProblem(Log.WARN, msg);
3985                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3986                                return null;
3987                            }
3988                        }
3989                        if (!recovered) {
3990                            mHasSystemUidErrors = true;
3991                        }
3992                    } else if (!recovered) {
3993                        // If we allow this install to proceed, we will be broken.
3994                        // Abort, abort!
3995                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
3996                        return null;
3997                    }
3998                    if (!recovered) {
3999                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4000                            + pkg.applicationInfo.uid + "/fs_"
4001                            + currentUid;
4002                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4003                        String msg = "Package " + pkg.packageName
4004                                + " has mismatched uid: "
4005                                + currentUid + " on disk, "
4006                                + pkg.applicationInfo.uid + " in settings";
4007                        // writer
4008                        synchronized (mPackages) {
4009                            mSettings.mReadMessages.append(msg);
4010                            mSettings.mReadMessages.append('\n');
4011                            uidError = true;
4012                            if (!pkgSetting.uidError) {
4013                                reportSettingsProblem(Log.ERROR, msg);
4014                            }
4015                        }
4016                    }
4017                }
4018                pkg.applicationInfo.dataDir = dataPath.getPath();
4019            } else {
4020                if (DEBUG_PACKAGE_SCANNING) {
4021                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4022                        Log.v(TAG, "Want this data dir: " + dataPath);
4023                }
4024                //invoke installer to do the actual installation
4025                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
4026                if (ret < 0) {
4027                    // Error from installer
4028                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4029                    return null;
4030                }
4031
4032                if (dataPath.exists()) {
4033                    pkg.applicationInfo.dataDir = dataPath.getPath();
4034                } else {
4035                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4036                    pkg.applicationInfo.dataDir = null;
4037                }
4038            }
4039
4040            /*
4041             * Set the data dir to the default "/data/data/<package name>/lib"
4042             * if we got here without anyone telling us different (e.g., apps
4043             * stored on SD card have their native libraries stored in the ASEC
4044             * container with the APK).
4045             *
4046             * This happens during an upgrade from a package settings file that
4047             * doesn't have a native library path attribute at all.
4048             */
4049            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4050                if (pkgSetting.nativeLibraryPathString == null) {
4051                    final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
4052                    pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4053                    pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4054                } else {
4055                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4056                }
4057            }
4058
4059            pkgSetting.uidError = uidError;
4060        }
4061
4062        String path = scanFile.getPath();
4063        /* Note: We don't want to unpack the native binaries for
4064         *        system applications, unless they have been updated
4065         *        (the binaries are already under /system/lib).
4066         *        Also, don't unpack libs for apps on the external card
4067         *        since they should have their libraries in the ASEC
4068         *        container already.
4069         *
4070         *        In other words, we're going to unpack the binaries
4071         *        only for non-system apps and system app upgrades.
4072         */
4073        if (pkg.applicationInfo.nativeLibraryDir != null) {
4074            try {
4075                final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4076                final String dataPathString = dataPath.getCanonicalPath();
4077
4078                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4079                    /*
4080                     * Upgrading from a previous version of the OS sometimes
4081                     * leaves native libraries in the /data/data/<app>/lib
4082                     * directory for system apps even when they shouldn't be.
4083                     * Recent changes in the JNI library search path
4084                     * necessitates we remove those to match previous behavior.
4085                     */
4086                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4087                        Log.i(TAG, "removed obsolete native libraries for system package "
4088                                + path);
4089                    }
4090                } else if (nativeLibraryDir.getParentFile().getCanonicalPath()
4091                        .equals(dataPathString)) {
4092                    /*
4093                     * Make sure the native library dir isn't a symlink to
4094                     * something. If it is, ask installd to remove it and create
4095                     * a directory so we can copy to it afterwards.
4096                     */
4097                    boolean isSymLink;
4098                    try {
4099                        isSymLink = S_ISLNK(Libcore.os.lstat(nativeLibraryDir.getPath()).st_mode);
4100                    } catch (ErrnoException e) {
4101                        // This shouldn't happen, but we'll fail-safe.
4102                        isSymLink = true;
4103                    }
4104                    if (isSymLink) {
4105                        mInstaller.unlinkNativeLibraryDirectory(dataPathString);
4106                    }
4107
4108                    /*
4109                     * If this is an internal application or our
4110                     * nativeLibraryPath points to our data directory, unpack
4111                     * the libraries if necessary.
4112                     */
4113                    NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
4114                } else {
4115                    Slog.i(TAG, "Linking native library dir for " + path);
4116                    int ret = mInstaller.linkNativeLibraryDirectory(dataPathString,
4117                            pkg.applicationInfo.nativeLibraryDir);
4118                    if (ret < 0) {
4119                        Slog.w(TAG, "Failed linking native library dir for " + path);
4120                        mLastScanError = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4121                        return null;
4122                    }
4123                }
4124            } catch (IOException ioe) {
4125                Log.e(TAG, "Unable to get canonical file " + ioe.toString());
4126            }
4127        }
4128        pkg.mScanPath = path;
4129
4130        if ((scanMode&SCAN_NO_DEX) == 0) {
4131            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
4132                    == DEX_OPT_FAILED) {
4133                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4134                return null;
4135            }
4136        }
4137
4138        if (mFactoryTest && pkg.requestedPermissions.contains(
4139                android.Manifest.permission.FACTORY_TEST)) {
4140            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4141        }
4142
4143        // Request the ActivityManager to kill the process(only for existing packages)
4144        // so that we do not end up in a confused state while the user is still using the older
4145        // version of the application while the new one gets installed.
4146        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4147            killApplication(pkg.applicationInfo.packageName,
4148                        pkg.applicationInfo.uid);
4149        }
4150
4151        // writer
4152        synchronized (mPackages) {
4153            // We don't expect installation to fail beyond this point,
4154            if ((scanMode&SCAN_MONITOR) != 0) {
4155                mAppDirs.put(pkg.mPath, pkg);
4156            }
4157            // Add the new setting to mSettings
4158            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
4159            // Add the new setting to mPackages
4160            mPackages.put(pkg.applicationInfo.packageName, pkg);
4161            // Make sure we don't accidentally delete its data.
4162            for (int i=0; i<mSettings.mPackagesToBeCleaned.size(); i++) {
4163                mSettings.mPackagesToBeCleaned.valueAt(i).remove(pkgName);
4164            }
4165
4166            // Take care of first install / last update times.
4167            if (currentTime != 0) {
4168                if (pkgSetting.firstInstallTime == 0) {
4169                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4170                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4171                    pkgSetting.lastUpdateTime = currentTime;
4172                }
4173            } else if (pkgSetting.firstInstallTime == 0) {
4174                // We need *something*.  Take time time stamp of the file.
4175                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4176            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4177                if (scanFileTime != pkgSetting.timeStamp) {
4178                    // A package on the system image has changed; consider this
4179                    // to be an update.
4180                    pkgSetting.lastUpdateTime = scanFileTime;
4181                }
4182            }
4183
4184            int N = pkg.providers.size();
4185            StringBuilder r = null;
4186            int i;
4187            for (i=0; i<N; i++) {
4188                PackageParser.Provider p = pkg.providers.get(i);
4189                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4190                        p.info.processName, pkg.applicationInfo.uid);
4191                mProvidersByComponent.put(new ComponentName(p.info.packageName,
4192                        p.info.name), p);
4193                p.syncable = p.info.isSyncable;
4194                if (p.info.authority != null) {
4195                    String names[] = p.info.authority.split(";");
4196                    p.info.authority = null;
4197                    for (int j = 0; j < names.length; j++) {
4198                        if (j == 1 && p.syncable) {
4199                            // We only want the first authority for a provider to possibly be
4200                            // syncable, so if we already added this provider using a different
4201                            // authority clear the syncable flag. We copy the provider before
4202                            // changing it because the mProviders object contains a reference
4203                            // to a provider that we don't want to change.
4204                            // Only do this for the second authority since the resulting provider
4205                            // object can be the same for all future authorities for this provider.
4206                            p = new PackageParser.Provider(p);
4207                            p.syncable = false;
4208                        }
4209                        if (!mProviders.containsKey(names[j])) {
4210                            mProviders.put(names[j], p);
4211                            if (p.info.authority == null) {
4212                                p.info.authority = names[j];
4213                            } else {
4214                                p.info.authority = p.info.authority + ";" + names[j];
4215                            }
4216                            if (DEBUG_PACKAGE_SCANNING) {
4217                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4218                                    Log.d(TAG, "Registered content provider: " + names[j]
4219                                            + ", className = " + p.info.name + ", isSyncable = "
4220                                            + p.info.isSyncable);
4221                            }
4222                        } else {
4223                            PackageParser.Provider other = mProviders.get(names[j]);
4224                            Slog.w(TAG, "Skipping provider name " + names[j] +
4225                                    " (in package " + pkg.applicationInfo.packageName +
4226                                    "): name already used by "
4227                                    + ((other != null && other.getComponentName() != null)
4228                                            ? other.getComponentName().getPackageName() : "?"));
4229                        }
4230                    }
4231                }
4232                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4233                    if (r == null) {
4234                        r = new StringBuilder(256);
4235                    } else {
4236                        r.append(' ');
4237                    }
4238                    r.append(p.info.name);
4239                }
4240            }
4241            if (r != null) {
4242                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
4243            }
4244
4245            N = pkg.services.size();
4246            r = null;
4247            for (i=0; i<N; i++) {
4248                PackageParser.Service s = pkg.services.get(i);
4249                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4250                        s.info.processName, pkg.applicationInfo.uid);
4251                mServices.addService(s);
4252                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4253                    if (r == null) {
4254                        r = new StringBuilder(256);
4255                    } else {
4256                        r.append(' ');
4257                    }
4258                    r.append(s.info.name);
4259                }
4260            }
4261            if (r != null) {
4262                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
4263            }
4264
4265            N = pkg.receivers.size();
4266            r = null;
4267            for (i=0; i<N; i++) {
4268                PackageParser.Activity a = pkg.receivers.get(i);
4269                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4270                        a.info.processName, pkg.applicationInfo.uid);
4271                mReceivers.addActivity(a, "receiver");
4272                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4273                    if (r == null) {
4274                        r = new StringBuilder(256);
4275                    } else {
4276                        r.append(' ');
4277                    }
4278                    r.append(a.info.name);
4279                }
4280            }
4281            if (r != null) {
4282                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
4283            }
4284
4285            N = pkg.activities.size();
4286            r = null;
4287            for (i=0; i<N; i++) {
4288                PackageParser.Activity a = pkg.activities.get(i);
4289                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4290                        a.info.processName, pkg.applicationInfo.uid);
4291                mActivities.addActivity(a, "activity");
4292                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4293                    if (r == null) {
4294                        r = new StringBuilder(256);
4295                    } else {
4296                        r.append(' ');
4297                    }
4298                    r.append(a.info.name);
4299                }
4300            }
4301            if (r != null) {
4302                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
4303            }
4304
4305            N = pkg.permissionGroups.size();
4306            r = null;
4307            for (i=0; i<N; i++) {
4308                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4309                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4310                if (cur == null) {
4311                    mPermissionGroups.put(pg.info.name, pg);
4312                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4313                        if (r == null) {
4314                            r = new StringBuilder(256);
4315                        } else {
4316                            r.append(' ');
4317                        }
4318                        r.append(pg.info.name);
4319                    }
4320                } else {
4321                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
4322                            + pg.info.packageName + " ignored: original from "
4323                            + cur.info.packageName);
4324                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4325                        if (r == null) {
4326                            r = new StringBuilder(256);
4327                        } else {
4328                            r.append(' ');
4329                        }
4330                        r.append("DUP:");
4331                        r.append(pg.info.name);
4332                    }
4333                }
4334            }
4335            if (r != null) {
4336                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
4337            }
4338
4339            N = pkg.permissions.size();
4340            r = null;
4341            for (i=0; i<N; i++) {
4342                PackageParser.Permission p = pkg.permissions.get(i);
4343                HashMap<String, BasePermission> permissionMap =
4344                        p.tree ? mSettings.mPermissionTrees
4345                        : mSettings.mPermissions;
4346                p.group = mPermissionGroups.get(p.info.group);
4347                if (p.info.group == null || p.group != null) {
4348                    BasePermission bp = permissionMap.get(p.info.name);
4349                    if (bp == null) {
4350                        bp = new BasePermission(p.info.name, p.info.packageName,
4351                                BasePermission.TYPE_NORMAL);
4352                        permissionMap.put(p.info.name, bp);
4353                    }
4354                    if (bp.perm == null) {
4355                        if (bp.sourcePackage == null
4356                                || bp.sourcePackage.equals(p.info.packageName)) {
4357                            BasePermission tree = findPermissionTreeLP(p.info.name);
4358                            if (tree == null
4359                                    || tree.sourcePackage.equals(p.info.packageName)) {
4360                                bp.packageSetting = pkgSetting;
4361                                bp.perm = p;
4362                                bp.uid = pkg.applicationInfo.uid;
4363                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4364                                    if (r == null) {
4365                                        r = new StringBuilder(256);
4366                                    } else {
4367                                        r.append(' ');
4368                                    }
4369                                    r.append(p.info.name);
4370                                }
4371                            } else {
4372                                Slog.w(TAG, "Permission " + p.info.name + " from package "
4373                                        + p.info.packageName + " ignored: base tree "
4374                                        + tree.name + " is from package "
4375                                        + tree.sourcePackage);
4376                            }
4377                        } else {
4378                            Slog.w(TAG, "Permission " + p.info.name + " from package "
4379                                    + p.info.packageName + " ignored: original from "
4380                                    + bp.sourcePackage);
4381                        }
4382                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4383                        if (r == null) {
4384                            r = new StringBuilder(256);
4385                        } else {
4386                            r.append(' ');
4387                        }
4388                        r.append("DUP:");
4389                        r.append(p.info.name);
4390                    }
4391                    if (bp.perm == p) {
4392                        bp.protectionLevel = p.info.protectionLevel;
4393                    }
4394                } else {
4395                    Slog.w(TAG, "Permission " + p.info.name + " from package "
4396                            + p.info.packageName + " ignored: no group "
4397                            + p.group);
4398                }
4399            }
4400            if (r != null) {
4401                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
4402            }
4403
4404            N = pkg.instrumentation.size();
4405            r = null;
4406            for (i=0; i<N; i++) {
4407                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4408                a.info.packageName = pkg.applicationInfo.packageName;
4409                a.info.sourceDir = pkg.applicationInfo.sourceDir;
4410                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4411                a.info.dataDir = pkg.applicationInfo.dataDir;
4412                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
4413                mInstrumentation.put(a.getComponentName(), a);
4414                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4415                    if (r == null) {
4416                        r = new StringBuilder(256);
4417                    } else {
4418                        r.append(' ');
4419                    }
4420                    r.append(a.info.name);
4421                }
4422            }
4423            if (r != null) {
4424                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
4425            }
4426
4427            if (pkg.protectedBroadcasts != null) {
4428                N = pkg.protectedBroadcasts.size();
4429                for (i=0; i<N; i++) {
4430                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4431                }
4432            }
4433
4434            pkgSetting.setTimeStamp(scanFileTime);
4435        }
4436
4437        return pkg;
4438    }
4439
4440    private void killApplication(String pkgName, int appId) {
4441        // Request the ActivityManager to kill the process(only for existing packages)
4442        // so that we do not end up in a confused state while the user is still using the older
4443        // version of the application while the new one gets installed.
4444        IActivityManager am = ActivityManagerNative.getDefault();
4445        if (am != null) {
4446            try {
4447                am.killApplicationWithAppId(pkgName, appId);
4448            } catch (RemoteException e) {
4449            }
4450        }
4451    }
4452
4453    void removePackageLI(PackageSetting ps, boolean chatty) {
4454        if (DEBUG_INSTALL) {
4455            if (chatty)
4456                Log.d(TAG, "Removing package " + ps.name);
4457        }
4458
4459        // writer
4460        synchronized (mPackages) {
4461            mPackages.remove(ps.name);
4462            if (ps.codePathString != null) {
4463                mAppDirs.remove(ps.codePathString);
4464            }
4465
4466            final PackageParser.Package pkg = ps.pkg;
4467            if (pkg != null) {
4468                cleanPackageDataStructuresLILPw(pkg, chatty);
4469            }
4470        }
4471    }
4472
4473    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
4474        if (DEBUG_INSTALL) {
4475            if (chatty)
4476                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4477        }
4478
4479        // writer
4480        synchronized (mPackages) {
4481            mPackages.remove(pkg.applicationInfo.packageName);
4482            if (pkg.mPath != null) {
4483                mAppDirs.remove(pkg.mPath);
4484            }
4485            cleanPackageDataStructuresLILPw(pkg, chatty);
4486        }
4487    }
4488
4489    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
4490        int N = pkg.providers.size();
4491        StringBuilder r = null;
4492        int i;
4493        for (i=0; i<N; i++) {
4494            PackageParser.Provider p = pkg.providers.get(i);
4495            mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4496                    p.info.name));
4497            if (p.info.authority == null) {
4498
4499                /* There was another ContentProvider with this authority when
4500                 * this app was installed so this authority is null,
4501                 * Ignore it as we don't have to unregister the provider.
4502                 */
4503                continue;
4504            }
4505            String names[] = p.info.authority.split(";");
4506            for (int j = 0; j < names.length; j++) {
4507                if (mProviders.get(names[j]) == p) {
4508                    mProviders.remove(names[j]);
4509                    if (DEBUG_REMOVE) {
4510                        if (chatty)
4511                            Log.d(TAG, "Unregistered content provider: " + names[j]
4512                                    + ", className = " + p.info.name + ", isSyncable = "
4513                                    + p.info.isSyncable);
4514                    }
4515                }
4516            }
4517            if (chatty) {
4518                if (r == null) {
4519                    r = new StringBuilder(256);
4520                } else {
4521                    r.append(' ');
4522                }
4523                r.append(p.info.name);
4524            }
4525        }
4526        if (r != null) {
4527            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
4528        }
4529
4530        N = pkg.services.size();
4531        r = null;
4532        for (i=0; i<N; i++) {
4533            PackageParser.Service s = pkg.services.get(i);
4534            mServices.removeService(s);
4535            if (chatty) {
4536                if (r == null) {
4537                    r = new StringBuilder(256);
4538                } else {
4539                    r.append(' ');
4540                }
4541                r.append(s.info.name);
4542            }
4543        }
4544        if (r != null) {
4545            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
4546        }
4547
4548        N = pkg.receivers.size();
4549        r = null;
4550        for (i=0; i<N; i++) {
4551            PackageParser.Activity a = pkg.receivers.get(i);
4552            mReceivers.removeActivity(a, "receiver");
4553            if (chatty) {
4554                if (r == null) {
4555                    r = new StringBuilder(256);
4556                } else {
4557                    r.append(' ');
4558                }
4559                r.append(a.info.name);
4560            }
4561        }
4562        if (r != null) {
4563            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
4564        }
4565
4566        N = pkg.activities.size();
4567        r = null;
4568        for (i=0; i<N; i++) {
4569            PackageParser.Activity a = pkg.activities.get(i);
4570            mActivities.removeActivity(a, "activity");
4571            if (chatty) {
4572                if (r == null) {
4573                    r = new StringBuilder(256);
4574                } else {
4575                    r.append(' ');
4576                }
4577                r.append(a.info.name);
4578            }
4579        }
4580        if (r != null) {
4581            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
4582        }
4583
4584        N = pkg.permissions.size();
4585        r = null;
4586        for (i=0; i<N; i++) {
4587            PackageParser.Permission p = pkg.permissions.get(i);
4588            BasePermission bp = mSettings.mPermissions.get(p.info.name);
4589            if (bp == null) {
4590                bp = mSettings.mPermissionTrees.get(p.info.name);
4591            }
4592            if (bp != null && bp.perm == p) {
4593                bp.perm = null;
4594                if (chatty) {
4595                    if (r == null) {
4596                        r = new StringBuilder(256);
4597                    } else {
4598                        r.append(' ');
4599                    }
4600                    r.append(p.info.name);
4601                }
4602            }
4603        }
4604        if (r != null) {
4605            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
4606        }
4607
4608        N = pkg.instrumentation.size();
4609        r = null;
4610        for (i=0; i<N; i++) {
4611            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4612            mInstrumentation.remove(a.getComponentName());
4613            if (chatty) {
4614                if (r == null) {
4615                    r = new StringBuilder(256);
4616                } else {
4617                    r.append(' ');
4618                }
4619                r.append(a.info.name);
4620            }
4621        }
4622        if (r != null) {
4623            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
4624        }
4625    }
4626
4627    private static final boolean isPackageFilename(String name) {
4628        return name != null && name.endsWith(".apk");
4629    }
4630
4631    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4632        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4633            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4634                return true;
4635            }
4636        }
4637        return false;
4638    }
4639
4640    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4641    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4642    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4643
4644    private void updatePermissionsLPw(String changingPkg,
4645            PackageParser.Package pkgInfo, int flags) {
4646        // Make sure there are no dangling permission trees.
4647        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
4648        while (it.hasNext()) {
4649            final BasePermission bp = it.next();
4650            if (bp.packageSetting == null) {
4651                // We may not yet have parsed the package, so just see if
4652                // we still know about its settings.
4653                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4654            }
4655            if (bp.packageSetting == null) {
4656                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
4657                        + " from package " + bp.sourcePackage);
4658                it.remove();
4659            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4660                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4661                    Slog.i(TAG, "Removing old permission tree: " + bp.name
4662                            + " from package " + bp.sourcePackage);
4663                    flags |= UPDATE_PERMISSIONS_ALL;
4664                    it.remove();
4665                }
4666            }
4667        }
4668
4669        // Make sure all dynamic permissions have been assigned to a package,
4670        // and make sure there are no dangling permissions.
4671        it = mSettings.mPermissions.values().iterator();
4672        while (it.hasNext()) {
4673            final BasePermission bp = it.next();
4674            if (bp.type == BasePermission.TYPE_DYNAMIC) {
4675                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4676                        + bp.name + " pkg=" + bp.sourcePackage
4677                        + " info=" + bp.pendingInfo);
4678                if (bp.packageSetting == null && bp.pendingInfo != null) {
4679                    final BasePermission tree = findPermissionTreeLP(bp.name);
4680                    if (tree != null && tree.perm != null) {
4681                        bp.packageSetting = tree.packageSetting;
4682                        bp.perm = new PackageParser.Permission(tree.perm.owner,
4683                                new PermissionInfo(bp.pendingInfo));
4684                        bp.perm.info.packageName = tree.perm.info.packageName;
4685                        bp.perm.info.name = bp.name;
4686                        bp.uid = tree.uid;
4687                    }
4688                }
4689            }
4690            if (bp.packageSetting == null) {
4691                // We may not yet have parsed the package, so just see if
4692                // we still know about its settings.
4693                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4694            }
4695            if (bp.packageSetting == null) {
4696                Slog.w(TAG, "Removing dangling permission: " + bp.name
4697                        + " from package " + bp.sourcePackage);
4698                it.remove();
4699            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4700                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4701                    Slog.i(TAG, "Removing old permission: " + bp.name
4702                            + " from package " + bp.sourcePackage);
4703                    flags |= UPDATE_PERMISSIONS_ALL;
4704                    it.remove();
4705                }
4706            }
4707        }
4708
4709        // Now update the permissions for all packages, in particular
4710        // replace the granted permissions of the system packages.
4711        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
4712            for (PackageParser.Package pkg : mPackages.values()) {
4713                if (pkg != pkgInfo) {
4714                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
4715                }
4716            }
4717        }
4718
4719        if (pkgInfo != null) {
4720            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
4721        }
4722    }
4723
4724    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4725        final PackageSetting ps = (PackageSetting) pkg.mExtras;
4726        if (ps == null) {
4727            return;
4728        }
4729        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
4730        HashSet<String> origPermissions = gp.grantedPermissions;
4731        boolean changedPermission = false;
4732
4733        if (replace) {
4734            ps.permissionsFixed = false;
4735            if (gp == ps) {
4736                origPermissions = new HashSet<String>(gp.grantedPermissions);
4737                gp.grantedPermissions.clear();
4738                gp.gids = mGlobalGids;
4739            }
4740        }
4741
4742        if (gp.gids == null) {
4743            gp.gids = mGlobalGids;
4744        }
4745
4746        final int N = pkg.requestedPermissions.size();
4747        for (int i=0; i<N; i++) {
4748            final String name = pkg.requestedPermissions.get(i);
4749            //final boolean required = pkg.requestedPermssionsRequired.get(i);
4750            final BasePermission bp = mSettings.mPermissions.get(name);
4751            if (DEBUG_INSTALL) {
4752                if (gp != ps) {
4753                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
4754                }
4755            }
4756            if (bp != null && bp.packageSetting != null) {
4757                final String perm = bp.name;
4758                boolean allowed;
4759                boolean allowedSig = false;
4760                final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4761                if (level == PermissionInfo.PROTECTION_NORMAL
4762                        || level == PermissionInfo.PROTECTION_DANGEROUS) {
4763                    allowed = true;
4764                } else if (bp.packageSetting == null) {
4765                    // This permission is invalid; skip it.
4766                    allowed = false;
4767                } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
4768                    allowed = (compareSignatures(
4769                            bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
4770                                    == PackageManager.SIGNATURE_MATCH)
4771                            || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
4772                                    == PackageManager.SIGNATURE_MATCH);
4773                    if (!allowed && (bp.protectionLevel
4774                            & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
4775                        if (isSystemApp(pkg)) {
4776                            // For updated system applications, a system permission
4777                            // is granted only if it had been defined by the original application.
4778                            if (isUpdatedSystemApp(pkg)) {
4779                                final PackageSetting sysPs = mSettings
4780                                        .getDisabledSystemPkgLPr(pkg.packageName);
4781                                final GrantedPermissions origGp = sysPs.sharedUser != null
4782                                        ? sysPs.sharedUser : sysPs;
4783                                if (origGp.grantedPermissions.contains(perm)) {
4784                                    allowed = true;
4785                                } else {
4786                                    allowed = false;
4787                                }
4788                            } else {
4789                                allowed = true;
4790                            }
4791                        }
4792                    }
4793                    if (!allowed && (bp.protectionLevel
4794                            & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4795                        // For development permissions, a development permission
4796                        // is granted only if it was already granted.
4797                        if (origPermissions.contains(perm)) {
4798                            allowed = true;
4799                        } else {
4800                            allowed = false;
4801                        }
4802                    }
4803                    if (allowed) {
4804                        allowedSig = true;
4805                    }
4806                } else {
4807                    allowed = false;
4808                }
4809                if (DEBUG_INSTALL) {
4810                    if (gp != ps) {
4811                        Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4812                    }
4813                }
4814                if (allowed) {
4815                    if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4816                            && ps.permissionsFixed) {
4817                        // If this is an existing, non-system package, then
4818                        // we can't add any new permissions to it.
4819                        if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
4820                            allowed = false;
4821                            // Except...  if this is a permission that was added
4822                            // to the platform (note: need to only do this when
4823                            // updating the platform).
4824                            final int NP = PackageParser.NEW_PERMISSIONS.length;
4825                            for (int ip=0; ip<NP; ip++) {
4826                                final PackageParser.NewPermissionInfo npi
4827                                        = PackageParser.NEW_PERMISSIONS[ip];
4828                                if (npi.name.equals(perm)
4829                                        && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4830                                    allowed = true;
4831                                    Log.i(TAG, "Auto-granting " + perm + " to old pkg "
4832                                            + pkg.packageName);
4833                                    break;
4834                                }
4835                            }
4836                        }
4837                    }
4838                    if (allowed) {
4839                        if (!gp.grantedPermissions.contains(perm)) {
4840                            changedPermission = true;
4841                            gp.grantedPermissions.add(perm);
4842                            gp.gids = appendInts(gp.gids, bp.gids);
4843                        } else if (!ps.haveGids) {
4844                            gp.gids = appendInts(gp.gids, bp.gids);
4845                        }
4846                    } else {
4847                        Slog.w(TAG, "Not granting permission " + perm
4848                                + " to package " + pkg.packageName
4849                                + " because it was previously installed without");
4850                    }
4851                } else {
4852                    if (gp.grantedPermissions.remove(perm)) {
4853                        changedPermission = true;
4854                        gp.gids = removeInts(gp.gids, bp.gids);
4855                        Slog.i(TAG, "Un-granting permission " + perm
4856                                + " from package " + pkg.packageName
4857                                + " (protectionLevel=" + bp.protectionLevel
4858                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4859                                + ")");
4860                    } else {
4861                        Slog.w(TAG, "Not granting permission " + perm
4862                                + " to package " + pkg.packageName
4863                                + " (protectionLevel=" + bp.protectionLevel
4864                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4865                                + ")");
4866                    }
4867                }
4868            } else {
4869                Slog.w(TAG, "Unknown permission " + name
4870                        + " in package " + pkg.packageName);
4871            }
4872        }
4873
4874        if ((changedPermission || replace) && !ps.permissionsFixed &&
4875                ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4876                ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
4877            // This is the first that we have heard about this package, so the
4878            // permissions we have now selected are fixed until explicitly
4879            // changed.
4880            ps.permissionsFixed = true;
4881        }
4882        ps.haveGids = true;
4883    }
4884
4885    private final class ActivityIntentResolver
4886            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
4887        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
4888                boolean defaultOnly, int userId) {
4889            if (!sUserManager.exists(userId)) return null;
4890            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
4891            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
4892        }
4893
4894        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4895                int userId) {
4896            if (!sUserManager.exists(userId)) return null;
4897            mFlags = flags;
4898            return super.queryIntent(intent, resolvedType,
4899                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
4900        }
4901
4902        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
4903                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
4904            if (!sUserManager.exists(userId)) return null;
4905            if (packageActivities == null) {
4906                return null;
4907            }
4908            mFlags = flags;
4909            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4910            final int N = packageActivities.size();
4911            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4912                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
4913
4914            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
4915            for (int i = 0; i < N; ++i) {
4916                intentFilters = packageActivities.get(i).intents;
4917                if (intentFilters != null && intentFilters.size() > 0) {
4918                    PackageParser.ActivityIntentInfo[] array =
4919                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
4920                    intentFilters.toArray(array);
4921                    listCut.add(array);
4922                }
4923            }
4924            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
4925        }
4926
4927        public final void addActivity(PackageParser.Activity a, String type) {
4928            final boolean systemApp = isSystemApp(a.info.applicationInfo);
4929            mActivities.put(a.getComponentName(), a);
4930            if (DEBUG_SHOW_INFO)
4931                Log.v(
4932                TAG, "  " + type + " " +
4933                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4934            if (DEBUG_SHOW_INFO)
4935                Log.v(TAG, "    Class=" + a.info.name);
4936            final int NI = a.intents.size();
4937            for (int j=0; j<NI; j++) {
4938                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4939                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4940                    intent.setPriority(0);
4941                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4942                            + a.className + " with priority > 0, forcing to 0");
4943                }
4944                if (DEBUG_SHOW_INFO) {
4945                    Log.v(TAG, "    IntentFilter:");
4946                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
4947                }
4948                if (!intent.debugCheck()) {
4949                    Log.w(TAG, "==> For Activity " + a.info.name);
4950                }
4951                addFilter(intent);
4952            }
4953        }
4954
4955        public final void removeActivity(PackageParser.Activity a, String type) {
4956            mActivities.remove(a.getComponentName());
4957            if (DEBUG_SHOW_INFO) {
4958                Log.v(TAG, "  " + type + " "
4959                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
4960                                : a.info.name) + ":");
4961                Log.v(TAG, "    Class=" + a.info.name);
4962            }
4963            final int NI = a.intents.size();
4964            for (int j=0; j<NI; j++) {
4965                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4966                if (DEBUG_SHOW_INFO) {
4967                    Log.v(TAG, "    IntentFilter:");
4968                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
4969                }
4970                removeFilter(intent);
4971            }
4972        }
4973
4974        @Override
4975        protected boolean allowFilterResult(
4976                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4977            ActivityInfo filterAi = filter.activity.info;
4978            for (int i=dest.size()-1; i>=0; i--) {
4979                ActivityInfo destAi = dest.get(i).activityInfo;
4980                if (destAi.name == filterAi.name
4981                        && destAi.packageName == filterAi.packageName) {
4982                    return false;
4983                }
4984            }
4985            return true;
4986        }
4987
4988        @Override
4989        protected ActivityIntentInfo[] newArray(int size) {
4990            return new ActivityIntentInfo[size];
4991        }
4992
4993        @Override
4994        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
4995            if (!sUserManager.exists(userId)) return true;
4996            PackageParser.Package p = filter.activity.owner;
4997            if (p != null) {
4998                PackageSetting ps = (PackageSetting)p.mExtras;
4999                if (ps != null) {
5000                    // System apps are never considered stopped for purposes of
5001                    // filtering, because there may be no way for the user to
5002                    // actually re-launch them.
5003                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5004                            && ps.getStopped(userId);
5005                }
5006            }
5007            return false;
5008        }
5009
5010        @Override
5011        protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
5012            return info.activity.owner.packageName;
5013        }
5014
5015        @Override
5016        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
5017                int match, int userId) {
5018            if (!sUserManager.exists(userId)) return null;
5019            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
5020                return null;
5021            }
5022            final PackageParser.Activity activity = info.activity;
5023            if (mSafeMode && (activity.info.applicationInfo.flags
5024                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5025                return null;
5026            }
5027            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
5028            if (ps == null) {
5029                return null;
5030            }
5031            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5032                    ps.readUserState(userId), userId);
5033            if (ai == null) {
5034                return null;
5035            }
5036            final ResolveInfo res = new ResolveInfo();
5037            res.activityInfo = ai;
5038            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5039                res.filter = info;
5040            }
5041            res.priority = info.getPriority();
5042            res.preferredOrder = activity.owner.mPreferredOrder;
5043            //System.out.println("Result: " + res.activityInfo.className +
5044            //                   " = " + res.priority);
5045            res.match = match;
5046            res.isDefault = info.hasDefault;
5047            res.labelRes = info.labelRes;
5048            res.nonLocalizedLabel = info.nonLocalizedLabel;
5049            res.icon = info.icon;
5050            res.system = isSystemApp(res.activityInfo.applicationInfo);
5051            return res;
5052        }
5053
5054        @Override
5055        protected void sortResults(List<ResolveInfo> results) {
5056            Collections.sort(results, mResolvePrioritySorter);
5057        }
5058
5059        @Override
5060        protected void dumpFilter(PrintWriter out, String prefix,
5061                PackageParser.ActivityIntentInfo filter) {
5062            out.print(prefix); out.print(
5063                    Integer.toHexString(System.identityHashCode(filter.activity)));
5064                    out.print(' ');
5065                    out.print(filter.activity.getComponentShortName());
5066                    out.print(" filter ");
5067                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5068        }
5069
5070//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5071//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5072//            final List<ResolveInfo> retList = Lists.newArrayList();
5073//            while (i.hasNext()) {
5074//                final ResolveInfo resolveInfo = i.next();
5075//                if (isEnabledLP(resolveInfo.activityInfo)) {
5076//                    retList.add(resolveInfo);
5077//                }
5078//            }
5079//            return retList;
5080//        }
5081
5082        // Keys are String (activity class name), values are Activity.
5083        private final HashMap<ComponentName, PackageParser.Activity> mActivities
5084                = new HashMap<ComponentName, PackageParser.Activity>();
5085        private int mFlags;
5086    }
5087
5088    private final class ServiceIntentResolver
5089            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
5090        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5091                boolean defaultOnly, int userId) {
5092            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5093            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5094        }
5095
5096        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5097                int userId) {
5098            if (!sUserManager.exists(userId)) return null;
5099            mFlags = flags;
5100            return super.queryIntent(intent, resolvedType,
5101                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5102        }
5103
5104        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5105                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
5106            if (!sUserManager.exists(userId)) return null;
5107            if (packageServices == null) {
5108                return null;
5109            }
5110            mFlags = flags;
5111            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5112            final int N = packageServices.size();
5113            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5114                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
5115
5116            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5117            for (int i = 0; i < N; ++i) {
5118                intentFilters = packageServices.get(i).intents;
5119                if (intentFilters != null && intentFilters.size() > 0) {
5120                    PackageParser.ServiceIntentInfo[] array =
5121                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
5122                    intentFilters.toArray(array);
5123                    listCut.add(array);
5124                }
5125            }
5126            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5127        }
5128
5129        public final void addService(PackageParser.Service s) {
5130            mServices.put(s.getComponentName(), s);
5131            if (DEBUG_SHOW_INFO) {
5132                Log.v(TAG, "  "
5133                        + (s.info.nonLocalizedLabel != null
5134                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5135                Log.v(TAG, "    Class=" + s.info.name);
5136            }
5137            final int NI = s.intents.size();
5138            int j;
5139            for (j=0; j<NI; j++) {
5140                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5141                if (DEBUG_SHOW_INFO) {
5142                    Log.v(TAG, "    IntentFilter:");
5143                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5144                }
5145                if (!intent.debugCheck()) {
5146                    Log.w(TAG, "==> For Service " + s.info.name);
5147                }
5148                addFilter(intent);
5149            }
5150        }
5151
5152        public final void removeService(PackageParser.Service s) {
5153            mServices.remove(s.getComponentName());
5154            if (DEBUG_SHOW_INFO) {
5155                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
5156                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5157                Log.v(TAG, "    Class=" + s.info.name);
5158            }
5159            final int NI = s.intents.size();
5160            int j;
5161            for (j=0; j<NI; j++) {
5162                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5163                if (DEBUG_SHOW_INFO) {
5164                    Log.v(TAG, "    IntentFilter:");
5165                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5166                }
5167                removeFilter(intent);
5168            }
5169        }
5170
5171        @Override
5172        protected boolean allowFilterResult(
5173                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5174            ServiceInfo filterSi = filter.service.info;
5175            for (int i=dest.size()-1; i>=0; i--) {
5176                ServiceInfo destAi = dest.get(i).serviceInfo;
5177                if (destAi.name == filterSi.name
5178                        && destAi.packageName == filterSi.packageName) {
5179                    return false;
5180                }
5181            }
5182            return true;
5183        }
5184
5185        @Override
5186        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5187            return new PackageParser.ServiceIntentInfo[size];
5188        }
5189
5190        @Override
5191        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
5192            if (!sUserManager.exists(userId)) return true;
5193            PackageParser.Package p = filter.service.owner;
5194            if (p != null) {
5195                PackageSetting ps = (PackageSetting)p.mExtras;
5196                if (ps != null) {
5197                    // System apps are never considered stopped for purposes of
5198                    // filtering, because there may be no way for the user to
5199                    // actually re-launch them.
5200                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5201                            && ps.getStopped(userId);
5202                }
5203            }
5204            return false;
5205        }
5206
5207        @Override
5208        protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5209            return info.service.owner.packageName;
5210        }
5211
5212        @Override
5213        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
5214                int match, int userId) {
5215            if (!sUserManager.exists(userId)) return null;
5216            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
5217            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
5218                return null;
5219            }
5220            final PackageParser.Service service = info.service;
5221            if (mSafeMode && (service.info.applicationInfo.flags
5222                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5223                return null;
5224            }
5225            PackageSetting ps = (PackageSetting) service.owner.mExtras;
5226            if (ps == null) {
5227                return null;
5228            }
5229            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5230                    ps.readUserState(userId), userId);
5231            if (si == null) {
5232                return null;
5233            }
5234            final ResolveInfo res = new ResolveInfo();
5235            res.serviceInfo = si;
5236            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5237                res.filter = filter;
5238            }
5239            res.priority = info.getPriority();
5240            res.preferredOrder = service.owner.mPreferredOrder;
5241            //System.out.println("Result: " + res.activityInfo.className +
5242            //                   " = " + res.priority);
5243            res.match = match;
5244            res.isDefault = info.hasDefault;
5245            res.labelRes = info.labelRes;
5246            res.nonLocalizedLabel = info.nonLocalizedLabel;
5247            res.icon = info.icon;
5248            res.system = isSystemApp(res.serviceInfo.applicationInfo);
5249            return res;
5250        }
5251
5252        @Override
5253        protected void sortResults(List<ResolveInfo> results) {
5254            Collections.sort(results, mResolvePrioritySorter);
5255        }
5256
5257        @Override
5258        protected void dumpFilter(PrintWriter out, String prefix,
5259                PackageParser.ServiceIntentInfo filter) {
5260            out.print(prefix); out.print(
5261                    Integer.toHexString(System.identityHashCode(filter.service)));
5262                    out.print(' ');
5263                    out.print(filter.service.getComponentShortName());
5264                    out.print(" filter ");
5265                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5266        }
5267
5268//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5269//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5270//            final List<ResolveInfo> retList = Lists.newArrayList();
5271//            while (i.hasNext()) {
5272//                final ResolveInfo resolveInfo = (ResolveInfo) i;
5273//                if (isEnabledLP(resolveInfo.serviceInfo)) {
5274//                    retList.add(resolveInfo);
5275//                }
5276//            }
5277//            return retList;
5278//        }
5279
5280        // Keys are String (activity class name), values are Activity.
5281        private final HashMap<ComponentName, PackageParser.Service> mServices
5282                = new HashMap<ComponentName, PackageParser.Service>();
5283        private int mFlags;
5284    };
5285
5286    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5287            new Comparator<ResolveInfo>() {
5288        public int compare(ResolveInfo r1, ResolveInfo r2) {
5289            int v1 = r1.priority;
5290            int v2 = r2.priority;
5291            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5292            if (v1 != v2) {
5293                return (v1 > v2) ? -1 : 1;
5294            }
5295            v1 = r1.preferredOrder;
5296            v2 = r2.preferredOrder;
5297            if (v1 != v2) {
5298                return (v1 > v2) ? -1 : 1;
5299            }
5300            if (r1.isDefault != r2.isDefault) {
5301                return r1.isDefault ? -1 : 1;
5302            }
5303            v1 = r1.match;
5304            v2 = r2.match;
5305            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
5306            if (v1 != v2) {
5307                return (v1 > v2) ? -1 : 1;
5308            }
5309            if (r1.system != r2.system) {
5310                return r1.system ? -1 : 1;
5311            }
5312            return 0;
5313        }
5314    };
5315
5316    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5317            new Comparator<ProviderInfo>() {
5318        public int compare(ProviderInfo p1, ProviderInfo p2) {
5319            final int v1 = p1.initOrder;
5320            final int v2 = p2.initOrder;
5321            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5322        }
5323    };
5324
5325    static final void sendPackageBroadcast(String action, String pkg,
5326            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5327            int[] userIds) {
5328        IActivityManager am = ActivityManagerNative.getDefault();
5329        if (am != null) {
5330            try {
5331                if (userIds == null) {
5332                    userIds = sUserManager.getUserIds();
5333                }
5334                for (int id : userIds) {
5335                    final Intent intent = new Intent(action,
5336                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
5337                    if (extras != null) {
5338                        intent.putExtras(extras);
5339                    }
5340                    if (targetPkg != null) {
5341                        intent.setPackage(targetPkg);
5342                    }
5343                    // Modify the UID when posting to other users
5344                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
5345                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
5346                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
5347                        intent.putExtra(Intent.EXTRA_UID, uid);
5348                    }
5349                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5350                    if (DEBUG_BROADCASTS) {
5351                        RuntimeException here = new RuntimeException("here");
5352                        here.fillInStackTrace();
5353                        Slog.d(TAG, "Sending to user " + id + ": "
5354                                + intent.toShortString(false, true, false, false)
5355                                + " " + intent.getExtras(), here);
5356                    }
5357                    am.broadcastIntent(null, intent, null, finishedReceiver,
5358                            0, null, null, null, finishedReceiver != null, false, id);
5359                }
5360            } catch (RemoteException ex) {
5361            }
5362        }
5363    }
5364
5365    /**
5366     * Check if the external storage media is available. This is true if there
5367     * is a mounted external storage medium or if the external storage is
5368     * emulated.
5369     */
5370    private boolean isExternalMediaAvailable() {
5371        return mMediaMounted || Environment.isExternalStorageEmulated();
5372    }
5373
5374    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
5375        // writer
5376        final int userId = UserHandle.getCallingUserId();
5377        synchronized (mPackages) {
5378            if (!isExternalMediaAvailable()) {
5379                // If the external storage is no longer mounted at this point,
5380                // the caller may not have been able to delete all of this
5381                // packages files and can not delete any more.  Bail.
5382                return null;
5383            }
5384            ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned.get(userId);
5385            if (pkgs != null) {
5386                if (lastPackage != null) {
5387                    pkgs.remove(lastPackage);
5388                }
5389                if (pkgs.size() > 0) {
5390                    return pkgs.get(0);
5391                }
5392            }
5393            mSettings.mPackagesToBeCleaned.remove(userId);
5394        }
5395        // Move on to the next user to clean.
5396        long ident = Binder.clearCallingIdentity();
5397        try {
5398            startCleaningPackages(userId);
5399        } finally {
5400            Binder.restoreCallingIdentity(ident);
5401        }
5402        return null;
5403    }
5404
5405    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5406        if (false) {
5407            RuntimeException here = new RuntimeException("here");
5408            here.fillInStackTrace();
5409            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5410                    + " andCode=" + andCode, here);
5411        }
5412        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5413                userId, andCode ? 1 : 0, packageName));
5414    }
5415
5416    void startCleaningPackages(int lastUser) {
5417        // reader
5418        int nextUser = -1;
5419        synchronized (mPackages) {
5420            if (!isExternalMediaAvailable()) {
5421                return;
5422            }
5423            final int N = mSettings.mPackagesToBeCleaned.size();
5424            if (N <= 0) {
5425                return;
5426            }
5427            for (int i=0; i<N; i++) {
5428                int user = mSettings.mPackagesToBeCleaned.keyAt(i);
5429                if (user > lastUser) {
5430                    nextUser = user;
5431                    break;
5432                }
5433            }
5434            if (nextUser < 0) {
5435                nextUser = mSettings.mPackagesToBeCleaned.keyAt(0);
5436            }
5437        }
5438        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5439        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5440        IActivityManager am = ActivityManagerNative.getDefault();
5441        if (am != null) {
5442            try {
5443                am.startService(null, intent, null, nextUser);
5444            } catch (RemoteException e) {
5445            }
5446        }
5447    }
5448
5449    private final class AppDirObserver extends FileObserver {
5450        public AppDirObserver(String path, int mask, boolean isrom) {
5451            super(path, mask);
5452            mRootDir = path;
5453            mIsRom = isrom;
5454        }
5455
5456        public void onEvent(int event, String path) {
5457            String removedPackage = null;
5458            int removedAppId = -1;
5459            int[] removedUsers = null;
5460            String addedPackage = null;
5461            int addedAppId = -1;
5462            int[] addedUsers = null;
5463
5464            // TODO post a message to the handler to obtain serial ordering
5465            synchronized (mInstallLock) {
5466                String fullPathStr = null;
5467                File fullPath = null;
5468                if (path != null) {
5469                    fullPath = new File(mRootDir, path);
5470                    fullPathStr = fullPath.getPath();
5471                }
5472
5473                if (DEBUG_APP_DIR_OBSERVER)
5474                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
5475
5476                if (!isPackageFilename(path)) {
5477                    if (DEBUG_APP_DIR_OBSERVER)
5478                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
5479                    return;
5480                }
5481
5482                // Ignore packages that are being installed or
5483                // have just been installed.
5484                if (ignoreCodePath(fullPathStr)) {
5485                    return;
5486                }
5487                PackageParser.Package p = null;
5488                PackageSetting ps = null;
5489                // reader
5490                synchronized (mPackages) {
5491                    p = mAppDirs.get(fullPathStr);
5492                    if (p != null) {
5493                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
5494                        if (ps != null) {
5495                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5496                        } else {
5497                            removedUsers = sUserManager.getUserIds();
5498                        }
5499                    }
5500                    addedUsers = sUserManager.getUserIds();
5501                }
5502                if ((event&REMOVE_EVENTS) != 0) {
5503                    if (ps != null) {
5504                        removePackageLI(ps, true);
5505                        removedPackage = ps.name;
5506                        removedAppId = ps.appId;
5507                    }
5508                }
5509
5510                if ((event&ADD_EVENTS) != 0) {
5511                    if (p == null) {
5512                        p = scanPackageLI(fullPath,
5513                                (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5514                                        | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
5515                                PackageParser.PARSE_CHATTY |
5516                                PackageParser.PARSE_MUST_BE_APK,
5517                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
5518                                System.currentTimeMillis(), UserHandle.ALL);
5519                        if (p != null) {
5520                            /*
5521                             * TODO this seems dangerous as the package may have
5522                             * changed since we last acquired the mPackages
5523                             * lock.
5524                             */
5525                            // writer
5526                            synchronized (mPackages) {
5527                                updatePermissionsLPw(p.packageName, p,
5528                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
5529                            }
5530                            addedPackage = p.applicationInfo.packageName;
5531                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
5532                        }
5533                    }
5534                }
5535
5536                // reader
5537                synchronized (mPackages) {
5538                    mSettings.writeLPr();
5539                }
5540            }
5541
5542            if (removedPackage != null) {
5543                Bundle extras = new Bundle(1);
5544                extras.putInt(Intent.EXTRA_UID, removedAppId);
5545                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
5546                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
5547                        extras, null, null, removedUsers);
5548            }
5549            if (addedPackage != null) {
5550                Bundle extras = new Bundle(1);
5551                extras.putInt(Intent.EXTRA_UID, addedAppId);
5552                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
5553                        extras, null, null, addedUsers);
5554            }
5555        }
5556
5557        private final String mRootDir;
5558        private final boolean mIsRom;
5559    }
5560
5561    /* Called when a downloaded package installation has been confirmed by the user */
5562    public void installPackage(
5563            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
5564        installPackage(packageURI, observer, flags, null);
5565    }
5566
5567    /* Called when a downloaded package installation has been confirmed by the user */
5568    public void installPackage(
5569            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5570            final String installerPackageName) {
5571        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
5572                null, null);
5573    }
5574
5575    @Override
5576    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5577            int flags, String installerPackageName, Uri verificationURI,
5578            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
5579        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
5580                manifestDigest);
5581        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
5582                installerPackageName, verificationParams, encryptionParams);
5583    }
5584
5585    public void installPackageWithVerificationAndEncryption(Uri packageURI,
5586            IPackageInstallObserver observer, int flags, String installerPackageName,
5587            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
5588        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5589                null);
5590
5591        final int uid = Binder.getCallingUid();
5592        UserHandle user;
5593        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
5594            user = UserHandle.ALL;
5595        } else {
5596            user = new UserHandle(UserHandle.getUserId(uid));
5597        }
5598
5599        final int filteredFlags;
5600
5601        if (uid == Process.SHELL_UID || uid == 0) {
5602            if (DEBUG_INSTALL) {
5603                Slog.v(TAG, "Install from ADB");
5604            }
5605            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5606        } else {
5607            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5608        }
5609
5610        final Message msg = mHandler.obtainMessage(INIT_COPY);
5611        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
5612                verificationParams, encryptionParams, user);
5613        mHandler.sendMessage(msg);
5614    }
5615
5616    /**
5617     * @hide
5618     */
5619    @Override
5620    public int installExistingPackage(String packageName) {
5621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5622                null);
5623        PackageSetting pkgSetting;
5624        final int uid = Binder.getCallingUid();
5625        final int userId = UserHandle.getUserId(uid);
5626
5627        long callingId = Binder.clearCallingIdentity();
5628        try {
5629            boolean sendAdded = false;
5630            Bundle extras = new Bundle(1);
5631
5632            // writer
5633            synchronized (mPackages) {
5634                pkgSetting = mSettings.mPackages.get(packageName);
5635                if (pkgSetting == null) {
5636                    return PackageManager.INSTALL_FAILED_INVALID_URI;
5637                }
5638                if (!pkgSetting.getInstalled(userId)) {
5639                    pkgSetting.setInstalled(true, userId);
5640                    mSettings.writePackageRestrictionsLPr(userId);
5641                    extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
5642                    sendAdded = true;
5643                }
5644            }
5645
5646            if (sendAdded) {
5647                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
5648                        packageName, extras, null, null, new int[] {userId});
5649            }
5650        } finally {
5651            Binder.restoreCallingIdentity(callingId);
5652        }
5653
5654        return PackageManager.INSTALL_SUCCEEDED;
5655    }
5656
5657    @Override
5658    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
5659        mContext.enforceCallingOrSelfPermission(
5660                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5661                "Only package verification agents can verify applications");
5662
5663        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5664        final PackageVerificationResponse response = new PackageVerificationResponse(
5665                verificationCode, Binder.getCallingUid());
5666        msg.arg1 = id;
5667        msg.obj = response;
5668        mHandler.sendMessage(msg);
5669    }
5670
5671    @Override
5672    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
5673            long millisecondsToDelay) {
5674        mContext.enforceCallingOrSelfPermission(
5675                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5676                "Only package verification agents can extend verification timeouts");
5677
5678        final PackageVerificationState state = mPendingVerification.get(id);
5679        final PackageVerificationResponse response = new PackageVerificationResponse(
5680                verificationCodeAtTimeout, Binder.getCallingUid());
5681
5682        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
5683            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
5684        }
5685        if (millisecondsToDelay < 0) {
5686            millisecondsToDelay = 0;
5687        }
5688        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
5689                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
5690            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
5691        }
5692
5693        if ((state != null) && !state.timeoutExtended()) {
5694            state.extendTimeout();
5695
5696            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5697            msg.arg1 = id;
5698            msg.obj = response;
5699            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
5700        }
5701    }
5702
5703    private void broadcastPackageVerified(int verificationId, Uri packageUri,
5704            int verificationCode) {
5705        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
5706        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
5707        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5708        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
5709        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
5710
5711        mContext.sendBroadcast(intent, android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
5712    }
5713
5714    private ComponentName matchComponentForVerifier(String packageName,
5715            List<ResolveInfo> receivers) {
5716        ActivityInfo targetReceiver = null;
5717
5718        final int NR = receivers.size();
5719        for (int i = 0; i < NR; i++) {
5720            final ResolveInfo info = receivers.get(i);
5721            if (info.activityInfo == null) {
5722                continue;
5723            }
5724
5725            if (packageName.equals(info.activityInfo.packageName)) {
5726                targetReceiver = info.activityInfo;
5727                break;
5728            }
5729        }
5730
5731        if (targetReceiver == null) {
5732            return null;
5733        }
5734
5735        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5736    }
5737
5738    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5739            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5740        if (pkgInfo.verifiers.length == 0) {
5741            return null;
5742        }
5743
5744        final int N = pkgInfo.verifiers.length;
5745        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5746        for (int i = 0; i < N; i++) {
5747            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5748
5749            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5750                    receivers);
5751            if (comp == null) {
5752                continue;
5753            }
5754
5755            final int verifierUid = getUidForVerifier(verifierInfo);
5756            if (verifierUid == -1) {
5757                continue;
5758            }
5759
5760            if (DEBUG_VERIFY) {
5761                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5762                        + " with the correct signature");
5763            }
5764            sufficientVerifiers.add(comp);
5765            verificationState.addSufficientVerifier(verifierUid);
5766        }
5767
5768        return sufficientVerifiers;
5769    }
5770
5771    private int getUidForVerifier(VerifierInfo verifierInfo) {
5772        synchronized (mPackages) {
5773            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5774            if (pkg == null) {
5775                return -1;
5776            } else if (pkg.mSignatures.length != 1) {
5777                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5778                        + " has more than one signature; ignoring");
5779                return -1;
5780            }
5781
5782            /*
5783             * If the public key of the package's signature does not match
5784             * our expected public key, then this is a different package and
5785             * we should skip.
5786             */
5787
5788            final byte[] expectedPublicKey;
5789            try {
5790                final Signature verifierSig = pkg.mSignatures[0];
5791                final PublicKey publicKey = verifierSig.getPublicKey();
5792                expectedPublicKey = publicKey.getEncoded();
5793            } catch (CertificateException e) {
5794                return -1;
5795            }
5796
5797            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5798
5799            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5800                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5801                        + " does not have the expected public key; ignoring");
5802                return -1;
5803            }
5804
5805            return pkg.applicationInfo.uid;
5806        }
5807    }
5808
5809    public void finishPackageInstall(int token) {
5810        enforceSystemOrRoot("Only the system is allowed to finish installs");
5811
5812        if (DEBUG_INSTALL) {
5813            Slog.v(TAG, "BM finishing package install for " + token);
5814        }
5815
5816        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5817        mHandler.sendMessage(msg);
5818    }
5819
5820    /**
5821     * Get the verification agent timeout.
5822     *
5823     * @return verification timeout in milliseconds
5824     */
5825    private long getVerificationTimeout() {
5826        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
5827                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
5828                DEFAULT_VERIFICATION_TIMEOUT);
5829    }
5830
5831    /**
5832     * Get the default verification agent response code.
5833     *
5834     * @return default verification response code
5835     */
5836    private int getDefaultVerificationResponse() {
5837        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5838                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
5839                DEFAULT_VERIFICATION_RESPONSE);
5840    }
5841
5842    /**
5843     * Check whether or not package verification has been enabled.
5844     *
5845     * @return true if verification should be performed
5846     */
5847    private boolean isVerificationEnabled() {
5848        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5849                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE,
5850                DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false;
5851    }
5852
5853    /**
5854     * Get the "allow unknown sources" setting.
5855     *
5856     * @return the current "allow unknown sources" setting
5857     */
5858    private int getUnknownSourcesSettings() {
5859        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
5860                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
5861                -1);
5862    }
5863
5864    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
5865        final int uid = Binder.getCallingUid();
5866        // writer
5867        synchronized (mPackages) {
5868            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5869            if (targetPackageSetting == null) {
5870                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5871            }
5872
5873            PackageSetting installerPackageSetting;
5874            if (installerPackageName != null) {
5875                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5876                if (installerPackageSetting == null) {
5877                    throw new IllegalArgumentException("Unknown installer package: "
5878                            + installerPackageName);
5879                }
5880            } else {
5881                installerPackageSetting = null;
5882            }
5883
5884            Signature[] callerSignature;
5885            Object obj = mSettings.getUserIdLPr(uid);
5886            if (obj != null) {
5887                if (obj instanceof SharedUserSetting) {
5888                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5889                } else if (obj instanceof PackageSetting) {
5890                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5891                } else {
5892                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
5893                }
5894            } else {
5895                throw new SecurityException("Unknown calling uid " + uid);
5896            }
5897
5898            // Verify: can't set installerPackageName to a package that is
5899            // not signed with the same cert as the caller.
5900            if (installerPackageSetting != null) {
5901                if (compareSignatures(callerSignature,
5902                        installerPackageSetting.signatures.mSignatures)
5903                        != PackageManager.SIGNATURE_MATCH) {
5904                    throw new SecurityException(
5905                            "Caller does not have same cert as new installer package "
5906                            + installerPackageName);
5907                }
5908            }
5909
5910            // Verify: if target already has an installer package, it must
5911            // be signed with the same cert as the caller.
5912            if (targetPackageSetting.installerPackageName != null) {
5913                PackageSetting setting = mSettings.mPackages.get(
5914                        targetPackageSetting.installerPackageName);
5915                // If the currently set package isn't valid, then it's always
5916                // okay to change it.
5917                if (setting != null) {
5918                    if (compareSignatures(callerSignature,
5919                            setting.signatures.mSignatures)
5920                            != PackageManager.SIGNATURE_MATCH) {
5921                        throw new SecurityException(
5922                                "Caller does not have same cert as old installer package "
5923                                + targetPackageSetting.installerPackageName);
5924                    }
5925                }
5926            }
5927
5928            // Okay!
5929            targetPackageSetting.installerPackageName = installerPackageName;
5930            scheduleWriteSettingsLocked();
5931        }
5932    }
5933
5934    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
5935        // Queue up an async operation since the package installation may take a little while.
5936        mHandler.post(new Runnable() {
5937            public void run() {
5938                mHandler.removeCallbacks(this);
5939                 // Result object to be returned
5940                PackageInstalledInfo res = new PackageInstalledInfo();
5941                res.returnCode = currentStatus;
5942                res.uid = -1;
5943                res.pkg = null;
5944                res.removedInfo = new PackageRemovedInfo();
5945                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5946                    args.doPreInstall(res.returnCode);
5947                    synchronized (mInstallLock) {
5948                        installPackageLI(args, true, res);
5949                    }
5950                    args.doPostInstall(res.returnCode, res.uid);
5951                }
5952
5953                // A restore should be performed at this point if (a) the install
5954                // succeeded, (b) the operation is not an update, and (c) the new
5955                // package has a backupAgent defined.
5956                final boolean update = res.removedInfo.removedPackage != null;
5957                boolean doRestore = (!update
5958                        && res.pkg != null
5959                        && res.pkg.applicationInfo.backupAgentName != null);
5960
5961                // Set up the post-install work request bookkeeping.  This will be used
5962                // and cleaned up by the post-install event handling regardless of whether
5963                // there's a restore pass performed.  Token values are >= 1.
5964                int token;
5965                if (mNextInstallToken < 0) mNextInstallToken = 1;
5966                token = mNextInstallToken++;
5967
5968                PostInstallData data = new PostInstallData(args, res);
5969                mRunningInstalls.put(token, data);
5970                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
5971
5972                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
5973                    // Pass responsibility to the Backup Manager.  It will perform a
5974                    // restore if appropriate, then pass responsibility back to the
5975                    // Package Manager to run the post-install observer callbacks
5976                    // and broadcasts.
5977                    IBackupManager bm = IBackupManager.Stub.asInterface(
5978                            ServiceManager.getService(Context.BACKUP_SERVICE));
5979                    if (bm != null) {
5980                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
5981                                + " to BM for possible restore");
5982                        try {
5983                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
5984                        } catch (RemoteException e) {
5985                            // can't happen; the backup manager is local
5986                        } catch (Exception e) {
5987                            Slog.e(TAG, "Exception trying to enqueue restore", e);
5988                            doRestore = false;
5989                        }
5990                    } else {
5991                        Slog.e(TAG, "Backup Manager not found!");
5992                        doRestore = false;
5993                    }
5994                }
5995
5996                if (!doRestore) {
5997                    // No restore possible, or the Backup Manager was mysteriously not
5998                    // available -- just fire the post-install work request directly.
5999                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
6000                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6001                    mHandler.sendMessage(msg);
6002                }
6003            }
6004        });
6005    }
6006
6007    private abstract class HandlerParams {
6008        private static final int MAX_RETRIES = 4;
6009
6010        /**
6011         * Number of times startCopy() has been attempted and had a non-fatal
6012         * error.
6013         */
6014        private int mRetries = 0;
6015
6016        /** User handle for the user requesting the information or installation. */
6017        private final UserHandle mUser;
6018
6019        HandlerParams(UserHandle user) {
6020            mUser = user;
6021        }
6022
6023        UserHandle getUser() {
6024            return mUser;
6025        }
6026
6027        final boolean startCopy() {
6028            boolean res;
6029            try {
6030                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
6031
6032                if (++mRetries > MAX_RETRIES) {
6033                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
6034                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
6035                    handleServiceError();
6036                    return false;
6037                } else {
6038                    handleStartCopy();
6039                    res = true;
6040                }
6041            } catch (RemoteException e) {
6042                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
6043                mHandler.sendEmptyMessage(MCS_RECONNECT);
6044                res = false;
6045            }
6046            handleReturnCode();
6047            return res;
6048        }
6049
6050        final void serviceError() {
6051            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
6052            handleServiceError();
6053            handleReturnCode();
6054        }
6055
6056        abstract void handleStartCopy() throws RemoteException;
6057        abstract void handleServiceError();
6058        abstract void handleReturnCode();
6059    }
6060
6061    class MeasureParams extends HandlerParams {
6062        private final PackageStats mStats;
6063        private boolean mSuccess;
6064
6065        private final IPackageStatsObserver mObserver;
6066
6067        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
6068            super(new UserHandle(stats.userHandle));
6069            mObserver = observer;
6070            mStats = stats;
6071        }
6072
6073        @Override
6074        void handleStartCopy() throws RemoteException {
6075            synchronized (mInstallLock) {
6076                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
6077            }
6078
6079            final boolean mounted;
6080            if (Environment.isExternalStorageEmulated()) {
6081                mounted = true;
6082            } else {
6083                final String status = Environment.getExternalStorageState();
6084
6085                mounted = status.equals(Environment.MEDIA_MOUNTED)
6086                        || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
6087            }
6088
6089            if (mounted) {
6090                final File externalCacheDir = Environment
6091                        .getExternalStorageAppCacheDirectory(mStats.packageName);
6092                final long externalCacheSize = mContainerService
6093                        .calculateDirectorySize(externalCacheDir.getPath());
6094                mStats.externalCacheSize = externalCacheSize;
6095
6096                final File externalDataDir = Environment
6097                        .getExternalStorageAppDataDirectory(mStats.packageName);
6098                long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6099                        .getPath());
6100
6101                if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6102                    externalDataSize -= externalCacheSize;
6103                }
6104                mStats.externalDataSize = externalDataSize;
6105
6106                final File externalMediaDir = Environment
6107                        .getExternalStorageAppMediaDirectory(mStats.packageName);
6108                mStats.externalMediaSize = mContainerService
6109                        .calculateDirectorySize(externalMediaDir.getPath());
6110
6111                final File externalObbDir = Environment
6112                        .getExternalStorageAppObbDirectory(mStats.packageName);
6113                mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6114                        .getPath());
6115            }
6116        }
6117
6118        @Override
6119        void handleReturnCode() {
6120            if (mObserver != null) {
6121                try {
6122                    mObserver.onGetStatsCompleted(mStats, mSuccess);
6123                } catch (RemoteException e) {
6124                    Slog.i(TAG, "Observer no longer exists.");
6125                }
6126            }
6127        }
6128
6129        @Override
6130        void handleServiceError() {
6131            Slog.e(TAG, "Could not measure application " + mStats.packageName
6132                            + " external storage");
6133        }
6134    }
6135
6136    class InstallParams extends HandlerParams {
6137        final IPackageInstallObserver observer;
6138        int flags;
6139
6140        private final Uri mPackageURI;
6141        final String installerPackageName;
6142        final VerificationParams verificationParams;
6143        private InstallArgs mArgs;
6144        private int mRet;
6145        private File mTempPackage;
6146        final ContainerEncryptionParams encryptionParams;
6147
6148        InstallParams(Uri packageURI,
6149                IPackageInstallObserver observer, int flags,
6150                String installerPackageName, VerificationParams verificationParams,
6151                ContainerEncryptionParams encryptionParams, UserHandle user) {
6152            super(user);
6153            this.mPackageURI = packageURI;
6154            this.flags = flags;
6155            this.observer = observer;
6156            this.installerPackageName = installerPackageName;
6157            this.verificationParams = verificationParams;
6158            this.encryptionParams = encryptionParams;
6159        }
6160
6161        public ManifestDigest getManifestDigest() {
6162            if (verificationParams == null) {
6163                return null;
6164            }
6165            return verificationParams.getManifestDigest();
6166        }
6167
6168        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6169            String packageName = pkgLite.packageName;
6170            int installLocation = pkgLite.installLocation;
6171            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6172            // reader
6173            synchronized (mPackages) {
6174                PackageParser.Package pkg = mPackages.get(packageName);
6175                if (pkg != null) {
6176                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
6177                        // Check for downgrading.
6178                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6179                            if (pkgLite.versionCode < pkg.mVersionCode) {
6180                                Slog.w(TAG, "Can't install update of " + packageName
6181                                        + " update version " + pkgLite.versionCode
6182                                        + " is older than installed version "
6183                                        + pkg.mVersionCode);
6184                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6185                            }
6186                        }
6187                        // Check for updated system application.
6188                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6189                            if (onSd) {
6190                                Slog.w(TAG, "Cannot install update to system app on sdcard");
6191                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6192                            }
6193                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6194                        } else {
6195                            if (onSd) {
6196                                // Install flag overrides everything.
6197                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6198                            }
6199                            // If current upgrade specifies particular preference
6200                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6201                                // Application explicitly specified internal.
6202                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6203                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6204                                // App explictly prefers external. Let policy decide
6205                            } else {
6206                                // Prefer previous location
6207                                if (isExternal(pkg)) {
6208                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6209                                }
6210                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6211                            }
6212                        }
6213                    } else {
6214                        // Invalid install. Return error code
6215                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6216                    }
6217                }
6218            }
6219            // All the special cases have been taken care of.
6220            // Return result based on recommended install location.
6221            if (onSd) {
6222                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6223            }
6224            return pkgLite.recommendedInstallLocation;
6225        }
6226
6227        /*
6228         * Invoke remote method to get package information and install
6229         * location values. Override install location based on default
6230         * policy if needed and then create install arguments based
6231         * on the install location.
6232         */
6233        public void handleStartCopy() throws RemoteException {
6234            int ret = PackageManager.INSTALL_SUCCEEDED;
6235            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6236            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6237            PackageInfoLite pkgLite = null;
6238
6239            if (onInt && onSd) {
6240                // Check if both bits are set.
6241                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6242                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6243            } else {
6244                final long lowThreshold;
6245
6246                final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6247                        .getService(DeviceStorageMonitorService.SERVICE);
6248                if (dsm == null) {
6249                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6250                    lowThreshold = 0L;
6251                } else {
6252                    lowThreshold = dsm.getMemoryLowThreshold();
6253                }
6254
6255                try {
6256                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
6257                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6258
6259                    final File packageFile;
6260                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
6261                        ParcelFileDescriptor out = null;
6262
6263                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6264                        if (mTempPackage != null) {
6265                            try {
6266                                out = ParcelFileDescriptor.open(mTempPackage,
6267                                        ParcelFileDescriptor.MODE_READ_WRITE);
6268                            } catch (FileNotFoundException e) {
6269                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6270                            }
6271
6272                            // Make a temporary file for decryption.
6273                            ret = mContainerService
6274                                    .copyResource(mPackageURI, encryptionParams, out);
6275
6276                            packageFile = mTempPackage;
6277
6278                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
6279                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IROTH,
6280                                    -1, -1);
6281                        } else {
6282                            packageFile = null;
6283                        }
6284                    } else {
6285                        packageFile = new File(mPackageURI.getPath());
6286                    }
6287
6288                    if (packageFile != null) {
6289                        // Remote call to find out default install location
6290                        pkgLite = mContainerService.getMinimalPackageInfo(
6291                                packageFile.getAbsolutePath(), flags, lowThreshold);
6292                    }
6293                } finally {
6294                    mContext.revokeUriPermission(mPackageURI,
6295                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6296                }
6297            }
6298
6299            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6300                int loc = pkgLite.recommendedInstallLocation;
6301                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
6302                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6303                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
6304                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
6305                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
6306                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6307                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6308                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
6309                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6310                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
6311                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
6312                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
6313                } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6314                    ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
6315                } else {
6316                    // Override with defaults if needed.
6317                    loc = installLocationPolicy(pkgLite, flags);
6318                    if (!onSd && !onInt) {
6319                        // Override install location with flags
6320                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6321                            // Set the flag to install on external media.
6322                            flags |= PackageManager.INSTALL_EXTERNAL;
6323                            flags &= ~PackageManager.INSTALL_INTERNAL;
6324                        } else {
6325                            // Make sure the flag for installing on external
6326                            // media is unset
6327                            flags |= PackageManager.INSTALL_INTERNAL;
6328                            flags &= ~PackageManager.INSTALL_EXTERNAL;
6329                        }
6330                    }
6331                }
6332            }
6333
6334            final InstallArgs args = createInstallArgs(this);
6335            mArgs = args;
6336
6337            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6338                /*
6339                 * Determine if we have any installed package verifiers. If we
6340                 * do, then we'll defer to them to verify the packages.
6341                 */
6342                final int requiredUid = mRequiredVerifierPackage == null ? -1
6343                        : getPackageUid(mRequiredVerifierPackage, 0);
6344                if (requiredUid != -1 && isVerificationEnabled()) {
6345                    final Intent verification = new Intent(
6346                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6347                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
6348                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6349
6350                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6351                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6352                            0 /* TODO: Which userId? */);
6353
6354                    if (DEBUG_VERIFY) {
6355                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
6356                                + verification.toString() + " with " + pkgLite.verifiers.length
6357                                + " optional verifiers");
6358                    }
6359
6360                    final int verificationId = mPendingVerificationToken++;
6361
6362                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6363
6364                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6365                            installerPackageName);
6366
6367                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6368
6369                    if (verificationParams != null) {
6370                        if (verificationParams.getVerificationURI() != null) {
6371                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6372                                 verificationParams.getVerificationURI());
6373                        }
6374                        if (verificationParams.getOriginatingURI() != null) {
6375                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6376                                  verificationParams.getOriginatingURI());
6377                        }
6378                        if (verificationParams.getReferrer() != null) {
6379                            verification.putExtra(Intent.EXTRA_REFERRER,
6380                                  verificationParams.getReferrer());
6381                        }
6382                    }
6383
6384                    final PackageVerificationState verificationState = new PackageVerificationState(
6385                            requiredUid, args);
6386
6387                    mPendingVerification.append(verificationId, verificationState);
6388
6389                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6390                            receivers, verificationState);
6391
6392                    /*
6393                     * If any sufficient verifiers were listed in the package
6394                     * manifest, attempt to ask them.
6395                     */
6396                    if (sufficientVerifiers != null) {
6397                        final int N = sufficientVerifiers.size();
6398                        if (N == 0) {
6399                            Slog.i(TAG, "Additional verifiers required, but none installed.");
6400                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6401                        } else {
6402                            for (int i = 0; i < N; i++) {
6403                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
6404
6405                                final Intent sufficientIntent = new Intent(verification);
6406                                sufficientIntent.setComponent(verifierComponent);
6407
6408                                mContext.sendBroadcast(sufficientIntent);
6409                            }
6410                        }
6411                    }
6412
6413                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6414                            mRequiredVerifierPackage, receivers);
6415                    if (ret == PackageManager.INSTALL_SUCCEEDED
6416                            && mRequiredVerifierPackage != null) {
6417                        /*
6418                         * Send the intent to the required verification agent,
6419                         * but only start the verification timeout after the
6420                         * target BroadcastReceivers have run.
6421                         */
6422                        verification.setComponent(requiredVerifierComponent);
6423                        mContext.sendOrderedBroadcast(verification,
6424                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6425                                new BroadcastReceiver() {
6426                                    @Override
6427                                    public void onReceive(Context context, Intent intent) {
6428                                        final Message msg = mHandler
6429                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
6430                                        msg.arg1 = verificationId;
6431                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6432                                    }
6433                                }, null, 0, null, null);
6434
6435                        /*
6436                         * We don't want the copy to proceed until verification
6437                         * succeeds, so null out this field.
6438                         */
6439                        mArgs = null;
6440                    }
6441                } else {
6442                    /*
6443                     * No package verification is enabled, so immediately start
6444                     * the remote call to initiate copy using temporary file.
6445                     */
6446                    ret = args.copyApk(mContainerService, true);
6447                }
6448            }
6449
6450            mRet = ret;
6451        }
6452
6453        @Override
6454        void handleReturnCode() {
6455            // If mArgs is null, then MCS couldn't be reached. When it
6456            // reconnects, it will try again to install. At that point, this
6457            // will succeed.
6458            if (mArgs != null) {
6459                processPendingInstall(mArgs, mRet);
6460            }
6461
6462            if (mTempPackage != null) {
6463                if (!mTempPackage.delete()) {
6464                    Slog.w(TAG, "Couldn't delete temporary file: "
6465                            + mTempPackage.getAbsolutePath());
6466                }
6467            }
6468        }
6469
6470        @Override
6471        void handleServiceError() {
6472            mArgs = createInstallArgs(this);
6473            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6474        }
6475
6476        public boolean isForwardLocked() {
6477            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6478        }
6479
6480        public Uri getPackageUri() {
6481            if (mTempPackage != null) {
6482                return Uri.fromFile(mTempPackage);
6483            } else {
6484                return mPackageURI;
6485            }
6486        }
6487    }
6488
6489    /*
6490     * Utility class used in movePackage api.
6491     * srcArgs and targetArgs are not set for invalid flags and make
6492     * sure to do null checks when invoking methods on them.
6493     * We probably want to return ErrorPrams for both failed installs
6494     * and moves.
6495     */
6496    class MoveParams extends HandlerParams {
6497        final IPackageMoveObserver observer;
6498        final int flags;
6499        final String packageName;
6500        final InstallArgs srcArgs;
6501        final InstallArgs targetArgs;
6502        int uid;
6503        int mRet;
6504
6505        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
6506                String packageName, String dataDir, int uid, UserHandle user) {
6507            super(user);
6508            this.srcArgs = srcArgs;
6509            this.observer = observer;
6510            this.flags = flags;
6511            this.packageName = packageName;
6512            this.uid = uid;
6513            if (srcArgs != null) {
6514                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
6515                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
6516            } else {
6517                targetArgs = null;
6518            }
6519        }
6520
6521        public void handleStartCopy() throws RemoteException {
6522            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6523            // Check for storage space on target medium
6524            if (!targetArgs.checkFreeStorage(mContainerService)) {
6525                Log.w(TAG, "Insufficient storage to install");
6526                return;
6527            }
6528
6529            mRet = srcArgs.doPreCopy();
6530            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6531                return;
6532            }
6533
6534            mRet = targetArgs.copyApk(mContainerService, false);
6535            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6536                srcArgs.doPostCopy(uid);
6537                return;
6538            }
6539
6540            mRet = srcArgs.doPostCopy(uid);
6541            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6542                return;
6543            }
6544
6545            mRet = targetArgs.doPreInstall(mRet);
6546            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6547                return;
6548            }
6549
6550            if (DEBUG_SD_INSTALL) {
6551                StringBuilder builder = new StringBuilder();
6552                if (srcArgs != null) {
6553                    builder.append("src: ");
6554                    builder.append(srcArgs.getCodePath());
6555                }
6556                if (targetArgs != null) {
6557                    builder.append(" target : ");
6558                    builder.append(targetArgs.getCodePath());
6559                }
6560                Log.i(TAG, builder.toString());
6561            }
6562        }
6563
6564        @Override
6565        void handleReturnCode() {
6566            targetArgs.doPostInstall(mRet, uid);
6567            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6568            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6569                currentStatus = PackageManager.MOVE_SUCCEEDED;
6570            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6571                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6572            }
6573            processPendingMove(this, currentStatus);
6574        }
6575
6576        @Override
6577        void handleServiceError() {
6578            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6579        }
6580    }
6581
6582    /**
6583     * Used during creation of InstallArgs
6584     *
6585     * @param flags package installation flags
6586     * @return true if should be installed on external storage
6587     */
6588    private static boolean installOnSd(int flags) {
6589        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6590            return false;
6591        }
6592        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6593            return true;
6594        }
6595        return false;
6596    }
6597
6598    /**
6599     * Used during creation of InstallArgs
6600     *
6601     * @param flags package installation flags
6602     * @return true if should be installed as forward locked
6603     */
6604    private static boolean installForwardLocked(int flags) {
6605        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6606    }
6607
6608    private InstallArgs createInstallArgs(InstallParams params) {
6609        if (installOnSd(params.flags) || params.isForwardLocked()) {
6610            return new AsecInstallArgs(params);
6611        } else {
6612            return new FileInstallArgs(params);
6613        }
6614    }
6615
6616    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6617            String nativeLibraryPath) {
6618        final boolean isInAsec;
6619        if (installOnSd(flags)) {
6620            /* Apps on SD card are always in ASEC containers. */
6621            isInAsec = true;
6622        } else if (installForwardLocked(flags)
6623                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6624            /*
6625             * Forward-locked apps are only in ASEC containers if they're the
6626             * new style
6627             */
6628            isInAsec = true;
6629        } else {
6630            isInAsec = false;
6631        }
6632
6633        if (isInAsec) {
6634            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
6635                    installOnSd(flags), installForwardLocked(flags));
6636        } else {
6637            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
6638        }
6639    }
6640
6641    // Used by package mover
6642    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
6643        if (installOnSd(flags) || installForwardLocked(flags)) {
6644            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6645                    + AsecInstallArgs.RES_FILE_NAME);
6646            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6647                    installForwardLocked(flags));
6648        } else {
6649            return new FileInstallArgs(packageURI, pkgName, dataDir);
6650        }
6651    }
6652
6653    static abstract class InstallArgs {
6654        final IPackageInstallObserver observer;
6655        // Always refers to PackageManager flags only
6656        final int flags;
6657        final Uri packageURI;
6658        final String installerPackageName;
6659        final ManifestDigest manifestDigest;
6660        final UserHandle user;
6661
6662        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
6663                String installerPackageName, ManifestDigest manifestDigest,
6664                UserHandle user) {
6665            this.packageURI = packageURI;
6666            this.flags = flags;
6667            this.observer = observer;
6668            this.installerPackageName = installerPackageName;
6669            this.manifestDigest = manifestDigest;
6670            this.user = user;
6671        }
6672
6673        abstract void createCopyFile();
6674        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
6675        abstract int doPreInstall(int status);
6676        abstract boolean doRename(int status, String pkgName, String oldCodePath);
6677
6678        abstract int doPostInstall(int status, int uid);
6679        abstract String getCodePath();
6680        abstract String getResourcePath();
6681        abstract String getNativeLibraryPath();
6682        // Need installer lock especially for dex file removal.
6683        abstract void cleanUpResourcesLI();
6684        abstract boolean doPostDeleteLI(boolean delete);
6685        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
6686
6687        /**
6688         * Called before the source arguments are copied. This is used mostly
6689         * for MoveParams when it needs to read the source file to put it in the
6690         * destination.
6691         */
6692        int doPreCopy() {
6693            return PackageManager.INSTALL_SUCCEEDED;
6694        }
6695
6696        /**
6697         * Called after the source arguments are copied. This is used mostly for
6698         * MoveParams when it needs to read the source file to put it in the
6699         * destination.
6700         *
6701         * @return
6702         */
6703        int doPostCopy(int uid) {
6704            return PackageManager.INSTALL_SUCCEEDED;
6705        }
6706
6707        protected boolean isFwdLocked() {
6708            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6709        }
6710    }
6711
6712    class FileInstallArgs extends InstallArgs {
6713        File installDir;
6714        String codeFileName;
6715        String resourceFileName;
6716        String libraryPath;
6717        boolean created = false;
6718
6719        FileInstallArgs(InstallParams params) {
6720            super(params.getPackageUri(), params.observer, params.flags,
6721                    params.installerPackageName, params.getManifestDigest(),
6722                    params.getUser());
6723        }
6724
6725        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
6726            super(null, null, 0, null, null, null);
6727            File codeFile = new File(fullCodePath);
6728            installDir = codeFile.getParentFile();
6729            codeFileName = fullCodePath;
6730            resourceFileName = fullResourcePath;
6731            libraryPath = nativeLibraryPath;
6732        }
6733
6734        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
6735            super(packageURI, null, 0, null, null, null);
6736            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6737            String apkName = getNextCodePath(null, pkgName, ".apk");
6738            codeFileName = new File(installDir, apkName + ".apk").getPath();
6739            resourceFileName = getResourcePathFromCodePath();
6740            libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
6741        }
6742
6743        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6744            final long lowThreshold;
6745
6746            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6747                    .getService(DeviceStorageMonitorService.SERVICE);
6748            if (dsm == null) {
6749                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6750                lowThreshold = 0L;
6751            } else {
6752                if (dsm.isMemoryLow()) {
6753                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
6754                    return false;
6755                }
6756
6757                lowThreshold = dsm.getMemoryLowThreshold();
6758            }
6759
6760            try {
6761                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6762                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6763                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
6764            } finally {
6765                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6766            }
6767        }
6768
6769        String getCodePath() {
6770            return codeFileName;
6771        }
6772
6773        void createCopyFile() {
6774            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6775            codeFileName = createTempPackageFile(installDir).getPath();
6776            resourceFileName = getResourcePathFromCodePath();
6777            created = true;
6778        }
6779
6780        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
6781            if (temp) {
6782                // Generate temp file name
6783                createCopyFile();
6784            }
6785            // Get a ParcelFileDescriptor to write to the output file
6786            File codeFile = new File(codeFileName);
6787            if (!created) {
6788                try {
6789                    codeFile.createNewFile();
6790                    // Set permissions
6791                    if (!setPermissions()) {
6792                        // Failed setting permissions.
6793                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6794                    }
6795                } catch (IOException e) {
6796                   Slog.w(TAG, "Failed to create file " + codeFile);
6797                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6798                }
6799            }
6800            ParcelFileDescriptor out = null;
6801            try {
6802                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
6803            } catch (FileNotFoundException e) {
6804                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
6805                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6806            }
6807            // Copy the resource now
6808            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6809            try {
6810                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6811                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6812                ret = imcs.copyResource(packageURI, null, out);
6813            } finally {
6814                IoUtils.closeQuietly(out);
6815                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6816            }
6817
6818            if (isFwdLocked()) {
6819                final File destResourceFile = new File(getResourcePath());
6820
6821                // Copy the public files
6822                try {
6823                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6824                } catch (IOException e) {
6825                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6826                            + " forward-locked app.");
6827                    destResourceFile.delete();
6828                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6829                }
6830            }
6831            return ret;
6832        }
6833
6834        int doPreInstall(int status) {
6835            if (status != PackageManager.INSTALL_SUCCEEDED) {
6836                cleanUp();
6837            }
6838            return status;
6839        }
6840
6841        boolean doRename(int status, final String pkgName, String oldCodePath) {
6842            if (status != PackageManager.INSTALL_SUCCEEDED) {
6843                cleanUp();
6844                return false;
6845            } else {
6846                final File oldCodeFile = new File(getCodePath());
6847                final File oldResourceFile = new File(getResourcePath());
6848
6849                // Rename APK file based on packageName
6850                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
6851                final File newCodeFile = new File(installDir, apkName + ".apk");
6852                if (!oldCodeFile.renameTo(newCodeFile)) {
6853                    return false;
6854                }
6855                codeFileName = newCodeFile.getPath();
6856
6857                // Rename public resource file if it's forward-locked.
6858                final File newResFile = new File(getResourcePathFromCodePath());
6859                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
6860                    return false;
6861                }
6862                resourceFileName = getResourcePathFromCodePath();
6863
6864                // Attempt to set permissions
6865                if (!setPermissions()) {
6866                    return false;
6867                }
6868
6869                if (!SELinux.restorecon(newCodeFile)) {
6870                    return false;
6871                }
6872
6873                return true;
6874            }
6875        }
6876
6877        int doPostInstall(int status, int uid) {
6878            if (status != PackageManager.INSTALL_SUCCEEDED) {
6879                cleanUp();
6880            }
6881            return status;
6882        }
6883
6884        String getResourcePath() {
6885            return resourceFileName;
6886        }
6887
6888        private String getResourcePathFromCodePath() {
6889            final String codePath = getCodePath();
6890            if (isFwdLocked()) {
6891                final StringBuilder sb = new StringBuilder();
6892
6893                sb.append(mAppInstallDir.getPath());
6894                sb.append('/');
6895                sb.append(getApkName(codePath));
6896                sb.append(".zip");
6897
6898                /*
6899                 * If our APK is a temporary file, mark the resource as a
6900                 * temporary file as well so it can be cleaned up after
6901                 * catastrophic failure.
6902                 */
6903                if (codePath.endsWith(".tmp")) {
6904                    sb.append(".tmp");
6905                }
6906
6907                return sb.toString();
6908            } else {
6909                return codePath;
6910            }
6911        }
6912
6913        @Override
6914        String getNativeLibraryPath() {
6915            return libraryPath;
6916        }
6917
6918        private boolean cleanUp() {
6919            boolean ret = true;
6920            String sourceDir = getCodePath();
6921            String publicSourceDir = getResourcePath();
6922            if (sourceDir != null) {
6923                File sourceFile = new File(sourceDir);
6924                if (!sourceFile.exists()) {
6925                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
6926                    ret = false;
6927                }
6928                // Delete application's code and resources
6929                sourceFile.delete();
6930            }
6931            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
6932                final File publicSourceFile = new File(publicSourceDir);
6933                if (!publicSourceFile.exists()) {
6934                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
6935                }
6936                if (publicSourceFile.exists()) {
6937                    publicSourceFile.delete();
6938                }
6939            }
6940            return ret;
6941        }
6942
6943        void cleanUpResourcesLI() {
6944            String sourceDir = getCodePath();
6945            if (cleanUp()) {
6946                int retCode = mInstaller.rmdex(sourceDir);
6947                if (retCode < 0) {
6948                    Slog.w(TAG, "Couldn't remove dex file for package: "
6949                            +  " at location "
6950                            + sourceDir + ", retcode=" + retCode);
6951                    // we don't consider this to be a failure of the core package deletion
6952                }
6953            }
6954        }
6955
6956        private boolean setPermissions() {
6957            // TODO Do this in a more elegant way later on. for now just a hack
6958            if (!isFwdLocked()) {
6959                final int filePermissions =
6960                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
6961                    |FileUtils.S_IROTH;
6962                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
6963                if (retCode != 0) {
6964                    Slog.e(TAG, "Couldn't set new package file permissions for " +
6965                            getCodePath()
6966                            + ". The return code was: " + retCode);
6967                    // TODO Define new internal error
6968                    return false;
6969                }
6970                return true;
6971            }
6972            return true;
6973        }
6974
6975        boolean doPostDeleteLI(boolean delete) {
6976            // XXX err, shouldn't we respect the delete flag?
6977            cleanUpResourcesLI();
6978            return true;
6979        }
6980    }
6981
6982    private boolean isAsecExternal(String cid) {
6983        final String asecPath = PackageHelper.getSdFilesystem(cid);
6984        return !asecPath.startsWith(mAsecInternalPath);
6985    }
6986
6987    /**
6988     * Extract the MountService "container ID" from the full code path of an
6989     * .apk.
6990     */
6991    static String cidFromCodePath(String fullCodePath) {
6992        int eidx = fullCodePath.lastIndexOf("/");
6993        String subStr1 = fullCodePath.substring(0, eidx);
6994        int sidx = subStr1.lastIndexOf("/");
6995        return subStr1.substring(sidx+1, eidx);
6996    }
6997
6998    class AsecInstallArgs extends InstallArgs {
6999        static final String RES_FILE_NAME = "pkg.apk";
7000        static final String PUBLIC_RES_FILE_NAME = "res.zip";
7001
7002        String cid;
7003        String packagePath;
7004        String resourcePath;
7005        String libraryPath;
7006
7007        AsecInstallArgs(InstallParams params) {
7008            super(params.getPackageUri(), params.observer, params.flags,
7009                    params.installerPackageName, params.getManifestDigest(),
7010                    params.getUser());
7011        }
7012
7013        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
7014                boolean isExternal, boolean isForwardLocked) {
7015            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7016                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7017                    null, null, null);
7018            // Extract cid from fullCodePath
7019            int eidx = fullCodePath.lastIndexOf("/");
7020            String subStr1 = fullCodePath.substring(0, eidx);
7021            int sidx = subStr1.lastIndexOf("/");
7022            cid = subStr1.substring(sidx+1, eidx);
7023            setCachePath(subStr1);
7024        }
7025
7026        AsecInstallArgs(String cid, boolean isForwardLocked) {
7027            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
7028                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7029                    null, null, null);
7030            this.cid = cid;
7031            setCachePath(PackageHelper.getSdDir(cid));
7032        }
7033
7034        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
7035            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7036                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7037                    null, null, null);
7038            this.cid = cid;
7039        }
7040
7041        void createCopyFile() {
7042            cid = getTempContainerId();
7043        }
7044
7045        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7046            try {
7047                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7048                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7049                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
7050            } finally {
7051                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7052            }
7053        }
7054
7055        private final boolean isExternal() {
7056            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7057        }
7058
7059        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
7060            if (temp) {
7061                createCopyFile();
7062            } else {
7063                /*
7064                 * Pre-emptively destroy the container since it's destroyed if
7065                 * copying fails due to it existing anyway.
7066                 */
7067                PackageHelper.destroySdDir(cid);
7068            }
7069
7070            final String newCachePath;
7071            try {
7072                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7073                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7074                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7075                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
7076            } finally {
7077                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7078            }
7079
7080            if (newCachePath != null) {
7081                setCachePath(newCachePath);
7082                return PackageManager.INSTALL_SUCCEEDED;
7083            } else {
7084                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7085            }
7086        }
7087
7088        @Override
7089        String getCodePath() {
7090            return packagePath;
7091        }
7092
7093        @Override
7094        String getResourcePath() {
7095            return resourcePath;
7096        }
7097
7098        @Override
7099        String getNativeLibraryPath() {
7100            return libraryPath;
7101        }
7102
7103        int doPreInstall(int status) {
7104            if (status != PackageManager.INSTALL_SUCCEEDED) {
7105                // Destroy container
7106                PackageHelper.destroySdDir(cid);
7107            } else {
7108                boolean mounted = PackageHelper.isContainerMounted(cid);
7109                if (!mounted) {
7110                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7111                            Process.SYSTEM_UID);
7112                    if (newCachePath != null) {
7113                        setCachePath(newCachePath);
7114                    } else {
7115                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7116                    }
7117                }
7118            }
7119            return status;
7120        }
7121
7122        boolean doRename(int status, final String pkgName,
7123                String oldCodePath) {
7124            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
7125            String newCachePath = null;
7126            if (PackageHelper.isContainerMounted(cid)) {
7127                // Unmount the container
7128                if (!PackageHelper.unMountSdDir(cid)) {
7129                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
7130                    return false;
7131                }
7132            }
7133            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7134                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7135                        " which might be stale. Will try to clean up.");
7136                // Clean up the stale container and proceed to recreate.
7137                if (!PackageHelper.destroySdDir(newCacheId)) {
7138                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7139                    return false;
7140                }
7141                // Successfully cleaned up stale container. Try to rename again.
7142                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7143                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7144                            + " inspite of cleaning it up.");
7145                    return false;
7146                }
7147            }
7148            if (!PackageHelper.isContainerMounted(newCacheId)) {
7149                Slog.w(TAG, "Mounting container " + newCacheId);
7150                newCachePath = PackageHelper.mountSdDir(newCacheId,
7151                        getEncryptKey(), Process.SYSTEM_UID);
7152            } else {
7153                newCachePath = PackageHelper.getSdDir(newCacheId);
7154            }
7155            if (newCachePath == null) {
7156                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
7157                return false;
7158            }
7159            Log.i(TAG, "Succesfully renamed " + cid +
7160                    " to " + newCacheId +
7161                    " at new path: " + newCachePath);
7162            cid = newCacheId;
7163            setCachePath(newCachePath);
7164            return true;
7165        }
7166
7167        private void setCachePath(String newCachePath) {
7168            File cachePath = new File(newCachePath);
7169            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7170            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
7171
7172            if (isFwdLocked()) {
7173                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7174            } else {
7175                resourcePath = packagePath;
7176            }
7177        }
7178
7179        int doPostInstall(int status, int uid) {
7180            if (status != PackageManager.INSTALL_SUCCEEDED) {
7181                cleanUp();
7182            } else {
7183                final int groupOwner;
7184                final String protectedFile;
7185                if (isFwdLocked()) {
7186                    groupOwner = uid;
7187                    protectedFile = RES_FILE_NAME;
7188                } else {
7189                    groupOwner = -1;
7190                    protectedFile = null;
7191                }
7192
7193                if (uid < Process.FIRST_APPLICATION_UID
7194                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
7195                    Slog.e(TAG, "Failed to finalize " + cid);
7196                    PackageHelper.destroySdDir(cid);
7197                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7198                }
7199
7200                boolean mounted = PackageHelper.isContainerMounted(cid);
7201                if (!mounted) {
7202                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
7203                }
7204            }
7205            return status;
7206        }
7207
7208        private void cleanUp() {
7209            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7210
7211            // Destroy secure container
7212            PackageHelper.destroySdDir(cid);
7213        }
7214
7215        void cleanUpResourcesLI() {
7216            String sourceFile = getCodePath();
7217            // Remove dex file
7218            int retCode = mInstaller.rmdex(sourceFile);
7219            if (retCode < 0) {
7220                Slog.w(TAG, "Couldn't remove dex file for package: "
7221                        + " at location "
7222                        + sourceFile.toString() + ", retcode=" + retCode);
7223                // we don't consider this to be a failure of the core package deletion
7224            }
7225            cleanUp();
7226        }
7227
7228        boolean matchContainer(String app) {
7229            if (cid.startsWith(app)) {
7230                return true;
7231            }
7232            return false;
7233        }
7234
7235        String getPackageName() {
7236            return getAsecPackageName(cid);
7237        }
7238
7239        boolean doPostDeleteLI(boolean delete) {
7240            boolean ret = false;
7241            boolean mounted = PackageHelper.isContainerMounted(cid);
7242            if (mounted) {
7243                // Unmount first
7244                ret = PackageHelper.unMountSdDir(cid);
7245            }
7246            if (ret && delete) {
7247                cleanUpResourcesLI();
7248            }
7249            return ret;
7250        }
7251
7252        @Override
7253        int doPreCopy() {
7254            if (isFwdLocked()) {
7255                if (!PackageHelper.fixSdPermissions(cid,
7256                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7257                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7258                }
7259            }
7260
7261            return PackageManager.INSTALL_SUCCEEDED;
7262        }
7263
7264        @Override
7265        int doPostCopy(int uid) {
7266            if (isFwdLocked()) {
7267                if (uid < Process.FIRST_APPLICATION_UID
7268                        || !PackageHelper.fixSdPermissions(cid, uid, RES_FILE_NAME)) {
7269                    Slog.e(TAG, "Failed to finalize " + cid);
7270                    PackageHelper.destroySdDir(cid);
7271                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7272                }
7273            }
7274
7275            return PackageManager.INSTALL_SUCCEEDED;
7276        }
7277    };
7278
7279    static String getAsecPackageName(String packageCid) {
7280        int idx = packageCid.lastIndexOf("-");
7281        if (idx == -1) {
7282            return packageCid;
7283        }
7284        return packageCid.substring(0, idx);
7285    }
7286
7287    // Utility method used to create code paths based on package name and available index.
7288    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7289        String idxStr = "";
7290        int idx = 1;
7291        // Fall back to default value of idx=1 if prefix is not
7292        // part of oldCodePath
7293        if (oldCodePath != null) {
7294            String subStr = oldCodePath;
7295            // Drop the suffix right away
7296            if (subStr.endsWith(suffix)) {
7297                subStr = subStr.substring(0, subStr.length() - suffix.length());
7298            }
7299            // If oldCodePath already contains prefix find out the
7300            // ending index to either increment or decrement.
7301            int sidx = subStr.lastIndexOf(prefix);
7302            if (sidx != -1) {
7303                subStr = subStr.substring(sidx + prefix.length());
7304                if (subStr != null) {
7305                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7306                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
7307                    }
7308                    try {
7309                        idx = Integer.parseInt(subStr);
7310                        if (idx <= 1) {
7311                            idx++;
7312                        } else {
7313                            idx--;
7314                        }
7315                    } catch(NumberFormatException e) {
7316                    }
7317                }
7318            }
7319        }
7320        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
7321        return prefix + idxStr;
7322    }
7323
7324    // Utility method used to ignore ADD/REMOVE events
7325    // by directory observer.
7326    private static boolean ignoreCodePath(String fullPathStr) {
7327        String apkName = getApkName(fullPathStr);
7328        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
7329        if (idx != -1 && ((idx+1) < apkName.length())) {
7330            // Make sure the package ends with a numeral
7331            String version = apkName.substring(idx+1);
7332            try {
7333                Integer.parseInt(version);
7334                return true;
7335            } catch (NumberFormatException e) {}
7336        }
7337        return false;
7338    }
7339
7340    // Utility method that returns the relative package path with respect
7341    // to the installation directory. Like say for /data/data/com.test-1.apk
7342    // string com.test-1 is returned.
7343    static String getApkName(String codePath) {
7344        if (codePath == null) {
7345            return null;
7346        }
7347        int sidx = codePath.lastIndexOf("/");
7348        int eidx = codePath.lastIndexOf(".");
7349        if (eidx == -1) {
7350            eidx = codePath.length();
7351        } else if (eidx == 0) {
7352            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
7353            return null;
7354        }
7355        return codePath.substring(sidx+1, eidx);
7356    }
7357
7358    class PackageInstalledInfo {
7359        String name;
7360        int uid;
7361        // The set of users that originally had this package installed.
7362        int[] origUsers;
7363        // The set of users that now have this package installed.
7364        int[] newUsers;
7365        PackageParser.Package pkg;
7366        int returnCode;
7367        PackageRemovedInfo removedInfo;
7368    }
7369
7370    /*
7371     * Install a non-existing package.
7372     */
7373    private void installNewPackageLI(PackageParser.Package pkg,
7374            int parseFlags, int scanMode, UserHandle user,
7375            String installerPackageName, PackageInstalledInfo res) {
7376        // Remember this for later, in case we need to rollback this install
7377        String pkgName = pkg.packageName;
7378
7379        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
7380        synchronized(mPackages) {
7381            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7382                // A package with the same name is already installed, though
7383                // it has been renamed to an older name.  The package we
7384                // are trying to install should be installed as an update to
7385                // the existing one, but that has not been requested, so bail.
7386                Slog.w(TAG, "Attempt to re-install " + pkgName
7387                        + " without first uninstalling package running as "
7388                        + mSettings.mRenamedPackages.get(pkgName));
7389                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7390                return;
7391            }
7392            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
7393                // Don't allow installation over an existing package with the same name.
7394                Slog.w(TAG, "Attempt to re-install " + pkgName
7395                        + " without first uninstalling.");
7396                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7397                return;
7398            }
7399        }
7400        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7401        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
7402                System.currentTimeMillis(), user);
7403        if (newPackage == null) {
7404            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7405            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7406                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7407            }
7408        } else {
7409            updateSettingsLI(newPackage,
7410                    installerPackageName,
7411                    res);
7412            // delete the partially installed application. the data directory will have to be
7413            // restored if it was already existing
7414            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7415                // remove package from internal structures.  Note that we want deletePackageX to
7416                // delete the package data and cache directories that it created in
7417                // scanPackageLocked, unless those directories existed before we even tried to
7418                // install.
7419                deletePackageLI(pkgName, UserHandle.ALL, false,
7420                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
7421                                res.removedInfo, true);
7422            }
7423        }
7424    }
7425
7426    private void replacePackageLI(PackageParser.Package pkg,
7427            int parseFlags, int scanMode, UserHandle user,
7428            String installerPackageName, PackageInstalledInfo res) {
7429
7430        PackageParser.Package oldPackage;
7431        String pkgName = pkg.packageName;
7432        // First find the old package info and check signatures
7433        synchronized(mPackages) {
7434            oldPackage = mPackages.get(pkgName);
7435            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
7436                    != PackageManager.SIGNATURE_MATCH) {
7437                Slog.w(TAG, "New package has a different signature: " + pkgName);
7438                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7439                return;
7440            }
7441        }
7442        boolean sysPkg = (isSystemApp(oldPackage));
7443        if (sysPkg) {
7444            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7445                    user, installerPackageName, res);
7446        } else {
7447            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7448                    user, installerPackageName, res);
7449        }
7450    }
7451
7452    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
7453            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7454            String installerPackageName, PackageInstalledInfo res) {
7455        PackageParser.Package newPackage = null;
7456        String pkgName = deletedPackage.packageName;
7457        boolean deletedPkg = true;
7458        boolean updatedSettings = false;
7459
7460        long origUpdateTime;
7461        if (pkg.mExtras != null) {
7462            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7463        } else {
7464            origUpdateTime = 0;
7465        }
7466
7467        // First delete the existing package while retaining the data directory
7468        if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA,
7469                res.removedInfo, true)) {
7470            // If the existing package wasn't successfully deleted
7471            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7472            deletedPkg = false;
7473        } else {
7474            // Successfully deleted the old package. Now proceed with re-installation
7475            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7476            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
7477                    System.currentTimeMillis(), user);
7478            if (newPackage == null) {
7479                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7480                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7481                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7482                }
7483            } else {
7484                updateSettingsLI(newPackage,
7485                        installerPackageName,
7486                        res);
7487                updatedSettings = true;
7488            }
7489        }
7490
7491        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7492            // remove package from internal structures.  Note that we want deletePackageX to
7493            // delete the package data and cache directories that it created in
7494            // scanPackageLocked, unless those directories existed before we even tried to
7495            // install.
7496            if(updatedSettings) {
7497                deletePackageLI(
7498                        pkgName, null, true,
7499                        PackageManager.DELETE_KEEP_DATA,
7500                                res.removedInfo, true);
7501            }
7502            // Since we failed to install the new package we need to restore the old
7503            // package that we deleted.
7504            if(deletedPkg) {
7505                File restoreFile = new File(deletedPackage.mPath);
7506                // Parse old package
7507                boolean oldOnSd = isExternal(deletedPackage);
7508                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
7509                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7510                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
7511                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7512                        | SCAN_UPDATE_TIME;
7513                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
7514                        origUpdateTime, null) == null) {
7515                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7516                    return;
7517                }
7518                // Restore of old package succeeded. Update permissions.
7519                // writer
7520                synchronized (mPackages) {
7521                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
7522                            UPDATE_PERMISSIONS_ALL);
7523                    // can downgrade to reader
7524                    mSettings.writeLPr();
7525                }
7526                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
7527            }
7528        }
7529    }
7530
7531    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
7532            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7533            String installerPackageName, PackageInstalledInfo res) {
7534        PackageParser.Package newPackage = null;
7535        boolean updatedSettings = false;
7536        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
7537                PackageParser.PARSE_IS_SYSTEM;
7538        String packageName = deletedPackage.packageName;
7539        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7540        if (packageName == null) {
7541            Slog.w(TAG, "Attempt to delete null packageName.");
7542            return;
7543        }
7544        PackageParser.Package oldPkg;
7545        PackageSetting oldPkgSetting;
7546        // reader
7547        synchronized (mPackages) {
7548            oldPkg = mPackages.get(packageName);
7549            oldPkgSetting = mSettings.mPackages.get(packageName);
7550            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7551                    (oldPkgSetting == null)) {
7552                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
7553                return;
7554            }
7555        }
7556
7557        killApplication(packageName, oldPkg.applicationInfo.uid);
7558
7559        res.removedInfo.uid = oldPkg.applicationInfo.uid;
7560        res.removedInfo.removedPackage = packageName;
7561        // Remove existing system package
7562        removePackageLI(oldPkgSetting, true);
7563        // writer
7564        synchronized (mPackages) {
7565            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
7566                // We didn't need to disable the .apk as a current system package,
7567                // which means we are replacing another update that is already
7568                // installed.  We need to make sure to delete the older one's .apk.
7569                res.removedInfo.args = createInstallArgs(0,
7570                        deletedPackage.applicationInfo.sourceDir,
7571                        deletedPackage.applicationInfo.publicSourceDir,
7572                        deletedPackage.applicationInfo.nativeLibraryDir);
7573            } else {
7574                res.removedInfo.args = null;
7575            }
7576        }
7577
7578        // Successfully disabled the old package. Now proceed with re-installation
7579        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7580        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7581        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
7582        if (newPackage == null) {
7583            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7584            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7585                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7586            }
7587        } else {
7588            if (newPackage.mExtras != null) {
7589                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7590                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7591                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7592            }
7593            updateSettingsLI(newPackage, installerPackageName, res);
7594            updatedSettings = true;
7595        }
7596
7597        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7598            // Re installation failed. Restore old information
7599            // Remove new pkg information
7600            if (newPackage != null) {
7601                removeInstalledPackageLI(newPackage, true);
7602            }
7603            // Add back the old system package
7604            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
7605            // Restore the old system information in Settings
7606            synchronized(mPackages) {
7607                if (updatedSettings) {
7608                    mSettings.enableSystemPackageLPw(packageName);
7609                    mSettings.setInstallerPackageName(packageName,
7610                            oldPkgSetting.installerPackageName);
7611                }
7612                mSettings.writeLPr();
7613            }
7614        }
7615    }
7616
7617    // Utility method used to move dex files during install.
7618    private int moveDexFilesLI(PackageParser.Package newPackage) {
7619        int retCode;
7620        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7621            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7622            if (retCode != 0) {
7623                if (mNoDexOpt) {
7624                    /*
7625                     * If we're in an engineering build, programs are lazily run
7626                     * through dexopt. If the .dex file doesn't exist yet, it
7627                     * will be created when the program is run next.
7628                     */
7629                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7630                } else {
7631                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7632                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7633                }
7634            }
7635        }
7636        return PackageManager.INSTALL_SUCCEEDED;
7637    }
7638
7639    private void updateSettingsLI(PackageParser.Package newPackage,
7640            String installerPackageName, PackageInstalledInfo res) {
7641        String pkgName = newPackage.packageName;
7642        synchronized (mPackages) {
7643            //write settings. the installStatus will be incomplete at this stage.
7644            //note that the new package setting would have already been
7645            //added to mPackages. It hasn't been persisted yet.
7646            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
7647            mSettings.writeLPr();
7648        }
7649
7650        if ((res.returnCode = moveDexFilesLI(newPackage))
7651                != PackageManager.INSTALL_SUCCEEDED) {
7652            // Discontinue if moving dex files failed.
7653            return;
7654        }
7655
7656        Log.d(TAG, "New package installed in " + newPackage.mPath);
7657
7658        synchronized (mPackages) {
7659            updatePermissionsLPw(newPackage.packageName, newPackage,
7660                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7661                            ? UPDATE_PERMISSIONS_ALL : 0));
7662            res.name = pkgName;
7663            res.uid = newPackage.applicationInfo.uid;
7664            res.pkg = newPackage;
7665            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
7666            mSettings.setInstallerPackageName(pkgName, installerPackageName);
7667            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7668            //to update install status
7669            mSettings.writeLPr();
7670        }
7671    }
7672
7673    private void installPackageLI(InstallArgs args,
7674            boolean newInstall, PackageInstalledInfo res) {
7675        int pFlags = args.flags;
7676        String installerPackageName = args.installerPackageName;
7677        File tmpPackageFile = new File(args.getCodePath());
7678        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
7679        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
7680        boolean replace = false;
7681        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
7682                | (newInstall ? SCAN_NEW_INSTALL : 0);
7683        // Result object to be returned
7684        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7685
7686        // Retrieve PackageSettings and parse package
7687        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7688                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7689                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
7690        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7691        pp.setSeparateProcesses(mSeparateProcesses);
7692        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7693                null, mMetrics, parseFlags);
7694        if (pkg == null) {
7695            res.returnCode = pp.getParseError();
7696            return;
7697        }
7698        String pkgName = res.name = pkg.packageName;
7699        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7700            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7701                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7702                return;
7703            }
7704        }
7705        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7706            res.returnCode = pp.getParseError();
7707            return;
7708        }
7709
7710        /* If the installer passed in a manifest digest, compare it now. */
7711        if (args.manifestDigest != null) {
7712            if (DEBUG_INSTALL) {
7713                final String parsedManifest = pkg.manifestDigest == null ? "null"
7714                        : pkg.manifestDigest.toString();
7715                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7716                        + parsedManifest);
7717            }
7718
7719            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7720                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7721                return;
7722            }
7723        } else if (DEBUG_INSTALL) {
7724            final String parsedManifest = pkg.manifestDigest == null
7725                    ? "null" : pkg.manifestDigest.toString();
7726            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7727        }
7728
7729        // Get rid of all references to package scan path via parser.
7730        pp = null;
7731        String oldCodePath = null;
7732        boolean systemApp = false;
7733        synchronized (mPackages) {
7734            // Check if installing already existing package
7735            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7736                String oldName = mSettings.mRenamedPackages.get(pkgName);
7737                if (pkg.mOriginalPackages != null
7738                        && pkg.mOriginalPackages.contains(oldName)
7739                        && mPackages.containsKey(oldName)) {
7740                    // This package is derived from an original package,
7741                    // and this device has been updating from that original
7742                    // name.  We must continue using the original name, so
7743                    // rename the new package here.
7744                    pkg.setPackageName(oldName);
7745                    pkgName = pkg.packageName;
7746                    replace = true;
7747                } else if (mPackages.containsKey(pkgName)) {
7748                    // This package, under its official name, already exists
7749                    // on the device; we should replace it.
7750                    replace = true;
7751                }
7752            }
7753            PackageSetting ps = mSettings.mPackages.get(pkgName);
7754            if (ps != null) {
7755                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7756                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7757                    systemApp = (ps.pkg.applicationInfo.flags &
7758                            ApplicationInfo.FLAG_SYSTEM) != 0;
7759                }
7760                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7761            }
7762        }
7763
7764        if (systemApp && onSd) {
7765            // Disable updates to system apps on sdcard
7766            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
7767            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7768            return;
7769        }
7770
7771        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7772            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7773            return;
7774        }
7775        // Set application objects path explicitly after the rename
7776        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
7777        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
7778        if (replace) {
7779            replacePackageLI(pkg, parseFlags, scanMode, args.user,
7780                    installerPackageName, res);
7781        } else {
7782            installNewPackageLI(pkg, parseFlags, scanMode, args.user,
7783                    installerPackageName, res);
7784        }
7785        synchronized (mPackages) {
7786            final PackageSetting ps = mSettings.mPackages.get(pkgName);
7787            if (ps != null) {
7788                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7789            }
7790        }
7791    }
7792
7793    private static boolean isForwardLocked(PackageParser.Package pkg) {
7794        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7795    }
7796
7797
7798    private boolean isForwardLocked(PackageSetting ps) {
7799        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7800    }
7801
7802    private static boolean isExternal(PackageParser.Package pkg) {
7803        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7804    }
7805
7806    private static boolean isExternal(PackageSetting ps) {
7807        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7808    }
7809
7810    private static boolean isSystemApp(PackageParser.Package pkg) {
7811        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7812    }
7813
7814    private static boolean isSystemApp(ApplicationInfo info) {
7815        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7816    }
7817
7818    private static boolean isSystemApp(PackageSetting ps) {
7819        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
7820    }
7821
7822    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
7823        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
7824    }
7825
7826    private int packageFlagsToInstallFlags(PackageSetting ps) {
7827        int installFlags = 0;
7828        if (isExternal(ps)) {
7829            installFlags |= PackageManager.INSTALL_EXTERNAL;
7830        }
7831        if (isForwardLocked(ps)) {
7832            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
7833        }
7834        return installFlags;
7835    }
7836
7837    private void deleteTempPackageFiles() {
7838        FilenameFilter filter = new FilenameFilter() {
7839            public boolean accept(File dir, String name) {
7840                return name.startsWith("vmdl") && name.endsWith(".tmp");
7841            }
7842        };
7843        String tmpFilesList[] = mAppInstallDir.list(filter);
7844        if(tmpFilesList == null) {
7845            return;
7846        }
7847        for(int i = 0; i < tmpFilesList.length; i++) {
7848            File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
7849            tmpFile.delete();
7850        }
7851    }
7852
7853    private File createTempPackageFile(File installDir) {
7854        File tmpPackageFile;
7855        try {
7856            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
7857        } catch (IOException e) {
7858            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
7859            return null;
7860        }
7861        try {
7862            FileUtils.setPermissions(
7863                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
7864                    -1, -1);
7865            if (!SELinux.restorecon(tmpPackageFile)) {
7866                return null;
7867            }
7868        } catch (IOException e) {
7869            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
7870            return null;
7871        }
7872        return tmpPackageFile;
7873    }
7874
7875    public void deletePackage(final String packageName,
7876                              final IPackageDeleteObserver observer,
7877                              final int flags) {
7878        mContext.enforceCallingOrSelfPermission(
7879                android.Manifest.permission.DELETE_PACKAGES, null);
7880        // Queue up an async operation since the package deletion may take a little while.
7881        final int uid = Binder.getCallingUid();
7882        mHandler.post(new Runnable() {
7883            public void run() {
7884                mHandler.removeCallbacks(this);
7885                final int returnCode = deletePackageX(packageName, uid, flags);
7886                if (observer != null) {
7887                    try {
7888                        observer.packageDeleted(packageName, returnCode);
7889                    } catch (RemoteException e) {
7890                        Log.i(TAG, "Observer no longer exists.");
7891                    } //end catch
7892                } //end if
7893            } //end run
7894        });
7895    }
7896
7897    /**
7898     *  This method is an internal method that could be get invoked either
7899     *  to delete an installed package or to clean up a failed installation.
7900     *  After deleting an installed package, a broadcast is sent to notify any
7901     *  listeners that the package has been installed. For cleaning up a failed
7902     *  installation, the broadcast is not necessary since the package's
7903     *  installation wouldn't have sent the initial broadcast either
7904     *  The key steps in deleting a package are
7905     *  deleting the package information in internal structures like mPackages,
7906     *  deleting the packages base directories through installd
7907     *  updating mSettings to reflect current status
7908     *  persisting settings for later use
7909     *  sending a broadcast if necessary
7910     */
7911    private int deletePackageX(String packageName, int uid, int flags) {
7912        final PackageRemovedInfo info = new PackageRemovedInfo();
7913        final boolean res;
7914
7915        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
7916                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
7917        try {
7918            if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
7919                Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
7920                return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
7921            }
7922        } catch (RemoteException e) {
7923        }
7924
7925        synchronized (mInstallLock) {
7926            res = deletePackageLI(packageName,
7927                    (flags & PackageManager.DELETE_ALL_USERS) != 0
7928                            ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)),
7929                    true, flags | REMOVE_CHATTY, info, true);
7930        }
7931
7932        if (res) {
7933            boolean systemUpdate = info.isRemovedPackageSystemUpdate;
7934            info.sendBroadcast(true, systemUpdate);
7935
7936            // If the removed package was a system update, the old system packaged
7937            // was re-enabled; we need to broadcast this information
7938            if (systemUpdate) {
7939                Bundle extras = new Bundle(1);
7940                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
7941                        ? info.removedAppId : info.uid);
7942                extras.putBoolean(Intent.EXTRA_REPLACING, true);
7943
7944                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
7945                        extras, null, null, null);
7946                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
7947                        extras, null, null, null);
7948                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
7949                        null, packageName, null, null);
7950            }
7951        }
7952        // Force a gc here.
7953        Runtime.getRuntime().gc();
7954        // Delete the resources here after sending the broadcast to let
7955        // other processes clean up before deleting resources.
7956        if (info.args != null) {
7957            synchronized (mInstallLock) {
7958                info.args.doPostDeleteLI(true);
7959            }
7960        }
7961
7962        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
7963    }
7964
7965    static class PackageRemovedInfo {
7966        String removedPackage;
7967        int uid = -1;
7968        int removedAppId = -1;
7969        int[] removedUsers = null;
7970        boolean isRemovedPackageSystemUpdate = false;
7971        // Clean up resources deleted packages.
7972        InstallArgs args = null;
7973
7974        void sendBroadcast(boolean fullRemove, boolean replacing) {
7975            Bundle extras = new Bundle(1);
7976            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
7977            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
7978            if (replacing) {
7979                extras.putBoolean(Intent.EXTRA_REPLACING, true);
7980            }
7981            if (removedPackage != null) {
7982                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7983                        extras, null, null, removedUsers);
7984                if (fullRemove && !replacing) {
7985                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
7986                            extras, null, null, removedUsers);
7987                }
7988            }
7989            if (removedAppId >= 0) {
7990                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
7991                        removedUsers);
7992            }
7993        }
7994    }
7995
7996    /*
7997     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
7998     * flag is not set, the data directory is removed as well.
7999     * make sure this flag is set for partially installed apps. If not its meaningless to
8000     * delete a partially installed application.
8001     */
8002    private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo,
8003            int flags, boolean writeSettings) {
8004        String packageName = ps.name;
8005        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
8006        // Retrieve object to delete permissions for shared user later on
8007        final PackageSetting deletedPs;
8008        // reader
8009        synchronized (mPackages) {
8010            deletedPs = mSettings.mPackages.get(packageName);
8011            if (outInfo != null) {
8012                outInfo.removedPackage = packageName;
8013                outInfo.removedUsers = deletedPs != null
8014                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
8015                        : null;
8016            }
8017        }
8018        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8019            removeDataDirsLI(packageName);
8020            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
8021        }
8022        // writer
8023        synchronized (mPackages) {
8024            if (deletedPs != null) {
8025                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8026                    if (outInfo != null) {
8027                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
8028                    }
8029                    if (deletedPs != null) {
8030                        updatePermissionsLPw(deletedPs.name, null, 0);
8031                        if (deletedPs.sharedUser != null) {
8032                            // remove permissions associated with package
8033                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
8034                        }
8035                    }
8036                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
8037                }
8038            }
8039            // can downgrade to reader
8040            if (writeSettings) {
8041                // Save settings now
8042                mSettings.writeLPr();
8043            }
8044        }
8045    }
8046
8047    /*
8048     * Tries to delete system package.
8049     */
8050    private boolean deleteSystemPackageLI(PackageSetting newPs,
8051            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
8052        PackageSetting disabledPs = null;
8053        // Confirm if the system package has been updated
8054        // An updated system app can be deleted. This will also have to restore
8055        // the system pkg from system partition
8056        // reader
8057        synchronized (mPackages) {
8058            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
8059        }
8060        if (disabledPs == null) {
8061            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
8062            return false;
8063        } else {
8064            Log.i(TAG, "Deleting system pkg from data partition");
8065        }
8066        // Delete the updated package
8067        outInfo.isRemovedPackageSystemUpdate = true;
8068        if (disabledPs.versionCode < newPs.versionCode) {
8069            // Delete data for downgrades
8070            flags &= ~PackageManager.DELETE_KEEP_DATA;
8071        } else {
8072            // Preserve data by setting flag
8073            flags |= PackageManager.DELETE_KEEP_DATA;
8074        }
8075        boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo,
8076                writeSettings);
8077        if (!ret) {
8078            return false;
8079        }
8080        // writer
8081        synchronized (mPackages) {
8082            // Reinstate the old system package
8083            mSettings.enableSystemPackageLPw(newPs.name);
8084            // Remove any native libraries from the upgraded package.
8085            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
8086        }
8087        // Install the system package
8088        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
8089                PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
8090                SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
8091
8092        if (newPkg == null) {
8093            Slog.w(TAG, "Failed to restore system package:" + newPs.name
8094                    + " with error:" + mLastScanError);
8095            return false;
8096        }
8097        // writer
8098        synchronized (mPackages) {
8099            updatePermissionsLPw(newPkg.packageName, newPkg,
8100                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
8101            // can downgrade to reader here
8102            if (writeSettings) {
8103                mSettings.writeLPr();
8104            }
8105        }
8106        return true;
8107    }
8108
8109    private boolean deleteInstalledPackageLI(PackageSetting ps,
8110            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8111            boolean writeSettings) {
8112        if (outInfo != null) {
8113            outInfo.uid = ps.appId;
8114        }
8115
8116        // Delete package data from internal structures and also remove data if flag is set
8117        removePackageDataLI(ps, outInfo, flags, writeSettings);
8118
8119        // Delete application code and resources
8120        if (deleteCodeAndResources) {
8121            // TODO can pick up from PackageSettings as well
8122            int installFlags = isExternal(ps) ? PackageManager.INSTALL_EXTERNAL : 0;
8123            installFlags |= isForwardLocked(ps) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
8124            outInfo.args = createInstallArgs(installFlags, ps.codePathString,
8125                    ps.resourcePathString, ps.nativeLibraryPathString);
8126        }
8127        return true;
8128    }
8129
8130    /*
8131     * This method handles package deletion in general
8132     */
8133    private boolean deletePackageLI(String packageName, UserHandle user,
8134            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8135            boolean writeSettings) {
8136        if (packageName == null) {
8137            Slog.w(TAG, "Attempt to delete null packageName.");
8138            return false;
8139        }
8140        PackageSetting ps;
8141        boolean dataOnly = false;
8142        int removeUser = -1;
8143        int appId = -1;
8144        synchronized (mPackages) {
8145            ps = mSettings.mPackages.get(packageName);
8146            if (ps == null) {
8147                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8148                return false;
8149            }
8150            if (!isSystemApp(ps) && user != null
8151                    && user.getIdentifier() != UserHandle.USER_ALL) {
8152                // The caller is asking that the package only be deleted for a single
8153                // user.  To do this, we just mark its uninstalled state and delete
8154                // its data.
8155                ps.setUserState(user.getIdentifier(),
8156                        COMPONENT_ENABLED_STATE_DEFAULT,
8157                        false, //installed
8158                        true,  //stopped
8159                        true,  //notLaunched
8160                        null, null);
8161                if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8162                    // Other user still have this package installed, so all
8163                    // we need to do is clear this user's data and save that
8164                    // it is uninstalled.
8165                    removeUser = user.getIdentifier();
8166                    appId = ps.appId;
8167                    mSettings.writePackageRestrictionsLPr(removeUser);
8168                } else {
8169                    // We need to set it back to 'installed' so the uninstall
8170                    // broadcasts will be sent correctly.
8171                    ps.setInstalled(true, user.getIdentifier());
8172                }
8173            }
8174        }
8175
8176        if (removeUser >= 0) {
8177            // From above, we determined that we are deleting this only
8178            // for a single user.  Continue the work here.
8179            if (outInfo != null) {
8180                outInfo.removedPackage = packageName;
8181                outInfo.removedAppId = appId;
8182                outInfo.removedUsers = new int[] {removeUser};
8183            }
8184            mInstaller.clearUserData(packageName, removeUser);
8185            schedulePackageCleaning(packageName, removeUser, false);
8186            return true;
8187        }
8188
8189        if (dataOnly) {
8190            // Delete application data first
8191            removePackageDataLI(ps, outInfo, flags, writeSettings);
8192            return true;
8193        }
8194        boolean ret = false;
8195        if (isSystemApp(ps)) {
8196            Log.i(TAG, "Removing system package:" + ps.name);
8197            // When an updated system application is deleted we delete the existing resources as well and
8198            // fall back to existing code in system partition
8199            ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings);
8200        } else {
8201            Log.i(TAG, "Removing non-system package:" + ps.name);
8202            // Kill application pre-emptively especially for apps on sd.
8203            killApplication(packageName, ps.appId);
8204            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo,
8205                    writeSettings);
8206        }
8207        return ret;
8208    }
8209
8210    private final class ClearStorageConnection implements ServiceConnection {
8211        IMediaContainerService mContainerService;
8212
8213        @Override
8214        public void onServiceConnected(ComponentName name, IBinder service) {
8215            synchronized (this) {
8216                mContainerService = IMediaContainerService.Stub.asInterface(service);
8217                notifyAll();
8218            }
8219        }
8220
8221        @Override
8222        public void onServiceDisconnected(ComponentName name) {
8223        }
8224    }
8225
8226    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
8227        final boolean mounted;
8228        if (Environment.isExternalStorageEmulated()) {
8229            mounted = true;
8230        } else {
8231            final String status = Environment.getExternalStorageState();
8232
8233            mounted = status.equals(Environment.MEDIA_MOUNTED)
8234                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
8235        }
8236
8237        if (!mounted) {
8238            return;
8239        }
8240
8241        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
8242        int[] users;
8243        if (userId == UserHandle.USER_ALL) {
8244            users = sUserManager.getUserIds();
8245        } else {
8246            users = new int[] { userId };
8247        }
8248        for (int curUser : users) {
8249            ClearStorageConnection conn = new ClearStorageConnection();
8250            if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE, curUser)) {
8251                try {
8252                    long timeout = SystemClock.uptimeMillis() + 5000;
8253                    synchronized (conn) {
8254                        long now = SystemClock.uptimeMillis();
8255                        while (conn.mContainerService == null && now < timeout) {
8256                            try {
8257                                conn.wait(timeout - now);
8258                            } catch (InterruptedException e) {
8259                            }
8260                        }
8261                    }
8262                    if (conn.mContainerService == null) {
8263                        return;
8264                    }
8265                    final File externalCacheDir = Environment
8266                            .getExternalStorageAppCacheDirectory(packageName);
8267                    try {
8268                        conn.mContainerService.clearDirectory(externalCacheDir.toString());
8269                    } catch (RemoteException e) {
8270                    }
8271                    if (allData) {
8272                        final File externalDataDir = Environment
8273                                .getExternalStorageAppDataDirectory(packageName);
8274                        try {
8275                            conn.mContainerService.clearDirectory(externalDataDir.toString());
8276                        } catch (RemoteException e) {
8277                        }
8278                        final File externalMediaDir = Environment
8279                                .getExternalStorageAppMediaDirectory(packageName);
8280                        try {
8281                            conn.mContainerService.clearDirectory(externalMediaDir.toString());
8282                        } catch (RemoteException e) {
8283                        }
8284                    }
8285                } finally {
8286                    mContext.unbindService(conn);
8287                }
8288            }
8289        }
8290    }
8291
8292    @Override
8293    public void clearApplicationUserData(final String packageName,
8294            final IPackageDataObserver observer, final int userId) {
8295        mContext.enforceCallingOrSelfPermission(
8296                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
8297        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
8298        // Queue up an async operation since the package deletion may take a little while.
8299        mHandler.post(new Runnable() {
8300            public void run() {
8301                mHandler.removeCallbacks(this);
8302                final boolean succeeded;
8303                synchronized (mInstallLock) {
8304                    succeeded = clearApplicationUserDataLI(packageName, userId);
8305                }
8306                clearExternalStorageDataSync(packageName, userId, true);
8307                if (succeeded) {
8308                    // invoke DeviceStorageMonitor's update method to clear any notifications
8309                    DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
8310                            ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
8311                    if (dsm != null) {
8312                        dsm.updateMemory();
8313                    }
8314                }
8315                if(observer != null) {
8316                    try {
8317                        observer.onRemoveCompleted(packageName, succeeded);
8318                    } catch (RemoteException e) {
8319                        Log.i(TAG, "Observer no longer exists.");
8320                    }
8321                } //end if observer
8322            } //end run
8323        });
8324    }
8325
8326    private boolean clearApplicationUserDataLI(String packageName, int userId) {
8327        if (packageName == null) {
8328            Slog.w(TAG, "Attempt to delete null packageName.");
8329            return false;
8330        }
8331        PackageParser.Package p;
8332        boolean dataOnly = false;
8333        synchronized (mPackages) {
8334            p = mPackages.get(packageName);
8335            if(p == null) {
8336                dataOnly = true;
8337                PackageSetting ps = mSettings.mPackages.get(packageName);
8338                if((ps == null) || (ps.pkg == null)) {
8339                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8340                    return false;
8341                }
8342                p = ps.pkg;
8343            }
8344        }
8345
8346        if (!dataOnly) {
8347            //need to check this only for fully installed applications
8348            if (p == null) {
8349                Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8350                return false;
8351            }
8352            final ApplicationInfo applicationInfo = p.applicationInfo;
8353            if (applicationInfo == null) {
8354                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8355                return false;
8356            }
8357        }
8358        int retCode = mInstaller.clearUserData(packageName, userId);
8359        if (retCode < 0) {
8360            Slog.w(TAG, "Couldn't remove cache files for package: "
8361                    + packageName);
8362            return false;
8363        }
8364        return true;
8365    }
8366
8367    public void deleteApplicationCacheFiles(final String packageName,
8368            final IPackageDataObserver observer) {
8369        mContext.enforceCallingOrSelfPermission(
8370                android.Manifest.permission.DELETE_CACHE_FILES, null);
8371        // Queue up an async operation since the package deletion may take a little while.
8372        final int userId = UserHandle.getCallingUserId();
8373        mHandler.post(new Runnable() {
8374            public void run() {
8375                mHandler.removeCallbacks(this);
8376                final boolean succeded;
8377                synchronized (mInstallLock) {
8378                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
8379                }
8380                clearExternalStorageDataSync(packageName, userId, false);
8381                if(observer != null) {
8382                    try {
8383                        observer.onRemoveCompleted(packageName, succeded);
8384                    } catch (RemoteException e) {
8385                        Log.i(TAG, "Observer no longer exists.");
8386                    }
8387                } //end if observer
8388            } //end run
8389        });
8390    }
8391
8392    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
8393        if (packageName == null) {
8394            Slog.w(TAG, "Attempt to delete null packageName.");
8395            return false;
8396        }
8397        PackageParser.Package p;
8398        synchronized (mPackages) {
8399            p = mPackages.get(packageName);
8400        }
8401        if (p == null) {
8402            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8403            return false;
8404        }
8405        final ApplicationInfo applicationInfo = p.applicationInfo;
8406        if (applicationInfo == null) {
8407            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8408            return false;
8409        }
8410        // TODO: Pass userId to deleteCacheFiles
8411        int retCode = mInstaller.deleteCacheFiles(packageName);
8412        if (retCode < 0) {
8413            Slog.w(TAG, "Couldn't remove cache files for package: "
8414                       + packageName);
8415            return false;
8416        }
8417        return true;
8418    }
8419
8420    public void getPackageSizeInfo(final String packageName, int userHandle,
8421            final IPackageStatsObserver observer) {
8422        mContext.enforceCallingOrSelfPermission(
8423                android.Manifest.permission.GET_PACKAGE_SIZE, null);
8424
8425        PackageStats stats = new PackageStats(packageName, userHandle);
8426
8427        /*
8428         * Queue up an async operation since the package measurement may take a
8429         * little while.
8430         */
8431        Message msg = mHandler.obtainMessage(INIT_COPY);
8432        msg.obj = new MeasureParams(stats, observer);
8433        mHandler.sendMessage(msg);
8434    }
8435
8436    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
8437            PackageStats pStats) {
8438        if (packageName == null) {
8439            Slog.w(TAG, "Attempt to get size of null packageName.");
8440            return false;
8441        }
8442        PackageParser.Package p;
8443        boolean dataOnly = false;
8444        String asecPath = null;
8445        synchronized (mPackages) {
8446            p = mPackages.get(packageName);
8447            if(p == null) {
8448                dataOnly = true;
8449                PackageSetting ps = mSettings.mPackages.get(packageName);
8450                if((ps == null) || (ps.pkg == null)) {
8451                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8452                    return false;
8453                }
8454                p = ps.pkg;
8455            }
8456            if (p != null && (isExternal(p) || isForwardLocked(p))) {
8457                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8458                if (secureContainerId != null) {
8459                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8460                }
8461            }
8462        }
8463        String publicSrcDir = null;
8464        if(!dataOnly) {
8465            final ApplicationInfo applicationInfo = p.applicationInfo;
8466            if (applicationInfo == null) {
8467                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8468                return false;
8469            }
8470            if (isForwardLocked(p)) {
8471                publicSrcDir = applicationInfo.publicSourceDir;
8472            }
8473        }
8474        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir,
8475                asecPath, pStats);
8476        if (res < 0) {
8477            return false;
8478        }
8479
8480        // Fix-up for forward-locked applications in ASEC containers.
8481        if (!isExternal(p)) {
8482            pStats.codeSize += pStats.externalCodeSize;
8483            pStats.externalCodeSize = 0L;
8484        }
8485
8486        return true;
8487    }
8488
8489
8490    public void addPackageToPreferred(String packageName) {
8491        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
8492    }
8493
8494    public void removePackageFromPreferred(String packageName) {
8495        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
8496    }
8497
8498    public List<PackageInfo> getPreferredPackages(int flags) {
8499        return new ArrayList<PackageInfo>();
8500    }
8501
8502    private int getUidTargetSdkVersionLockedLPr(int uid) {
8503        Object obj = mSettings.getUserIdLPr(uid);
8504        if (obj instanceof SharedUserSetting) {
8505            final SharedUserSetting sus = (SharedUserSetting) obj;
8506            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
8507            final Iterator<PackageSetting> it = sus.packages.iterator();
8508            while (it.hasNext()) {
8509                final PackageSetting ps = it.next();
8510                if (ps.pkg != null) {
8511                    int v = ps.pkg.applicationInfo.targetSdkVersion;
8512                    if (v < vers) vers = v;
8513                }
8514            }
8515            return vers;
8516        } else if (obj instanceof PackageSetting) {
8517            final PackageSetting ps = (PackageSetting) obj;
8518            if (ps.pkg != null) {
8519                return ps.pkg.applicationInfo.targetSdkVersion;
8520            }
8521        }
8522        return Build.VERSION_CODES.CUR_DEVELOPMENT;
8523    }
8524
8525    public void addPreferredActivity(IntentFilter filter, int match,
8526            ComponentName[] set, ComponentName activity, int userId) {
8527        // writer
8528        int callingUid = Binder.getCallingUid();
8529        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
8530        synchronized (mPackages) {
8531            if (mContext.checkCallingOrSelfPermission(
8532                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8533                    != PackageManager.PERMISSION_GRANTED) {
8534                if (getUidTargetSdkVersionLockedLPr(callingUid)
8535                        < Build.VERSION_CODES.FROYO) {
8536                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
8537                            + callingUid);
8538                    return;
8539                }
8540                mContext.enforceCallingOrSelfPermission(
8541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8542            }
8543
8544            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
8545            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8546            mSettings.mPreferredActivities.addFilter(
8547                    new PreferredActivity(filter, match, set, activity, userId));
8548            scheduleWriteSettingsLocked();
8549        }
8550    }
8551
8552    public void replacePreferredActivity(IntentFilter filter, int match,
8553            ComponentName[] set, ComponentName activity) {
8554        if (filter.countActions() != 1) {
8555            throw new IllegalArgumentException(
8556                    "replacePreferredActivity expects filter to have only 1 action.");
8557        }
8558        if (filter.countCategories() != 1) {
8559            throw new IllegalArgumentException(
8560                    "replacePreferredActivity expects filter to have only 1 category.");
8561        }
8562        if (filter.countDataAuthorities() != 0
8563                || filter.countDataPaths() != 0
8564                || filter.countDataSchemes() != 0
8565                || filter.countDataTypes() != 0) {
8566            throw new IllegalArgumentException(
8567                    "replacePreferredActivity expects filter to have no data authorities, " +
8568                    "paths, schemes or types.");
8569        }
8570        synchronized (mPackages) {
8571            if (mContext.checkCallingOrSelfPermission(
8572                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8573                    != PackageManager.PERMISSION_GRANTED) {
8574                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8575                        < Build.VERSION_CODES.FROYO) {
8576                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8577                            + Binder.getCallingUid());
8578                    return;
8579                }
8580                mContext.enforceCallingOrSelfPermission(
8581                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8582            }
8583
8584            final int callingUserId = UserHandle.getCallingUserId();
8585            ArrayList<PreferredActivity> removed = null;
8586            Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8587            String action = filter.getAction(0);
8588            String category = filter.getCategory(0);
8589            while (it.hasNext()) {
8590                PreferredActivity pa = it.next();
8591                if (pa.mUserId != callingUserId) continue;
8592                if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
8593                    if (removed == null) {
8594                        removed = new ArrayList<PreferredActivity>();
8595                    }
8596                    removed.add(pa);
8597                    Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
8598                    filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8599                }
8600            }
8601            if (removed != null) {
8602                for (int i=0; i<removed.size(); i++) {
8603                    PreferredActivity pa = removed.get(i);
8604                    mSettings.mPreferredActivities.removeFilter(pa);
8605                }
8606            }
8607            addPreferredActivity(filter, match, set, activity, callingUserId);
8608        }
8609    }
8610
8611    public void clearPackagePreferredActivities(String packageName) {
8612        final int uid = Binder.getCallingUid();
8613        // writer
8614        synchronized (mPackages) {
8615            PackageParser.Package pkg = mPackages.get(packageName);
8616            if (pkg == null || pkg.applicationInfo.uid != uid) {
8617                if (mContext.checkCallingOrSelfPermission(
8618                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8619                        != PackageManager.PERMISSION_GRANTED) {
8620                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8621                            < Build.VERSION_CODES.FROYO) {
8622                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8623                                + Binder.getCallingUid());
8624                        return;
8625                    }
8626                    mContext.enforceCallingOrSelfPermission(
8627                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8628                }
8629            }
8630
8631            if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
8632                scheduleWriteSettingsLocked();
8633            }
8634        }
8635    }
8636
8637    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8638    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
8639        ArrayList<PreferredActivity> removed = null;
8640        Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8641        while (it.hasNext()) {
8642            PreferredActivity pa = it.next();
8643            if (userId != UserHandle.USER_ALL && pa.mUserId != userId) {
8644                continue;
8645            }
8646            if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
8647                if (removed == null) {
8648                    removed = new ArrayList<PreferredActivity>();
8649                }
8650                removed.add(pa);
8651            }
8652        }
8653        if (removed != null) {
8654            for (int i=0; i<removed.size(); i++) {
8655                PreferredActivity pa = removed.get(i);
8656                mSettings.mPreferredActivities.removeFilter(pa);
8657            }
8658            return true;
8659        }
8660        return false;
8661    }
8662
8663    public int getPreferredActivities(List<IntentFilter> outFilters,
8664            List<ComponentName> outActivities, String packageName) {
8665
8666        int num = 0;
8667        final int userId = UserHandle.getCallingUserId();
8668        // reader
8669        synchronized (mPackages) {
8670            final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8671            while (it.hasNext()) {
8672                final PreferredActivity pa = it.next();
8673                if (pa.mUserId != userId) {
8674                    continue;
8675                }
8676                if (packageName == null
8677                        || pa.mPref.mComponent.getPackageName().equals(packageName)) {
8678                    if (outFilters != null) {
8679                        outFilters.add(new IntentFilter(pa));
8680                    }
8681                    if (outActivities != null) {
8682                        outActivities.add(pa.mPref.mComponent);
8683                    }
8684                }
8685            }
8686        }
8687
8688        return num;
8689    }
8690
8691    @Override
8692    public void setApplicationEnabledSetting(String appPackageName,
8693            int newState, int flags, int userId) {
8694        if (!sUserManager.exists(userId)) return;
8695        setEnabledSetting(appPackageName, null, newState, flags, userId);
8696    }
8697
8698    @Override
8699    public void setComponentEnabledSetting(ComponentName componentName,
8700            int newState, int flags, int userId) {
8701        if (!sUserManager.exists(userId)) return;
8702        setEnabledSetting(componentName.getPackageName(),
8703                componentName.getClassName(), newState, flags, userId);
8704    }
8705
8706    private void setEnabledSetting(
8707            final String packageName, String className, int newState, final int flags, int userId) {
8708        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8709              || newState == COMPONENT_ENABLED_STATE_ENABLED
8710              || newState == COMPONENT_ENABLED_STATE_DISABLED
8711              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
8712            throw new IllegalArgumentException("Invalid new component state: "
8713                    + newState);
8714        }
8715        PackageSetting pkgSetting;
8716        final int uid = Binder.getCallingUid();
8717        final int permission = mContext.checkCallingPermission(
8718                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8719        enforceCrossUserPermission(uid, userId, false, "set enabled");
8720        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8721        boolean sendNow = false;
8722        boolean isApp = (className == null);
8723        String componentName = isApp ? packageName : className;
8724        int packageUid = -1;
8725        ArrayList<String> components;
8726
8727        // writer
8728        synchronized (mPackages) {
8729            pkgSetting = mSettings.mPackages.get(packageName);
8730            if (pkgSetting == null) {
8731                if (className == null) {
8732                    throw new IllegalArgumentException(
8733                            "Unknown package: " + packageName);
8734                }
8735                throw new IllegalArgumentException(
8736                        "Unknown component: " + packageName
8737                        + "/" + className);
8738            }
8739            // Allow root and verify that userId is not being specified by a different user
8740            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
8741                throw new SecurityException(
8742                        "Permission Denial: attempt to change component state from pid="
8743                        + Binder.getCallingPid()
8744                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
8745            }
8746            if (className == null) {
8747                // We're dealing with an application/package level state change
8748                if (pkgSetting.getEnabled(userId) == newState) {
8749                    // Nothing to do
8750                    return;
8751                }
8752                pkgSetting.setEnabled(newState, userId);
8753                // pkgSetting.pkg.mSetEnabled = newState;
8754            } else {
8755                // We're dealing with a component level state change
8756                // First, verify that this is a valid class name.
8757                PackageParser.Package pkg = pkgSetting.pkg;
8758                if (pkg == null || !pkg.hasComponentClassName(className)) {
8759                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8760                        throw new IllegalArgumentException("Component class " + className
8761                                + " does not exist in " + packageName);
8762                    } else {
8763                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8764                                + className + " does not exist in " + packageName);
8765                    }
8766                }
8767                switch (newState) {
8768                case COMPONENT_ENABLED_STATE_ENABLED:
8769                    if (!pkgSetting.enableComponentLPw(className, userId)) {
8770                        return;
8771                    }
8772                    break;
8773                case COMPONENT_ENABLED_STATE_DISABLED:
8774                    if (!pkgSetting.disableComponentLPw(className, userId)) {
8775                        return;
8776                    }
8777                    break;
8778                case COMPONENT_ENABLED_STATE_DEFAULT:
8779                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
8780                        return;
8781                    }
8782                    break;
8783                default:
8784                    Slog.e(TAG, "Invalid new component state: " + newState);
8785                    return;
8786                }
8787            }
8788            mSettings.writePackageRestrictionsLPr(userId);
8789            packageUid = UserHandle.getUid(userId, pkgSetting.appId);
8790            components = mPendingBroadcasts.get(packageName);
8791            final boolean newPackage = components == null;
8792            if (newPackage) {
8793                components = new ArrayList<String>();
8794            }
8795            if (!components.contains(componentName)) {
8796                components.add(componentName);
8797            }
8798            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
8799                sendNow = true;
8800                // Purge entry from pending broadcast list if another one exists already
8801                // since we are sending one right away.
8802                mPendingBroadcasts.remove(packageName);
8803            } else {
8804                if (newPackage) {
8805                    mPendingBroadcasts.put(packageName, components);
8806                }
8807                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
8808                    // Schedule a message
8809                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
8810                }
8811            }
8812        }
8813
8814        long callingId = Binder.clearCallingIdentity();
8815        try {
8816            if (sendNow) {
8817                sendPackageChangedBroadcast(packageName,
8818                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
8819            }
8820        } finally {
8821            Binder.restoreCallingIdentity(callingId);
8822        }
8823    }
8824
8825    private void sendPackageChangedBroadcast(String packageName,
8826            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
8827        if (DEBUG_INSTALL)
8828            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
8829                    + componentNames);
8830        Bundle extras = new Bundle(4);
8831        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
8832        String nameList[] = new String[componentNames.size()];
8833        componentNames.toArray(nameList);
8834        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
8835        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
8836        extras.putInt(Intent.EXTRA_UID, packageUid);
8837        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
8838                new int[] {UserHandle.getUserId(packageUid)});
8839    }
8840
8841    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
8842        if (!sUserManager.exists(userId)) return;
8843        final int uid = Binder.getCallingUid();
8844        final int permission = mContext.checkCallingOrSelfPermission(
8845                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8846        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8847        enforceCrossUserPermission(uid, userId, true, "stop package");
8848        // writer
8849        synchronized (mPackages) {
8850            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
8851                    uid, userId)) {
8852                scheduleWritePackageRestrictionsLocked(userId);
8853            }
8854        }
8855    }
8856
8857    public String getInstallerPackageName(String packageName) {
8858        // reader
8859        synchronized (mPackages) {
8860            return mSettings.getInstallerPackageNameLPr(packageName);
8861        }
8862    }
8863
8864    @Override
8865    public int getApplicationEnabledSetting(String packageName, int userId) {
8866        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
8867        int uid = Binder.getCallingUid();
8868        enforceCrossUserPermission(uid, userId, false, "get enabled");
8869        // reader
8870        synchronized (mPackages) {
8871            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
8872        }
8873    }
8874
8875    @Override
8876    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
8877        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
8878        int uid = Binder.getCallingUid();
8879        enforceCrossUserPermission(uid, userId, false, "get component enabled");
8880        // reader
8881        synchronized (mPackages) {
8882            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
8883        }
8884    }
8885
8886    public void enterSafeMode() {
8887        enforceSystemOrRoot("Only the system can request entering safe mode");
8888
8889        if (!mSystemReady) {
8890            mSafeMode = true;
8891        }
8892    }
8893
8894    public void systemReady() {
8895        mSystemReady = true;
8896
8897        // Read the compatibilty setting when the system is ready.
8898        boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
8899                mContext.getContentResolver(),
8900                android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
8901        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
8902        if (DEBUG_SETTINGS) {
8903            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
8904        }
8905    }
8906
8907    public boolean isSafeMode() {
8908        return mSafeMode;
8909    }
8910
8911    public boolean hasSystemUidErrors() {
8912        return mHasSystemUidErrors;
8913    }
8914
8915    static String arrayToString(int[] array) {
8916        StringBuffer buf = new StringBuffer(128);
8917        buf.append('[');
8918        if (array != null) {
8919            for (int i=0; i<array.length; i++) {
8920                if (i > 0) buf.append(", ");
8921                buf.append(array[i]);
8922            }
8923        }
8924        buf.append(']');
8925        return buf.toString();
8926    }
8927
8928    static class DumpState {
8929        public static final int DUMP_LIBS = 1 << 0;
8930
8931        public static final int DUMP_FEATURES = 1 << 1;
8932
8933        public static final int DUMP_RESOLVERS = 1 << 2;
8934
8935        public static final int DUMP_PERMISSIONS = 1 << 3;
8936
8937        public static final int DUMP_PACKAGES = 1 << 4;
8938
8939        public static final int DUMP_SHARED_USERS = 1 << 5;
8940
8941        public static final int DUMP_MESSAGES = 1 << 6;
8942
8943        public static final int DUMP_PROVIDERS = 1 << 7;
8944
8945        public static final int DUMP_VERIFIERS = 1 << 8;
8946
8947        public static final int DUMP_PREFERRED = 1 << 9;
8948
8949        public static final int DUMP_PREFERRED_XML = 1 << 10;
8950
8951        public static final int OPTION_SHOW_FILTERS = 1 << 0;
8952
8953        private int mTypes;
8954
8955        private int mOptions;
8956
8957        private boolean mTitlePrinted;
8958
8959        private SharedUserSetting mSharedUser;
8960
8961        public boolean isDumping(int type) {
8962            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
8963                return true;
8964            }
8965
8966            return (mTypes & type) != 0;
8967        }
8968
8969        public void setDump(int type) {
8970            mTypes |= type;
8971        }
8972
8973        public boolean isOptionEnabled(int option) {
8974            return (mOptions & option) != 0;
8975        }
8976
8977        public void setOptionEnabled(int option) {
8978            mOptions |= option;
8979        }
8980
8981        public boolean onTitlePrinted() {
8982            final boolean printed = mTitlePrinted;
8983            mTitlePrinted = true;
8984            return printed;
8985        }
8986
8987        public boolean getTitlePrinted() {
8988            return mTitlePrinted;
8989        }
8990
8991        public void setTitlePrinted(boolean enabled) {
8992            mTitlePrinted = enabled;
8993        }
8994
8995        public SharedUserSetting getSharedUser() {
8996            return mSharedUser;
8997        }
8998
8999        public void setSharedUser(SharedUserSetting user) {
9000            mSharedUser = user;
9001        }
9002    }
9003
9004    @Override
9005    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9006        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
9007                != PackageManager.PERMISSION_GRANTED) {
9008            pw.println("Permission Denial: can't dump ActivityManager from from pid="
9009                    + Binder.getCallingPid()
9010                    + ", uid=" + Binder.getCallingUid()
9011                    + " without permission "
9012                    + android.Manifest.permission.DUMP);
9013            return;
9014        }
9015
9016        DumpState dumpState = new DumpState();
9017
9018        String packageName = null;
9019
9020        int opti = 0;
9021        while (opti < args.length) {
9022            String opt = args[opti];
9023            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9024                break;
9025            }
9026            opti++;
9027            if ("-a".equals(opt)) {
9028                // Right now we only know how to print all.
9029            } else if ("-h".equals(opt)) {
9030                pw.println("Package manager dump options:");
9031                pw.println("  [-h] [-f] [cmd] ...");
9032                pw.println("    -f: print details of intent filters");
9033                pw.println("    -h: print this help");
9034                pw.println("  cmd may be one of:");
9035                pw.println("    l[ibraries]: list known shared libraries");
9036                pw.println("    f[ibraries]: list device features");
9037                pw.println("    r[esolvers]: dump intent resolvers");
9038                pw.println("    perm[issions]: dump permissions");
9039                pw.println("    pref[erred]: print preferred package settings");
9040                pw.println("    preferred-xml: print preferred package settings as xml");
9041                pw.println("    prov[iders]: dump content providers");
9042                pw.println("    p[ackages]: dump installed packages");
9043                pw.println("    s[hared-users]: dump shared user IDs");
9044                pw.println("    m[essages]: print collected runtime messages");
9045                pw.println("    v[erifiers]: print package verifier info");
9046                pw.println("    <package.name>: info about given package");
9047                return;
9048            } else if ("-f".equals(opt)) {
9049                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
9050            } else {
9051                pw.println("Unknown argument: " + opt + "; use -h for help");
9052            }
9053        }
9054
9055        // Is the caller requesting to dump a particular piece of data?
9056        if (opti < args.length) {
9057            String cmd = args[opti];
9058            opti++;
9059            // Is this a package name?
9060            if ("android".equals(cmd) || cmd.contains(".")) {
9061                packageName = cmd;
9062            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
9063                dumpState.setDump(DumpState.DUMP_LIBS);
9064            } else if ("f".equals(cmd) || "features".equals(cmd)) {
9065                dumpState.setDump(DumpState.DUMP_FEATURES);
9066            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
9067                dumpState.setDump(DumpState.DUMP_RESOLVERS);
9068            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
9069                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
9070            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
9071                dumpState.setDump(DumpState.DUMP_PREFERRED);
9072            } else if ("preferred-xml".equals(cmd)) {
9073                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
9074            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
9075                dumpState.setDump(DumpState.DUMP_PACKAGES);
9076            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
9077                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
9078            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
9079                dumpState.setDump(DumpState.DUMP_PROVIDERS);
9080            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
9081                dumpState.setDump(DumpState.DUMP_MESSAGES);
9082            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
9083                dumpState.setDump(DumpState.DUMP_VERIFIERS);
9084            }
9085        }
9086
9087        // reader
9088        synchronized (mPackages) {
9089            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
9090                if (dumpState.onTitlePrinted())
9091                    pw.println(" ");
9092                pw.println("Verifiers:");
9093                pw.print("  Required: ");
9094                pw.print(mRequiredVerifierPackage);
9095                pw.print(" (uid=");
9096                pw.print(getPackageUid(mRequiredVerifierPackage, 0));
9097                pw.println(")");
9098            }
9099
9100            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
9101                if (dumpState.onTitlePrinted())
9102                    pw.println(" ");
9103                pw.println("Libraries:");
9104                final Iterator<String> it = mSharedLibraries.keySet().iterator();
9105                while (it.hasNext()) {
9106                    String name = it.next();
9107                    pw.print("  ");
9108                    pw.print(name);
9109                    pw.print(" -> ");
9110                    pw.println(mSharedLibraries.get(name));
9111                }
9112            }
9113
9114            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
9115                if (dumpState.onTitlePrinted())
9116                    pw.println(" ");
9117                pw.println("Features:");
9118                Iterator<String> it = mAvailableFeatures.keySet().iterator();
9119                while (it.hasNext()) {
9120                    String name = it.next();
9121                    pw.print("  ");
9122                    pw.println(name);
9123                }
9124            }
9125
9126            if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
9127                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
9128                        : "Activity Resolver Table:", "  ", packageName,
9129                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9130                    dumpState.setTitlePrinted(true);
9131                }
9132                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
9133                        : "Receiver Resolver Table:", "  ", packageName,
9134                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9135                    dumpState.setTitlePrinted(true);
9136                }
9137                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
9138                        : "Service Resolver Table:", "  ", packageName,
9139                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9140                    dumpState.setTitlePrinted(true);
9141                }
9142            }
9143
9144            if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
9145                if (mSettings.mPreferredActivities.dump(pw,
9146                        dumpState.getTitlePrinted() ? "\nPreferred Activities:"
9147                            : "Preferred Activities:", "  ",
9148                        packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9149                    dumpState.setTitlePrinted(true);
9150                }
9151            }
9152
9153            if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
9154                pw.flush();
9155                FileOutputStream fout = new FileOutputStream(fd);
9156                BufferedOutputStream str = new BufferedOutputStream(fout);
9157                XmlSerializer serializer = new FastXmlSerializer();
9158                try {
9159                    serializer.setOutput(str, "utf-8");
9160                    serializer.startDocument(null, true);
9161                    serializer.setFeature(
9162                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
9163                    mSettings.writePreferredActivitiesLPr(serializer);
9164                    serializer.endDocument();
9165                    serializer.flush();
9166                } catch (IllegalArgumentException e) {
9167                    pw.println("Failed writing: " + e);
9168                } catch (IllegalStateException e) {
9169                    pw.println("Failed writing: " + e);
9170                } catch (IOException e) {
9171                    pw.println("Failed writing: " + e);
9172                }
9173            }
9174
9175            if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
9176                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
9177            }
9178
9179            if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
9180                boolean printedSomething = false;
9181                for (PackageParser.Provider p : mProvidersByComponent.values()) {
9182                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9183                        continue;
9184                    }
9185                    if (!printedSomething) {
9186                        if (dumpState.onTitlePrinted())
9187                            pw.println(" ");
9188                        pw.println("Registered ContentProviders:");
9189                        printedSomething = true;
9190                    }
9191                    pw.print("  "); pw.print(p.getComponentShortName()); pw.println(":");
9192                    pw.print("    "); pw.println(p.toString());
9193                }
9194                printedSomething = false;
9195                for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
9196                    PackageParser.Provider p = entry.getValue();
9197                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9198                        continue;
9199                    }
9200                    if (!printedSomething) {
9201                        if (dumpState.onTitlePrinted())
9202                            pw.println(" ");
9203                        pw.println("ContentProvider Authorities:");
9204                        printedSomething = true;
9205                    }
9206                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
9207                    pw.print("    "); pw.println(p.toString());
9208                    if (p.info != null && p.info.applicationInfo != null) {
9209                        final String appInfo = p.info.applicationInfo.toString();
9210                        pw.print("      applicationInfo="); pw.println(appInfo);
9211                    }
9212                }
9213            }
9214
9215            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
9216                mSettings.dumpPackagesLPr(pw, packageName, dumpState);
9217            }
9218
9219            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
9220                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
9221            }
9222
9223            if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
9224                if (dumpState.onTitlePrinted())
9225                    pw.println(" ");
9226                mSettings.dumpReadMessagesLPr(pw, dumpState);
9227
9228                pw.println(" ");
9229                pw.println("Package warning messages:");
9230                final File fname = getSettingsProblemFile();
9231                FileInputStream in = null;
9232                try {
9233                    in = new FileInputStream(fname);
9234                    final int avail = in.available();
9235                    final byte[] data = new byte[avail];
9236                    in.read(data);
9237                    pw.print(new String(data));
9238                } catch (FileNotFoundException e) {
9239                } catch (IOException e) {
9240                } finally {
9241                    if (in != null) {
9242                        try {
9243                            in.close();
9244                        } catch (IOException e) {
9245                        }
9246                    }
9247                }
9248            }
9249        }
9250    }
9251
9252    // ------- apps on sdcard specific code -------
9253    static final boolean DEBUG_SD_INSTALL = false;
9254
9255    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9256
9257    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9258
9259    private boolean mMediaMounted = false;
9260
9261    private String getEncryptKey() {
9262        try {
9263            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9264                    SD_ENCRYPTION_KEYSTORE_NAME);
9265            if (sdEncKey == null) {
9266                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9267                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
9268                if (sdEncKey == null) {
9269                    Slog.e(TAG, "Failed to create encryption keys");
9270                    return null;
9271                }
9272            }
9273            return sdEncKey;
9274        } catch (NoSuchAlgorithmException nsae) {
9275            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
9276            return null;
9277        } catch (IOException ioe) {
9278            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
9279            return null;
9280        }
9281
9282    }
9283
9284    /* package */static String getTempContainerId() {
9285        int tmpIdx = 1;
9286        String list[] = PackageHelper.getSecureContainerList();
9287        if (list != null) {
9288            for (final String name : list) {
9289                // Ignore null and non-temporary container entries
9290                if (name == null || !name.startsWith(mTempContainerPrefix)) {
9291                    continue;
9292                }
9293
9294                String subStr = name.substring(mTempContainerPrefix.length());
9295                try {
9296                    int cid = Integer.parseInt(subStr);
9297                    if (cid >= tmpIdx) {
9298                        tmpIdx = cid + 1;
9299                    }
9300                } catch (NumberFormatException e) {
9301                }
9302            }
9303        }
9304        return mTempContainerPrefix + tmpIdx;
9305    }
9306
9307    /*
9308     * Update media status on PackageManager.
9309     */
9310    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9311        int callingUid = Binder.getCallingUid();
9312        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
9313            throw new SecurityException("Media status can only be updated by the system");
9314        }
9315        // reader; this apparently protects mMediaMounted, but should probably
9316        // be a different lock in that case.
9317        synchronized (mPackages) {
9318            Log.i(TAG, "Updating external media status from "
9319                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
9320                    + (mediaStatus ? "mounted" : "unmounted"));
9321            if (DEBUG_SD_INSTALL)
9322                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
9323                        + ", mMediaMounted=" + mMediaMounted);
9324            if (mediaStatus == mMediaMounted) {
9325                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
9326                        : 0, -1);
9327                mHandler.sendMessage(msg);
9328                return;
9329            }
9330            mMediaMounted = mediaStatus;
9331        }
9332        // Queue up an async operation since the package installation may take a
9333        // little while.
9334        mHandler.post(new Runnable() {
9335            public void run() {
9336                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
9337            }
9338        });
9339    }
9340
9341    /**
9342     * Called by MountService when the initial ASECs to scan are available.
9343     * Should block until all the ASEC containers are finished being scanned.
9344     */
9345    public void scanAvailableAsecs() {
9346        updateExternalMediaStatusInner(true, false, false);
9347    }
9348
9349    /*
9350     * Collect information of applications on external media, map them against
9351     * existing containers and update information based on current mount status.
9352     * Please note that we always have to report status if reportStatus has been
9353     * set to true especially when unloading packages.
9354     */
9355    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
9356            boolean externalStorage) {
9357        // Collection of uids
9358        int uidArr[] = null;
9359        // Collection of stale containers
9360        HashSet<String> removeCids = new HashSet<String>();
9361        // Collection of packages on external media with valid containers.
9362        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
9363        // Get list of secure containers.
9364        final String list[] = PackageHelper.getSecureContainerList();
9365        if (list == null || list.length == 0) {
9366            Log.i(TAG, "No secure containers on sdcard");
9367        } else {
9368            // Process list of secure containers and categorize them
9369            // as active or stale based on their package internal state.
9370            int uidList[] = new int[list.length];
9371            int num = 0;
9372            // reader
9373            synchronized (mPackages) {
9374                for (String cid : list) {
9375                    if (DEBUG_SD_INSTALL)
9376                        Log.i(TAG, "Processing container " + cid);
9377                    String pkgName = getAsecPackageName(cid);
9378                    if (pkgName == null) {
9379                        if (DEBUG_SD_INSTALL)
9380                            Log.i(TAG, "Container : " + cid + " stale");
9381                        removeCids.add(cid);
9382                        continue;
9383                    }
9384                    if (DEBUG_SD_INSTALL)
9385                        Log.i(TAG, "Looking for pkg : " + pkgName);
9386
9387                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
9388                    if (ps == null) {
9389                        Log.i(TAG, "Deleting container with no matching settings " + cid);
9390                        removeCids.add(cid);
9391                        continue;
9392                    }
9393
9394                    /*
9395                     * Skip packages that are not external if we're unmounting
9396                     * external storage.
9397                     */
9398                    if (externalStorage && !isMounted && !isExternal(ps)) {
9399                        continue;
9400                    }
9401
9402                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
9403                    // The package status is changed only if the code path
9404                    // matches between settings and the container id.
9405                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
9406                        if (DEBUG_SD_INSTALL) {
9407                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9408                                    + " at code path: " + ps.codePathString);
9409                        }
9410
9411                        // We do have a valid package installed on sdcard
9412                        processCids.put(args, ps.codePathString);
9413                        final int uid = ps.appId;
9414                        if (uid != -1) {
9415                            uidList[num++] = uid;
9416                        }
9417                    } else {
9418                        Log.i(TAG, "Deleting stale container for " + cid);
9419                        removeCids.add(cid);
9420                    }
9421                }
9422            }
9423
9424            if (num > 0) {
9425                // Sort uid list
9426                Arrays.sort(uidList, 0, num);
9427                // Throw away duplicates
9428                uidArr = new int[num];
9429                uidArr[0] = uidList[0];
9430                int di = 0;
9431                for (int i = 1; i < num; i++) {
9432                    if (uidList[i - 1] != uidList[i]) {
9433                        uidArr[di++] = uidList[i];
9434                    }
9435                }
9436            }
9437        }
9438        // Process packages with valid entries.
9439        if (isMounted) {
9440            if (DEBUG_SD_INSTALL)
9441                Log.i(TAG, "Loading packages");
9442            loadMediaPackages(processCids, uidArr, removeCids);
9443            startCleaningPackages(-1);
9444        } else {
9445            if (DEBUG_SD_INSTALL)
9446                Log.i(TAG, "Unloading packages");
9447            unloadMediaPackages(processCids, uidArr, reportStatus);
9448        }
9449    }
9450
9451   private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9452            int uidArr[], IIntentReceiver finishedReceiver) {
9453        int size = pkgList.size();
9454        if (size > 0) {
9455            // Send broadcasts here
9456            Bundle extras = new Bundle();
9457            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9458                    .toArray(new String[size]));
9459            if (uidArr != null) {
9460                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9461            }
9462            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9463                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
9464            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
9465        }
9466    }
9467
9468   /*
9469     * Look at potentially valid container ids from processCids If package
9470     * information doesn't match the one on record or package scanning fails,
9471     * the cid is added to list of removeCids. We currently don't delete stale
9472     * containers.
9473     */
9474   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9475            HashSet<String> removeCids) {
9476        ArrayList<String> pkgList = new ArrayList<String>();
9477        Set<AsecInstallArgs> keys = processCids.keySet();
9478        boolean doGc = false;
9479        for (AsecInstallArgs args : keys) {
9480            String codePath = processCids.get(args);
9481            if (DEBUG_SD_INSTALL)
9482                Log.i(TAG, "Loading container : " + args.cid);
9483            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9484            try {
9485                // Make sure there are no container errors first.
9486                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9487                    Slog.e(TAG, "Failed to mount cid : " + args.cid
9488                            + " when installing from sdcard");
9489                    continue;
9490                }
9491                // Check code path here.
9492                if (codePath == null || !codePath.equals(args.getCodePath())) {
9493                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9494                            + " does not match one in settings " + codePath);
9495                    continue;
9496                }
9497                // Parse package
9498                int parseFlags = mDefParseFlags;
9499                if (args.isExternal()) {
9500                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
9501                }
9502                if (args.isFwdLocked()) {
9503                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9504                }
9505
9506                doGc = true;
9507                synchronized (mInstallLock) {
9508                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
9509                            0, 0, null);
9510                    // Scan the package
9511                    if (pkg != null) {
9512                        /*
9513                         * TODO why is the lock being held? doPostInstall is
9514                         * called in other places without the lock. This needs
9515                         * to be straightened out.
9516                         */
9517                        // writer
9518                        synchronized (mPackages) {
9519                            retCode = PackageManager.INSTALL_SUCCEEDED;
9520                            pkgList.add(pkg.packageName);
9521                            // Post process args
9522                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9523                                    pkg.applicationInfo.uid);
9524                        }
9525                    } else {
9526                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
9527                    }
9528                }
9529
9530            } finally {
9531                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9532                    // Don't destroy container here. Wait till gc clears things
9533                    // up.
9534                    removeCids.add(args.cid);
9535                }
9536            }
9537        }
9538        // writer
9539        synchronized (mPackages) {
9540            // If the platform SDK has changed since the last time we booted,
9541            // we need to re-grant app permission to catch any new ones that
9542            // appear. This is really a hack, and means that apps can in some
9543            // cases get permissions that the user didn't initially explicitly
9544            // allow... it would be nice to have some better way to handle
9545            // this situation.
9546            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9547            if (regrantPermissions)
9548                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9549                        + mSdkVersion + "; regranting permissions for external storage");
9550            mSettings.mExternalSdkPlatform = mSdkVersion;
9551
9552            // Make sure group IDs have been assigned, and any permission
9553            // changes in other apps are accounted for
9554            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9555                    | (regrantPermissions
9556                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9557                            : 0));
9558            // can downgrade to reader
9559            // Persist settings
9560            mSettings.writeLPr();
9561        }
9562        // Send a broadcast to let everyone know we are done processing
9563        if (pkgList.size() > 0) {
9564            sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9565        }
9566        // Force gc to avoid any stale parser references that we might have.
9567        if (doGc) {
9568            Runtime.getRuntime().gc();
9569        }
9570        // List stale containers and destroy stale temporary containers.
9571        if (removeCids != null) {
9572            for (String cid : removeCids) {
9573                if (cid.startsWith(mTempContainerPrefix)) {
9574                    Log.i(TAG, "Destroying stale temporary container " + cid);
9575                    PackageHelper.destroySdDir(cid);
9576                } else {
9577                    Log.w(TAG, "Container " + cid + " is stale");
9578               }
9579           }
9580        }
9581    }
9582
9583   /*
9584     * Utility method to unload a list of specified containers
9585     */
9586    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
9587        // Just unmount all valid containers.
9588        for (AsecInstallArgs arg : cidArgs) {
9589            synchronized (mInstallLock) {
9590                arg.doPostDeleteLI(false);
9591           }
9592       }
9593   }
9594
9595    /*
9596     * Unload packages mounted on external media. This involves deleting package
9597     * data from internal structures, sending broadcasts about diabled packages,
9598     * gc'ing to free up references, unmounting all secure containers
9599     * corresponding to packages on external media, and posting a
9600     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9601     * that we always have to post this message if status has been requested no
9602     * matter what.
9603     */
9604    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9605            final boolean reportStatus) {
9606        if (DEBUG_SD_INSTALL)
9607            Log.i(TAG, "unloading media packages");
9608        ArrayList<String> pkgList = new ArrayList<String>();
9609        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9610        final Set<AsecInstallArgs> keys = processCids.keySet();
9611        for (AsecInstallArgs args : keys) {
9612            String pkgName = args.getPackageName();
9613            if (DEBUG_SD_INSTALL)
9614                Log.i(TAG, "Trying to unload pkg : " + pkgName);
9615            // Delete package internally
9616            PackageRemovedInfo outInfo = new PackageRemovedInfo();
9617            synchronized (mInstallLock) {
9618                boolean res = deletePackageLI(pkgName, null, false,
9619                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
9620                if (res) {
9621                    pkgList.add(pkgName);
9622                } else {
9623                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9624                    failedList.add(args);
9625                }
9626            }
9627        }
9628
9629        // reader
9630        synchronized (mPackages) {
9631            // We didn't update the settings after removing each package;
9632            // write them now for all packages.
9633            mSettings.writeLPr();
9634        }
9635
9636        // We have to absolutely send UPDATED_MEDIA_STATUS only
9637        // after confirming that all the receivers processed the ordered
9638        // broadcast when packages get disabled, force a gc to clean things up.
9639        // and unload all the containers.
9640        if (pkgList.size() > 0) {
9641            sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9642                public void performReceive(Intent intent, int resultCode, String data,
9643                        Bundle extras, boolean ordered, boolean sticky,
9644                        int sendingUser) throws RemoteException {
9645                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9646                            reportStatus ? 1 : 0, 1, keys);
9647                    mHandler.sendMessage(msg);
9648                }
9649            });
9650        } else {
9651            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9652                    keys);
9653            mHandler.sendMessage(msg);
9654        }
9655    }
9656
9657    /** Binder call */
9658    @Override
9659    public void movePackage(final String packageName, final IPackageMoveObserver observer,
9660            final int flags) {
9661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
9662        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
9663        int returnCode = PackageManager.MOVE_SUCCEEDED;
9664        int currFlags = 0;
9665        int newFlags = 0;
9666        // reader
9667        synchronized (mPackages) {
9668            PackageParser.Package pkg = mPackages.get(packageName);
9669            if (pkg == null) {
9670                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9671            } else {
9672                // Disable moving fwd locked apps and system packages
9673                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9674                    Slog.w(TAG, "Cannot move system application");
9675                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9676                } else if (pkg.mOperationPending) {
9677                    Slog.w(TAG, "Attempt to move package which has pending operations");
9678                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9679                } else {
9680                    // Find install location first
9681                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9682                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9683                        Slog.w(TAG, "Ambigous flags specified for move location.");
9684                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9685                    } else {
9686                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9687                                : PackageManager.INSTALL_INTERNAL;
9688                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9689                                : PackageManager.INSTALL_INTERNAL;
9690
9691                        if (newFlags == currFlags) {
9692                            Slog.w(TAG, "No move required. Trying to move to same location");
9693                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9694                        } else {
9695                            if (isForwardLocked(pkg)) {
9696                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9697                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9698                            }
9699                        }
9700                    }
9701                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9702                        pkg.mOperationPending = true;
9703                    }
9704                }
9705            }
9706
9707            /*
9708             * TODO this next block probably shouldn't be inside the lock. We
9709             * can't guarantee these won't change after this is fired off
9710             * anyway.
9711             */
9712            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9713                processPendingMove(new MoveParams(null, observer, 0, packageName,
9714                        null, -1, user),
9715                        returnCode);
9716            } else {
9717                Message msg = mHandler.obtainMessage(INIT_COPY);
9718                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9719                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9720                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9721                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
9722                msg.obj = mp;
9723                mHandler.sendMessage(msg);
9724            }
9725        }
9726    }
9727
9728    private void processPendingMove(final MoveParams mp, final int currentStatus) {
9729        // Queue up an async operation since the package deletion may take a
9730        // little while.
9731        mHandler.post(new Runnable() {
9732            public void run() {
9733                // TODO fix this; this does nothing.
9734                mHandler.removeCallbacks(this);
9735                int returnCode = currentStatus;
9736                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9737                    int uidArr[] = null;
9738                    ArrayList<String> pkgList = null;
9739                    synchronized (mPackages) {
9740                        PackageParser.Package pkg = mPackages.get(mp.packageName);
9741                        if (pkg == null) {
9742                            Slog.w(TAG, " Package " + mp.packageName
9743                                    + " doesn't exist. Aborting move");
9744                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9745                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9746                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
9747                                    + mp.srcArgs.getCodePath() + " to "
9748                                    + pkg.applicationInfo.sourceDir
9749                                    + " Aborting move and returning error");
9750                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9751                        } else {
9752                            uidArr = new int[] {
9753                                pkg.applicationInfo.uid
9754                            };
9755                            pkgList = new ArrayList<String>();
9756                            pkgList.add(mp.packageName);
9757                        }
9758                    }
9759                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9760                        // Send resources unavailable broadcast
9761                        sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
9762                        // Update package code and resource paths
9763                        synchronized (mInstallLock) {
9764                            synchronized (mPackages) {
9765                                PackageParser.Package pkg = mPackages.get(mp.packageName);
9766                                // Recheck for package again.
9767                                if (pkg == null) {
9768                                    Slog.w(TAG, " Package " + mp.packageName
9769                                            + " doesn't exist. Aborting move");
9770                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9771                                } else if (!mp.srcArgs.getCodePath().equals(
9772                                        pkg.applicationInfo.sourceDir)) {
9773                                    Slog.w(TAG, "Package " + mp.packageName
9774                                            + " code path changed from " + mp.srcArgs.getCodePath()
9775                                            + " to " + pkg.applicationInfo.sourceDir
9776                                            + " Aborting move and returning error");
9777                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9778                                } else {
9779                                    final String oldCodePath = pkg.mPath;
9780                                    final String newCodePath = mp.targetArgs.getCodePath();
9781                                    final String newResPath = mp.targetArgs.getResourcePath();
9782                                    final String newNativePath = mp.targetArgs
9783                                            .getNativeLibraryPath();
9784
9785                                    try {
9786                                        final File newNativeDir = new File(newNativePath);
9787
9788                                        final String libParentDir = newNativeDir.getParentFile()
9789                                                .getCanonicalPath();
9790                                        if (newNativeDir.getParentFile().getCanonicalPath()
9791                                                .equals(pkg.applicationInfo.dataDir)) {
9792                                            if (mInstaller
9793                                                    .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
9794                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9795                                            } else {
9796                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
9797                                                        new File(newCodePath), newNativeDir);
9798                                            }
9799                                        } else {
9800                                            if (mInstaller.linkNativeLibraryDirectory(
9801                                                    pkg.applicationInfo.dataDir, newNativePath) < 0) {
9802                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9803                                            }
9804                                        }
9805                                    } catch (IOException e) {
9806                                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9807                                    }
9808
9809
9810                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9811                                        pkg.mPath = newCodePath;
9812                                        // Move dex files around
9813                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
9814                                            // Moving of dex files failed. Set
9815                                            // error code and abort move.
9816                                            pkg.mPath = pkg.mScanPath;
9817                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9818                                        }
9819                                    }
9820
9821                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9822                                        pkg.mScanPath = newCodePath;
9823                                        pkg.applicationInfo.sourceDir = newCodePath;
9824                                        pkg.applicationInfo.publicSourceDir = newResPath;
9825                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
9826                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
9827                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
9828                                        ps.codePathString = ps.codePath.getPath();
9829                                        ps.resourcePath = new File(
9830                                                pkg.applicationInfo.publicSourceDir);
9831                                        ps.resourcePathString = ps.resourcePath.getPath();
9832                                        ps.nativeLibraryPathString = newNativePath;
9833                                        // Set the application info flag
9834                                        // correctly.
9835                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9836                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9837                                        } else {
9838                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9839                                        }
9840                                        ps.setFlags(pkg.applicationInfo.flags);
9841                                        mAppDirs.remove(oldCodePath);
9842                                        mAppDirs.put(newCodePath, pkg);
9843                                        // Persist settings
9844                                        mSettings.writeLPr();
9845                                    }
9846                                }
9847                            }
9848                        }
9849                        // Send resources available broadcast
9850                        sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9851                    }
9852                }
9853                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9854                    // Clean up failed installation
9855                    if (mp.targetArgs != null) {
9856                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
9857                                -1);
9858                    }
9859                } else {
9860                    // Force a gc to clear things up.
9861                    Runtime.getRuntime().gc();
9862                    // Delete older code
9863                    synchronized (mInstallLock) {
9864                        mp.srcArgs.doPostDeleteLI(true);
9865                    }
9866                }
9867
9868                // Allow more operations on this file if we didn't fail because
9869                // an operation was already pending for this package.
9870                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9871                    synchronized (mPackages) {
9872                        PackageParser.Package pkg = mPackages.get(mp.packageName);
9873                        if (pkg != null) {
9874                            pkg.mOperationPending = false;
9875                       }
9876                   }
9877                }
9878
9879                IPackageMoveObserver observer = mp.observer;
9880                if (observer != null) {
9881                    try {
9882                        observer.packageMoved(mp.packageName, returnCode);
9883                    } catch (RemoteException e) {
9884                        Log.i(TAG, "Observer no longer exists.");
9885                    }
9886                }
9887            }
9888        });
9889    }
9890
9891    public boolean setInstallLocation(int loc) {
9892        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
9893                null);
9894        if (getInstallLocation() == loc) {
9895            return true;
9896        }
9897        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
9898                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9899            android.provider.Settings.System.putInt(mContext.getContentResolver(),
9900                    android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9901            return true;
9902        }
9903        return false;
9904   }
9905
9906    public int getInstallLocation() {
9907        return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9908                android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION,
9909                PackageHelper.APP_INSTALL_AUTO);
9910    }
9911
9912    /** Called by UserManagerService */
9913    void cleanUpUserLILPw(int userHandle) {
9914        // Disable all the packages for the user first
9915        Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet();
9916        for (Entry<String, PackageSetting> entry : entries) {
9917            entry.getValue().removeUser(userHandle);
9918        }
9919        if (mDirtyUsers.remove(userHandle));
9920        mSettings.removeUserLPr(userHandle);
9921        if (mInstaller != null) {
9922            // Technically, we shouldn't be doing this with the package lock
9923            // held.  However, this is very rare, and there is already so much
9924            // other disk I/O going on, that we'll let it slide for now.
9925            mInstaller.removeUserDataDirs(userHandle);
9926        }
9927    }
9928
9929    /** Called by UserManagerService */
9930    void createNewUserLILPw(int userHandle, File path) {
9931        if (mInstaller != null) {
9932            path.mkdir();
9933            FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
9934                    | FileUtils.S_IXOTH, -1, -1);
9935            for (PackageSetting ps : mSettings.mPackages.values()) {
9936                // Only system apps are initially installed.
9937                ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
9938                // Need to create a data directory for all apps under this user.
9939                mInstaller.createUserData(ps.name,
9940                        UserHandle.getUid(userHandle, ps.appId), userHandle);
9941            }
9942            mSettings.writePackageRestrictionsLPr(userHandle);
9943        }
9944    }
9945
9946    @Override
9947    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
9948        mContext.enforceCallingOrSelfPermission(
9949                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9950                "Only package verification agents can read the verifier device identity");
9951
9952        synchronized (mPackages) {
9953            return mSettings.getVerifierDeviceIdentityLPw();
9954        }
9955    }
9956
9957    @Override
9958    public void setPermissionEnforced(String permission, boolean enforced) {
9959        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
9960        if (READ_EXTERNAL_STORAGE.equals(permission)) {
9961            synchronized (mPackages) {
9962                if (mSettings.mReadExternalStorageEnforced == null
9963                        || mSettings.mReadExternalStorageEnforced != enforced) {
9964                    mSettings.mReadExternalStorageEnforced = enforced;
9965                    mSettings.writeLPr();
9966
9967                    // kill any non-foreground processes so we restart them and
9968                    // grant/revoke the GID.
9969                    final IActivityManager am = ActivityManagerNative.getDefault();
9970                    if (am != null) {
9971                        final long token = Binder.clearCallingIdentity();
9972                        try {
9973                            am.killProcessesBelowForeground("setPermissionEnforcement");
9974                        } catch (RemoteException e) {
9975                        } finally {
9976                            Binder.restoreCallingIdentity(token);
9977                        }
9978                    }
9979                }
9980            }
9981        } else {
9982            throw new IllegalArgumentException("No selective enforcement for " + permission);
9983        }
9984    }
9985
9986    @Override
9987    public boolean isPermissionEnforced(String permission) {
9988        synchronized (mPackages) {
9989            return isPermissionEnforcedLocked(permission);
9990        }
9991    }
9992
9993    private boolean isPermissionEnforcedLocked(String permission) {
9994        if (READ_EXTERNAL_STORAGE.equals(permission)) {
9995            if (mSettings.mReadExternalStorageEnforced != null) {
9996                return mSettings.mReadExternalStorageEnforced;
9997            } else {
9998                // if user hasn't defined, fall back to secure default
9999                return Secure.getInt(mContext.getContentResolver(),
10000                        Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0;
10001            }
10002        } else {
10003            return true;
10004        }
10005    }
10006
10007    public boolean isStorageLow() {
10008        final long token = Binder.clearCallingIdentity();
10009        try {
10010            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
10011                    .getService(DeviceStorageMonitorService.SERVICE);
10012            return dsm.isMemoryLow();
10013        } finally {
10014            Binder.restoreCallingIdentity(token);
10015        }
10016    }
10017}
10018