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