PackageManagerService.java revision d11f223c535ed9ce628fe5aaf0fd5692dd0cf9e4
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.IntentSender.SendIntentException;
64import android.content.ServiceConnection;
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.ManifestDigest;
78import android.content.pm.PackageCleanItem;
79import android.content.pm.PackageInfo;
80import android.content.pm.PackageInfoLite;
81import android.content.pm.PackageManager;
82import android.content.pm.PackageParser;
83import android.content.pm.PackageParser.ActivityIntentInfo;
84import android.content.pm.PackageStats;
85import android.content.pm.PackageUserState;
86import android.content.pm.ParceledListSlice;
87import android.content.pm.PermissionGroupInfo;
88import android.content.pm.PermissionInfo;
89import android.content.pm.ProviderInfo;
90import android.content.pm.ResolveInfo;
91import android.content.pm.ServiceInfo;
92import android.content.pm.Signature;
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.Environment.UserEnvironment;
104import android.os.FileObserver;
105import android.os.FileUtils;
106import android.os.Handler;
107import android.os.HandlerThread;
108import android.os.IBinder;
109import android.os.Looper;
110import android.os.Message;
111import android.os.Parcel;
112import android.os.ParcelFileDescriptor;
113import android.os.Process;
114import android.os.RemoteException;
115import android.os.SELinux;
116import android.os.ServiceManager;
117import android.os.SystemClock;
118import android.os.SystemProperties;
119import android.os.UserHandle;
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                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
4874                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
4875                                Slog.e(TAG, "Unable to copy native libraries");
4876                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4877                                return null;
4878                            }
4879                        } catch (IOException e) {
4880                            Slog.e(TAG, "Unable to copy native libraries", e);
4881                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4882                            return null;
4883                        }
4884                    }
4885
4886                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
4887                    final int[] userIds = sUserManager.getUserIds();
4888                    synchronized (mInstallLock) {
4889                        for (int userId : userIds) {
4890                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
4891                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
4892                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
4893                                        + ")");
4894                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4895                                return null;
4896                            }
4897                        }
4898                    }
4899                }
4900            } catch (IOException ioe) {
4901                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4902            }
4903        }
4904        pkg.mScanPath = path;
4905
4906        if ((scanMode&SCAN_NO_DEX) == 0) {
4907            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4908                    == DEX_OPT_FAILED) {
4909                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4910                    removeDataDirsLI(pkg.packageName);
4911                }
4912
4913                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4914                return null;
4915            }
4916        }
4917
4918        if (mFactoryTest && pkg.requestedPermissions.contains(
4919                android.Manifest.permission.FACTORY_TEST)) {
4920            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4921        }
4922
4923        ArrayList<PackageParser.Package> clientLibPkgs = null;
4924
4925        // writer
4926        synchronized (mPackages) {
4927            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4928                // Only system apps can add new shared libraries.
4929                if (pkg.libraryNames != null) {
4930                    for (int i=0; i<pkg.libraryNames.size(); i++) {
4931                        String name = pkg.libraryNames.get(i);
4932                        boolean allowed = false;
4933                        if (isUpdatedSystemApp(pkg)) {
4934                            // New library entries can only be added through the
4935                            // system image.  This is important to get rid of a lot
4936                            // of nasty edge cases: for example if we allowed a non-
4937                            // system update of the app to add a library, then uninstalling
4938                            // the update would make the library go away, and assumptions
4939                            // we made such as through app install filtering would now
4940                            // have allowed apps on the device which aren't compatible
4941                            // with it.  Better to just have the restriction here, be
4942                            // conservative, and create many fewer cases that can negatively
4943                            // impact the user experience.
4944                            final PackageSetting sysPs = mSettings
4945                                    .getDisabledSystemPkgLPr(pkg.packageName);
4946                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
4947                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
4948                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
4949                                        allowed = true;
4950                                        allowed = true;
4951                                        break;
4952                                    }
4953                                }
4954                            }
4955                        } else {
4956                            allowed = true;
4957                        }
4958                        if (allowed) {
4959                            if (!mSharedLibraries.containsKey(name)) {
4960                                mSharedLibraries.put(name, new SharedLibraryEntry(null,
4961                                        pkg.packageName));
4962                            } else if (!name.equals(pkg.packageName)) {
4963                                Slog.w(TAG, "Package " + pkg.packageName + " library "
4964                                        + name + " already exists; skipping");
4965                            }
4966                        } else {
4967                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
4968                                    + name + " that is not declared on system image; skipping");
4969                        }
4970                    }
4971                    if ((scanMode&SCAN_BOOTING) == 0) {
4972                        // If we are not booting, we need to update any applications
4973                        // that are clients of our shared library.  If we are booting,
4974                        // this will all be done once the scan is complete.
4975                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
4976                    }
4977                }
4978            }
4979        }
4980
4981        // We also need to dexopt any apps that are dependent on this library.  Note that
4982        // if these fail, we should abort the install since installing the library will
4983        // result in some apps being broken.
4984        if (clientLibPkgs != null) {
4985            if ((scanMode&SCAN_NO_DEX) == 0) {
4986                for (int i=0; i<clientLibPkgs.size(); i++) {
4987                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
4988                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
4989                            == DEX_OPT_FAILED) {
4990                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4991                            removeDataDirsLI(pkg.packageName);
4992                        }
4993
4994                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4995                        return null;
4996                    }
4997                }
4998            }
4999        }
5000
5001        // Request the ActivityManager to kill the process(only for existing packages)
5002        // so that we do not end up in a confused state while the user is still using the older
5003        // version of the application while the new one gets installed.
5004        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5005            // If the package lives in an asec, tell everyone that the container is going
5006            // away so they can clean up any references to its resources (which would prevent
5007            // vold from being able to unmount the asec)
5008            if (isForwardLocked(pkg) || isExternal(pkg)) {
5009                if (DEBUG_INSTALL) {
5010                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5011                }
5012                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5013                final ArrayList<String> pkgList = new ArrayList<String>(1);
5014                pkgList.add(pkg.applicationInfo.packageName);
5015                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5016            }
5017
5018            // Post the request that it be killed now that the going-away broadcast is en route
5019            killApplication(pkg.applicationInfo.packageName,
5020                        pkg.applicationInfo.uid, "update pkg");
5021        }
5022
5023        // Also need to kill any apps that are dependent on the library.
5024        if (clientLibPkgs != null) {
5025            for (int i=0; i<clientLibPkgs.size(); i++) {
5026                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5027                killApplication(clientPkg.applicationInfo.packageName,
5028                        clientPkg.applicationInfo.uid, "update lib");
5029            }
5030        }
5031
5032        // writer
5033        synchronized (mPackages) {
5034            // We don't expect installation to fail beyond this point,
5035            if ((scanMode&SCAN_MONITOR) != 0) {
5036                mAppDirs.put(pkg.mPath, pkg);
5037            }
5038            // Add the new setting to mSettings
5039            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5040            // Add the new setting to mPackages
5041            mPackages.put(pkg.applicationInfo.packageName, pkg);
5042            // Make sure we don't accidentally delete its data.
5043            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5044            while (iter.hasNext()) {
5045                PackageCleanItem item = iter.next();
5046                if (pkgName.equals(item.packageName)) {
5047                    iter.remove();
5048                }
5049            }
5050
5051            // Take care of first install / last update times.
5052            if (currentTime != 0) {
5053                if (pkgSetting.firstInstallTime == 0) {
5054                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5055                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5056                    pkgSetting.lastUpdateTime = currentTime;
5057                }
5058            } else if (pkgSetting.firstInstallTime == 0) {
5059                // We need *something*.  Take time time stamp of the file.
5060                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5061            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5062                if (scanFileTime != pkgSetting.timeStamp) {
5063                    // A package on the system image has changed; consider this
5064                    // to be an update.
5065                    pkgSetting.lastUpdateTime = scanFileTime;
5066                }
5067            }
5068
5069            // Add the package's KeySets to the global KeySetManager
5070            KeySetManager ksm = mSettings.mKeySetManager;
5071            try {
5072                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5073                if (pkg.mKeySetMapping != null) {
5074                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5075                        if (entry.getValue() != null) {
5076                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5077                                entry.getValue(), entry.getKey());
5078                        }
5079                    }
5080                }
5081            } catch (NullPointerException e) {
5082                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5083            } catch (IllegalArgumentException e) {
5084                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5085            }
5086
5087            int N = pkg.providers.size();
5088            StringBuilder r = null;
5089            int i;
5090            for (i=0; i<N; i++) {
5091                PackageParser.Provider p = pkg.providers.get(i);
5092                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5093                        p.info.processName, pkg.applicationInfo.uid);
5094                mProviders.addProvider(p);
5095                p.syncable = p.info.isSyncable;
5096                if (p.info.authority != null) {
5097                    String names[] = p.info.authority.split(";");
5098                    p.info.authority = null;
5099                    for (int j = 0; j < names.length; j++) {
5100                        if (j == 1 && p.syncable) {
5101                            // We only want the first authority for a provider to possibly be
5102                            // syncable, so if we already added this provider using a different
5103                            // authority clear the syncable flag. We copy the provider before
5104                            // changing it because the mProviders object contains a reference
5105                            // to a provider that we don't want to change.
5106                            // Only do this for the second authority since the resulting provider
5107                            // object can be the same for all future authorities for this provider.
5108                            p = new PackageParser.Provider(p);
5109                            p.syncable = false;
5110                        }
5111                        if (!mProvidersByAuthority.containsKey(names[j])) {
5112                            mProvidersByAuthority.put(names[j], p);
5113                            if (p.info.authority == null) {
5114                                p.info.authority = names[j];
5115                            } else {
5116                                p.info.authority = p.info.authority + ";" + names[j];
5117                            }
5118                            if (DEBUG_PACKAGE_SCANNING) {
5119                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5120                                    Log.d(TAG, "Registered content provider: " + names[j]
5121                                            + ", className = " + p.info.name + ", isSyncable = "
5122                                            + p.info.isSyncable);
5123                            }
5124                        } else {
5125                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5126                            Slog.w(TAG, "Skipping provider name " + names[j] +
5127                                    " (in package " + pkg.applicationInfo.packageName +
5128                                    "): name already used by "
5129                                    + ((other != null && other.getComponentName() != null)
5130                                            ? other.getComponentName().getPackageName() : "?"));
5131                        }
5132                    }
5133                }
5134                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5135                    if (r == null) {
5136                        r = new StringBuilder(256);
5137                    } else {
5138                        r.append(' ');
5139                    }
5140                    r.append(p.info.name);
5141                }
5142            }
5143            if (r != null) {
5144                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5145            }
5146
5147            N = pkg.services.size();
5148            r = null;
5149            for (i=0; i<N; i++) {
5150                PackageParser.Service s = pkg.services.get(i);
5151                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5152                        s.info.processName, pkg.applicationInfo.uid);
5153                mServices.addService(s);
5154                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5155                    if (r == null) {
5156                        r = new StringBuilder(256);
5157                    } else {
5158                        r.append(' ');
5159                    }
5160                    r.append(s.info.name);
5161                }
5162            }
5163            if (r != null) {
5164                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5165            }
5166
5167            N = pkg.receivers.size();
5168            r = null;
5169            for (i=0; i<N; i++) {
5170                PackageParser.Activity a = pkg.receivers.get(i);
5171                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5172                        a.info.processName, pkg.applicationInfo.uid);
5173                mReceivers.addActivity(a, "receiver");
5174                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5175                    if (r == null) {
5176                        r = new StringBuilder(256);
5177                    } else {
5178                        r.append(' ');
5179                    }
5180                    r.append(a.info.name);
5181                }
5182            }
5183            if (r != null) {
5184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5185            }
5186
5187            N = pkg.activities.size();
5188            r = null;
5189            for (i=0; i<N; i++) {
5190                PackageParser.Activity a = pkg.activities.get(i);
5191                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5192                        a.info.processName, pkg.applicationInfo.uid);
5193                mActivities.addActivity(a, "activity");
5194                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5195                    if (r == null) {
5196                        r = new StringBuilder(256);
5197                    } else {
5198                        r.append(' ');
5199                    }
5200                    r.append(a.info.name);
5201                }
5202            }
5203            if (r != null) {
5204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5205            }
5206
5207            N = pkg.permissionGroups.size();
5208            r = null;
5209            for (i=0; i<N; i++) {
5210                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5211                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5212                if (cur == null) {
5213                    mPermissionGroups.put(pg.info.name, pg);
5214                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5215                        if (r == null) {
5216                            r = new StringBuilder(256);
5217                        } else {
5218                            r.append(' ');
5219                        }
5220                        r.append(pg.info.name);
5221                    }
5222                } else {
5223                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5224                            + pg.info.packageName + " ignored: original from "
5225                            + cur.info.packageName);
5226                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5227                        if (r == null) {
5228                            r = new StringBuilder(256);
5229                        } else {
5230                            r.append(' ');
5231                        }
5232                        r.append("DUP:");
5233                        r.append(pg.info.name);
5234                    }
5235                }
5236            }
5237            if (r != null) {
5238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5239            }
5240
5241            N = pkg.permissions.size();
5242            r = null;
5243            for (i=0; i<N; i++) {
5244                PackageParser.Permission p = pkg.permissions.get(i);
5245                HashMap<String, BasePermission> permissionMap =
5246                        p.tree ? mSettings.mPermissionTrees
5247                        : mSettings.mPermissions;
5248                p.group = mPermissionGroups.get(p.info.group);
5249                if (p.info.group == null || p.group != null) {
5250                    BasePermission bp = permissionMap.get(p.info.name);
5251                    if (bp == null) {
5252                        bp = new BasePermission(p.info.name, p.info.packageName,
5253                                BasePermission.TYPE_NORMAL);
5254                        permissionMap.put(p.info.name, bp);
5255                    }
5256                    if (bp.perm == null) {
5257                        if (bp.sourcePackage != null
5258                                && !bp.sourcePackage.equals(p.info.packageName)) {
5259                            // If this is a permission that was formerly defined by a non-system
5260                            // app, but is now defined by a system app (following an upgrade),
5261                            // discard the previous declaration and consider the system's to be
5262                            // canonical.
5263                            if (isSystemApp(p.owner)) {
5264                                String msg = "New decl " + p.owner + " of permission  "
5265                                        + p.info.name + " is system";
5266                                reportSettingsProblem(Log.WARN, msg);
5267                                bp.sourcePackage = null;
5268                            }
5269                        }
5270                        if (bp.sourcePackage == null
5271                                || bp.sourcePackage.equals(p.info.packageName)) {
5272                            BasePermission tree = findPermissionTreeLP(p.info.name);
5273                            if (tree == null
5274                                    || tree.sourcePackage.equals(p.info.packageName)) {
5275                                bp.packageSetting = pkgSetting;
5276                                bp.perm = p;
5277                                bp.uid = pkg.applicationInfo.uid;
5278                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5279                                    if (r == null) {
5280                                        r = new StringBuilder(256);
5281                                    } else {
5282                                        r.append(' ');
5283                                    }
5284                                    r.append(p.info.name);
5285                                }
5286                            } else {
5287                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5288                                        + p.info.packageName + " ignored: base tree "
5289                                        + tree.name + " is from package "
5290                                        + tree.sourcePackage);
5291                            }
5292                        } else {
5293                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5294                                    + p.info.packageName + " ignored: original from "
5295                                    + bp.sourcePackage);
5296                        }
5297                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5298                        if (r == null) {
5299                            r = new StringBuilder(256);
5300                        } else {
5301                            r.append(' ');
5302                        }
5303                        r.append("DUP:");
5304                        r.append(p.info.name);
5305                    }
5306                    if (bp.perm == p) {
5307                        bp.protectionLevel = p.info.protectionLevel;
5308                    }
5309                } else {
5310                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5311                            + p.info.packageName + " ignored: no group "
5312                            + p.group);
5313                }
5314            }
5315            if (r != null) {
5316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5317            }
5318
5319            N = pkg.instrumentation.size();
5320            r = null;
5321            for (i=0; i<N; i++) {
5322                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5323                a.info.packageName = pkg.applicationInfo.packageName;
5324                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5325                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5326                a.info.dataDir = pkg.applicationInfo.dataDir;
5327                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5328                mInstrumentation.put(a.getComponentName(), a);
5329                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5330                    if (r == null) {
5331                        r = new StringBuilder(256);
5332                    } else {
5333                        r.append(' ');
5334                    }
5335                    r.append(a.info.name);
5336                }
5337            }
5338            if (r != null) {
5339                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5340            }
5341
5342            if (pkg.protectedBroadcasts != null) {
5343                N = pkg.protectedBroadcasts.size();
5344                for (i=0; i<N; i++) {
5345                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5346                }
5347            }
5348
5349            pkgSetting.setTimeStamp(scanFileTime);
5350
5351            // Create idmap files for pairs of (packages, overlay packages).
5352            // Note: "android", ie framework-res.apk, is handled by native layers.
5353            if (pkg.mOverlayTarget != null) {
5354                // This is an overlay package.
5355                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5356                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5357                        mOverlays.put(pkg.mOverlayTarget,
5358                                new HashMap<String, PackageParser.Package>());
5359                    }
5360                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5361                    map.put(pkg.packageName, pkg);
5362                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5363                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5364                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5365                        return null;
5366                    }
5367                }
5368            } else if (mOverlays.containsKey(pkg.packageName) &&
5369                    !pkg.packageName.equals("android")) {
5370                // This is a regular package, with one or more known overlay packages.
5371                createIdmapsForPackageLI(pkg);
5372            }
5373        }
5374
5375        return pkg;
5376    }
5377
5378    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5379        synchronized (mPackages) {
5380            mResolverReplaced = true;
5381            // Set up information for custom user intent resolution activity.
5382            mResolveActivity.applicationInfo = pkg.applicationInfo;
5383            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5384            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5385            mResolveActivity.processName = null;
5386            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5387            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5388                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5389            mResolveActivity.theme = 0;
5390            mResolveActivity.exported = true;
5391            mResolveActivity.enabled = true;
5392            mResolveInfo.activityInfo = mResolveActivity;
5393            mResolveInfo.priority = 0;
5394            mResolveInfo.preferredOrder = 0;
5395            mResolveInfo.match = 0;
5396            mResolveComponentName = mCustomResolverComponentName;
5397            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5398                    mResolveComponentName);
5399        }
5400    }
5401
5402    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5403            PackageSetting pkgSetting) {
5404        final String apkLibPath = getApkName(pkgSetting.codePathString);
5405        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
5406        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
5407        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
5408    }
5409
5410    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
5411            throws IOException {
5412        if (!nativeLibraryDir.isDirectory()) {
5413            nativeLibraryDir.delete();
5414
5415            if (!nativeLibraryDir.mkdir()) {
5416                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
5417            }
5418
5419            try {
5420                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
5421                        | S_IXOTH);
5422            } catch (ErrnoException e) {
5423                throw new IOException("Cannot chmod native library directory "
5424                        + nativeLibraryDir.getPath(), e);
5425            }
5426        } else if (!SELinux.restorecon(nativeLibraryDir)) {
5427            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
5428        }
5429
5430        /*
5431         * If this is an internal application or our nativeLibraryPath points to
5432         * the app-lib directory, unpack the libraries if necessary.
5433         */
5434        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5435        try {
5436            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5437            if (abi >= 0) {
5438                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
5439                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
5440                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
5441                    return copyRet;
5442                }
5443            }
5444
5445            return abi;
5446        } finally {
5447            handle.close();
5448        }
5449    }
5450
5451    private void killApplication(String pkgName, int appId, String reason) {
5452        // Request the ActivityManager to kill the process(only for existing packages)
5453        // so that we do not end up in a confused state while the user is still using the older
5454        // version of the application while the new one gets installed.
5455        IActivityManager am = ActivityManagerNative.getDefault();
5456        if (am != null) {
5457            try {
5458                am.killApplicationWithAppId(pkgName, appId, reason);
5459            } catch (RemoteException e) {
5460            }
5461        }
5462    }
5463
5464    void removePackageLI(PackageSetting ps, boolean chatty) {
5465        if (DEBUG_INSTALL) {
5466            if (chatty)
5467                Log.d(TAG, "Removing package " + ps.name);
5468        }
5469
5470        // writer
5471        synchronized (mPackages) {
5472            mPackages.remove(ps.name);
5473            if (ps.codePathString != null) {
5474                mAppDirs.remove(ps.codePathString);
5475            }
5476
5477            final PackageParser.Package pkg = ps.pkg;
5478            if (pkg != null) {
5479                cleanPackageDataStructuresLILPw(pkg, chatty);
5480            }
5481        }
5482    }
5483
5484    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
5485        if (DEBUG_INSTALL) {
5486            if (chatty)
5487                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
5488        }
5489
5490        // writer
5491        synchronized (mPackages) {
5492            mPackages.remove(pkg.applicationInfo.packageName);
5493            if (pkg.mPath != null) {
5494                mAppDirs.remove(pkg.mPath);
5495            }
5496            cleanPackageDataStructuresLILPw(pkg, chatty);
5497        }
5498    }
5499
5500    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
5501        int N = pkg.providers.size();
5502        StringBuilder r = null;
5503        int i;
5504        for (i=0; i<N; i++) {
5505            PackageParser.Provider p = pkg.providers.get(i);
5506            mProviders.removeProvider(p);
5507            if (p.info.authority == null) {
5508
5509                /* There was another ContentProvider with this authority when
5510                 * this app was installed so this authority is null,
5511                 * Ignore it as we don't have to unregister the provider.
5512                 */
5513                continue;
5514            }
5515            String names[] = p.info.authority.split(";");
5516            for (int j = 0; j < names.length; j++) {
5517                if (mProvidersByAuthority.get(names[j]) == p) {
5518                    mProvidersByAuthority.remove(names[j]);
5519                    if (DEBUG_REMOVE) {
5520                        if (chatty)
5521                            Log.d(TAG, "Unregistered content provider: " + names[j]
5522                                    + ", className = " + p.info.name + ", isSyncable = "
5523                                    + p.info.isSyncable);
5524                    }
5525                }
5526            }
5527            if (DEBUG_REMOVE && chatty) {
5528                if (r == null) {
5529                    r = new StringBuilder(256);
5530                } else {
5531                    r.append(' ');
5532                }
5533                r.append(p.info.name);
5534            }
5535        }
5536        if (r != null) {
5537            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
5538        }
5539
5540        N = pkg.services.size();
5541        r = null;
5542        for (i=0; i<N; i++) {
5543            PackageParser.Service s = pkg.services.get(i);
5544            mServices.removeService(s);
5545            if (chatty) {
5546                if (r == null) {
5547                    r = new StringBuilder(256);
5548                } else {
5549                    r.append(' ');
5550                }
5551                r.append(s.info.name);
5552            }
5553        }
5554        if (r != null) {
5555            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
5556        }
5557
5558        N = pkg.receivers.size();
5559        r = null;
5560        for (i=0; i<N; i++) {
5561            PackageParser.Activity a = pkg.receivers.get(i);
5562            mReceivers.removeActivity(a, "receiver");
5563            if (DEBUG_REMOVE && chatty) {
5564                if (r == null) {
5565                    r = new StringBuilder(256);
5566                } else {
5567                    r.append(' ');
5568                }
5569                r.append(a.info.name);
5570            }
5571        }
5572        if (r != null) {
5573            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
5574        }
5575
5576        N = pkg.activities.size();
5577        r = null;
5578        for (i=0; i<N; i++) {
5579            PackageParser.Activity a = pkg.activities.get(i);
5580            mActivities.removeActivity(a, "activity");
5581            if (DEBUG_REMOVE && chatty) {
5582                if (r == null) {
5583                    r = new StringBuilder(256);
5584                } else {
5585                    r.append(' ');
5586                }
5587                r.append(a.info.name);
5588            }
5589        }
5590        if (r != null) {
5591            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
5592        }
5593
5594        N = pkg.permissions.size();
5595        r = null;
5596        for (i=0; i<N; i++) {
5597            PackageParser.Permission p = pkg.permissions.get(i);
5598            BasePermission bp = mSettings.mPermissions.get(p.info.name);
5599            if (bp == null) {
5600                bp = mSettings.mPermissionTrees.get(p.info.name);
5601            }
5602            if (bp != null && bp.perm == p) {
5603                bp.perm = null;
5604                if (DEBUG_REMOVE && chatty) {
5605                    if (r == null) {
5606                        r = new StringBuilder(256);
5607                    } else {
5608                        r.append(' ');
5609                    }
5610                    r.append(p.info.name);
5611                }
5612            }
5613        }
5614        if (r != null) {
5615            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
5616        }
5617
5618        N = pkg.instrumentation.size();
5619        r = null;
5620        for (i=0; i<N; i++) {
5621            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5622            mInstrumentation.remove(a.getComponentName());
5623            if (DEBUG_REMOVE && chatty) {
5624                if (r == null) {
5625                    r = new StringBuilder(256);
5626                } else {
5627                    r.append(' ');
5628                }
5629                r.append(a.info.name);
5630            }
5631        }
5632        if (r != null) {
5633            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
5634        }
5635
5636        r = null;
5637        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5638            // Only system apps can hold shared libraries.
5639            if (pkg.libraryNames != null) {
5640                for (i=0; i<pkg.libraryNames.size(); i++) {
5641                    String name = pkg.libraryNames.get(i);
5642                    SharedLibraryEntry cur = mSharedLibraries.get(name);
5643                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
5644                        mSharedLibraries.remove(name);
5645                        if (DEBUG_REMOVE && chatty) {
5646                            if (r == null) {
5647                                r = new StringBuilder(256);
5648                            } else {
5649                                r.append(' ');
5650                            }
5651                            r.append(name);
5652                        }
5653                    }
5654                }
5655            }
5656        }
5657        if (r != null) {
5658            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
5659        }
5660    }
5661
5662    private static final boolean isPackageFilename(String name) {
5663        return name != null && name.endsWith(".apk");
5664    }
5665
5666    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
5667        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
5668            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
5669                return true;
5670            }
5671        }
5672        return false;
5673    }
5674
5675    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
5676    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
5677    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
5678
5679    private void updatePermissionsLPw(String changingPkg,
5680            PackageParser.Package pkgInfo, int flags) {
5681        // Make sure there are no dangling permission trees.
5682        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
5683        while (it.hasNext()) {
5684            final BasePermission bp = it.next();
5685            if (bp.packageSetting == null) {
5686                // We may not yet have parsed the package, so just see if
5687                // we still know about its settings.
5688                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5689            }
5690            if (bp.packageSetting == null) {
5691                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
5692                        + " from package " + bp.sourcePackage);
5693                it.remove();
5694            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5695                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5696                    Slog.i(TAG, "Removing old permission tree: " + bp.name
5697                            + " from package " + bp.sourcePackage);
5698                    flags |= UPDATE_PERMISSIONS_ALL;
5699                    it.remove();
5700                }
5701            }
5702        }
5703
5704        // Make sure all dynamic permissions have been assigned to a package,
5705        // and make sure there are no dangling permissions.
5706        it = mSettings.mPermissions.values().iterator();
5707        while (it.hasNext()) {
5708            final BasePermission bp = it.next();
5709            if (bp.type == BasePermission.TYPE_DYNAMIC) {
5710                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
5711                        + bp.name + " pkg=" + bp.sourcePackage
5712                        + " info=" + bp.pendingInfo);
5713                if (bp.packageSetting == null && bp.pendingInfo != null) {
5714                    final BasePermission tree = findPermissionTreeLP(bp.name);
5715                    if (tree != null && tree.perm != null) {
5716                        bp.packageSetting = tree.packageSetting;
5717                        bp.perm = new PackageParser.Permission(tree.perm.owner,
5718                                new PermissionInfo(bp.pendingInfo));
5719                        bp.perm.info.packageName = tree.perm.info.packageName;
5720                        bp.perm.info.name = bp.name;
5721                        bp.uid = tree.uid;
5722                    }
5723                }
5724            }
5725            if (bp.packageSetting == null) {
5726                // We may not yet have parsed the package, so just see if
5727                // we still know about its settings.
5728                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
5729            }
5730            if (bp.packageSetting == null) {
5731                Slog.w(TAG, "Removing dangling permission: " + bp.name
5732                        + " from package " + bp.sourcePackage);
5733                it.remove();
5734            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
5735                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
5736                    Slog.i(TAG, "Removing old permission: " + bp.name
5737                            + " from package " + bp.sourcePackage);
5738                    flags |= UPDATE_PERMISSIONS_ALL;
5739                    it.remove();
5740                }
5741            }
5742        }
5743
5744        // Now update the permissions for all packages, in particular
5745        // replace the granted permissions of the system packages.
5746        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
5747            for (PackageParser.Package pkg : mPackages.values()) {
5748                if (pkg != pkgInfo) {
5749                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
5750                }
5751            }
5752        }
5753
5754        if (pkgInfo != null) {
5755            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
5756        }
5757    }
5758
5759    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
5760        final PackageSetting ps = (PackageSetting) pkg.mExtras;
5761        if (ps == null) {
5762            return;
5763        }
5764        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
5765        HashSet<String> origPermissions = gp.grantedPermissions;
5766        boolean changedPermission = false;
5767
5768        if (replace) {
5769            ps.permissionsFixed = false;
5770            if (gp == ps) {
5771                origPermissions = new HashSet<String>(gp.grantedPermissions);
5772                gp.grantedPermissions.clear();
5773                gp.gids = mGlobalGids;
5774            }
5775        }
5776
5777        if (gp.gids == null) {
5778            gp.gids = mGlobalGids;
5779        }
5780
5781        final int N = pkg.requestedPermissions.size();
5782        for (int i=0; i<N; i++) {
5783            final String name = pkg.requestedPermissions.get(i);
5784            final boolean required = pkg.requestedPermissionsRequired.get(i);
5785            final BasePermission bp = mSettings.mPermissions.get(name);
5786            if (DEBUG_INSTALL) {
5787                if (gp != ps) {
5788                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
5789                }
5790            }
5791
5792            if (bp == null || bp.packageSetting == null) {
5793                Slog.w(TAG, "Unknown permission " + name
5794                        + " in package " + pkg.packageName);
5795                continue;
5796            }
5797
5798            final String perm = bp.name;
5799            boolean allowed;
5800            boolean allowedSig = false;
5801            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
5802            if (level == PermissionInfo.PROTECTION_NORMAL
5803                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
5804                // We grant a normal or dangerous permission if any of the following
5805                // are true:
5806                // 1) The permission is required
5807                // 2) The permission is optional, but was granted in the past
5808                // 3) The permission is optional, but was requested by an
5809                //    app in /system (not /data)
5810                //
5811                // Otherwise, reject the permission.
5812                allowed = (required || origPermissions.contains(perm)
5813                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
5814            } else if (bp.packageSetting == null) {
5815                // This permission is invalid; skip it.
5816                allowed = false;
5817            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
5818                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
5819                if (allowed) {
5820                    allowedSig = true;
5821                }
5822            } else {
5823                allowed = false;
5824            }
5825            if (DEBUG_INSTALL) {
5826                if (gp != ps) {
5827                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
5828                }
5829            }
5830            if (allowed) {
5831                if (!isSystemApp(ps) && ps.permissionsFixed) {
5832                    // If this is an existing, non-system package, then
5833                    // we can't add any new permissions to it.
5834                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
5835                        // Except...  if this is a permission that was added
5836                        // to the platform (note: need to only do this when
5837                        // updating the platform).
5838                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
5839                    }
5840                }
5841                if (allowed) {
5842                    if (!gp.grantedPermissions.contains(perm)) {
5843                        changedPermission = true;
5844                        gp.grantedPermissions.add(perm);
5845                        gp.gids = appendInts(gp.gids, bp.gids);
5846                    } else if (!ps.haveGids) {
5847                        gp.gids = appendInts(gp.gids, bp.gids);
5848                    }
5849                } else {
5850                    Slog.w(TAG, "Not granting permission " + perm
5851                            + " to package " + pkg.packageName
5852                            + " because it was previously installed without");
5853                }
5854            } else {
5855                if (gp.grantedPermissions.remove(perm)) {
5856                    changedPermission = true;
5857                    gp.gids = removeInts(gp.gids, bp.gids);
5858                    Slog.i(TAG, "Un-granting permission " + perm
5859                            + " from package " + pkg.packageName
5860                            + " (protectionLevel=" + bp.protectionLevel
5861                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5862                            + ")");
5863                } else {
5864                    Slog.w(TAG, "Not granting permission " + perm
5865                            + " to package " + pkg.packageName
5866                            + " (protectionLevel=" + bp.protectionLevel
5867                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
5868                            + ")");
5869                }
5870            }
5871        }
5872
5873        if ((changedPermission || replace) && !ps.permissionsFixed &&
5874                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
5875            // This is the first that we have heard about this package, so the
5876            // permissions we have now selected are fixed until explicitly
5877            // changed.
5878            ps.permissionsFixed = true;
5879        }
5880        ps.haveGids = true;
5881    }
5882
5883    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
5884        boolean allowed = false;
5885        final int NP = PackageParser.NEW_PERMISSIONS.length;
5886        for (int ip=0; ip<NP; ip++) {
5887            final PackageParser.NewPermissionInfo npi
5888                    = PackageParser.NEW_PERMISSIONS[ip];
5889            if (npi.name.equals(perm)
5890                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
5891                allowed = true;
5892                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
5893                        + pkg.packageName);
5894                break;
5895            }
5896        }
5897        return allowed;
5898    }
5899
5900    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
5901                                          BasePermission bp, HashSet<String> origPermissions) {
5902        boolean allowed;
5903        allowed = (compareSignatures(
5904                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
5905                        == PackageManager.SIGNATURE_MATCH)
5906                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
5907                        == PackageManager.SIGNATURE_MATCH);
5908        if (!allowed && (bp.protectionLevel
5909                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
5910            if (isSystemApp(pkg)) {
5911                // For updated system applications, a system permission
5912                // is granted only if it had been defined by the original application.
5913                if (isUpdatedSystemApp(pkg)) {
5914                    final PackageSetting sysPs = mSettings
5915                            .getDisabledSystemPkgLPr(pkg.packageName);
5916                    final GrantedPermissions origGp = sysPs.sharedUser != null
5917                            ? sysPs.sharedUser : sysPs;
5918
5919                    if (origGp.grantedPermissions.contains(perm)) {
5920                        // If the original was granted this permission, we take
5921                        // that grant decision as read and propagate it to the
5922                        // update.
5923                        allowed = true;
5924                    } else {
5925                        // The system apk may have been updated with an older
5926                        // version of the one on the data partition, but which
5927                        // granted a new system permission that it didn't have
5928                        // before.  In this case we do want to allow the app to
5929                        // now get the new permission if the ancestral apk is
5930                        // privileged to get it.
5931                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
5932                            for (int j=0;
5933                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
5934                                if (perm.equals(
5935                                        sysPs.pkg.requestedPermissions.get(j))) {
5936                                    allowed = true;
5937                                    break;
5938                                }
5939                            }
5940                        }
5941                    }
5942                } else {
5943                    allowed = isPrivilegedApp(pkg);
5944                }
5945            }
5946        }
5947        if (!allowed && (bp.protectionLevel
5948                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
5949            // For development permissions, a development permission
5950            // is granted only if it was already granted.
5951            allowed = origPermissions.contains(perm);
5952        }
5953        return allowed;
5954    }
5955
5956    final class ActivityIntentResolver
5957            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
5958        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5959                boolean defaultOnly, int userId) {
5960            if (!sUserManager.exists(userId)) return null;
5961            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5962            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5963        }
5964
5965        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5966                int userId) {
5967            if (!sUserManager.exists(userId)) return null;
5968            mFlags = flags;
5969            return super.queryIntent(intent, resolvedType,
5970                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5971        }
5972
5973        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5974                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
5975            if (!sUserManager.exists(userId)) return null;
5976            if (packageActivities == null) {
5977                return null;
5978            }
5979            mFlags = flags;
5980            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5981            final int N = packageActivities.size();
5982            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
5983                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
5984
5985            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
5986            for (int i = 0; i < N; ++i) {
5987                intentFilters = packageActivities.get(i).intents;
5988                if (intentFilters != null && intentFilters.size() > 0) {
5989                    PackageParser.ActivityIntentInfo[] array =
5990                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
5991                    intentFilters.toArray(array);
5992                    listCut.add(array);
5993                }
5994            }
5995            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5996        }
5997
5998        public final void addActivity(PackageParser.Activity a, String type) {
5999            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6000            mActivities.put(a.getComponentName(), a);
6001            if (DEBUG_SHOW_INFO)
6002                Log.v(
6003                TAG, "  " + type + " " +
6004                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6005            if (DEBUG_SHOW_INFO)
6006                Log.v(TAG, "    Class=" + a.info.name);
6007            final int NI = a.intents.size();
6008            for (int j=0; j<NI; j++) {
6009                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6010                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6011                    intent.setPriority(0);
6012                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6013                            + a.className + " with priority > 0, forcing to 0");
6014                }
6015                if (DEBUG_SHOW_INFO) {
6016                    Log.v(TAG, "    IntentFilter:");
6017                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6018                }
6019                if (!intent.debugCheck()) {
6020                    Log.w(TAG, "==> For Activity " + a.info.name);
6021                }
6022                addFilter(intent);
6023            }
6024        }
6025
6026        public final void removeActivity(PackageParser.Activity a, String type) {
6027            mActivities.remove(a.getComponentName());
6028            if (DEBUG_SHOW_INFO) {
6029                Log.v(TAG, "  " + type + " "
6030                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6031                                : a.info.name) + ":");
6032                Log.v(TAG, "    Class=" + a.info.name);
6033            }
6034            final int NI = a.intents.size();
6035            for (int j=0; j<NI; j++) {
6036                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6037                if (DEBUG_SHOW_INFO) {
6038                    Log.v(TAG, "    IntentFilter:");
6039                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6040                }
6041                removeFilter(intent);
6042            }
6043        }
6044
6045        @Override
6046        protected boolean allowFilterResult(
6047                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6048            ActivityInfo filterAi = filter.activity.info;
6049            for (int i=dest.size()-1; i>=0; i--) {
6050                ActivityInfo destAi = dest.get(i).activityInfo;
6051                if (destAi.name == filterAi.name
6052                        && destAi.packageName == filterAi.packageName) {
6053                    return false;
6054                }
6055            }
6056            return true;
6057        }
6058
6059        @Override
6060        protected ActivityIntentInfo[] newArray(int size) {
6061            return new ActivityIntentInfo[size];
6062        }
6063
6064        @Override
6065        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6066            if (!sUserManager.exists(userId)) return true;
6067            PackageParser.Package p = filter.activity.owner;
6068            if (p != null) {
6069                PackageSetting ps = (PackageSetting)p.mExtras;
6070                if (ps != null) {
6071                    // System apps are never considered stopped for purposes of
6072                    // filtering, because there may be no way for the user to
6073                    // actually re-launch them.
6074                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6075                            && ps.getStopped(userId);
6076                }
6077            }
6078            return false;
6079        }
6080
6081        @Override
6082        protected boolean isPackageForFilter(String packageName,
6083                PackageParser.ActivityIntentInfo info) {
6084            return packageName.equals(info.activity.owner.packageName);
6085        }
6086
6087        @Override
6088        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6089                int match, int userId) {
6090            if (!sUserManager.exists(userId)) return null;
6091            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6092                return null;
6093            }
6094            final PackageParser.Activity activity = info.activity;
6095            if (mSafeMode && (activity.info.applicationInfo.flags
6096                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6097                return null;
6098            }
6099            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6100            if (ps == null) {
6101                return null;
6102            }
6103            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6104                    ps.readUserState(userId), userId);
6105            if (ai == null) {
6106                return null;
6107            }
6108            final ResolveInfo res = new ResolveInfo();
6109            res.activityInfo = ai;
6110            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6111                res.filter = info;
6112            }
6113            res.priority = info.getPriority();
6114            res.preferredOrder = activity.owner.mPreferredOrder;
6115            //System.out.println("Result: " + res.activityInfo.className +
6116            //                   " = " + res.priority);
6117            res.match = match;
6118            res.isDefault = info.hasDefault;
6119            res.labelRes = info.labelRes;
6120            res.nonLocalizedLabel = info.nonLocalizedLabel;
6121            res.icon = info.icon;
6122            res.system = isSystemApp(res.activityInfo.applicationInfo);
6123            return res;
6124        }
6125
6126        @Override
6127        protected void sortResults(List<ResolveInfo> results) {
6128            Collections.sort(results, mResolvePrioritySorter);
6129        }
6130
6131        @Override
6132        protected void dumpFilter(PrintWriter out, String prefix,
6133                PackageParser.ActivityIntentInfo filter) {
6134            out.print(prefix); out.print(
6135                    Integer.toHexString(System.identityHashCode(filter.activity)));
6136                    out.print(' ');
6137                    filter.activity.printComponentShortName(out);
6138                    out.print(" filter ");
6139                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6140        }
6141
6142//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6143//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6144//            final List<ResolveInfo> retList = Lists.newArrayList();
6145//            while (i.hasNext()) {
6146//                final ResolveInfo resolveInfo = i.next();
6147//                if (isEnabledLP(resolveInfo.activityInfo)) {
6148//                    retList.add(resolveInfo);
6149//                }
6150//            }
6151//            return retList;
6152//        }
6153
6154        // Keys are String (activity class name), values are Activity.
6155        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6156                = new HashMap<ComponentName, PackageParser.Activity>();
6157        private int mFlags;
6158    }
6159
6160    private final class ServiceIntentResolver
6161            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6162        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6163                boolean defaultOnly, int userId) {
6164            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6165            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6166        }
6167
6168        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6169                int userId) {
6170            if (!sUserManager.exists(userId)) return null;
6171            mFlags = flags;
6172            return super.queryIntent(intent, resolvedType,
6173                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6174        }
6175
6176        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6177                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6178            if (!sUserManager.exists(userId)) return null;
6179            if (packageServices == null) {
6180                return null;
6181            }
6182            mFlags = flags;
6183            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6184            final int N = packageServices.size();
6185            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6186                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6187
6188            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6189            for (int i = 0; i < N; ++i) {
6190                intentFilters = packageServices.get(i).intents;
6191                if (intentFilters != null && intentFilters.size() > 0) {
6192                    PackageParser.ServiceIntentInfo[] array =
6193                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6194                    intentFilters.toArray(array);
6195                    listCut.add(array);
6196                }
6197            }
6198            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6199        }
6200
6201        public final void addService(PackageParser.Service s) {
6202            mServices.put(s.getComponentName(), s);
6203            if (DEBUG_SHOW_INFO) {
6204                Log.v(TAG, "  "
6205                        + (s.info.nonLocalizedLabel != null
6206                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6207                Log.v(TAG, "    Class=" + s.info.name);
6208            }
6209            final int NI = s.intents.size();
6210            int j;
6211            for (j=0; j<NI; j++) {
6212                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6213                if (DEBUG_SHOW_INFO) {
6214                    Log.v(TAG, "    IntentFilter:");
6215                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6216                }
6217                if (!intent.debugCheck()) {
6218                    Log.w(TAG, "==> For Service " + s.info.name);
6219                }
6220                addFilter(intent);
6221            }
6222        }
6223
6224        public final void removeService(PackageParser.Service s) {
6225            mServices.remove(s.getComponentName());
6226            if (DEBUG_SHOW_INFO) {
6227                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6228                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6229                Log.v(TAG, "    Class=" + s.info.name);
6230            }
6231            final int NI = s.intents.size();
6232            int j;
6233            for (j=0; j<NI; j++) {
6234                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6235                if (DEBUG_SHOW_INFO) {
6236                    Log.v(TAG, "    IntentFilter:");
6237                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6238                }
6239                removeFilter(intent);
6240            }
6241        }
6242
6243        @Override
6244        protected boolean allowFilterResult(
6245                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6246            ServiceInfo filterSi = filter.service.info;
6247            for (int i=dest.size()-1; i>=0; i--) {
6248                ServiceInfo destAi = dest.get(i).serviceInfo;
6249                if (destAi.name == filterSi.name
6250                        && destAi.packageName == filterSi.packageName) {
6251                    return false;
6252                }
6253            }
6254            return true;
6255        }
6256
6257        @Override
6258        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6259            return new PackageParser.ServiceIntentInfo[size];
6260        }
6261
6262        @Override
6263        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6264            if (!sUserManager.exists(userId)) return true;
6265            PackageParser.Package p = filter.service.owner;
6266            if (p != null) {
6267                PackageSetting ps = (PackageSetting)p.mExtras;
6268                if (ps != null) {
6269                    // System apps are never considered stopped for purposes of
6270                    // filtering, because there may be no way for the user to
6271                    // actually re-launch them.
6272                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6273                            && ps.getStopped(userId);
6274                }
6275            }
6276            return false;
6277        }
6278
6279        @Override
6280        protected boolean isPackageForFilter(String packageName,
6281                PackageParser.ServiceIntentInfo info) {
6282            return packageName.equals(info.service.owner.packageName);
6283        }
6284
6285        @Override
6286        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6287                int match, int userId) {
6288            if (!sUserManager.exists(userId)) return null;
6289            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6290            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6291                return null;
6292            }
6293            final PackageParser.Service service = info.service;
6294            if (mSafeMode && (service.info.applicationInfo.flags
6295                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6296                return null;
6297            }
6298            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6299            if (ps == null) {
6300                return null;
6301            }
6302            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6303                    ps.readUserState(userId), userId);
6304            if (si == null) {
6305                return null;
6306            }
6307            final ResolveInfo res = new ResolveInfo();
6308            res.serviceInfo = si;
6309            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6310                res.filter = filter;
6311            }
6312            res.priority = info.getPriority();
6313            res.preferredOrder = service.owner.mPreferredOrder;
6314            //System.out.println("Result: " + res.activityInfo.className +
6315            //                   " = " + res.priority);
6316            res.match = match;
6317            res.isDefault = info.hasDefault;
6318            res.labelRes = info.labelRes;
6319            res.nonLocalizedLabel = info.nonLocalizedLabel;
6320            res.icon = info.icon;
6321            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6322            return res;
6323        }
6324
6325        @Override
6326        protected void sortResults(List<ResolveInfo> results) {
6327            Collections.sort(results, mResolvePrioritySorter);
6328        }
6329
6330        @Override
6331        protected void dumpFilter(PrintWriter out, String prefix,
6332                PackageParser.ServiceIntentInfo filter) {
6333            out.print(prefix); out.print(
6334                    Integer.toHexString(System.identityHashCode(filter.service)));
6335                    out.print(' ');
6336                    filter.service.printComponentShortName(out);
6337                    out.print(" filter ");
6338                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6339        }
6340
6341//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6342//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6343//            final List<ResolveInfo> retList = Lists.newArrayList();
6344//            while (i.hasNext()) {
6345//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6346//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6347//                    retList.add(resolveInfo);
6348//                }
6349//            }
6350//            return retList;
6351//        }
6352
6353        // Keys are String (activity class name), values are Activity.
6354        private final HashMap<ComponentName, PackageParser.Service> mServices
6355                = new HashMap<ComponentName, PackageParser.Service>();
6356        private int mFlags;
6357    };
6358
6359    private final class ProviderIntentResolver
6360            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6361        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6362                boolean defaultOnly, int userId) {
6363            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6364            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6365        }
6366
6367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6368                int userId) {
6369            if (!sUserManager.exists(userId))
6370                return null;
6371            mFlags = flags;
6372            return super.queryIntent(intent, resolvedType,
6373                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6374        }
6375
6376        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6377                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6378            if (!sUserManager.exists(userId))
6379                return null;
6380            if (packageProviders == null) {
6381                return null;
6382            }
6383            mFlags = flags;
6384            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
6385            final int N = packageProviders.size();
6386            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
6387                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
6388
6389            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
6390            for (int i = 0; i < N; ++i) {
6391                intentFilters = packageProviders.get(i).intents;
6392                if (intentFilters != null && intentFilters.size() > 0) {
6393                    PackageParser.ProviderIntentInfo[] array =
6394                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
6395                    intentFilters.toArray(array);
6396                    listCut.add(array);
6397                }
6398            }
6399            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6400        }
6401
6402        public final void addProvider(PackageParser.Provider p) {
6403            if (mProviders.containsKey(p.getComponentName())) {
6404                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
6405                return;
6406            }
6407
6408            mProviders.put(p.getComponentName(), p);
6409            if (DEBUG_SHOW_INFO) {
6410                Log.v(TAG, "  "
6411                        + (p.info.nonLocalizedLabel != null
6412                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
6413                Log.v(TAG, "    Class=" + p.info.name);
6414            }
6415            final int NI = p.intents.size();
6416            int j;
6417            for (j = 0; j < NI; j++) {
6418                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6419                if (DEBUG_SHOW_INFO) {
6420                    Log.v(TAG, "    IntentFilter:");
6421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6422                }
6423                if (!intent.debugCheck()) {
6424                    Log.w(TAG, "==> For Provider " + p.info.name);
6425                }
6426                addFilter(intent);
6427            }
6428        }
6429
6430        public final void removeProvider(PackageParser.Provider p) {
6431            mProviders.remove(p.getComponentName());
6432            if (DEBUG_SHOW_INFO) {
6433                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
6434                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
6435                Log.v(TAG, "    Class=" + p.info.name);
6436            }
6437            final int NI = p.intents.size();
6438            int j;
6439            for (j = 0; j < NI; j++) {
6440                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
6441                if (DEBUG_SHOW_INFO) {
6442                    Log.v(TAG, "    IntentFilter:");
6443                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6444                }
6445                removeFilter(intent);
6446            }
6447        }
6448
6449        @Override
6450        protected boolean allowFilterResult(
6451                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
6452            ProviderInfo filterPi = filter.provider.info;
6453            for (int i = dest.size() - 1; i >= 0; i--) {
6454                ProviderInfo destPi = dest.get(i).providerInfo;
6455                if (destPi.name == filterPi.name
6456                        && destPi.packageName == filterPi.packageName) {
6457                    return false;
6458                }
6459            }
6460            return true;
6461        }
6462
6463        @Override
6464        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
6465            return new PackageParser.ProviderIntentInfo[size];
6466        }
6467
6468        @Override
6469        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
6470            if (!sUserManager.exists(userId))
6471                return true;
6472            PackageParser.Package p = filter.provider.owner;
6473            if (p != null) {
6474                PackageSetting ps = (PackageSetting) p.mExtras;
6475                if (ps != null) {
6476                    // System apps are never considered stopped for purposes of
6477                    // filtering, because there may be no way for the user to
6478                    // actually re-launch them.
6479                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6480                            && ps.getStopped(userId);
6481                }
6482            }
6483            return false;
6484        }
6485
6486        @Override
6487        protected boolean isPackageForFilter(String packageName,
6488                PackageParser.ProviderIntentInfo info) {
6489            return packageName.equals(info.provider.owner.packageName);
6490        }
6491
6492        @Override
6493        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
6494                int match, int userId) {
6495            if (!sUserManager.exists(userId))
6496                return null;
6497            final PackageParser.ProviderIntentInfo info = filter;
6498            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
6499                return null;
6500            }
6501            final PackageParser.Provider provider = info.provider;
6502            if (mSafeMode && (provider.info.applicationInfo.flags
6503                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
6504                return null;
6505            }
6506            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
6507            if (ps == null) {
6508                return null;
6509            }
6510            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
6511                    ps.readUserState(userId), userId);
6512            if (pi == null) {
6513                return null;
6514            }
6515            final ResolveInfo res = new ResolveInfo();
6516            res.providerInfo = pi;
6517            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
6518                res.filter = filter;
6519            }
6520            res.priority = info.getPriority();
6521            res.preferredOrder = provider.owner.mPreferredOrder;
6522            res.match = match;
6523            res.isDefault = info.hasDefault;
6524            res.labelRes = info.labelRes;
6525            res.nonLocalizedLabel = info.nonLocalizedLabel;
6526            res.icon = info.icon;
6527            res.system = isSystemApp(res.providerInfo.applicationInfo);
6528            return res;
6529        }
6530
6531        @Override
6532        protected void sortResults(List<ResolveInfo> results) {
6533            Collections.sort(results, mResolvePrioritySorter);
6534        }
6535
6536        @Override
6537        protected void dumpFilter(PrintWriter out, String prefix,
6538                PackageParser.ProviderIntentInfo filter) {
6539            out.print(prefix);
6540            out.print(
6541                    Integer.toHexString(System.identityHashCode(filter.provider)));
6542            out.print(' ');
6543            filter.provider.printComponentShortName(out);
6544            out.print(" filter ");
6545            out.println(Integer.toHexString(System.identityHashCode(filter)));
6546        }
6547
6548        private final HashMap<ComponentName, PackageParser.Provider> mProviders
6549                = new HashMap<ComponentName, PackageParser.Provider>();
6550        private int mFlags;
6551    };
6552
6553    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
6554            new Comparator<ResolveInfo>() {
6555        public int compare(ResolveInfo r1, ResolveInfo r2) {
6556            int v1 = r1.priority;
6557            int v2 = r2.priority;
6558            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
6559            if (v1 != v2) {
6560                return (v1 > v2) ? -1 : 1;
6561            }
6562            v1 = r1.preferredOrder;
6563            v2 = r2.preferredOrder;
6564            if (v1 != v2) {
6565                return (v1 > v2) ? -1 : 1;
6566            }
6567            if (r1.isDefault != r2.isDefault) {
6568                return r1.isDefault ? -1 : 1;
6569            }
6570            v1 = r1.match;
6571            v2 = r2.match;
6572            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
6573            if (v1 != v2) {
6574                return (v1 > v2) ? -1 : 1;
6575            }
6576            if (r1.system != r2.system) {
6577                return r1.system ? -1 : 1;
6578            }
6579            return 0;
6580        }
6581    };
6582
6583    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
6584            new Comparator<ProviderInfo>() {
6585        public int compare(ProviderInfo p1, ProviderInfo p2) {
6586            final int v1 = p1.initOrder;
6587            final int v2 = p2.initOrder;
6588            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
6589        }
6590    };
6591
6592    static final void sendPackageBroadcast(String action, String pkg,
6593            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
6594            int[] userIds) {
6595        IActivityManager am = ActivityManagerNative.getDefault();
6596        if (am != null) {
6597            try {
6598                if (userIds == null) {
6599                    userIds = am.getRunningUserIds();
6600                }
6601                for (int id : userIds) {
6602                    final Intent intent = new Intent(action,
6603                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
6604                    if (extras != null) {
6605                        intent.putExtras(extras);
6606                    }
6607                    if (targetPkg != null) {
6608                        intent.setPackage(targetPkg);
6609                    }
6610                    // Modify the UID when posting to other users
6611                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
6612                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
6613                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
6614                        intent.putExtra(Intent.EXTRA_UID, uid);
6615                    }
6616                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
6617                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6618                    if (DEBUG_BROADCASTS) {
6619                        RuntimeException here = new RuntimeException("here");
6620                        here.fillInStackTrace();
6621                        Slog.d(TAG, "Sending to user " + id + ": "
6622                                + intent.toShortString(false, true, false, false)
6623                                + " " + intent.getExtras(), here);
6624                    }
6625                    am.broadcastIntent(null, intent, null, finishedReceiver,
6626                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
6627                            finishedReceiver != null, false, id);
6628                }
6629            } catch (RemoteException ex) {
6630            }
6631        }
6632    }
6633
6634    /**
6635     * Check if the external storage media is available. This is true if there
6636     * is a mounted external storage medium or if the external storage is
6637     * emulated.
6638     */
6639    private boolean isExternalMediaAvailable() {
6640        return mMediaMounted || Environment.isExternalStorageEmulated();
6641    }
6642
6643    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
6644        // writer
6645        synchronized (mPackages) {
6646            if (!isExternalMediaAvailable()) {
6647                // If the external storage is no longer mounted at this point,
6648                // the caller may not have been able to delete all of this
6649                // packages files and can not delete any more.  Bail.
6650                return null;
6651            }
6652            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
6653            if (lastPackage != null) {
6654                pkgs.remove(lastPackage);
6655            }
6656            if (pkgs.size() > 0) {
6657                return pkgs.get(0);
6658            }
6659        }
6660        return null;
6661    }
6662
6663    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
6664        if (false) {
6665            RuntimeException here = new RuntimeException("here");
6666            here.fillInStackTrace();
6667            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
6668                    + " andCode=" + andCode, here);
6669        }
6670        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
6671                userId, andCode ? 1 : 0, packageName));
6672    }
6673
6674    void startCleaningPackages() {
6675        // reader
6676        synchronized (mPackages) {
6677            if (!isExternalMediaAvailable()) {
6678                return;
6679            }
6680            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
6681                return;
6682            }
6683        }
6684        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
6685        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
6686        IActivityManager am = ActivityManagerNative.getDefault();
6687        if (am != null) {
6688            try {
6689                am.startService(null, intent, null, UserHandle.USER_OWNER);
6690            } catch (RemoteException e) {
6691            }
6692        }
6693    }
6694
6695    private final class AppDirObserver extends FileObserver {
6696        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
6697            super(path, mask);
6698            mRootDir = path;
6699            mIsRom = isrom;
6700            mIsPrivileged = isPrivileged;
6701        }
6702
6703        public void onEvent(int event, String path) {
6704            String removedPackage = null;
6705            int removedAppId = -1;
6706            int[] removedUsers = null;
6707            String addedPackage = null;
6708            int addedAppId = -1;
6709            int[] addedUsers = null;
6710
6711            // TODO post a message to the handler to obtain serial ordering
6712            synchronized (mInstallLock) {
6713                String fullPathStr = null;
6714                File fullPath = null;
6715                if (path != null) {
6716                    fullPath = new File(mRootDir, path);
6717                    fullPathStr = fullPath.getPath();
6718                }
6719
6720                if (DEBUG_APP_DIR_OBSERVER)
6721                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
6722
6723                if (!isPackageFilename(path)) {
6724                    if (DEBUG_APP_DIR_OBSERVER)
6725                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
6726                    return;
6727                }
6728
6729                // Ignore packages that are being installed or
6730                // have just been installed.
6731                if (ignoreCodePath(fullPathStr)) {
6732                    return;
6733                }
6734                PackageParser.Package p = null;
6735                PackageSetting ps = null;
6736                // reader
6737                synchronized (mPackages) {
6738                    p = mAppDirs.get(fullPathStr);
6739                    if (p != null) {
6740                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
6741                        if (ps != null) {
6742                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
6743                        } else {
6744                            removedUsers = sUserManager.getUserIds();
6745                        }
6746                    }
6747                    addedUsers = sUserManager.getUserIds();
6748                }
6749                if ((event&REMOVE_EVENTS) != 0) {
6750                    if (ps != null) {
6751                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
6752                        removePackageLI(ps, true);
6753                        removedPackage = ps.name;
6754                        removedAppId = ps.appId;
6755                    }
6756                }
6757
6758                if ((event&ADD_EVENTS) != 0) {
6759                    if (p == null) {
6760                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
6761                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
6762                        if (mIsRom) {
6763                            flags |= PackageParser.PARSE_IS_SYSTEM
6764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
6765                            if (mIsPrivileged) {
6766                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
6767                            }
6768                        }
6769                        p = scanPackageLI(fullPath, flags,
6770                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
6771                                System.currentTimeMillis(), UserHandle.ALL);
6772                        if (p != null) {
6773                            /*
6774                             * TODO this seems dangerous as the package may have
6775                             * changed since we last acquired the mPackages
6776                             * lock.
6777                             */
6778                            // writer
6779                            synchronized (mPackages) {
6780                                updatePermissionsLPw(p.packageName, p,
6781                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
6782                            }
6783                            addedPackage = p.applicationInfo.packageName;
6784                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
6785                        }
6786                    }
6787                }
6788
6789                // reader
6790                synchronized (mPackages) {
6791                    mSettings.writeLPr();
6792                }
6793            }
6794
6795            if (removedPackage != null) {
6796                Bundle extras = new Bundle(1);
6797                extras.putInt(Intent.EXTRA_UID, removedAppId);
6798                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
6799                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
6800                        extras, null, null, removedUsers);
6801            }
6802            if (addedPackage != null) {
6803                Bundle extras = new Bundle(1);
6804                extras.putInt(Intent.EXTRA_UID, addedAppId);
6805                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
6806                        extras, null, null, addedUsers);
6807            }
6808        }
6809
6810        private final String mRootDir;
6811        private final boolean mIsRom;
6812        private final boolean mIsPrivileged;
6813    }
6814
6815    /*
6816     * The old-style observer methods all just trampoline to the newer signature with
6817     * expanded install observer API.  The older API continues to work but does not
6818     * supply the additional details of the Observer2 API.
6819     */
6820
6821    /* Called when a downloaded package installation has been confirmed by the user */
6822    public void installPackage(
6823            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
6824        installPackageEtc(packageURI, observer, null, flags, null);
6825    }
6826
6827    /* Called when a downloaded package installation has been confirmed by the user */
6828    public void installPackage(
6829            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
6830            final String installerPackageName) {
6831        installPackageWithVerificationEtc(packageURI, observer, null, flags,
6832                installerPackageName, null, null, null);
6833    }
6834
6835    @Override
6836    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
6837            int flags, String installerPackageName, Uri verificationURI,
6838            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6839        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6840                VerificationParams.NO_UID, manifestDigest);
6841        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6842                installerPackageName, verificationParams, encryptionParams);
6843    }
6844
6845    public void installPackageWithVerificationAndEncryption(Uri packageURI,
6846            IPackageInstallObserver observer, int flags, String installerPackageName,
6847            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6848        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
6849                installerPackageName, verificationParams, encryptionParams);
6850    }
6851
6852    /*
6853     * And here are the "live" versions that take both observer arguments
6854     */
6855    public void installPackageEtc(
6856            final Uri packageURI, final IPackageInstallObserver observer,
6857            IPackageInstallObserver2 observer2, final int flags) {
6858        installPackageEtc(packageURI, observer, observer2, flags, null);
6859    }
6860
6861    public void installPackageEtc(
6862            final Uri packageURI, final IPackageInstallObserver observer,
6863            final IPackageInstallObserver2 observer2, final int flags,
6864            final String installerPackageName) {
6865        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
6866                installerPackageName, null, null, null);
6867    }
6868
6869    @Override
6870    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
6871            IPackageInstallObserver2 observer2,
6872            int flags, String installerPackageName, Uri verificationURI,
6873            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
6874        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
6875                VerificationParams.NO_UID, manifestDigest);
6876        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
6877                installerPackageName, verificationParams, encryptionParams);
6878    }
6879
6880    /*
6881     * All of the installPackage...*() methods redirect to this one for the master implementation
6882     */
6883    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
6884            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
6885            int flags, String installerPackageName,
6886            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
6887        if (observer == null && observer2 == null) {
6888            throw new IllegalArgumentException("No install observer supplied");
6889        }
6890        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
6891                null);
6892
6893        final int uid = Binder.getCallingUid();
6894        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
6895            try {
6896                if (observer != null) {
6897                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6898                }
6899                if (observer2 != null) {
6900                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
6901                }
6902            } catch (RemoteException re) {
6903            }
6904            return;
6905        }
6906
6907        UserHandle user;
6908        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
6909            user = UserHandle.ALL;
6910        } else {
6911            user = new UserHandle(UserHandle.getUserId(uid));
6912        }
6913
6914        final int filteredFlags;
6915
6916        if (uid == Process.SHELL_UID || uid == 0) {
6917            if (DEBUG_INSTALL) {
6918                Slog.v(TAG, "Install from ADB");
6919            }
6920            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
6921        } else {
6922            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
6923        }
6924
6925        verificationParams.setInstallerUid(uid);
6926
6927        final Message msg = mHandler.obtainMessage(INIT_COPY);
6928        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
6929                installerPackageName, verificationParams, encryptionParams, user);
6930        mHandler.sendMessage(msg);
6931    }
6932
6933    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
6934        Bundle extras = new Bundle(1);
6935        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
6936
6937        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
6938                packageName, extras, null, null, new int[] {userId});
6939        try {
6940            IActivityManager am = ActivityManagerNative.getDefault();
6941            final boolean isSystem =
6942                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
6943            if (isSystem && am.isUserRunning(userId, false)) {
6944                // The just-installed/enabled app is bundled on the system, so presumed
6945                // to be able to run automatically without needing an explicit launch.
6946                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
6947                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
6948                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
6949                        .setPackage(packageName);
6950                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
6951                        android.app.AppOpsManager.OP_NONE, false, false, userId);
6952            }
6953        } catch (RemoteException e) {
6954            // shouldn't happen
6955            Slog.w(TAG, "Unable to bootstrap installed package", e);
6956        }
6957    }
6958
6959    @Override
6960    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
6961            int userId) {
6962        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6963        PackageSetting pkgSetting;
6964        final int uid = Binder.getCallingUid();
6965        if (UserHandle.getUserId(uid) != userId) {
6966            mContext.enforceCallingOrSelfPermission(
6967                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6968                    "setApplicationBlockedSetting for user " + userId);
6969        }
6970
6971        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
6972            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
6973            return false;
6974        }
6975
6976        long callingId = Binder.clearCallingIdentity();
6977        try {
6978            boolean sendAdded = false;
6979            boolean sendRemoved = false;
6980            // writer
6981            synchronized (mPackages) {
6982                pkgSetting = mSettings.mPackages.get(packageName);
6983                if (pkgSetting == null) {
6984                    return false;
6985                }
6986                if (pkgSetting.getBlocked(userId) != blocked) {
6987                    pkgSetting.setBlocked(blocked, userId);
6988                    mSettings.writePackageRestrictionsLPr(userId);
6989                    if (blocked) {
6990                        sendRemoved = true;
6991                    } else {
6992                        sendAdded = true;
6993                    }
6994                }
6995            }
6996            if (sendAdded) {
6997                sendPackageAddedForUser(packageName, pkgSetting, userId);
6998                return true;
6999            }
7000            if (sendRemoved) {
7001                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7002                        "blocking pkg");
7003                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7004            }
7005        } finally {
7006            Binder.restoreCallingIdentity(callingId);
7007        }
7008        return false;
7009    }
7010
7011    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7012            int userId) {
7013        final PackageRemovedInfo info = new PackageRemovedInfo();
7014        info.removedPackage = packageName;
7015        info.removedUsers = new int[] {userId};
7016        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7017        info.sendBroadcast(false, false, false);
7018    }
7019
7020    /**
7021     * Returns true if application is not found or there was an error. Otherwise it returns
7022     * the blocked state of the package for the given user.
7023     */
7024    @Override
7025    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7026        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7027        PackageSetting pkgSetting;
7028        final int uid = Binder.getCallingUid();
7029        if (UserHandle.getUserId(uid) != userId) {
7030            mContext.enforceCallingPermission(
7031                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7032                    "getApplicationBlocked for user " + userId);
7033        }
7034        long callingId = Binder.clearCallingIdentity();
7035        try {
7036            // writer
7037            synchronized (mPackages) {
7038                pkgSetting = mSettings.mPackages.get(packageName);
7039                if (pkgSetting == null) {
7040                    return true;
7041                }
7042                return pkgSetting.getBlocked(userId);
7043            }
7044        } finally {
7045            Binder.restoreCallingIdentity(callingId);
7046        }
7047    }
7048
7049    /**
7050     * @hide
7051     */
7052    @Override
7053    public int installExistingPackageAsUser(String packageName, int userId) {
7054        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7055                null);
7056        PackageSetting pkgSetting;
7057        final int uid = Binder.getCallingUid();
7058        if (UserHandle.getUserId(uid) != userId) {
7059            mContext.enforceCallingPermission(
7060                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7061                    "installExistingPackage for user " + userId);
7062        }
7063        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7064            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7065        }
7066
7067        long callingId = Binder.clearCallingIdentity();
7068        try {
7069            boolean sendAdded = false;
7070            Bundle extras = new Bundle(1);
7071
7072            // writer
7073            synchronized (mPackages) {
7074                pkgSetting = mSettings.mPackages.get(packageName);
7075                if (pkgSetting == null) {
7076                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7077                }
7078                if (!pkgSetting.getInstalled(userId)) {
7079                    pkgSetting.setInstalled(true, userId);
7080                    pkgSetting.setBlocked(false, userId);
7081                    mSettings.writePackageRestrictionsLPr(userId);
7082                    sendAdded = true;
7083                }
7084            }
7085
7086            if (sendAdded) {
7087                sendPackageAddedForUser(packageName, pkgSetting, userId);
7088            }
7089        } finally {
7090            Binder.restoreCallingIdentity(callingId);
7091        }
7092
7093        return PackageManager.INSTALL_SUCCEEDED;
7094    }
7095
7096    private boolean isUserRestricted(int userId, String restrictionKey) {
7097        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7098        if (restrictions.getBoolean(restrictionKey, false)) {
7099            Log.w(TAG, "User is restricted: " + restrictionKey);
7100            return true;
7101        }
7102        return false;
7103    }
7104
7105    @Override
7106    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7107        mContext.enforceCallingOrSelfPermission(
7108                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7109                "Only package verification agents can verify applications");
7110
7111        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7112        final PackageVerificationResponse response = new PackageVerificationResponse(
7113                verificationCode, Binder.getCallingUid());
7114        msg.arg1 = id;
7115        msg.obj = response;
7116        mHandler.sendMessage(msg);
7117    }
7118
7119    @Override
7120    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7121            long millisecondsToDelay) {
7122        mContext.enforceCallingOrSelfPermission(
7123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7124                "Only package verification agents can extend verification timeouts");
7125
7126        final PackageVerificationState state = mPendingVerification.get(id);
7127        final PackageVerificationResponse response = new PackageVerificationResponse(
7128                verificationCodeAtTimeout, Binder.getCallingUid());
7129
7130        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7131            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7132        }
7133        if (millisecondsToDelay < 0) {
7134            millisecondsToDelay = 0;
7135        }
7136        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7137                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7138            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7139        }
7140
7141        if ((state != null) && !state.timeoutExtended()) {
7142            state.extendTimeout();
7143
7144            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7145            msg.arg1 = id;
7146            msg.obj = response;
7147            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7148        }
7149    }
7150
7151    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7152            int verificationCode, UserHandle user) {
7153        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7154        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7155        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7156        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7157        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7158
7159        mContext.sendBroadcastAsUser(intent, user,
7160                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7161    }
7162
7163    private ComponentName matchComponentForVerifier(String packageName,
7164            List<ResolveInfo> receivers) {
7165        ActivityInfo targetReceiver = null;
7166
7167        final int NR = receivers.size();
7168        for (int i = 0; i < NR; i++) {
7169            final ResolveInfo info = receivers.get(i);
7170            if (info.activityInfo == null) {
7171                continue;
7172            }
7173
7174            if (packageName.equals(info.activityInfo.packageName)) {
7175                targetReceiver = info.activityInfo;
7176                break;
7177            }
7178        }
7179
7180        if (targetReceiver == null) {
7181            return null;
7182        }
7183
7184        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7185    }
7186
7187    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7188            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7189        if (pkgInfo.verifiers.length == 0) {
7190            return null;
7191        }
7192
7193        final int N = pkgInfo.verifiers.length;
7194        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7195        for (int i = 0; i < N; i++) {
7196            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7197
7198            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7199                    receivers);
7200            if (comp == null) {
7201                continue;
7202            }
7203
7204            final int verifierUid = getUidForVerifier(verifierInfo);
7205            if (verifierUid == -1) {
7206                continue;
7207            }
7208
7209            if (DEBUG_VERIFY) {
7210                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7211                        + " with the correct signature");
7212            }
7213            sufficientVerifiers.add(comp);
7214            verificationState.addSufficientVerifier(verifierUid);
7215        }
7216
7217        return sufficientVerifiers;
7218    }
7219
7220    private int getUidForVerifier(VerifierInfo verifierInfo) {
7221        synchronized (mPackages) {
7222            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7223            if (pkg == null) {
7224                return -1;
7225            } else if (pkg.mSignatures.length != 1) {
7226                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7227                        + " has more than one signature; ignoring");
7228                return -1;
7229            }
7230
7231            /*
7232             * If the public key of the package's signature does not match
7233             * our expected public key, then this is a different package and
7234             * we should skip.
7235             */
7236
7237            final byte[] expectedPublicKey;
7238            try {
7239                final Signature verifierSig = pkg.mSignatures[0];
7240                final PublicKey publicKey = verifierSig.getPublicKey();
7241                expectedPublicKey = publicKey.getEncoded();
7242            } catch (CertificateException e) {
7243                return -1;
7244            }
7245
7246            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7247
7248            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7249                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7250                        + " does not have the expected public key; ignoring");
7251                return -1;
7252            }
7253
7254            return pkg.applicationInfo.uid;
7255        }
7256    }
7257
7258    public void finishPackageInstall(int token) {
7259        enforceSystemOrRoot("Only the system is allowed to finish installs");
7260
7261        if (DEBUG_INSTALL) {
7262            Slog.v(TAG, "BM finishing package install for " + token);
7263        }
7264
7265        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7266        mHandler.sendMessage(msg);
7267    }
7268
7269    /**
7270     * Get the verification agent timeout.
7271     *
7272     * @return verification timeout in milliseconds
7273     */
7274    private long getVerificationTimeout() {
7275        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7276                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7277                DEFAULT_VERIFICATION_TIMEOUT);
7278    }
7279
7280    /**
7281     * Get the default verification agent response code.
7282     *
7283     * @return default verification response code
7284     */
7285    private int getDefaultVerificationResponse() {
7286        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7287                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7288                DEFAULT_VERIFICATION_RESPONSE);
7289    }
7290
7291    /**
7292     * Check whether or not package verification has been enabled.
7293     *
7294     * @return true if verification should be performed
7295     */
7296    private boolean isVerificationEnabled(int flags) {
7297        if (!DEFAULT_VERIFY_ENABLE) {
7298            return false;
7299        }
7300
7301        // Check if installing from ADB
7302        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7303            // Do not run verification in a test harness environment
7304            if (ActivityManager.isRunningInTestHarness()) {
7305                return false;
7306            }
7307            // Check if the developer does not want package verification for ADB installs
7308            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7309                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7310                return false;
7311            }
7312        }
7313
7314        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7315                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7316    }
7317
7318    /**
7319     * Get the "allow unknown sources" setting.
7320     *
7321     * @return the current "allow unknown sources" setting
7322     */
7323    private int getUnknownSourcesSettings() {
7324        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7325                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7326                -1);
7327    }
7328
7329    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7330        final int uid = Binder.getCallingUid();
7331        // writer
7332        synchronized (mPackages) {
7333            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7334            if (targetPackageSetting == null) {
7335                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7336            }
7337
7338            PackageSetting installerPackageSetting;
7339            if (installerPackageName != null) {
7340                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7341                if (installerPackageSetting == null) {
7342                    throw new IllegalArgumentException("Unknown installer package: "
7343                            + installerPackageName);
7344                }
7345            } else {
7346                installerPackageSetting = null;
7347            }
7348
7349            Signature[] callerSignature;
7350            Object obj = mSettings.getUserIdLPr(uid);
7351            if (obj != null) {
7352                if (obj instanceof SharedUserSetting) {
7353                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7354                } else if (obj instanceof PackageSetting) {
7355                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7356                } else {
7357                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7358                }
7359            } else {
7360                throw new SecurityException("Unknown calling uid " + uid);
7361            }
7362
7363            // Verify: can't set installerPackageName to a package that is
7364            // not signed with the same cert as the caller.
7365            if (installerPackageSetting != null) {
7366                if (compareSignatures(callerSignature,
7367                        installerPackageSetting.signatures.mSignatures)
7368                        != PackageManager.SIGNATURE_MATCH) {
7369                    throw new SecurityException(
7370                            "Caller does not have same cert as new installer package "
7371                            + installerPackageName);
7372                }
7373            }
7374
7375            // Verify: if target already has an installer package, it must
7376            // be signed with the same cert as the caller.
7377            if (targetPackageSetting.installerPackageName != null) {
7378                PackageSetting setting = mSettings.mPackages.get(
7379                        targetPackageSetting.installerPackageName);
7380                // If the currently set package isn't valid, then it's always
7381                // okay to change it.
7382                if (setting != null) {
7383                    if (compareSignatures(callerSignature,
7384                            setting.signatures.mSignatures)
7385                            != PackageManager.SIGNATURE_MATCH) {
7386                        throw new SecurityException(
7387                                "Caller does not have same cert as old installer package "
7388                                + targetPackageSetting.installerPackageName);
7389                    }
7390                }
7391            }
7392
7393            // Okay!
7394            targetPackageSetting.installerPackageName = installerPackageName;
7395            scheduleWriteSettingsLocked();
7396        }
7397    }
7398
7399    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
7400        // Queue up an async operation since the package installation may take a little while.
7401        mHandler.post(new Runnable() {
7402            public void run() {
7403                mHandler.removeCallbacks(this);
7404                 // Result object to be returned
7405                PackageInstalledInfo res = new PackageInstalledInfo();
7406                res.returnCode = currentStatus;
7407                res.uid = -1;
7408                res.pkg = null;
7409                res.removedInfo = new PackageRemovedInfo();
7410                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
7411                    args.doPreInstall(res.returnCode);
7412                    synchronized (mInstallLock) {
7413                        installPackageLI(args, true, res);
7414                    }
7415                    args.doPostInstall(res.returnCode, res.uid);
7416                }
7417
7418                // A restore should be performed at this point if (a) the install
7419                // succeeded, (b) the operation is not an update, and (c) the new
7420                // package has a backupAgent defined.
7421                final boolean update = res.removedInfo.removedPackage != null;
7422                boolean doRestore = (!update
7423                        && res.pkg != null
7424                        && res.pkg.applicationInfo.backupAgentName != null);
7425
7426                // Set up the post-install work request bookkeeping.  This will be used
7427                // and cleaned up by the post-install event handling regardless of whether
7428                // there's a restore pass performed.  Token values are >= 1.
7429                int token;
7430                if (mNextInstallToken < 0) mNextInstallToken = 1;
7431                token = mNextInstallToken++;
7432
7433                PostInstallData data = new PostInstallData(args, res);
7434                mRunningInstalls.put(token, data);
7435                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
7436
7437                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
7438                    // Pass responsibility to the Backup Manager.  It will perform a
7439                    // restore if appropriate, then pass responsibility back to the
7440                    // Package Manager to run the post-install observer callbacks
7441                    // and broadcasts.
7442                    IBackupManager bm = IBackupManager.Stub.asInterface(
7443                            ServiceManager.getService(Context.BACKUP_SERVICE));
7444                    if (bm != null) {
7445                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
7446                                + " to BM for possible restore");
7447                        try {
7448                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
7449                        } catch (RemoteException e) {
7450                            // can't happen; the backup manager is local
7451                        } catch (Exception e) {
7452                            Slog.e(TAG, "Exception trying to enqueue restore", e);
7453                            doRestore = false;
7454                        }
7455                    } else {
7456                        Slog.e(TAG, "Backup Manager not found!");
7457                        doRestore = false;
7458                    }
7459                }
7460
7461                if (!doRestore) {
7462                    // No restore possible, or the Backup Manager was mysteriously not
7463                    // available -- just fire the post-install work request directly.
7464                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
7465                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7466                    mHandler.sendMessage(msg);
7467                }
7468            }
7469        });
7470    }
7471
7472    private abstract class HandlerParams {
7473        private static final int MAX_RETRIES = 4;
7474
7475        /**
7476         * Number of times startCopy() has been attempted and had a non-fatal
7477         * error.
7478         */
7479        private int mRetries = 0;
7480
7481        /** User handle for the user requesting the information or installation. */
7482        private final UserHandle mUser;
7483
7484        HandlerParams(UserHandle user) {
7485            mUser = user;
7486        }
7487
7488        UserHandle getUser() {
7489            return mUser;
7490        }
7491
7492        final boolean startCopy() {
7493            boolean res;
7494            try {
7495                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
7496
7497                if (++mRetries > MAX_RETRIES) {
7498                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
7499                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
7500                    handleServiceError();
7501                    return false;
7502                } else {
7503                    handleStartCopy();
7504                    res = true;
7505                }
7506            } catch (RemoteException e) {
7507                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
7508                mHandler.sendEmptyMessage(MCS_RECONNECT);
7509                res = false;
7510            }
7511            handleReturnCode();
7512            return res;
7513        }
7514
7515        final void serviceError() {
7516            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
7517            handleServiceError();
7518            handleReturnCode();
7519        }
7520
7521        abstract void handleStartCopy() throws RemoteException;
7522        abstract void handleServiceError();
7523        abstract void handleReturnCode();
7524    }
7525
7526    class MeasureParams extends HandlerParams {
7527        private final PackageStats mStats;
7528        private boolean mSuccess;
7529
7530        private final IPackageStatsObserver mObserver;
7531
7532        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
7533            super(new UserHandle(stats.userHandle));
7534            mObserver = observer;
7535            mStats = stats;
7536        }
7537
7538        @Override
7539        public String toString() {
7540            return "MeasureParams{"
7541                + Integer.toHexString(System.identityHashCode(this))
7542                + " " + mStats.packageName + "}";
7543        }
7544
7545        @Override
7546        void handleStartCopy() throws RemoteException {
7547            synchronized (mInstallLock) {
7548                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
7549            }
7550
7551            if (mSuccess) {
7552                final boolean mounted;
7553                if (Environment.isExternalStorageEmulated()) {
7554                    mounted = true;
7555                } else {
7556                    final String status = Environment.getExternalStorageState();
7557                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
7558                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
7559                }
7560
7561                if (mounted) {
7562                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
7563
7564                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
7565                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
7566
7567                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
7568                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
7569
7570                    // Always subtract cache size, since it's a subdirectory
7571                    mStats.externalDataSize -= mStats.externalCacheSize;
7572
7573                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
7574                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
7575
7576                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
7577                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
7578                }
7579            }
7580        }
7581
7582        @Override
7583        void handleReturnCode() {
7584            if (mObserver != null) {
7585                try {
7586                    mObserver.onGetStatsCompleted(mStats, mSuccess);
7587                } catch (RemoteException e) {
7588                    Slog.i(TAG, "Observer no longer exists.");
7589                }
7590            }
7591        }
7592
7593        @Override
7594        void handleServiceError() {
7595            Slog.e(TAG, "Could not measure application " + mStats.packageName
7596                            + " external storage");
7597        }
7598    }
7599
7600    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
7601            throws RemoteException {
7602        long result = 0;
7603        for (File path : paths) {
7604            result += mcs.calculateDirectorySize(path.getAbsolutePath());
7605        }
7606        return result;
7607    }
7608
7609    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
7610        for (File path : paths) {
7611            try {
7612                mcs.clearDirectory(path.getAbsolutePath());
7613            } catch (RemoteException e) {
7614            }
7615        }
7616    }
7617
7618    class InstallParams extends HandlerParams {
7619        final IPackageInstallObserver observer;
7620        final IPackageInstallObserver2 observer2;
7621        int flags;
7622
7623        private final Uri mPackageURI;
7624        final String installerPackageName;
7625        final VerificationParams verificationParams;
7626        private InstallArgs mArgs;
7627        private int mRet;
7628        private File mTempPackage;
7629        final ContainerEncryptionParams encryptionParams;
7630
7631        InstallParams(Uri packageURI,
7632                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7633                int flags, String installerPackageName, VerificationParams verificationParams,
7634                ContainerEncryptionParams encryptionParams, UserHandle user) {
7635            super(user);
7636            this.mPackageURI = packageURI;
7637            this.flags = flags;
7638            this.observer = observer;
7639            this.observer2 = observer2;
7640            this.installerPackageName = installerPackageName;
7641            this.verificationParams = verificationParams;
7642            this.encryptionParams = encryptionParams;
7643        }
7644
7645        @Override
7646        public String toString() {
7647            return "InstallParams{"
7648                + Integer.toHexString(System.identityHashCode(this))
7649                + " " + mPackageURI + "}";
7650        }
7651
7652        public ManifestDigest getManifestDigest() {
7653            if (verificationParams == null) {
7654                return null;
7655            }
7656            return verificationParams.getManifestDigest();
7657        }
7658
7659        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
7660            String packageName = pkgLite.packageName;
7661            int installLocation = pkgLite.installLocation;
7662            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7663            // reader
7664            synchronized (mPackages) {
7665                PackageParser.Package pkg = mPackages.get(packageName);
7666                if (pkg != null) {
7667                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7668                        // Check for downgrading.
7669                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
7670                            if (pkgLite.versionCode < pkg.mVersionCode) {
7671                                Slog.w(TAG, "Can't install update of " + packageName
7672                                        + " update version " + pkgLite.versionCode
7673                                        + " is older than installed version "
7674                                        + pkg.mVersionCode);
7675                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
7676                            }
7677                        }
7678                        // Check for updated system application.
7679                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7680                            if (onSd) {
7681                                Slog.w(TAG, "Cannot install update to system app on sdcard");
7682                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
7683                            }
7684                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7685                        } else {
7686                            if (onSd) {
7687                                // Install flag overrides everything.
7688                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7689                            }
7690                            // If current upgrade specifies particular preference
7691                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
7692                                // Application explicitly specified internal.
7693                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7694                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
7695                                // App explictly prefers external. Let policy decide
7696                            } else {
7697                                // Prefer previous location
7698                                if (isExternal(pkg)) {
7699                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7700                                }
7701                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
7702                            }
7703                        }
7704                    } else {
7705                        // Invalid install. Return error code
7706                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
7707                    }
7708                }
7709            }
7710            // All the special cases have been taken care of.
7711            // Return result based on recommended install location.
7712            if (onSd) {
7713                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
7714            }
7715            return pkgLite.recommendedInstallLocation;
7716        }
7717
7718        private long getMemoryLowThreshold() {
7719            final DeviceStorageMonitorInternal
7720                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
7721            if (dsm == null) {
7722                return 0L;
7723            }
7724            return dsm.getMemoryLowThreshold();
7725        }
7726
7727        /*
7728         * Invoke remote method to get package information and install
7729         * location values. Override install location based on default
7730         * policy if needed and then create install arguments based
7731         * on the install location.
7732         */
7733        public void handleStartCopy() throws RemoteException {
7734            int ret = PackageManager.INSTALL_SUCCEEDED;
7735            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7736            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
7737            PackageInfoLite pkgLite = null;
7738
7739            if (onInt && onSd) {
7740                // Check if both bits are set.
7741                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
7742                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7743            } else {
7744                final long lowThreshold = getMemoryLowThreshold();
7745                if (lowThreshold == 0L) {
7746                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
7747                }
7748
7749                try {
7750                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
7751                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7752
7753                    final File packageFile;
7754                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
7755                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
7756                        if (mTempPackage != null) {
7757                            ParcelFileDescriptor out;
7758                            try {
7759                                out = ParcelFileDescriptor.open(mTempPackage,
7760                                        ParcelFileDescriptor.MODE_READ_WRITE);
7761                            } catch (FileNotFoundException e) {
7762                                out = null;
7763                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
7764                            }
7765
7766                            // Make a temporary file for decryption.
7767                            ret = mContainerService
7768                                    .copyResource(mPackageURI, encryptionParams, out);
7769                            IoUtils.closeQuietly(out);
7770
7771                            packageFile = mTempPackage;
7772
7773                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
7774                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
7775                                            | FileUtils.S_IROTH,
7776                                    -1, -1);
7777                        } else {
7778                            packageFile = null;
7779                        }
7780                    } else {
7781                        packageFile = new File(mPackageURI.getPath());
7782                    }
7783
7784                    if (packageFile != null) {
7785                        // Remote call to find out default install location
7786                        final String packageFilePath = packageFile.getAbsolutePath();
7787                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
7788                                lowThreshold);
7789
7790                        /*
7791                         * If we have too little free space, try to free cache
7792                         * before giving up.
7793                         */
7794                        if (pkgLite.recommendedInstallLocation
7795                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7796                            final long size = mContainerService.calculateInstalledSize(
7797                                    packageFilePath, isForwardLocked());
7798                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
7799                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
7800                                        flags, lowThreshold);
7801                            }
7802                            /*
7803                             * The cache free must have deleted the file we
7804                             * downloaded to install.
7805                             *
7806                             * TODO: fix the "freeCache" call to not delete
7807                             *       the file we care about.
7808                             */
7809                            if (pkgLite.recommendedInstallLocation
7810                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7811                                pkgLite.recommendedInstallLocation
7812                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
7813                            }
7814                        }
7815                    }
7816                } finally {
7817                    mContext.revokeUriPermission(mPackageURI,
7818                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
7819                }
7820            }
7821
7822            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7823                int loc = pkgLite.recommendedInstallLocation;
7824                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
7825                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7826                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
7827                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7828                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
7829                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7830                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
7831                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
7832                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
7833                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
7834                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
7835                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
7836                } else {
7837                    // Override with defaults if needed.
7838                    loc = installLocationPolicy(pkgLite, flags);
7839                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
7840                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
7841                    } else if (!onSd && !onInt) {
7842                        // Override install location with flags
7843                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
7844                            // Set the flag to install on external media.
7845                            flags |= PackageManager.INSTALL_EXTERNAL;
7846                            flags &= ~PackageManager.INSTALL_INTERNAL;
7847                        } else {
7848                            // Make sure the flag for installing on external
7849                            // media is unset
7850                            flags |= PackageManager.INSTALL_INTERNAL;
7851                            flags &= ~PackageManager.INSTALL_EXTERNAL;
7852                        }
7853                    }
7854                }
7855            }
7856
7857            final InstallArgs args = createInstallArgs(this);
7858            mArgs = args;
7859
7860            if (ret == PackageManager.INSTALL_SUCCEEDED) {
7861                 /*
7862                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
7863                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
7864                 */
7865                int userIdentifier = getUser().getIdentifier();
7866                if (userIdentifier == UserHandle.USER_ALL
7867                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
7868                    userIdentifier = UserHandle.USER_OWNER;
7869                }
7870
7871                /*
7872                 * Determine if we have any installed package verifiers. If we
7873                 * do, then we'll defer to them to verify the packages.
7874                 */
7875                final int requiredUid = mRequiredVerifierPackage == null ? -1
7876                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
7877                if (requiredUid != -1 && isVerificationEnabled(flags)) {
7878                    final Intent verification = new Intent(
7879                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
7880                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
7881                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7882
7883                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
7884                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
7885                            0 /* TODO: Which userId? */);
7886
7887                    if (DEBUG_VERIFY) {
7888                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
7889                                + verification.toString() + " with " + pkgLite.verifiers.length
7890                                + " optional verifiers");
7891                    }
7892
7893                    final int verificationId = mPendingVerificationToken++;
7894
7895                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7896
7897                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
7898                            installerPackageName);
7899
7900                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
7901
7902                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
7903                            pkgLite.packageName);
7904
7905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
7906                            pkgLite.versionCode);
7907
7908                    if (verificationParams != null) {
7909                        if (verificationParams.getVerificationURI() != null) {
7910                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
7911                                 verificationParams.getVerificationURI());
7912                        }
7913                        if (verificationParams.getOriginatingURI() != null) {
7914                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
7915                                  verificationParams.getOriginatingURI());
7916                        }
7917                        if (verificationParams.getReferrer() != null) {
7918                            verification.putExtra(Intent.EXTRA_REFERRER,
7919                                  verificationParams.getReferrer());
7920                        }
7921                        if (verificationParams.getOriginatingUid() >= 0) {
7922                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
7923                                  verificationParams.getOriginatingUid());
7924                        }
7925                        if (verificationParams.getInstallerUid() >= 0) {
7926                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
7927                                  verificationParams.getInstallerUid());
7928                        }
7929                    }
7930
7931                    final PackageVerificationState verificationState = new PackageVerificationState(
7932                            requiredUid, args);
7933
7934                    mPendingVerification.append(verificationId, verificationState);
7935
7936                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
7937                            receivers, verificationState);
7938
7939                    /*
7940                     * If any sufficient verifiers were listed in the package
7941                     * manifest, attempt to ask them.
7942                     */
7943                    if (sufficientVerifiers != null) {
7944                        final int N = sufficientVerifiers.size();
7945                        if (N == 0) {
7946                            Slog.i(TAG, "Additional verifiers required, but none installed.");
7947                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
7948                        } else {
7949                            for (int i = 0; i < N; i++) {
7950                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
7951
7952                                final Intent sufficientIntent = new Intent(verification);
7953                                sufficientIntent.setComponent(verifierComponent);
7954
7955                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
7956                            }
7957                        }
7958                    }
7959
7960                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
7961                            mRequiredVerifierPackage, receivers);
7962                    if (ret == PackageManager.INSTALL_SUCCEEDED
7963                            && mRequiredVerifierPackage != null) {
7964                        /*
7965                         * Send the intent to the required verification agent,
7966                         * but only start the verification timeout after the
7967                         * target BroadcastReceivers have run.
7968                         */
7969                        verification.setComponent(requiredVerifierComponent);
7970                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
7971                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7972                                new BroadcastReceiver() {
7973                                    @Override
7974                                    public void onReceive(Context context, Intent intent) {
7975                                        final Message msg = mHandler
7976                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
7977                                        msg.arg1 = verificationId;
7978                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
7979                                    }
7980                                }, null, 0, null, null);
7981
7982                        /*
7983                         * We don't want the copy to proceed until verification
7984                         * succeeds, so null out this field.
7985                         */
7986                        mArgs = null;
7987                    }
7988                } else {
7989                    /*
7990                     * No package verification is enabled, so immediately start
7991                     * the remote call to initiate copy using temporary file.
7992                     */
7993                    ret = args.copyApk(mContainerService, true);
7994                }
7995            }
7996
7997            mRet = ret;
7998        }
7999
8000        @Override
8001        void handleReturnCode() {
8002            // If mArgs is null, then MCS couldn't be reached. When it
8003            // reconnects, it will try again to install. At that point, this
8004            // will succeed.
8005            if (mArgs != null) {
8006                processPendingInstall(mArgs, mRet);
8007
8008                if (mTempPackage != null) {
8009                    if (!mTempPackage.delete()) {
8010                        Slog.w(TAG, "Couldn't delete temporary file: " +
8011                                mTempPackage.getAbsolutePath());
8012                    }
8013                }
8014            }
8015        }
8016
8017        @Override
8018        void handleServiceError() {
8019            mArgs = createInstallArgs(this);
8020            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8021        }
8022
8023        public boolean isForwardLocked() {
8024            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8025        }
8026
8027        public Uri getPackageUri() {
8028            if (mTempPackage != null) {
8029                return Uri.fromFile(mTempPackage);
8030            } else {
8031                return mPackageURI;
8032            }
8033        }
8034    }
8035
8036    /*
8037     * Utility class used in movePackage api.
8038     * srcArgs and targetArgs are not set for invalid flags and make
8039     * sure to do null checks when invoking methods on them.
8040     * We probably want to return ErrorPrams for both failed installs
8041     * and moves.
8042     */
8043    class MoveParams extends HandlerParams {
8044        final IPackageMoveObserver observer;
8045        final int flags;
8046        final String packageName;
8047        final InstallArgs srcArgs;
8048        final InstallArgs targetArgs;
8049        int uid;
8050        int mRet;
8051
8052        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8053                String packageName, String dataDir, int uid, UserHandle user) {
8054            super(user);
8055            this.srcArgs = srcArgs;
8056            this.observer = observer;
8057            this.flags = flags;
8058            this.packageName = packageName;
8059            this.uid = uid;
8060            if (srcArgs != null) {
8061                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8062                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
8063            } else {
8064                targetArgs = null;
8065            }
8066        }
8067
8068        @Override
8069        public String toString() {
8070            return "MoveParams{"
8071                + Integer.toHexString(System.identityHashCode(this))
8072                + " " + packageName + "}";
8073        }
8074
8075        public void handleStartCopy() throws RemoteException {
8076            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8077            // Check for storage space on target medium
8078            if (!targetArgs.checkFreeStorage(mContainerService)) {
8079                Log.w(TAG, "Insufficient storage to install");
8080                return;
8081            }
8082
8083            mRet = srcArgs.doPreCopy();
8084            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8085                return;
8086            }
8087
8088            mRet = targetArgs.copyApk(mContainerService, false);
8089            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8090                srcArgs.doPostCopy(uid);
8091                return;
8092            }
8093
8094            mRet = srcArgs.doPostCopy(uid);
8095            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8096                return;
8097            }
8098
8099            mRet = targetArgs.doPreInstall(mRet);
8100            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8101                return;
8102            }
8103
8104            if (DEBUG_SD_INSTALL) {
8105                StringBuilder builder = new StringBuilder();
8106                if (srcArgs != null) {
8107                    builder.append("src: ");
8108                    builder.append(srcArgs.getCodePath());
8109                }
8110                if (targetArgs != null) {
8111                    builder.append(" target : ");
8112                    builder.append(targetArgs.getCodePath());
8113                }
8114                Log.i(TAG, builder.toString());
8115            }
8116        }
8117
8118        @Override
8119        void handleReturnCode() {
8120            targetArgs.doPostInstall(mRet, uid);
8121            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8122            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8123                currentStatus = PackageManager.MOVE_SUCCEEDED;
8124            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8125                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8126            }
8127            processPendingMove(this, currentStatus);
8128        }
8129
8130        @Override
8131        void handleServiceError() {
8132            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8133        }
8134    }
8135
8136    /**
8137     * Used during creation of InstallArgs
8138     *
8139     * @param flags package installation flags
8140     * @return true if should be installed on external storage
8141     */
8142    private static boolean installOnSd(int flags) {
8143        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8144            return false;
8145        }
8146        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8147            return true;
8148        }
8149        return false;
8150    }
8151
8152    /**
8153     * Used during creation of InstallArgs
8154     *
8155     * @param flags package installation flags
8156     * @return true if should be installed as forward locked
8157     */
8158    private static boolean installForwardLocked(int flags) {
8159        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8160    }
8161
8162    private InstallArgs createInstallArgs(InstallParams params) {
8163        if (installOnSd(params.flags) || params.isForwardLocked()) {
8164            return new AsecInstallArgs(params);
8165        } else {
8166            return new FileInstallArgs(params);
8167        }
8168    }
8169
8170    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8171            String nativeLibraryPath) {
8172        final boolean isInAsec;
8173        if (installOnSd(flags)) {
8174            /* Apps on SD card are always in ASEC containers. */
8175            isInAsec = true;
8176        } else if (installForwardLocked(flags)
8177                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8178            /*
8179             * Forward-locked apps are only in ASEC containers if they're the
8180             * new style
8181             */
8182            isInAsec = true;
8183        } else {
8184            isInAsec = false;
8185        }
8186
8187        if (isInAsec) {
8188            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8189                    installOnSd(flags), installForwardLocked(flags));
8190        } else {
8191            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
8192        }
8193    }
8194
8195    // Used by package mover
8196    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
8197        if (installOnSd(flags) || installForwardLocked(flags)) {
8198            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8199                    + AsecInstallArgs.RES_FILE_NAME);
8200            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
8201                    installForwardLocked(flags));
8202        } else {
8203            return new FileInstallArgs(packageURI, pkgName, dataDir);
8204        }
8205    }
8206
8207    static abstract class InstallArgs {
8208        final IPackageInstallObserver observer;
8209        final IPackageInstallObserver2 observer2;
8210        // Always refers to PackageManager flags only
8211        final int flags;
8212        final Uri packageURI;
8213        final String installerPackageName;
8214        final ManifestDigest manifestDigest;
8215        final UserHandle user;
8216
8217        InstallArgs(Uri packageURI,
8218                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8219                int flags, String installerPackageName, ManifestDigest manifestDigest,
8220                UserHandle user) {
8221            this.packageURI = packageURI;
8222            this.flags = flags;
8223            this.observer = observer;
8224            this.observer2 = observer2;
8225            this.installerPackageName = installerPackageName;
8226            this.manifestDigest = manifestDigest;
8227            this.user = user;
8228        }
8229
8230        abstract void createCopyFile();
8231        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8232        abstract int doPreInstall(int status);
8233        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8234
8235        abstract int doPostInstall(int status, int uid);
8236        abstract String getCodePath();
8237        abstract String getResourcePath();
8238        abstract String getNativeLibraryPath();
8239        // Need installer lock especially for dex file removal.
8240        abstract void cleanUpResourcesLI();
8241        abstract boolean doPostDeleteLI(boolean delete);
8242        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8243
8244        /**
8245         * Called before the source arguments are copied. This is used mostly
8246         * for MoveParams when it needs to read the source file to put it in the
8247         * destination.
8248         */
8249        int doPreCopy() {
8250            return PackageManager.INSTALL_SUCCEEDED;
8251        }
8252
8253        /**
8254         * Called after the source arguments are copied. This is used mostly for
8255         * MoveParams when it needs to read the source file to put it in the
8256         * destination.
8257         *
8258         * @return
8259         */
8260        int doPostCopy(int uid) {
8261            return PackageManager.INSTALL_SUCCEEDED;
8262        }
8263
8264        protected boolean isFwdLocked() {
8265            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8266        }
8267
8268        UserHandle getUser() {
8269            return user;
8270        }
8271    }
8272
8273    class FileInstallArgs extends InstallArgs {
8274        File installDir;
8275        String codeFileName;
8276        String resourceFileName;
8277        String libraryPath;
8278        boolean created = false;
8279
8280        FileInstallArgs(InstallParams params) {
8281            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8282                    params.installerPackageName, params.getManifestDigest(),
8283                    params.getUser());
8284        }
8285
8286        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
8287            super(null, null, null, 0, null, null, null);
8288            File codeFile = new File(fullCodePath);
8289            installDir = codeFile.getParentFile();
8290            codeFileName = fullCodePath;
8291            resourceFileName = fullResourcePath;
8292            libraryPath = nativeLibraryPath;
8293        }
8294
8295        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
8296            super(packageURI, null, null, 0, null, null, null);
8297            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8298            String apkName = getNextCodePath(null, pkgName, ".apk");
8299            codeFileName = new File(installDir, apkName + ".apk").getPath();
8300            resourceFileName = getResourcePathFromCodePath();
8301            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8302        }
8303
8304        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8305            final long lowThreshold;
8306
8307            final DeviceStorageMonitorInternal
8308                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8309            if (dsm == null) {
8310                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8311                lowThreshold = 0L;
8312            } else {
8313                if (dsm.isMemoryLow()) {
8314                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8315                    return false;
8316                }
8317
8318                lowThreshold = dsm.getMemoryLowThreshold();
8319            }
8320
8321            try {
8322                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8323                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8324                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8325            } finally {
8326                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8327            }
8328        }
8329
8330        String getCodePath() {
8331            return codeFileName;
8332        }
8333
8334        void createCopyFile() {
8335            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8336            codeFileName = createTempPackageFile(installDir).getPath();
8337            resourceFileName = getResourcePathFromCodePath();
8338            libraryPath = getLibraryPathFromCodePath();
8339            created = true;
8340        }
8341
8342        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8343            if (temp) {
8344                // Generate temp file name
8345                createCopyFile();
8346            }
8347            // Get a ParcelFileDescriptor to write to the output file
8348            File codeFile = new File(codeFileName);
8349            if (!created) {
8350                try {
8351                    codeFile.createNewFile();
8352                    // Set permissions
8353                    if (!setPermissions()) {
8354                        // Failed setting permissions.
8355                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8356                    }
8357                } catch (IOException e) {
8358                   Slog.w(TAG, "Failed to create file " + codeFile);
8359                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8360                }
8361            }
8362            ParcelFileDescriptor out = null;
8363            try {
8364                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8365            } catch (FileNotFoundException e) {
8366                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8367                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8368            }
8369            // Copy the resource now
8370            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8371            try {
8372                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8373                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8374                ret = imcs.copyResource(packageURI, null, out);
8375            } finally {
8376                IoUtils.closeQuietly(out);
8377                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8378            }
8379
8380            if (isFwdLocked()) {
8381                final File destResourceFile = new File(getResourcePath());
8382
8383                // Copy the public files
8384                try {
8385                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
8386                } catch (IOException e) {
8387                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
8388                            + " forward-locked app.");
8389                    destResourceFile.delete();
8390                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8391                }
8392            }
8393
8394            final File nativeLibraryFile = new File(getNativeLibraryPath());
8395            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
8396            if (nativeLibraryFile.exists()) {
8397                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8398                nativeLibraryFile.delete();
8399            }
8400            try {
8401                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
8402                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8403                    return copyRet;
8404                }
8405            } catch (IOException e) {
8406                Slog.e(TAG, "Copying native libraries failed", e);
8407                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8408            }
8409
8410            return ret;
8411        }
8412
8413        int doPreInstall(int status) {
8414            if (status != PackageManager.INSTALL_SUCCEEDED) {
8415                cleanUp();
8416            }
8417            return status;
8418        }
8419
8420        boolean doRename(int status, final String pkgName, String oldCodePath) {
8421            if (status != PackageManager.INSTALL_SUCCEEDED) {
8422                cleanUp();
8423                return false;
8424            } else {
8425                final File oldCodeFile = new File(getCodePath());
8426                final File oldResourceFile = new File(getResourcePath());
8427                final File oldLibraryFile = new File(getNativeLibraryPath());
8428
8429                // Rename APK file based on packageName
8430                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
8431                final File newCodeFile = new File(installDir, apkName + ".apk");
8432                if (!oldCodeFile.renameTo(newCodeFile)) {
8433                    return false;
8434                }
8435                codeFileName = newCodeFile.getPath();
8436
8437                // Rename public resource file if it's forward-locked.
8438                final File newResFile = new File(getResourcePathFromCodePath());
8439                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
8440                    return false;
8441                }
8442                resourceFileName = newResFile.getPath();
8443
8444                // Rename library path
8445                final File newLibraryFile = new File(getLibraryPathFromCodePath());
8446                if (newLibraryFile.exists()) {
8447                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
8448                    newLibraryFile.delete();
8449                }
8450                if (!oldLibraryFile.renameTo(newLibraryFile)) {
8451                    Slog.e(TAG, "Cannot rename native library directory "
8452                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
8453                    return false;
8454                }
8455                libraryPath = newLibraryFile.getPath();
8456
8457                // Attempt to set permissions
8458                if (!setPermissions()) {
8459                    return false;
8460                }
8461
8462                if (!SELinux.restorecon(newCodeFile)) {
8463                    return false;
8464                }
8465
8466                return true;
8467            }
8468        }
8469
8470        int doPostInstall(int status, int uid) {
8471            if (status != PackageManager.INSTALL_SUCCEEDED) {
8472                cleanUp();
8473            }
8474            return status;
8475        }
8476
8477        String getResourcePath() {
8478            return resourceFileName;
8479        }
8480
8481        private String getResourcePathFromCodePath() {
8482            final String codePath = getCodePath();
8483            if (isFwdLocked()) {
8484                final StringBuilder sb = new StringBuilder();
8485
8486                sb.append(mAppInstallDir.getPath());
8487                sb.append('/');
8488                sb.append(getApkName(codePath));
8489                sb.append(".zip");
8490
8491                /*
8492                 * If our APK is a temporary file, mark the resource as a
8493                 * temporary file as well so it can be cleaned up after
8494                 * catastrophic failure.
8495                 */
8496                if (codePath.endsWith(".tmp")) {
8497                    sb.append(".tmp");
8498                }
8499
8500                return sb.toString();
8501            } else {
8502                return codePath;
8503            }
8504        }
8505
8506        private String getLibraryPathFromCodePath() {
8507            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
8508        }
8509
8510        @Override
8511        String getNativeLibraryPath() {
8512            if (libraryPath == null) {
8513                libraryPath = getLibraryPathFromCodePath();
8514            }
8515            return libraryPath;
8516        }
8517
8518        private boolean cleanUp() {
8519            boolean ret = true;
8520            String sourceDir = getCodePath();
8521            String publicSourceDir = getResourcePath();
8522            if (sourceDir != null) {
8523                File sourceFile = new File(sourceDir);
8524                if (!sourceFile.exists()) {
8525                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
8526                    ret = false;
8527                }
8528                // Delete application's code and resources
8529                sourceFile.delete();
8530            }
8531            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
8532                final File publicSourceFile = new File(publicSourceDir);
8533                if (!publicSourceFile.exists()) {
8534                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
8535                }
8536                if (publicSourceFile.exists()) {
8537                    publicSourceFile.delete();
8538                }
8539            }
8540
8541            if (libraryPath != null) {
8542                File nativeLibraryFile = new File(libraryPath);
8543                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
8544                if (!nativeLibraryFile.delete()) {
8545                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
8546                }
8547            }
8548
8549            return ret;
8550        }
8551
8552        void cleanUpResourcesLI() {
8553            String sourceDir = getCodePath();
8554            if (cleanUp()) {
8555                int retCode = mInstaller.rmdex(sourceDir);
8556                if (retCode < 0) {
8557                    Slog.w(TAG, "Couldn't remove dex file for package: "
8558                            +  " at location "
8559                            + sourceDir + ", retcode=" + retCode);
8560                    // we don't consider this to be a failure of the core package deletion
8561                }
8562            }
8563        }
8564
8565        private boolean setPermissions() {
8566            // TODO Do this in a more elegant way later on. for now just a hack
8567            if (!isFwdLocked()) {
8568                final int filePermissions =
8569                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
8570                    |FileUtils.S_IROTH;
8571                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
8572                if (retCode != 0) {
8573                    Slog.e(TAG, "Couldn't set new package file permissions for " +
8574                            getCodePath()
8575                            + ". The return code was: " + retCode);
8576                    // TODO Define new internal error
8577                    return false;
8578                }
8579                return true;
8580            }
8581            return true;
8582        }
8583
8584        boolean doPostDeleteLI(boolean delete) {
8585            // XXX err, shouldn't we respect the delete flag?
8586            cleanUpResourcesLI();
8587            return true;
8588        }
8589    }
8590
8591    private boolean isAsecExternal(String cid) {
8592        final String asecPath = PackageHelper.getSdFilesystem(cid);
8593        return !asecPath.startsWith(mAsecInternalPath);
8594    }
8595
8596    /**
8597     * Extract the MountService "container ID" from the full code path of an
8598     * .apk.
8599     */
8600    static String cidFromCodePath(String fullCodePath) {
8601        int eidx = fullCodePath.lastIndexOf("/");
8602        String subStr1 = fullCodePath.substring(0, eidx);
8603        int sidx = subStr1.lastIndexOf("/");
8604        return subStr1.substring(sidx+1, eidx);
8605    }
8606
8607    class AsecInstallArgs extends InstallArgs {
8608        static final String RES_FILE_NAME = "pkg.apk";
8609        static final String PUBLIC_RES_FILE_NAME = "res.zip";
8610
8611        String cid;
8612        String packagePath;
8613        String resourcePath;
8614        String libraryPath;
8615
8616        AsecInstallArgs(InstallParams params) {
8617            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8618                    params.installerPackageName, params.getManifestDigest(),
8619                    params.getUser());
8620        }
8621
8622        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8623                boolean isExternal, boolean isForwardLocked) {
8624            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8625                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8626                    null, null, null);
8627            // Extract cid from fullCodePath
8628            int eidx = fullCodePath.lastIndexOf("/");
8629            String subStr1 = fullCodePath.substring(0, eidx);
8630            int sidx = subStr1.lastIndexOf("/");
8631            cid = subStr1.substring(sidx+1, eidx);
8632            setCachePath(subStr1);
8633        }
8634
8635        AsecInstallArgs(String cid, boolean isForwardLocked) {
8636            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
8637                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8638                    null, null, null);
8639            this.cid = cid;
8640            setCachePath(PackageHelper.getSdDir(cid));
8641        }
8642
8643        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
8644            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
8645                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
8646                    null, null, null);
8647            this.cid = cid;
8648        }
8649
8650        void createCopyFile() {
8651            cid = getTempContainerId();
8652        }
8653
8654        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8655            try {
8656                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8657                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8658                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
8659            } finally {
8660                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8661            }
8662        }
8663
8664        private final boolean isExternal() {
8665            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8666        }
8667
8668        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8669            if (temp) {
8670                createCopyFile();
8671            } else {
8672                /*
8673                 * Pre-emptively destroy the container since it's destroyed if
8674                 * copying fails due to it existing anyway.
8675                 */
8676                PackageHelper.destroySdDir(cid);
8677            }
8678
8679            final String newCachePath;
8680            try {
8681                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8682                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8683                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
8684                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
8685            } finally {
8686                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8687            }
8688
8689            if (newCachePath != null) {
8690                setCachePath(newCachePath);
8691                return PackageManager.INSTALL_SUCCEEDED;
8692            } else {
8693                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8694            }
8695        }
8696
8697        @Override
8698        String getCodePath() {
8699            return packagePath;
8700        }
8701
8702        @Override
8703        String getResourcePath() {
8704            return resourcePath;
8705        }
8706
8707        @Override
8708        String getNativeLibraryPath() {
8709            return libraryPath;
8710        }
8711
8712        int doPreInstall(int status) {
8713            if (status != PackageManager.INSTALL_SUCCEEDED) {
8714                // Destroy container
8715                PackageHelper.destroySdDir(cid);
8716            } else {
8717                boolean mounted = PackageHelper.isContainerMounted(cid);
8718                if (!mounted) {
8719                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
8720                            Process.SYSTEM_UID);
8721                    if (newCachePath != null) {
8722                        setCachePath(newCachePath);
8723                    } else {
8724                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8725                    }
8726                }
8727            }
8728            return status;
8729        }
8730
8731        boolean doRename(int status, final String pkgName,
8732                String oldCodePath) {
8733            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
8734            String newCachePath = null;
8735            if (PackageHelper.isContainerMounted(cid)) {
8736                // Unmount the container
8737                if (!PackageHelper.unMountSdDir(cid)) {
8738                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
8739                    return false;
8740                }
8741            }
8742            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8743                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
8744                        " which might be stale. Will try to clean up.");
8745                // Clean up the stale container and proceed to recreate.
8746                if (!PackageHelper.destroySdDir(newCacheId)) {
8747                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
8748                    return false;
8749                }
8750                // Successfully cleaned up stale container. Try to rename again.
8751                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
8752                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
8753                            + " inspite of cleaning it up.");
8754                    return false;
8755                }
8756            }
8757            if (!PackageHelper.isContainerMounted(newCacheId)) {
8758                Slog.w(TAG, "Mounting container " + newCacheId);
8759                newCachePath = PackageHelper.mountSdDir(newCacheId,
8760                        getEncryptKey(), Process.SYSTEM_UID);
8761            } else {
8762                newCachePath = PackageHelper.getSdDir(newCacheId);
8763            }
8764            if (newCachePath == null) {
8765                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
8766                return false;
8767            }
8768            Log.i(TAG, "Succesfully renamed " + cid +
8769                    " to " + newCacheId +
8770                    " at new path: " + newCachePath);
8771            cid = newCacheId;
8772            setCachePath(newCachePath);
8773            return true;
8774        }
8775
8776        private void setCachePath(String newCachePath) {
8777            File cachePath = new File(newCachePath);
8778            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
8779            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
8780
8781            if (isFwdLocked()) {
8782                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
8783            } else {
8784                resourcePath = packagePath;
8785            }
8786        }
8787
8788        int doPostInstall(int status, int uid) {
8789            if (status != PackageManager.INSTALL_SUCCEEDED) {
8790                cleanUp();
8791            } else {
8792                final int groupOwner;
8793                final String protectedFile;
8794                if (isFwdLocked()) {
8795                    groupOwner = UserHandle.getSharedAppGid(uid);
8796                    protectedFile = RES_FILE_NAME;
8797                } else {
8798                    groupOwner = -1;
8799                    protectedFile = null;
8800                }
8801
8802                if (uid < Process.FIRST_APPLICATION_UID
8803                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
8804                    Slog.e(TAG, "Failed to finalize " + cid);
8805                    PackageHelper.destroySdDir(cid);
8806                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8807                }
8808
8809                boolean mounted = PackageHelper.isContainerMounted(cid);
8810                if (!mounted) {
8811                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
8812                }
8813            }
8814            return status;
8815        }
8816
8817        private void cleanUp() {
8818            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
8819
8820            // Destroy secure container
8821            PackageHelper.destroySdDir(cid);
8822        }
8823
8824        void cleanUpResourcesLI() {
8825            String sourceFile = getCodePath();
8826            // Remove dex file
8827            int retCode = mInstaller.rmdex(sourceFile);
8828            if (retCode < 0) {
8829                Slog.w(TAG, "Couldn't remove dex file for package: "
8830                        + " at location "
8831                        + sourceFile.toString() + ", retcode=" + retCode);
8832                // we don't consider this to be a failure of the core package deletion
8833            }
8834            cleanUp();
8835        }
8836
8837        boolean matchContainer(String app) {
8838            if (cid.startsWith(app)) {
8839                return true;
8840            }
8841            return false;
8842        }
8843
8844        String getPackageName() {
8845            return getAsecPackageName(cid);
8846        }
8847
8848        boolean doPostDeleteLI(boolean delete) {
8849            boolean ret = false;
8850            boolean mounted = PackageHelper.isContainerMounted(cid);
8851            if (mounted) {
8852                // Unmount first
8853                ret = PackageHelper.unMountSdDir(cid);
8854            }
8855            if (ret && delete) {
8856                cleanUpResourcesLI();
8857            }
8858            return ret;
8859        }
8860
8861        @Override
8862        int doPreCopy() {
8863            if (isFwdLocked()) {
8864                if (!PackageHelper.fixSdPermissions(cid,
8865                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
8866                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8867                }
8868            }
8869
8870            return PackageManager.INSTALL_SUCCEEDED;
8871        }
8872
8873        @Override
8874        int doPostCopy(int uid) {
8875            if (isFwdLocked()) {
8876                if (uid < Process.FIRST_APPLICATION_UID
8877                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
8878                                RES_FILE_NAME)) {
8879                    Slog.e(TAG, "Failed to finalize " + cid);
8880                    PackageHelper.destroySdDir(cid);
8881                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8882                }
8883            }
8884
8885            return PackageManager.INSTALL_SUCCEEDED;
8886        }
8887    };
8888
8889    static String getAsecPackageName(String packageCid) {
8890        int idx = packageCid.lastIndexOf("-");
8891        if (idx == -1) {
8892            return packageCid;
8893        }
8894        return packageCid.substring(0, idx);
8895    }
8896
8897    // Utility method used to create code paths based on package name and available index.
8898    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
8899        String idxStr = "";
8900        int idx = 1;
8901        // Fall back to default value of idx=1 if prefix is not
8902        // part of oldCodePath
8903        if (oldCodePath != null) {
8904            String subStr = oldCodePath;
8905            // Drop the suffix right away
8906            if (subStr.endsWith(suffix)) {
8907                subStr = subStr.substring(0, subStr.length() - suffix.length());
8908            }
8909            // If oldCodePath already contains prefix find out the
8910            // ending index to either increment or decrement.
8911            int sidx = subStr.lastIndexOf(prefix);
8912            if (sidx != -1) {
8913                subStr = subStr.substring(sidx + prefix.length());
8914                if (subStr != null) {
8915                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
8916                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
8917                    }
8918                    try {
8919                        idx = Integer.parseInt(subStr);
8920                        if (idx <= 1) {
8921                            idx++;
8922                        } else {
8923                            idx--;
8924                        }
8925                    } catch(NumberFormatException e) {
8926                    }
8927                }
8928            }
8929        }
8930        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
8931        return prefix + idxStr;
8932    }
8933
8934    // Utility method used to ignore ADD/REMOVE events
8935    // by directory observer.
8936    private static boolean ignoreCodePath(String fullPathStr) {
8937        String apkName = getApkName(fullPathStr);
8938        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
8939        if (idx != -1 && ((idx+1) < apkName.length())) {
8940            // Make sure the package ends with a numeral
8941            String version = apkName.substring(idx+1);
8942            try {
8943                Integer.parseInt(version);
8944                return true;
8945            } catch (NumberFormatException e) {}
8946        }
8947        return false;
8948    }
8949
8950    // Utility method that returns the relative package path with respect
8951    // to the installation directory. Like say for /data/data/com.test-1.apk
8952    // string com.test-1 is returned.
8953    static String getApkName(String codePath) {
8954        if (codePath == null) {
8955            return null;
8956        }
8957        int sidx = codePath.lastIndexOf("/");
8958        int eidx = codePath.lastIndexOf(".");
8959        if (eidx == -1) {
8960            eidx = codePath.length();
8961        } else if (eidx == 0) {
8962            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
8963            return null;
8964        }
8965        return codePath.substring(sidx+1, eidx);
8966    }
8967
8968    class PackageInstalledInfo {
8969        String name;
8970        int uid;
8971        // The set of users that originally had this package installed.
8972        int[] origUsers;
8973        // The set of users that now have this package installed.
8974        int[] newUsers;
8975        PackageParser.Package pkg;
8976        int returnCode;
8977        PackageRemovedInfo removedInfo;
8978
8979        // In some error cases we want to convey more info back to the observer
8980        String origPackage;
8981        String origPermission;
8982    }
8983
8984    /*
8985     * Install a non-existing package.
8986     */
8987    private void installNewPackageLI(PackageParser.Package pkg,
8988            int parseFlags, int scanMode, UserHandle user,
8989            String installerPackageName, PackageInstalledInfo res) {
8990        // Remember this for later, in case we need to rollback this install
8991        String pkgName = pkg.packageName;
8992
8993        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
8994        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
8995        synchronized(mPackages) {
8996            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
8997                // A package with the same name is already installed, though
8998                // it has been renamed to an older name.  The package we
8999                // are trying to install should be installed as an update to
9000                // the existing one, but that has not been requested, so bail.
9001                Slog.w(TAG, "Attempt to re-install " + pkgName
9002                        + " without first uninstalling package running as "
9003                        + mSettings.mRenamedPackages.get(pkgName));
9004                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9005                return;
9006            }
9007            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9008                // Don't allow installation over an existing package with the same name.
9009                Slog.w(TAG, "Attempt to re-install " + pkgName
9010                        + " without first uninstalling.");
9011                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9012                return;
9013            }
9014        }
9015        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9016        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9017                System.currentTimeMillis(), user);
9018        if (newPackage == null) {
9019            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9020            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9021                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9022            }
9023        } else {
9024            updateSettingsLI(newPackage,
9025                    installerPackageName,
9026                    null, null,
9027                    res);
9028            // delete the partially installed application. the data directory will have to be
9029            // restored if it was already existing
9030            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9031                // remove package from internal structures.  Note that we want deletePackageX to
9032                // delete the package data and cache directories that it created in
9033                // scanPackageLocked, unless those directories existed before we even tried to
9034                // install.
9035                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9036                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9037                                res.removedInfo, true);
9038            }
9039        }
9040    }
9041
9042    private void replacePackageLI(PackageParser.Package pkg,
9043            int parseFlags, int scanMode, UserHandle user,
9044            String installerPackageName, PackageInstalledInfo res) {
9045
9046        PackageParser.Package oldPackage;
9047        String pkgName = pkg.packageName;
9048        int[] allUsers;
9049        boolean[] perUserInstalled;
9050
9051        // First find the old package info and check signatures
9052        synchronized(mPackages) {
9053            oldPackage = mPackages.get(pkgName);
9054            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9055            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9056                    != PackageManager.SIGNATURE_MATCH) {
9057                Slog.w(TAG, "New package has a different signature: " + pkgName);
9058                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9059                return;
9060            }
9061
9062            // In case of rollback, remember per-user/profile install state
9063            PackageSetting ps = mSettings.mPackages.get(pkgName);
9064            allUsers = sUserManager.getUserIds();
9065            perUserInstalled = new boolean[allUsers.length];
9066            for (int i = 0; i < allUsers.length; i++) {
9067                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9068            }
9069        }
9070        boolean sysPkg = (isSystemApp(oldPackage));
9071        if (sysPkg) {
9072            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9073                    user, allUsers, perUserInstalled, installerPackageName, res);
9074        } else {
9075            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9076                    user, allUsers, perUserInstalled, installerPackageName, res);
9077        }
9078    }
9079
9080    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9081            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9082            int[] allUsers, boolean[] perUserInstalled,
9083            String installerPackageName, PackageInstalledInfo res) {
9084        PackageParser.Package newPackage = null;
9085        String pkgName = deletedPackage.packageName;
9086        boolean deletedPkg = true;
9087        boolean updatedSettings = false;
9088
9089        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9090                + deletedPackage);
9091        long origUpdateTime;
9092        if (pkg.mExtras != null) {
9093            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9094        } else {
9095            origUpdateTime = 0;
9096        }
9097
9098        // First delete the existing package while retaining the data directory
9099        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9100                res.removedInfo, true)) {
9101            // If the existing package wasn't successfully deleted
9102            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9103            deletedPkg = false;
9104        } else {
9105            // Successfully deleted the old package. Now proceed with re-installation
9106            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9107            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9108                    System.currentTimeMillis(), user);
9109            if (newPackage == null) {
9110                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9111                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9112                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9113                }
9114            } else {
9115                updateSettingsLI(newPackage,
9116                        installerPackageName,
9117                        allUsers, perUserInstalled,
9118                        res);
9119                updatedSettings = true;
9120            }
9121        }
9122
9123        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9124            // remove package from internal structures.  Note that we want deletePackageX to
9125            // delete the package data and cache directories that it created in
9126            // scanPackageLocked, unless those directories existed before we even tried to
9127            // install.
9128            if(updatedSettings) {
9129                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9130                deletePackageLI(
9131                        pkgName, null, true, allUsers, perUserInstalled,
9132                        PackageManager.DELETE_KEEP_DATA,
9133                                res.removedInfo, true);
9134            }
9135            // Since we failed to install the new package we need to restore the old
9136            // package that we deleted.
9137            if(deletedPkg) {
9138                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9139                File restoreFile = new File(deletedPackage.mPath);
9140                // Parse old package
9141                boolean oldOnSd = isExternal(deletedPackage);
9142                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9143                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9144                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9145                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9146                        | SCAN_UPDATE_TIME;
9147                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9148                        origUpdateTime, null) == null) {
9149                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9150                    return;
9151                }
9152                // Restore of old package succeeded. Update permissions.
9153                // writer
9154                synchronized (mPackages) {
9155                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9156                            UPDATE_PERMISSIONS_ALL);
9157                    // can downgrade to reader
9158                    mSettings.writeLPr();
9159                }
9160                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9161            }
9162        }
9163    }
9164
9165    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9166            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9167            int[] allUsers, boolean[] perUserInstalled,
9168            String installerPackageName, PackageInstalledInfo res) {
9169        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9170                + ", old=" + deletedPackage);
9171        PackageParser.Package newPackage = null;
9172        boolean updatedSettings = false;
9173        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9174                PackageParser.PARSE_IS_SYSTEM;
9175        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9176            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9177        }
9178        String packageName = deletedPackage.packageName;
9179        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9180        if (packageName == null) {
9181            Slog.w(TAG, "Attempt to delete null packageName.");
9182            return;
9183        }
9184        PackageParser.Package oldPkg;
9185        PackageSetting oldPkgSetting;
9186        // reader
9187        synchronized (mPackages) {
9188            oldPkg = mPackages.get(packageName);
9189            oldPkgSetting = mSettings.mPackages.get(packageName);
9190            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9191                    (oldPkgSetting == null)) {
9192                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9193                return;
9194            }
9195        }
9196
9197        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9198
9199        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9200        res.removedInfo.removedPackage = packageName;
9201        // Remove existing system package
9202        removePackageLI(oldPkgSetting, true);
9203        // writer
9204        synchronized (mPackages) {
9205            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9206                // We didn't need to disable the .apk as a current system package,
9207                // which means we are replacing another update that is already
9208                // installed.  We need to make sure to delete the older one's .apk.
9209                res.removedInfo.args = createInstallArgs(0,
9210                        deletedPackage.applicationInfo.sourceDir,
9211                        deletedPackage.applicationInfo.publicSourceDir,
9212                        deletedPackage.applicationInfo.nativeLibraryDir);
9213            } else {
9214                res.removedInfo.args = null;
9215            }
9216        }
9217
9218        // Successfully disabled the old package. Now proceed with re-installation
9219        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9220        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9221        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9222        if (newPackage == null) {
9223            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9224            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9225                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9226            }
9227        } else {
9228            if (newPackage.mExtras != null) {
9229                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9230                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9231                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9232
9233                // is the update attempting to change shared user? that isn't going to work...
9234                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9235                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9236                            + " to " + newPkgSetting.sharedUser);
9237                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9238                    updatedSettings = true;
9239                }
9240            }
9241
9242            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9243                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9244                updatedSettings = true;
9245            }
9246        }
9247
9248        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9249            // Re installation failed. Restore old information
9250            // Remove new pkg information
9251            if (newPackage != null) {
9252                removeInstalledPackageLI(newPackage, true);
9253            }
9254            // Add back the old system package
9255            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9256            // Restore the old system information in Settings
9257            synchronized(mPackages) {
9258                if (updatedSettings) {
9259                    mSettings.enableSystemPackageLPw(packageName);
9260                    mSettings.setInstallerPackageName(packageName,
9261                            oldPkgSetting.installerPackageName);
9262                }
9263                mSettings.writeLPr();
9264            }
9265        }
9266    }
9267
9268    // Utility method used to move dex files during install.
9269    private int moveDexFilesLI(PackageParser.Package newPackage) {
9270        int retCode;
9271        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9272            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
9273            if (retCode != 0) {
9274                if (mNoDexOpt) {
9275                    /*
9276                     * If we're in an engineering build, programs are lazily run
9277                     * through dexopt. If the .dex file doesn't exist yet, it
9278                     * will be created when the program is run next.
9279                     */
9280                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
9281                } else {
9282                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
9283                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9284                }
9285            }
9286        }
9287        return PackageManager.INSTALL_SUCCEEDED;
9288    }
9289
9290    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9291            int[] allUsers, boolean[] perUserInstalled,
9292            PackageInstalledInfo res) {
9293        String pkgName = newPackage.packageName;
9294        synchronized (mPackages) {
9295            //write settings. the installStatus will be incomplete at this stage.
9296            //note that the new package setting would have already been
9297            //added to mPackages. It hasn't been persisted yet.
9298            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9299            mSettings.writeLPr();
9300        }
9301
9302        if ((res.returnCode = moveDexFilesLI(newPackage))
9303                != PackageManager.INSTALL_SUCCEEDED) {
9304            // Discontinue if moving dex files failed.
9305            return;
9306        }
9307
9308        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9309
9310        synchronized (mPackages) {
9311            updatePermissionsLPw(newPackage.packageName, newPackage,
9312                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9313                            ? UPDATE_PERMISSIONS_ALL : 0));
9314            // For system-bundled packages, we assume that installing an upgraded version
9315            // of the package implies that the user actually wants to run that new code,
9316            // so we enable the package.
9317            if (isSystemApp(newPackage)) {
9318                // NB: implicit assumption that system package upgrades apply to all users
9319                if (DEBUG_INSTALL) {
9320                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9321                }
9322                PackageSetting ps = mSettings.mPackages.get(pkgName);
9323                if (ps != null) {
9324                    if (res.origUsers != null) {
9325                        for (int userHandle : res.origUsers) {
9326                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9327                                    userHandle, installerPackageName);
9328                        }
9329                    }
9330                    // Also convey the prior install/uninstall state
9331                    if (allUsers != null && perUserInstalled != null) {
9332                        for (int i = 0; i < allUsers.length; i++) {
9333                            if (DEBUG_INSTALL) {
9334                                Slog.d(TAG, "    user " + allUsers[i]
9335                                        + " => " + perUserInstalled[i]);
9336                            }
9337                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9338                        }
9339                        // these install state changes will be persisted in the
9340                        // upcoming call to mSettings.writeLPr().
9341                    }
9342                }
9343            }
9344            res.name = pkgName;
9345            res.uid = newPackage.applicationInfo.uid;
9346            res.pkg = newPackage;
9347            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9348            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9349            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9350            //to update install status
9351            mSettings.writeLPr();
9352        }
9353    }
9354
9355    private void installPackageLI(InstallArgs args,
9356            boolean newInstall, PackageInstalledInfo res) {
9357        int pFlags = args.flags;
9358        String installerPackageName = args.installerPackageName;
9359        File tmpPackageFile = new File(args.getCodePath());
9360        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9361        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9362        boolean replace = false;
9363        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9364                | (newInstall ? SCAN_NEW_INSTALL : 0);
9365        // Result object to be returned
9366        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9367
9368        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
9369        // Retrieve PackageSettings and parse package
9370        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
9371                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
9372                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
9373        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
9374        pp.setSeparateProcesses(mSeparateProcesses);
9375        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
9376                null, mMetrics, parseFlags);
9377        if (pkg == null) {
9378            res.returnCode = pp.getParseError();
9379            return;
9380        }
9381        String pkgName = res.name = pkg.packageName;
9382        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
9383            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
9384                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
9385                return;
9386            }
9387        }
9388        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
9389            res.returnCode = pp.getParseError();
9390            return;
9391        }
9392
9393        /* If the installer passed in a manifest digest, compare it now. */
9394        if (args.manifestDigest != null) {
9395            if (DEBUG_INSTALL) {
9396                final String parsedManifest = pkg.manifestDigest == null ? "null"
9397                        : pkg.manifestDigest.toString();
9398                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
9399                        + parsedManifest);
9400            }
9401
9402            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
9403                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
9404                return;
9405            }
9406        } else if (DEBUG_INSTALL) {
9407            final String parsedManifest = pkg.manifestDigest == null
9408                    ? "null" : pkg.manifestDigest.toString();
9409            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
9410        }
9411
9412        // Get rid of all references to package scan path via parser.
9413        pp = null;
9414        String oldCodePath = null;
9415        boolean systemApp = false;
9416        synchronized (mPackages) {
9417            // Check whether the newly-scanned package wants to define an already-defined perm
9418            int N = pkg.permissions.size();
9419            for (int i = 0; i < N; i++) {
9420                PackageParser.Permission perm = pkg.permissions.get(i);
9421                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
9422                if (bp != null) {
9423                    // If the defining package is signed with our cert, it's okay.  This
9424                    // also includes the "updating the same package" case, of course.
9425                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
9426                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9427                        Slog.w(TAG, "Package " + pkg.packageName
9428                                + " attempting to redeclare permission " + perm.info.name
9429                                + " already owned by " + bp.sourcePackage);
9430                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
9431                        res.origPermission = perm.info.name;
9432                        res.origPackage = bp.sourcePackage;
9433                        return;
9434                    }
9435                }
9436            }
9437
9438            // Check if installing already existing package
9439            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9440                String oldName = mSettings.mRenamedPackages.get(pkgName);
9441                if (pkg.mOriginalPackages != null
9442                        && pkg.mOriginalPackages.contains(oldName)
9443                        && mPackages.containsKey(oldName)) {
9444                    // This package is derived from an original package,
9445                    // and this device has been updating from that original
9446                    // name.  We must continue using the original name, so
9447                    // rename the new package here.
9448                    pkg.setPackageName(oldName);
9449                    pkgName = pkg.packageName;
9450                    replace = true;
9451                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
9452                            + oldName + " pkgName=" + pkgName);
9453                } else if (mPackages.containsKey(pkgName)) {
9454                    // This package, under its official name, already exists
9455                    // on the device; we should replace it.
9456                    replace = true;
9457                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
9458                }
9459            }
9460            PackageSetting ps = mSettings.mPackages.get(pkgName);
9461            if (ps != null) {
9462                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
9463                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
9464                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
9465                    systemApp = (ps.pkg.applicationInfo.flags &
9466                            ApplicationInfo.FLAG_SYSTEM) != 0;
9467                }
9468                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9469            }
9470        }
9471
9472        if (systemApp && onSd) {
9473            // Disable updates to system apps on sdcard
9474            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
9475            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9476            return;
9477        }
9478
9479        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
9480            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9481            return;
9482        }
9483        // Set application objects path explicitly after the rename
9484        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
9485        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
9486        if (replace) {
9487            replacePackageLI(pkg, parseFlags, scanMode, args.user,
9488                    installerPackageName, res);
9489        } else {
9490            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
9491                    installerPackageName, res);
9492        }
9493        synchronized (mPackages) {
9494            final PackageSetting ps = mSettings.mPackages.get(pkgName);
9495            if (ps != null) {
9496                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
9497            }
9498        }
9499    }
9500
9501    private static boolean isForwardLocked(PackageParser.Package pkg) {
9502        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9503    }
9504
9505
9506    private boolean isForwardLocked(PackageSetting ps) {
9507        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
9508    }
9509
9510    private static boolean isExternal(PackageParser.Package pkg) {
9511        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9512    }
9513
9514    private static boolean isExternal(PackageSetting ps) {
9515        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
9516    }
9517
9518    private static boolean isSystemApp(PackageParser.Package pkg) {
9519        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9520    }
9521
9522    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
9523        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
9524    }
9525
9526    private static boolean isSystemApp(ApplicationInfo info) {
9527        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9528    }
9529
9530    private static boolean isSystemApp(PackageSetting ps) {
9531        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
9532    }
9533
9534    private static boolean isUpdatedSystemApp(PackageSetting ps) {
9535        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9536    }
9537
9538    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
9539        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
9540    }
9541
9542    private int packageFlagsToInstallFlags(PackageSetting ps) {
9543        int installFlags = 0;
9544        if (isExternal(ps)) {
9545            installFlags |= PackageManager.INSTALL_EXTERNAL;
9546        }
9547        if (isForwardLocked(ps)) {
9548            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9549        }
9550        return installFlags;
9551    }
9552
9553    private void deleteTempPackageFiles() {
9554        final FilenameFilter filter = new FilenameFilter() {
9555            public boolean accept(File dir, String name) {
9556                return name.startsWith("vmdl") && name.endsWith(".tmp");
9557            }
9558        };
9559        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
9560        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
9561    }
9562
9563    private static final void deleteTempPackageFilesInDirectory(File directory,
9564            FilenameFilter filter) {
9565        final String[] tmpFilesList = directory.list(filter);
9566        if (tmpFilesList == null) {
9567            return;
9568        }
9569        for (int i = 0; i < tmpFilesList.length; i++) {
9570            final File tmpFile = new File(directory, tmpFilesList[i]);
9571            tmpFile.delete();
9572        }
9573    }
9574
9575    private File createTempPackageFile(File installDir) {
9576        File tmpPackageFile;
9577        try {
9578            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
9579        } catch (IOException e) {
9580            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
9581            return null;
9582        }
9583        try {
9584            FileUtils.setPermissions(
9585                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
9586                    -1, -1);
9587            if (!SELinux.restorecon(tmpPackageFile)) {
9588                return null;
9589            }
9590        } catch (IOException e) {
9591            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
9592            return null;
9593        }
9594        return tmpPackageFile;
9595    }
9596
9597    @Override
9598    public void deletePackageAsUser(final String packageName,
9599                                    final IPackageDeleteObserver observer,
9600                                    final int userId, final int flags) {
9601        mContext.enforceCallingOrSelfPermission(
9602                android.Manifest.permission.DELETE_PACKAGES, null);
9603        final int uid = Binder.getCallingUid();
9604        if (UserHandle.getUserId(uid) != userId) {
9605            mContext.enforceCallingPermission(
9606                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9607                    "deletePackage for user " + userId);
9608        }
9609        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
9610            try {
9611                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
9612            } catch (RemoteException re) {
9613            }
9614            return;
9615        }
9616
9617        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
9618        // Queue up an async operation since the package deletion may take a little while.
9619        mHandler.post(new Runnable() {
9620            public void run() {
9621                mHandler.removeCallbacks(this);
9622                final int returnCode = deletePackageX(packageName, userId, flags);
9623                if (observer != null) {
9624                    try {
9625                        observer.packageDeleted(packageName, returnCode);
9626                    } catch (RemoteException e) {
9627                        Log.i(TAG, "Observer no longer exists.");
9628                    } //end catch
9629                } //end if
9630            } //end run
9631        });
9632    }
9633
9634    private boolean isPackageDeviceAdmin(String packageName, int userId) {
9635        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
9636                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
9637        try {
9638            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
9639                    || dpm.isDeviceOwner(packageName))) {
9640                return true;
9641            }
9642        } catch (RemoteException e) {
9643        }
9644        return false;
9645    }
9646
9647    /**
9648     *  This method is an internal method that could be get invoked either
9649     *  to delete an installed package or to clean up a failed installation.
9650     *  After deleting an installed package, a broadcast is sent to notify any
9651     *  listeners that the package has been installed. For cleaning up a failed
9652     *  installation, the broadcast is not necessary since the package's
9653     *  installation wouldn't have sent the initial broadcast either
9654     *  The key steps in deleting a package are
9655     *  deleting the package information in internal structures like mPackages,
9656     *  deleting the packages base directories through installd
9657     *  updating mSettings to reflect current status
9658     *  persisting settings for later use
9659     *  sending a broadcast if necessary
9660     */
9661    private int deletePackageX(String packageName, int userId, int flags) {
9662        final PackageRemovedInfo info = new PackageRemovedInfo();
9663        final boolean res;
9664
9665        if (isPackageDeviceAdmin(packageName, userId)) {
9666            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
9667            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
9668        }
9669
9670        boolean removedForAllUsers = false;
9671        boolean systemUpdate = false;
9672
9673        // for the uninstall-updates case and restricted profiles, remember the per-
9674        // userhandle installed state
9675        int[] allUsers;
9676        boolean[] perUserInstalled;
9677        synchronized (mPackages) {
9678            PackageSetting ps = mSettings.mPackages.get(packageName);
9679            allUsers = sUserManager.getUserIds();
9680            perUserInstalled = new boolean[allUsers.length];
9681            for (int i = 0; i < allUsers.length; i++) {
9682                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9683            }
9684        }
9685
9686        synchronized (mInstallLock) {
9687            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
9688            res = deletePackageLI(packageName,
9689                    (flags & PackageManager.DELETE_ALL_USERS) != 0
9690                            ? UserHandle.ALL : new UserHandle(userId),
9691                    true, allUsers, perUserInstalled,
9692                    flags | REMOVE_CHATTY, info, true);
9693            systemUpdate = info.isRemovedPackageSystemUpdate;
9694            if (res && !systemUpdate && mPackages.get(packageName) == null) {
9695                removedForAllUsers = true;
9696            }
9697            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
9698                    + " removedForAllUsers=" + removedForAllUsers);
9699        }
9700
9701        if (res) {
9702            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
9703
9704            // If the removed package was a system update, the old system package
9705            // was re-enabled; we need to broadcast this information
9706            if (systemUpdate) {
9707                Bundle extras = new Bundle(1);
9708                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
9709                        ? info.removedAppId : info.uid);
9710                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9711
9712                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
9713                        extras, null, null, null);
9714                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
9715                        extras, null, null, null);
9716                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
9717                        null, packageName, null, null);
9718            }
9719        }
9720        // Force a gc here.
9721        Runtime.getRuntime().gc();
9722        // Delete the resources here after sending the broadcast to let
9723        // other processes clean up before deleting resources.
9724        if (info.args != null) {
9725            synchronized (mInstallLock) {
9726                info.args.doPostDeleteLI(true);
9727            }
9728        }
9729
9730        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
9731    }
9732
9733    static class PackageRemovedInfo {
9734        String removedPackage;
9735        int uid = -1;
9736        int removedAppId = -1;
9737        int[] removedUsers = null;
9738        boolean isRemovedPackageSystemUpdate = false;
9739        // Clean up resources deleted packages.
9740        InstallArgs args = null;
9741
9742        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
9743            Bundle extras = new Bundle(1);
9744            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
9745            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
9746            if (replacing) {
9747                extras.putBoolean(Intent.EXTRA_REPLACING, true);
9748            }
9749            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
9750            if (removedPackage != null) {
9751                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
9752                        extras, null, null, removedUsers);
9753                if (fullRemove && !replacing) {
9754                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
9755                            extras, null, null, removedUsers);
9756                }
9757            }
9758            if (removedAppId >= 0) {
9759                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
9760                        removedUsers);
9761            }
9762        }
9763    }
9764
9765    /*
9766     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
9767     * flag is not set, the data directory is removed as well.
9768     * make sure this flag is set for partially installed apps. If not its meaningless to
9769     * delete a partially installed application.
9770     */
9771    private void removePackageDataLI(PackageSetting ps,
9772            int[] allUserHandles, boolean[] perUserInstalled,
9773            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
9774        String packageName = ps.name;
9775        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
9776        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
9777        // Retrieve object to delete permissions for shared user later on
9778        final PackageSetting deletedPs;
9779        // reader
9780        synchronized (mPackages) {
9781            deletedPs = mSettings.mPackages.get(packageName);
9782            if (outInfo != null) {
9783                outInfo.removedPackage = packageName;
9784                outInfo.removedUsers = deletedPs != null
9785                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
9786                        : null;
9787            }
9788        }
9789        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9790            removeDataDirsLI(packageName);
9791            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
9792        }
9793        // writer
9794        synchronized (mPackages) {
9795            if (deletedPs != null) {
9796                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
9797                    if (outInfo != null) {
9798                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
9799                    }
9800                    if (deletedPs != null) {
9801                        updatePermissionsLPw(deletedPs.name, null, 0);
9802                        if (deletedPs.sharedUser != null) {
9803                            // remove permissions associated with package
9804                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
9805                        }
9806                    }
9807                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
9808                }
9809                // make sure to preserve per-user disabled state if this removal was just
9810                // a downgrade of a system app to the factory package
9811                if (allUserHandles != null && perUserInstalled != null) {
9812                    if (DEBUG_REMOVE) {
9813                        Slog.d(TAG, "Propagating install state across downgrade");
9814                    }
9815                    for (int i = 0; i < allUserHandles.length; i++) {
9816                        if (DEBUG_REMOVE) {
9817                            Slog.d(TAG, "    user " + allUserHandles[i]
9818                                    + " => " + perUserInstalled[i]);
9819                        }
9820                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9821                    }
9822                }
9823            }
9824            // can downgrade to reader
9825            if (writeSettings) {
9826                // Save settings now
9827                mSettings.writeLPr();
9828            }
9829        }
9830        if (outInfo != null) {
9831            // A user ID was deleted here. Go through all users and remove it
9832            // from KeyStore.
9833            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
9834        }
9835    }
9836
9837    static boolean locationIsPrivileged(File path) {
9838        try {
9839            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
9840                    .getCanonicalPath();
9841            return path.getCanonicalPath().startsWith(privilegedAppDir);
9842        } catch (IOException e) {
9843            Slog.e(TAG, "Unable to access code path " + path);
9844        }
9845        return false;
9846    }
9847
9848    /*
9849     * Tries to delete system package.
9850     */
9851    private boolean deleteSystemPackageLI(PackageSetting newPs,
9852            int[] allUserHandles, boolean[] perUserInstalled,
9853            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
9854        final boolean applyUserRestrictions
9855                = (allUserHandles != null) && (perUserInstalled != null);
9856        PackageSetting disabledPs = null;
9857        // Confirm if the system package has been updated
9858        // An updated system app can be deleted. This will also have to restore
9859        // the system pkg from system partition
9860        // reader
9861        synchronized (mPackages) {
9862            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
9863        }
9864        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
9865                + " disabledPs=" + disabledPs);
9866        if (disabledPs == null) {
9867            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
9868            return false;
9869        } else if (DEBUG_REMOVE) {
9870            Slog.d(TAG, "Deleting system pkg from data partition");
9871        }
9872        if (DEBUG_REMOVE) {
9873            if (applyUserRestrictions) {
9874                Slog.d(TAG, "Remembering install states:");
9875                for (int i = 0; i < allUserHandles.length; i++) {
9876                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
9877                }
9878            }
9879        }
9880        // Delete the updated package
9881        outInfo.isRemovedPackageSystemUpdate = true;
9882        if (disabledPs.versionCode < newPs.versionCode) {
9883            // Delete data for downgrades
9884            flags &= ~PackageManager.DELETE_KEEP_DATA;
9885        } else {
9886            // Preserve data by setting flag
9887            flags |= PackageManager.DELETE_KEEP_DATA;
9888        }
9889        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
9890                allUserHandles, perUserInstalled, outInfo, writeSettings);
9891        if (!ret) {
9892            return false;
9893        }
9894        // writer
9895        synchronized (mPackages) {
9896            // Reinstate the old system package
9897            mSettings.enableSystemPackageLPw(newPs.name);
9898            // Remove any native libraries from the upgraded package.
9899            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
9900        }
9901        // Install the system package
9902        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
9903        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
9904        if (locationIsPrivileged(disabledPs.codePath)) {
9905            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9906        }
9907        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
9908                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
9909
9910        if (newPkg == null) {
9911            Slog.w(TAG, "Failed to restore system package:" + newPs.name
9912                    + " with error:" + mLastScanError);
9913            return false;
9914        }
9915        // writer
9916        synchronized (mPackages) {
9917            updatePermissionsLPw(newPkg.packageName, newPkg,
9918                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
9919            if (applyUserRestrictions) {
9920                if (DEBUG_REMOVE) {
9921                    Slog.d(TAG, "Propagating install state across reinstall");
9922                }
9923                PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
9924                for (int i = 0; i < allUserHandles.length; i++) {
9925                    if (DEBUG_REMOVE) {
9926                        Slog.d(TAG, "    user " + allUserHandles[i]
9927                                + " => " + perUserInstalled[i]);
9928                    }
9929                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
9930                }
9931                // Regardless of writeSettings we need to ensure that this restriction
9932                // state propagation is persisted
9933                mSettings.writeAllUsersPackageRestrictionsLPr();
9934            }
9935            // can downgrade to reader here
9936            if (writeSettings) {
9937                mSettings.writeLPr();
9938            }
9939        }
9940        return true;
9941    }
9942
9943    private boolean deleteInstalledPackageLI(PackageSetting ps,
9944            boolean deleteCodeAndResources, int flags,
9945            int[] allUserHandles, boolean[] perUserInstalled,
9946            PackageRemovedInfo outInfo, boolean writeSettings) {
9947        if (outInfo != null) {
9948            outInfo.uid = ps.appId;
9949        }
9950
9951        // Delete package data from internal structures and also remove data if flag is set
9952        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
9953
9954        // Delete application code and resources
9955        if (deleteCodeAndResources && (outInfo != null)) {
9956            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
9957                    ps.resourcePathString, ps.nativeLibraryPathString);
9958        }
9959        return true;
9960    }
9961
9962    /*
9963     * This method handles package deletion in general
9964     */
9965    private boolean deletePackageLI(String packageName, UserHandle user,
9966            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
9967            int flags, PackageRemovedInfo outInfo,
9968            boolean writeSettings) {
9969        if (packageName == null) {
9970            Slog.w(TAG, "Attempt to delete null packageName.");
9971            return false;
9972        }
9973        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
9974        PackageSetting ps;
9975        boolean dataOnly = false;
9976        int removeUser = -1;
9977        int appId = -1;
9978        synchronized (mPackages) {
9979            ps = mSettings.mPackages.get(packageName);
9980            if (ps == null) {
9981                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
9982                return false;
9983            }
9984            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
9985                    && user.getIdentifier() != UserHandle.USER_ALL) {
9986                // The caller is asking that the package only be deleted for a single
9987                // user.  To do this, we just mark its uninstalled state and delete
9988                // its data.  If this is a system app, we only allow this to happen if
9989                // they have set the special DELETE_SYSTEM_APP which requests different
9990                // semantics than normal for uninstalling system apps.
9991                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
9992                ps.setUserState(user.getIdentifier(),
9993                        COMPONENT_ENABLED_STATE_DEFAULT,
9994                        false, //installed
9995                        true,  //stopped
9996                        true,  //notLaunched
9997                        false, //blocked
9998                        null, null, null);
9999                if (!isSystemApp(ps)) {
10000                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10001                        // Other user 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, "Still installed by other users");
10005                        removeUser = user.getIdentifier();
10006                        appId = ps.appId;
10007                        mSettings.writePackageRestrictionsLPr(removeUser);
10008                    } else {
10009                        // We need to set it back to 'installed' so the uninstall
10010                        // broadcasts will be sent correctly.
10011                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10012                        ps.setInstalled(true, user.getIdentifier());
10013                    }
10014                } else {
10015                    // This is a system app, so we assume that the
10016                    // other users still have this package installed, so all
10017                    // we need to do is clear this user's data and save that
10018                    // it is uninstalled.
10019                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10020                    removeUser = user.getIdentifier();
10021                    appId = ps.appId;
10022                    mSettings.writePackageRestrictionsLPr(removeUser);
10023                }
10024            }
10025        }
10026
10027        if (removeUser >= 0) {
10028            // From above, we determined that we are deleting this only
10029            // for a single user.  Continue the work here.
10030            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10031            if (outInfo != null) {
10032                outInfo.removedPackage = packageName;
10033                outInfo.removedAppId = appId;
10034                outInfo.removedUsers = new int[] {removeUser};
10035            }
10036            mInstaller.clearUserData(packageName, removeUser);
10037            removeKeystoreDataIfNeeded(removeUser, appId);
10038            schedulePackageCleaning(packageName, removeUser, false);
10039            return true;
10040        }
10041
10042        if (dataOnly) {
10043            // Delete application data first
10044            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10045            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10046            return true;
10047        }
10048
10049        boolean ret = false;
10050        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10051        if (isSystemApp(ps)) {
10052            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10053            // When an updated system application is deleted we delete the existing resources as well and
10054            // fall back to existing code in system partition
10055            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10056                    flags, outInfo, writeSettings);
10057        } else {
10058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10059            // Kill application pre-emptively especially for apps on sd.
10060            killApplication(packageName, ps.appId, "uninstall pkg");
10061            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10062                    allUserHandles, perUserInstalled,
10063                    outInfo, writeSettings);
10064        }
10065
10066        return ret;
10067    }
10068
10069    private final class ClearStorageConnection implements ServiceConnection {
10070        IMediaContainerService mContainerService;
10071
10072        @Override
10073        public void onServiceConnected(ComponentName name, IBinder service) {
10074            synchronized (this) {
10075                mContainerService = IMediaContainerService.Stub.asInterface(service);
10076                notifyAll();
10077            }
10078        }
10079
10080        @Override
10081        public void onServiceDisconnected(ComponentName name) {
10082        }
10083    }
10084
10085    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10086        final boolean mounted;
10087        if (Environment.isExternalStorageEmulated()) {
10088            mounted = true;
10089        } else {
10090            final String status = Environment.getExternalStorageState();
10091
10092            mounted = status.equals(Environment.MEDIA_MOUNTED)
10093                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10094        }
10095
10096        if (!mounted) {
10097            return;
10098        }
10099
10100        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10101        int[] users;
10102        if (userId == UserHandle.USER_ALL) {
10103            users = sUserManager.getUserIds();
10104        } else {
10105            users = new int[] { userId };
10106        }
10107        final ClearStorageConnection conn = new ClearStorageConnection();
10108        if (mContext.bindServiceAsUser(
10109                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10110            try {
10111                for (int curUser : users) {
10112                    long timeout = SystemClock.uptimeMillis() + 5000;
10113                    synchronized (conn) {
10114                        long now = SystemClock.uptimeMillis();
10115                        while (conn.mContainerService == null && now < timeout) {
10116                            try {
10117                                conn.wait(timeout - now);
10118                            } catch (InterruptedException e) {
10119                            }
10120                        }
10121                    }
10122                    if (conn.mContainerService == null) {
10123                        return;
10124                    }
10125
10126                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10127                    clearDirectory(conn.mContainerService,
10128                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10129                    if (allData) {
10130                        clearDirectory(conn.mContainerService,
10131                                userEnv.buildExternalStorageAppDataDirs(packageName));
10132                        clearDirectory(conn.mContainerService,
10133                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10134                    }
10135                }
10136            } finally {
10137                mContext.unbindService(conn);
10138            }
10139        }
10140    }
10141
10142    @Override
10143    public void clearApplicationUserData(final String packageName,
10144            final IPackageDataObserver observer, final int userId) {
10145        mContext.enforceCallingOrSelfPermission(
10146                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10147        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10148        // Queue up an async operation since the package deletion may take a little while.
10149        mHandler.post(new Runnable() {
10150            public void run() {
10151                mHandler.removeCallbacks(this);
10152                final boolean succeeded;
10153                synchronized (mInstallLock) {
10154                    succeeded = clearApplicationUserDataLI(packageName, userId);
10155                }
10156                clearExternalStorageDataSync(packageName, userId, true);
10157                if (succeeded) {
10158                    // invoke DeviceStorageMonitor's update method to clear any notifications
10159                    DeviceStorageMonitorInternal
10160                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10161                    if (dsm != null) {
10162                        dsm.checkMemory();
10163                    }
10164                }
10165                if(observer != null) {
10166                    try {
10167                        observer.onRemoveCompleted(packageName, succeeded);
10168                    } catch (RemoteException e) {
10169                        Log.i(TAG, "Observer no longer exists.");
10170                    }
10171                } //end if observer
10172            } //end run
10173        });
10174    }
10175
10176    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10177        if (packageName == null) {
10178            Slog.w(TAG, "Attempt to delete null packageName.");
10179            return false;
10180        }
10181        PackageParser.Package p;
10182        boolean dataOnly = false;
10183        final int appId;
10184        synchronized (mPackages) {
10185            p = mPackages.get(packageName);
10186            if (p == null) {
10187                dataOnly = true;
10188                PackageSetting ps = mSettings.mPackages.get(packageName);
10189                if ((ps == null) || (ps.pkg == null)) {
10190                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10191                    return false;
10192                }
10193                p = ps.pkg;
10194            }
10195            if (!dataOnly) {
10196                // need to check this only for fully installed applications
10197                if (p == null) {
10198                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10199                    return false;
10200                }
10201                final ApplicationInfo applicationInfo = p.applicationInfo;
10202                if (applicationInfo == null) {
10203                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10204                    return false;
10205                }
10206            }
10207            if (p != null && p.applicationInfo != null) {
10208                appId = p.applicationInfo.uid;
10209            } else {
10210                appId = -1;
10211            }
10212        }
10213        int retCode = mInstaller.clearUserData(packageName, userId);
10214        if (retCode < 0) {
10215            Slog.w(TAG, "Couldn't remove cache files for package: "
10216                    + packageName);
10217            return false;
10218        }
10219        removeKeystoreDataIfNeeded(userId, appId);
10220        return true;
10221    }
10222
10223    /**
10224     * Remove entries from the keystore daemon. Will only remove it if the
10225     * {@code appId} is valid.
10226     */
10227    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10228        if (appId < 0) {
10229            return;
10230        }
10231
10232        final KeyStore keyStore = KeyStore.getInstance();
10233        if (keyStore != null) {
10234            if (userId == UserHandle.USER_ALL) {
10235                for (final int individual : sUserManager.getUserIds()) {
10236                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10237                }
10238            } else {
10239                keyStore.clearUid(UserHandle.getUid(userId, appId));
10240            }
10241        } else {
10242            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10243        }
10244    }
10245
10246    public void deleteApplicationCacheFiles(final String packageName,
10247            final IPackageDataObserver observer) {
10248        mContext.enforceCallingOrSelfPermission(
10249                android.Manifest.permission.DELETE_CACHE_FILES, null);
10250        // Queue up an async operation since the package deletion may take a little while.
10251        final int userId = UserHandle.getCallingUserId();
10252        mHandler.post(new Runnable() {
10253            public void run() {
10254                mHandler.removeCallbacks(this);
10255                final boolean succeded;
10256                synchronized (mInstallLock) {
10257                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10258                }
10259                clearExternalStorageDataSync(packageName, userId, false);
10260                if(observer != null) {
10261                    try {
10262                        observer.onRemoveCompleted(packageName, succeded);
10263                    } catch (RemoteException e) {
10264                        Log.i(TAG, "Observer no longer exists.");
10265                    }
10266                } //end if observer
10267            } //end run
10268        });
10269    }
10270
10271    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10272        if (packageName == null) {
10273            Slog.w(TAG, "Attempt to delete null packageName.");
10274            return false;
10275        }
10276        PackageParser.Package p;
10277        synchronized (mPackages) {
10278            p = mPackages.get(packageName);
10279        }
10280        if (p == null) {
10281            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10282            return false;
10283        }
10284        final ApplicationInfo applicationInfo = p.applicationInfo;
10285        if (applicationInfo == null) {
10286            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10287            return false;
10288        }
10289        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10290        if (retCode < 0) {
10291            Slog.w(TAG, "Couldn't remove cache files for package: "
10292                       + packageName + " u" + userId);
10293            return false;
10294        }
10295        return true;
10296    }
10297
10298    public void getPackageSizeInfo(final String packageName, int userHandle,
10299            final IPackageStatsObserver observer) {
10300        mContext.enforceCallingOrSelfPermission(
10301                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10302        if (packageName == null) {
10303            throw new IllegalArgumentException("Attempt to get size of null packageName");
10304        }
10305
10306        PackageStats stats = new PackageStats(packageName, userHandle);
10307
10308        /*
10309         * Queue up an async operation since the package measurement may take a
10310         * little while.
10311         */
10312        Message msg = mHandler.obtainMessage(INIT_COPY);
10313        msg.obj = new MeasureParams(stats, observer);
10314        mHandler.sendMessage(msg);
10315    }
10316
10317    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10318            PackageStats pStats) {
10319        if (packageName == null) {
10320            Slog.w(TAG, "Attempt to get size of null packageName.");
10321            return false;
10322        }
10323        PackageParser.Package p;
10324        boolean dataOnly = false;
10325        String libDirPath = null;
10326        String asecPath = null;
10327        synchronized (mPackages) {
10328            p = mPackages.get(packageName);
10329            PackageSetting ps = mSettings.mPackages.get(packageName);
10330            if(p == null) {
10331                dataOnly = true;
10332                if((ps == null) || (ps.pkg == null)) {
10333                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10334                    return false;
10335                }
10336                p = ps.pkg;
10337            }
10338            if (ps != null) {
10339                libDirPath = ps.nativeLibraryPathString;
10340            }
10341            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10342                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10343                if (secureContainerId != null) {
10344                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10345                }
10346            }
10347        }
10348        String publicSrcDir = null;
10349        if(!dataOnly) {
10350            final ApplicationInfo applicationInfo = p.applicationInfo;
10351            if (applicationInfo == null) {
10352                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10353                return false;
10354            }
10355            if (isForwardLocked(p)) {
10356                publicSrcDir = applicationInfo.publicSourceDir;
10357            }
10358        }
10359        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10360                publicSrcDir, asecPath, pStats);
10361        if (res < 0) {
10362            return false;
10363        }
10364
10365        // Fix-up for forward-locked applications in ASEC containers.
10366        if (!isExternal(p)) {
10367            pStats.codeSize += pStats.externalCodeSize;
10368            pStats.externalCodeSize = 0L;
10369        }
10370
10371        return true;
10372    }
10373
10374
10375    public void addPackageToPreferred(String packageName) {
10376        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
10377    }
10378
10379    public void removePackageFromPreferred(String packageName) {
10380        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
10381    }
10382
10383    public List<PackageInfo> getPreferredPackages(int flags) {
10384        return new ArrayList<PackageInfo>();
10385    }
10386
10387    private int getUidTargetSdkVersionLockedLPr(int uid) {
10388        Object obj = mSettings.getUserIdLPr(uid);
10389        if (obj instanceof SharedUserSetting) {
10390            final SharedUserSetting sus = (SharedUserSetting) obj;
10391            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
10392            final Iterator<PackageSetting> it = sus.packages.iterator();
10393            while (it.hasNext()) {
10394                final PackageSetting ps = it.next();
10395                if (ps.pkg != null) {
10396                    int v = ps.pkg.applicationInfo.targetSdkVersion;
10397                    if (v < vers) vers = v;
10398                }
10399            }
10400            return vers;
10401        } else if (obj instanceof PackageSetting) {
10402            final PackageSetting ps = (PackageSetting) obj;
10403            if (ps.pkg != null) {
10404                return ps.pkg.applicationInfo.targetSdkVersion;
10405            }
10406        }
10407        return Build.VERSION_CODES.CUR_DEVELOPMENT;
10408    }
10409
10410    public void addPreferredActivity(IntentFilter filter, int match,
10411            ComponentName[] set, ComponentName activity, int userId) {
10412        addPreferredActivityInternal(filter, match, set, activity, true, userId);
10413    }
10414
10415    private void addPreferredActivityInternal(IntentFilter filter, int match,
10416            ComponentName[] set, ComponentName activity, boolean always, int userId) {
10417        // writer
10418        int callingUid = Binder.getCallingUid();
10419        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
10420        if (filter.countActions() == 0) {
10421            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10422            return;
10423        }
10424        synchronized (mPackages) {
10425            if (mContext.checkCallingOrSelfPermission(
10426                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10427                    != PackageManager.PERMISSION_GRANTED) {
10428                if (getUidTargetSdkVersionLockedLPr(callingUid)
10429                        < Build.VERSION_CODES.FROYO) {
10430                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
10431                            + callingUid);
10432                    return;
10433                }
10434                mContext.enforceCallingOrSelfPermission(
10435                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10436            }
10437
10438            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
10439            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10440            mSettings.editPreferredActivitiesLPw(userId).addFilter(
10441                    new PreferredActivity(filter, match, set, activity, always));
10442            mSettings.writePackageRestrictionsLPr(userId);
10443        }
10444    }
10445
10446    public void replacePreferredActivity(IntentFilter filter, int match,
10447            ComponentName[] set, ComponentName activity) {
10448        if (filter.countActions() != 1) {
10449            throw new IllegalArgumentException(
10450                    "replacePreferredActivity expects filter to have only 1 action.");
10451        }
10452        if (filter.countDataAuthorities() != 0
10453                || filter.countDataPaths() != 0
10454                || filter.countDataSchemes() > 1
10455                || filter.countDataTypes() != 0) {
10456            throw new IllegalArgumentException(
10457                    "replacePreferredActivity expects filter to have no data authorities, " +
10458                    "paths, or types; and at most one scheme.");
10459        }
10460        synchronized (mPackages) {
10461            if (mContext.checkCallingOrSelfPermission(
10462                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10463                    != PackageManager.PERMISSION_GRANTED) {
10464                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10465                        < Build.VERSION_CODES.FROYO) {
10466                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
10467                            + Binder.getCallingUid());
10468                    return;
10469                }
10470                mContext.enforceCallingOrSelfPermission(
10471                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10472            }
10473
10474            final int callingUserId = UserHandle.getCallingUserId();
10475            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
10476            if (pir != null) {
10477                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
10478                if (filter.countDataSchemes() == 1) {
10479                    Uri.Builder builder = new Uri.Builder();
10480                    builder.scheme(filter.getDataScheme(0));
10481                    intent.setData(builder.build());
10482                }
10483                List<PreferredActivity> matches = pir.queryIntent(
10484                        intent, null, true, callingUserId);
10485                if (DEBUG_PREFERRED) {
10486                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
10487                }
10488                for (int i = 0; i < matches.size(); i++) {
10489                    PreferredActivity pa = matches.get(i);
10490                    if (DEBUG_PREFERRED) {
10491                        Slog.i(TAG, "Removing preferred activity "
10492                                + pa.mPref.mComponent + ":");
10493                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10494                    }
10495                    pir.removeFilter(pa);
10496                }
10497            }
10498            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
10499        }
10500    }
10501
10502    public void clearPackagePreferredActivities(String packageName) {
10503        final int uid = Binder.getCallingUid();
10504        // writer
10505        synchronized (mPackages) {
10506            PackageParser.Package pkg = mPackages.get(packageName);
10507            if (pkg == null || pkg.applicationInfo.uid != uid) {
10508                if (mContext.checkCallingOrSelfPermission(
10509                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
10510                        != PackageManager.PERMISSION_GRANTED) {
10511                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
10512                            < Build.VERSION_CODES.FROYO) {
10513                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
10514                                + Binder.getCallingUid());
10515                        return;
10516                    }
10517                    mContext.enforceCallingOrSelfPermission(
10518                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10519                }
10520            }
10521
10522            int user = UserHandle.getCallingUserId();
10523            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
10524                mSettings.writePackageRestrictionsLPr(user);
10525                scheduleWriteSettingsLocked();
10526            }
10527        }
10528    }
10529
10530    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
10531    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
10532        ArrayList<PreferredActivity> removed = null;
10533        boolean changed = false;
10534        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10535            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
10536            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10537            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
10538                continue;
10539            }
10540            Iterator<PreferredActivity> it = pir.filterIterator();
10541            while (it.hasNext()) {
10542                PreferredActivity pa = it.next();
10543                // Mark entry for removal only if it matches the package name
10544                // and the entry is of type "always".
10545                if (packageName == null ||
10546                        (pa.mPref.mComponent.getPackageName().equals(packageName)
10547                                && pa.mPref.mAlways)) {
10548                    if (removed == null) {
10549                        removed = new ArrayList<PreferredActivity>();
10550                    }
10551                    removed.add(pa);
10552                }
10553            }
10554            if (removed != null) {
10555                for (int j=0; j<removed.size(); j++) {
10556                    PreferredActivity pa = removed.get(j);
10557                    pir.removeFilter(pa);
10558                }
10559                changed = true;
10560            }
10561        }
10562        return changed;
10563    }
10564
10565    public void resetPreferredActivities(int userId) {
10566        mContext.enforceCallingOrSelfPermission(
10567                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10568        // writer
10569        synchronized (mPackages) {
10570            int user = UserHandle.getCallingUserId();
10571            clearPackagePreferredActivitiesLPw(null, user);
10572            mSettings.readDefaultPreferredAppsLPw(this, user);
10573            mSettings.writePackageRestrictionsLPr(user);
10574            scheduleWriteSettingsLocked();
10575        }
10576    }
10577
10578    public int getPreferredActivities(List<IntentFilter> outFilters,
10579            List<ComponentName> outActivities, String packageName) {
10580
10581        int num = 0;
10582        final int userId = UserHandle.getCallingUserId();
10583        // reader
10584        synchronized (mPackages) {
10585            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
10586            if (pir != null) {
10587                final Iterator<PreferredActivity> it = pir.filterIterator();
10588                while (it.hasNext()) {
10589                    final PreferredActivity pa = it.next();
10590                    if (packageName == null
10591                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
10592                                    && pa.mPref.mAlways)) {
10593                        if (outFilters != null) {
10594                            outFilters.add(new IntentFilter(pa));
10595                        }
10596                        if (outActivities != null) {
10597                            outActivities.add(pa.mPref.mComponent);
10598                        }
10599                    }
10600                }
10601            }
10602        }
10603
10604        return num;
10605    }
10606
10607    @Override
10608    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
10609            int userId) {
10610        int callingUid = Binder.getCallingUid();
10611        if (callingUid != Process.SYSTEM_UID) {
10612            throw new SecurityException(
10613                    "addPersistentPreferredActivity can only be run by the system");
10614        }
10615        if (filter.countActions() == 0) {
10616            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
10617            return;
10618        }
10619        synchronized (mPackages) {
10620            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
10621                    " :");
10622            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
10623            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
10624                    new PersistentPreferredActivity(filter, activity));
10625            mSettings.writePackageRestrictionsLPr(userId);
10626        }
10627    }
10628
10629    @Override
10630    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
10631        int callingUid = Binder.getCallingUid();
10632        if (callingUid != Process.SYSTEM_UID) {
10633            throw new SecurityException(
10634                    "clearPackagePersistentPreferredActivities can only be run by the system");
10635        }
10636        ArrayList<PersistentPreferredActivity> removed = null;
10637        boolean changed = false;
10638        synchronized (mPackages) {
10639            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
10640                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
10641                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
10642                        .valueAt(i);
10643                if (userId != thisUserId) {
10644                    continue;
10645                }
10646                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
10647                while (it.hasNext()) {
10648                    PersistentPreferredActivity ppa = it.next();
10649                    // Mark entry for removal only if it matches the package name.
10650                    if (ppa.mComponent.getPackageName().equals(packageName)) {
10651                        if (removed == null) {
10652                            removed = new ArrayList<PersistentPreferredActivity>();
10653                        }
10654                        removed.add(ppa);
10655                    }
10656                }
10657                if (removed != null) {
10658                    for (int j=0; j<removed.size(); j++) {
10659                        PersistentPreferredActivity ppa = removed.get(j);
10660                        ppir.removeFilter(ppa);
10661                    }
10662                    changed = true;
10663                }
10664            }
10665
10666            if (changed) {
10667                mSettings.writePackageRestrictionsLPr(userId);
10668            }
10669        }
10670    }
10671
10672    @Override
10673    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
10674        Intent intent = new Intent(Intent.ACTION_MAIN);
10675        intent.addCategory(Intent.CATEGORY_HOME);
10676
10677        final int callingUserId = UserHandle.getCallingUserId();
10678        List<ResolveInfo> list = queryIntentActivities(intent, null,
10679                PackageManager.GET_META_DATA, callingUserId);
10680        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
10681                true, false, false, callingUserId);
10682
10683        allHomeCandidates.clear();
10684        if (list != null) {
10685            for (ResolveInfo ri : list) {
10686                allHomeCandidates.add(ri);
10687            }
10688        }
10689        return (preferred == null || preferred.activityInfo == null)
10690                ? null
10691                : new ComponentName(preferred.activityInfo.packageName,
10692                        preferred.activityInfo.name);
10693    }
10694
10695    @Override
10696    public void setApplicationEnabledSetting(String appPackageName,
10697            int newState, int flags, int userId, String callingPackage) {
10698        if (!sUserManager.exists(userId)) return;
10699        if (callingPackage == null) {
10700            callingPackage = Integer.toString(Binder.getCallingUid());
10701        }
10702        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
10703    }
10704
10705    @Override
10706    public void setComponentEnabledSetting(ComponentName componentName,
10707            int newState, int flags, int userId) {
10708        if (!sUserManager.exists(userId)) return;
10709        setEnabledSetting(componentName.getPackageName(),
10710                componentName.getClassName(), newState, flags, userId, null);
10711    }
10712
10713    private void setEnabledSetting(final String packageName, String className, int newState,
10714            final int flags, int userId, String callingPackage) {
10715        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
10716              || newState == COMPONENT_ENABLED_STATE_ENABLED
10717              || newState == COMPONENT_ENABLED_STATE_DISABLED
10718              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
10719              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
10720            throw new IllegalArgumentException("Invalid new component state: "
10721                    + newState);
10722        }
10723        PackageSetting pkgSetting;
10724        final int uid = Binder.getCallingUid();
10725        final int permission = mContext.checkCallingOrSelfPermission(
10726                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10727        enforceCrossUserPermission(uid, userId, false, "set enabled");
10728        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10729        boolean sendNow = false;
10730        boolean isApp = (className == null);
10731        String componentName = isApp ? packageName : className;
10732        int packageUid = -1;
10733        ArrayList<String> components;
10734
10735        // writer
10736        synchronized (mPackages) {
10737            pkgSetting = mSettings.mPackages.get(packageName);
10738            if (pkgSetting == null) {
10739                if (className == null) {
10740                    throw new IllegalArgumentException(
10741                            "Unknown package: " + packageName);
10742                }
10743                throw new IllegalArgumentException(
10744                        "Unknown component: " + packageName
10745                        + "/" + className);
10746            }
10747            // Allow root and verify that userId is not being specified by a different user
10748            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
10749                throw new SecurityException(
10750                        "Permission Denial: attempt to change component state from pid="
10751                        + Binder.getCallingPid()
10752                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
10753            }
10754            if (className == null) {
10755                // We're dealing with an application/package level state change
10756                if (pkgSetting.getEnabled(userId) == newState) {
10757                    // Nothing to do
10758                    return;
10759                }
10760                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
10761                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
10762                    // Don't care about who enables an app.
10763                    callingPackage = null;
10764                }
10765                pkgSetting.setEnabled(newState, userId, callingPackage);
10766                // pkgSetting.pkg.mSetEnabled = newState;
10767            } else {
10768                // We're dealing with a component level state change
10769                // First, verify that this is a valid class name.
10770                PackageParser.Package pkg = pkgSetting.pkg;
10771                if (pkg == null || !pkg.hasComponentClassName(className)) {
10772                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
10773                        throw new IllegalArgumentException("Component class " + className
10774                                + " does not exist in " + packageName);
10775                    } else {
10776                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
10777                                + className + " does not exist in " + packageName);
10778                    }
10779                }
10780                switch (newState) {
10781                case COMPONENT_ENABLED_STATE_ENABLED:
10782                    if (!pkgSetting.enableComponentLPw(className, userId)) {
10783                        return;
10784                    }
10785                    break;
10786                case COMPONENT_ENABLED_STATE_DISABLED:
10787                    if (!pkgSetting.disableComponentLPw(className, userId)) {
10788                        return;
10789                    }
10790                    break;
10791                case COMPONENT_ENABLED_STATE_DEFAULT:
10792                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
10793                        return;
10794                    }
10795                    break;
10796                default:
10797                    Slog.e(TAG, "Invalid new component state: " + newState);
10798                    return;
10799                }
10800            }
10801            mSettings.writePackageRestrictionsLPr(userId);
10802            components = mPendingBroadcasts.get(userId, packageName);
10803            final boolean newPackage = components == null;
10804            if (newPackage) {
10805                components = new ArrayList<String>();
10806            }
10807            if (!components.contains(componentName)) {
10808                components.add(componentName);
10809            }
10810            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
10811                sendNow = true;
10812                // Purge entry from pending broadcast list if another one exists already
10813                // since we are sending one right away.
10814                mPendingBroadcasts.remove(userId, packageName);
10815            } else {
10816                if (newPackage) {
10817                    mPendingBroadcasts.put(userId, packageName, components);
10818                }
10819                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
10820                    // Schedule a message
10821                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
10822                }
10823            }
10824        }
10825
10826        long callingId = Binder.clearCallingIdentity();
10827        try {
10828            if (sendNow) {
10829                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
10830                sendPackageChangedBroadcast(packageName,
10831                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
10832            }
10833        } finally {
10834            Binder.restoreCallingIdentity(callingId);
10835        }
10836    }
10837
10838    private void sendPackageChangedBroadcast(String packageName,
10839            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
10840        if (DEBUG_INSTALL)
10841            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
10842                    + componentNames);
10843        Bundle extras = new Bundle(4);
10844        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
10845        String nameList[] = new String[componentNames.size()];
10846        componentNames.toArray(nameList);
10847        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
10848        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
10849        extras.putInt(Intent.EXTRA_UID, packageUid);
10850        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
10851                new int[] {UserHandle.getUserId(packageUid)});
10852    }
10853
10854    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
10855        if (!sUserManager.exists(userId)) return;
10856        final int uid = Binder.getCallingUid();
10857        final int permission = mContext.checkCallingOrSelfPermission(
10858                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
10859        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
10860        enforceCrossUserPermission(uid, userId, true, "stop package");
10861        // writer
10862        synchronized (mPackages) {
10863            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
10864                    uid, userId)) {
10865                scheduleWritePackageRestrictionsLocked(userId);
10866            }
10867        }
10868    }
10869
10870    public String getInstallerPackageName(String packageName) {
10871        // reader
10872        synchronized (mPackages) {
10873            return mSettings.getInstallerPackageNameLPr(packageName);
10874        }
10875    }
10876
10877    @Override
10878    public int getApplicationEnabledSetting(String packageName, int userId) {
10879        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10880        int uid = Binder.getCallingUid();
10881        enforceCrossUserPermission(uid, userId, false, "get enabled");
10882        // reader
10883        synchronized (mPackages) {
10884            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
10885        }
10886    }
10887
10888    @Override
10889    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
10890        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
10891        int uid = Binder.getCallingUid();
10892        enforceCrossUserPermission(uid, userId, false, "get component enabled");
10893        // reader
10894        synchronized (mPackages) {
10895            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
10896        }
10897    }
10898
10899    public void enterSafeMode() {
10900        enforceSystemOrRoot("Only the system can request entering safe mode");
10901
10902        if (!mSystemReady) {
10903            mSafeMode = true;
10904        }
10905    }
10906
10907    public void systemReady() {
10908        mSystemReady = true;
10909
10910        // Read the compatibilty setting when the system is ready.
10911        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
10912                mContext.getContentResolver(),
10913                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
10914        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
10915        if (DEBUG_SETTINGS) {
10916            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
10917        }
10918
10919        synchronized (mPackages) {
10920            // Verify that all of the preferred activity components actually
10921            // exist.  It is possible for applications to be updated and at
10922            // that point remove a previously declared activity component that
10923            // had been set as a preferred activity.  We try to clean this up
10924            // the next time we encounter that preferred activity, but it is
10925            // possible for the user flow to never be able to return to that
10926            // situation so here we do a sanity check to make sure we haven't
10927            // left any junk around.
10928            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
10929            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
10930                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
10931                removed.clear();
10932                for (PreferredActivity pa : pir.filterSet()) {
10933                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
10934                        removed.add(pa);
10935                    }
10936                }
10937                if (removed.size() > 0) {
10938                    for (int j=0; j<removed.size(); j++) {
10939                        PreferredActivity pa = removed.get(i);
10940                        Slog.w(TAG, "Removing dangling preferred activity: "
10941                                + pa.mPref.mComponent);
10942                        pir.removeFilter(pa);
10943                    }
10944                    mSettings.writePackageRestrictionsLPr(
10945                            mSettings.mPreferredActivities.keyAt(i));
10946                }
10947            }
10948        }
10949        sUserManager.systemReady();
10950    }
10951
10952    public boolean isSafeMode() {
10953        return mSafeMode;
10954    }
10955
10956    public boolean hasSystemUidErrors() {
10957        return mHasSystemUidErrors;
10958    }
10959
10960    static String arrayToString(int[] array) {
10961        StringBuffer buf = new StringBuffer(128);
10962        buf.append('[');
10963        if (array != null) {
10964            for (int i=0; i<array.length; i++) {
10965                if (i > 0) buf.append(", ");
10966                buf.append(array[i]);
10967            }
10968        }
10969        buf.append(']');
10970        return buf.toString();
10971    }
10972
10973    static class DumpState {
10974        public static final int DUMP_LIBS = 1 << 0;
10975
10976        public static final int DUMP_FEATURES = 1 << 1;
10977
10978        public static final int DUMP_RESOLVERS = 1 << 2;
10979
10980        public static final int DUMP_PERMISSIONS = 1 << 3;
10981
10982        public static final int DUMP_PACKAGES = 1 << 4;
10983
10984        public static final int DUMP_SHARED_USERS = 1 << 5;
10985
10986        public static final int DUMP_MESSAGES = 1 << 6;
10987
10988        public static final int DUMP_PROVIDERS = 1 << 7;
10989
10990        public static final int DUMP_VERIFIERS = 1 << 8;
10991
10992        public static final int DUMP_PREFERRED = 1 << 9;
10993
10994        public static final int DUMP_PREFERRED_XML = 1 << 10;
10995
10996        public static final int DUMP_KEYSETS = 1 << 11;
10997
10998        public static final int OPTION_SHOW_FILTERS = 1 << 0;
10999
11000        private int mTypes;
11001
11002        private int mOptions;
11003
11004        private boolean mTitlePrinted;
11005
11006        private SharedUserSetting mSharedUser;
11007
11008        public boolean isDumping(int type) {
11009            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11010                return true;
11011            }
11012
11013            return (mTypes & type) != 0;
11014        }
11015
11016        public void setDump(int type) {
11017            mTypes |= type;
11018        }
11019
11020        public boolean isOptionEnabled(int option) {
11021            return (mOptions & option) != 0;
11022        }
11023
11024        public void setOptionEnabled(int option) {
11025            mOptions |= option;
11026        }
11027
11028        public boolean onTitlePrinted() {
11029            final boolean printed = mTitlePrinted;
11030            mTitlePrinted = true;
11031            return printed;
11032        }
11033
11034        public boolean getTitlePrinted() {
11035            return mTitlePrinted;
11036        }
11037
11038        public void setTitlePrinted(boolean enabled) {
11039            mTitlePrinted = enabled;
11040        }
11041
11042        public SharedUserSetting getSharedUser() {
11043            return mSharedUser;
11044        }
11045
11046        public void setSharedUser(SharedUserSetting user) {
11047            mSharedUser = user;
11048        }
11049    }
11050
11051    @Override
11052    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11053        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11054                != PackageManager.PERMISSION_GRANTED) {
11055            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11056                    + Binder.getCallingPid()
11057                    + ", uid=" + Binder.getCallingUid()
11058                    + " without permission "
11059                    + android.Manifest.permission.DUMP);
11060            return;
11061        }
11062
11063        DumpState dumpState = new DumpState();
11064        boolean fullPreferred = false;
11065        boolean checkin = false;
11066
11067        String packageName = null;
11068
11069        int opti = 0;
11070        while (opti < args.length) {
11071            String opt = args[opti];
11072            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11073                break;
11074            }
11075            opti++;
11076            if ("-a".equals(opt)) {
11077                // Right now we only know how to print all.
11078            } else if ("-h".equals(opt)) {
11079                pw.println("Package manager dump options:");
11080                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11081                pw.println("    --checkin: dump for a checkin");
11082                pw.println("    -f: print details of intent filters");
11083                pw.println("    -h: print this help");
11084                pw.println("  cmd may be one of:");
11085                pw.println("    l[ibraries]: list known shared libraries");
11086                pw.println("    f[ibraries]: list device features");
11087                pw.println("    r[esolvers]: dump intent resolvers");
11088                pw.println("    perm[issions]: dump permissions");
11089                pw.println("    pref[erred]: print preferred package settings");
11090                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11091                pw.println("    prov[iders]: dump content providers");
11092                pw.println("    p[ackages]: dump installed packages");
11093                pw.println("    s[hared-users]: dump shared user IDs");
11094                pw.println("    m[essages]: print collected runtime messages");
11095                pw.println("    v[erifiers]: print package verifier info");
11096                pw.println("    <package.name>: info about given package");
11097                pw.println("    k[eysets]: print known keysets");
11098                return;
11099            } else if ("--checkin".equals(opt)) {
11100                checkin = true;
11101            } else if ("-f".equals(opt)) {
11102                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11103            } else {
11104                pw.println("Unknown argument: " + opt + "; use -h for help");
11105            }
11106        }
11107
11108        // Is the caller requesting to dump a particular piece of data?
11109        if (opti < args.length) {
11110            String cmd = args[opti];
11111            opti++;
11112            // Is this a package name?
11113            if ("android".equals(cmd) || cmd.contains(".")) {
11114                packageName = cmd;
11115                // When dumping a single package, we always dump all of its
11116                // filter information since the amount of data will be reasonable.
11117                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11118            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11119                dumpState.setDump(DumpState.DUMP_LIBS);
11120            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11121                dumpState.setDump(DumpState.DUMP_FEATURES);
11122            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11123                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11124            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11125                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11126            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11127                dumpState.setDump(DumpState.DUMP_PREFERRED);
11128            } else if ("preferred-xml".equals(cmd)) {
11129                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11130                if (opti < args.length && "--full".equals(args[opti])) {
11131                    fullPreferred = true;
11132                    opti++;
11133                }
11134            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11135                dumpState.setDump(DumpState.DUMP_PACKAGES);
11136            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11137                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11138            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11139                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11140            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11141                dumpState.setDump(DumpState.DUMP_MESSAGES);
11142            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11143                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11144            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11145                dumpState.setDump(DumpState.DUMP_KEYSETS);
11146            }
11147        }
11148
11149        if (checkin) {
11150            pw.println("vers,1");
11151        }
11152
11153        // reader
11154        synchronized (mPackages) {
11155            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11156                if (!checkin) {
11157                    if (dumpState.onTitlePrinted())
11158                        pw.println();
11159                    pw.println("Verifiers:");
11160                    pw.print("  Required: ");
11161                    pw.print(mRequiredVerifierPackage);
11162                    pw.print(" (uid=");
11163                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11164                    pw.println(")");
11165                } else if (mRequiredVerifierPackage != null) {
11166                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11167                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11168                }
11169            }
11170
11171            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11172                boolean printedHeader = false;
11173                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11174                while (it.hasNext()) {
11175                    String name = it.next();
11176                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11177                    if (!checkin) {
11178                        if (!printedHeader) {
11179                            if (dumpState.onTitlePrinted())
11180                                pw.println();
11181                            pw.println("Libraries:");
11182                            printedHeader = true;
11183                        }
11184                        pw.print("  ");
11185                    } else {
11186                        pw.print("lib,");
11187                    }
11188                    pw.print(name);
11189                    if (!checkin) {
11190                        pw.print(" -> ");
11191                    }
11192                    if (ent.path != null) {
11193                        if (!checkin) {
11194                            pw.print("(jar) ");
11195                            pw.print(ent.path);
11196                        } else {
11197                            pw.print(",jar,");
11198                            pw.print(ent.path);
11199                        }
11200                    } else {
11201                        if (!checkin) {
11202                            pw.print("(apk) ");
11203                            pw.print(ent.apk);
11204                        } else {
11205                            pw.print(",apk,");
11206                            pw.print(ent.apk);
11207                        }
11208                    }
11209                    pw.println();
11210                }
11211            }
11212
11213            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11214                if (dumpState.onTitlePrinted())
11215                    pw.println();
11216                if (!checkin) {
11217                    pw.println("Features:");
11218                }
11219                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11220                while (it.hasNext()) {
11221                    String name = it.next();
11222                    if (!checkin) {
11223                        pw.print("  ");
11224                    } else {
11225                        pw.print("feat,");
11226                    }
11227                    pw.println(name);
11228                }
11229            }
11230
11231            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11232                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11233                        : "Activity Resolver Table:", "  ", packageName,
11234                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11235                    dumpState.setTitlePrinted(true);
11236                }
11237                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11238                        : "Receiver Resolver Table:", "  ", packageName,
11239                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11240                    dumpState.setTitlePrinted(true);
11241                }
11242                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11243                        : "Service Resolver Table:", "  ", packageName,
11244                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11245                    dumpState.setTitlePrinted(true);
11246                }
11247                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11248                        : "Provider Resolver Table:", "  ", packageName,
11249                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11250                    dumpState.setTitlePrinted(true);
11251                }
11252            }
11253
11254            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11255                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11256                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11257                    int user = mSettings.mPreferredActivities.keyAt(i);
11258                    if (pir.dump(pw,
11259                            dumpState.getTitlePrinted()
11260                                ? "\nPreferred Activities User " + user + ":"
11261                                : "Preferred Activities User " + user + ":", "  ",
11262                            packageName, true)) {
11263                        dumpState.setTitlePrinted(true);
11264                    }
11265                }
11266            }
11267
11268            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11269                pw.flush();
11270                FileOutputStream fout = new FileOutputStream(fd);
11271                BufferedOutputStream str = new BufferedOutputStream(fout);
11272                XmlSerializer serializer = new FastXmlSerializer();
11273                try {
11274                    serializer.setOutput(str, "utf-8");
11275                    serializer.startDocument(null, true);
11276                    serializer.setFeature(
11277                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11278                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11279                    serializer.endDocument();
11280                    serializer.flush();
11281                } catch (IllegalArgumentException e) {
11282                    pw.println("Failed writing: " + e);
11283                } catch (IllegalStateException e) {
11284                    pw.println("Failed writing: " + e);
11285                } catch (IOException e) {
11286                    pw.println("Failed writing: " + e);
11287                }
11288            }
11289
11290            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11291                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11292            }
11293
11294            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11295                boolean printedSomething = false;
11296                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11297                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11298                        continue;
11299                    }
11300                    if (!printedSomething) {
11301                        if (dumpState.onTitlePrinted())
11302                            pw.println();
11303                        pw.println("Registered ContentProviders:");
11304                        printedSomething = true;
11305                    }
11306                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11307                    pw.print("    "); pw.println(p.toString());
11308                }
11309                printedSomething = false;
11310                for (Map.Entry<String, PackageParser.Provider> entry :
11311                        mProvidersByAuthority.entrySet()) {
11312                    PackageParser.Provider p = entry.getValue();
11313                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11314                        continue;
11315                    }
11316                    if (!printedSomething) {
11317                        if (dumpState.onTitlePrinted())
11318                            pw.println();
11319                        pw.println("ContentProvider Authorities:");
11320                        printedSomething = true;
11321                    }
11322                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
11323                    pw.print("    "); pw.println(p.toString());
11324                    if (p.info != null && p.info.applicationInfo != null) {
11325                        final String appInfo = p.info.applicationInfo.toString();
11326                        pw.print("      applicationInfo="); pw.println(appInfo);
11327                    }
11328                }
11329            }
11330
11331            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
11332                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
11333            }
11334
11335            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
11336                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
11337            }
11338
11339            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
11340                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
11341            }
11342
11343            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
11344                if (dumpState.onTitlePrinted())
11345                    pw.println();
11346                mSettings.dumpReadMessagesLPr(pw, dumpState);
11347
11348                pw.println();
11349                pw.println("Package warning messages:");
11350                final File fname = getSettingsProblemFile();
11351                FileInputStream in = null;
11352                try {
11353                    in = new FileInputStream(fname);
11354                    final int avail = in.available();
11355                    final byte[] data = new byte[avail];
11356                    in.read(data);
11357                    pw.print(new String(data));
11358                } catch (FileNotFoundException e) {
11359                } catch (IOException e) {
11360                } finally {
11361                    if (in != null) {
11362                        try {
11363                            in.close();
11364                        } catch (IOException e) {
11365                        }
11366                    }
11367                }
11368            }
11369        }
11370    }
11371
11372    // ------- apps on sdcard specific code -------
11373    static final boolean DEBUG_SD_INSTALL = false;
11374
11375    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
11376
11377    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
11378
11379    private boolean mMediaMounted = false;
11380
11381    private String getEncryptKey() {
11382        try {
11383            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
11384                    SD_ENCRYPTION_KEYSTORE_NAME);
11385            if (sdEncKey == null) {
11386                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
11387                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
11388                if (sdEncKey == null) {
11389                    Slog.e(TAG, "Failed to create encryption keys");
11390                    return null;
11391                }
11392            }
11393            return sdEncKey;
11394        } catch (NoSuchAlgorithmException nsae) {
11395            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
11396            return null;
11397        } catch (IOException ioe) {
11398            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
11399            return null;
11400        }
11401
11402    }
11403
11404    /* package */static String getTempContainerId() {
11405        int tmpIdx = 1;
11406        String list[] = PackageHelper.getSecureContainerList();
11407        if (list != null) {
11408            for (final String name : list) {
11409                // Ignore null and non-temporary container entries
11410                if (name == null || !name.startsWith(mTempContainerPrefix)) {
11411                    continue;
11412                }
11413
11414                String subStr = name.substring(mTempContainerPrefix.length());
11415                try {
11416                    int cid = Integer.parseInt(subStr);
11417                    if (cid >= tmpIdx) {
11418                        tmpIdx = cid + 1;
11419                    }
11420                } catch (NumberFormatException e) {
11421                }
11422            }
11423        }
11424        return mTempContainerPrefix + tmpIdx;
11425    }
11426
11427    /*
11428     * Update media status on PackageManager.
11429     */
11430    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
11431        int callingUid = Binder.getCallingUid();
11432        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11433            throw new SecurityException("Media status can only be updated by the system");
11434        }
11435        // reader; this apparently protects mMediaMounted, but should probably
11436        // be a different lock in that case.
11437        synchronized (mPackages) {
11438            Log.i(TAG, "Updating external media status from "
11439                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
11440                    + (mediaStatus ? "mounted" : "unmounted"));
11441            if (DEBUG_SD_INSTALL)
11442                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
11443                        + ", mMediaMounted=" + mMediaMounted);
11444            if (mediaStatus == mMediaMounted) {
11445                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
11446                        : 0, -1);
11447                mHandler.sendMessage(msg);
11448                return;
11449            }
11450            mMediaMounted = mediaStatus;
11451        }
11452        // Queue up an async operation since the package installation may take a
11453        // little while.
11454        mHandler.post(new Runnable() {
11455            public void run() {
11456                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
11457            }
11458        });
11459    }
11460
11461    /**
11462     * Called by MountService when the initial ASECs to scan are available.
11463     * Should block until all the ASEC containers are finished being scanned.
11464     */
11465    public void scanAvailableAsecs() {
11466        updateExternalMediaStatusInner(true, false, false);
11467        if (mShouldRestoreconData) {
11468            SELinuxMMAC.setRestoreconDone();
11469            mShouldRestoreconData = false;
11470        }
11471    }
11472
11473    /*
11474     * Collect information of applications on external media, map them against
11475     * existing containers and update information based on current mount status.
11476     * Please note that we always have to report status if reportStatus has been
11477     * set to true especially when unloading packages.
11478     */
11479    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
11480            boolean externalStorage) {
11481        // Collection of uids
11482        int uidArr[] = null;
11483        // Collection of stale containers
11484        HashSet<String> removeCids = new HashSet<String>();
11485        // Collection of packages on external media with valid containers.
11486        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
11487        // Get list of secure containers.
11488        final String list[] = PackageHelper.getSecureContainerList();
11489        if (list == null || list.length == 0) {
11490            Log.i(TAG, "No secure containers on sdcard");
11491        } else {
11492            // Process list of secure containers and categorize them
11493            // as active or stale based on their package internal state.
11494            int uidList[] = new int[list.length];
11495            int num = 0;
11496            // reader
11497            synchronized (mPackages) {
11498                for (String cid : list) {
11499                    if (DEBUG_SD_INSTALL)
11500                        Log.i(TAG, "Processing container " + cid);
11501                    String pkgName = getAsecPackageName(cid);
11502                    if (pkgName == null) {
11503                        if (DEBUG_SD_INSTALL)
11504                            Log.i(TAG, "Container : " + cid + " stale");
11505                        removeCids.add(cid);
11506                        continue;
11507                    }
11508                    if (DEBUG_SD_INSTALL)
11509                        Log.i(TAG, "Looking for pkg : " + pkgName);
11510
11511                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
11512                    if (ps == null) {
11513                        Log.i(TAG, "Deleting container with no matching settings " + cid);
11514                        removeCids.add(cid);
11515                        continue;
11516                    }
11517
11518                    /*
11519                     * Skip packages that are not external if we're unmounting
11520                     * external storage.
11521                     */
11522                    if (externalStorage && !isMounted && !isExternal(ps)) {
11523                        continue;
11524                    }
11525
11526                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
11527                    // The package status is changed only if the code path
11528                    // matches between settings and the container id.
11529                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
11530                        if (DEBUG_SD_INSTALL) {
11531                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
11532                                    + " at code path: " + ps.codePathString);
11533                        }
11534
11535                        // We do have a valid package installed on sdcard
11536                        processCids.put(args, ps.codePathString);
11537                        final int uid = ps.appId;
11538                        if (uid != -1) {
11539                            uidList[num++] = uid;
11540                        }
11541                    } else {
11542                        Log.i(TAG, "Deleting stale container for " + cid);
11543                        removeCids.add(cid);
11544                    }
11545                }
11546            }
11547
11548            if (num > 0) {
11549                // Sort uid list
11550                Arrays.sort(uidList, 0, num);
11551                // Throw away duplicates
11552                uidArr = new int[num];
11553                uidArr[0] = uidList[0];
11554                int di = 0;
11555                for (int i = 1; i < num; i++) {
11556                    if (uidList[i - 1] != uidList[i]) {
11557                        uidArr[di++] = uidList[i];
11558                    }
11559                }
11560            }
11561        }
11562        // Process packages with valid entries.
11563        if (isMounted) {
11564            if (DEBUG_SD_INSTALL)
11565                Log.i(TAG, "Loading packages");
11566            loadMediaPackages(processCids, uidArr, removeCids);
11567            startCleaningPackages();
11568        } else {
11569            if (DEBUG_SD_INSTALL)
11570                Log.i(TAG, "Unloading packages");
11571            unloadMediaPackages(processCids, uidArr, reportStatus);
11572        }
11573    }
11574
11575   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
11576           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
11577        int size = pkgList.size();
11578        if (size > 0) {
11579            // Send broadcasts here
11580            Bundle extras = new Bundle();
11581            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
11582                    .toArray(new String[size]));
11583            if (uidArr != null) {
11584                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
11585            }
11586            if (replacing) {
11587                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
11588            }
11589            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
11590                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
11591            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
11592        }
11593    }
11594
11595   /*
11596     * Look at potentially valid container ids from processCids If package
11597     * information doesn't match the one on record or package scanning fails,
11598     * the cid is added to list of removeCids. We currently don't delete stale
11599     * containers.
11600     */
11601   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11602            HashSet<String> removeCids) {
11603        ArrayList<String> pkgList = new ArrayList<String>();
11604        Set<AsecInstallArgs> keys = processCids.keySet();
11605        boolean doGc = false;
11606        for (AsecInstallArgs args : keys) {
11607            String codePath = processCids.get(args);
11608            if (DEBUG_SD_INSTALL)
11609                Log.i(TAG, "Loading container : " + args.cid);
11610            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11611            try {
11612                // Make sure there are no container errors first.
11613                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
11614                    Slog.e(TAG, "Failed to mount cid : " + args.cid
11615                            + " when installing from sdcard");
11616                    continue;
11617                }
11618                // Check code path here.
11619                if (codePath == null || !codePath.equals(args.getCodePath())) {
11620                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
11621                            + " does not match one in settings " + codePath);
11622                    continue;
11623                }
11624                // Parse package
11625                int parseFlags = mDefParseFlags;
11626                if (args.isExternal()) {
11627                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
11628                }
11629                if (args.isFwdLocked()) {
11630                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
11631                }
11632
11633                doGc = true;
11634                synchronized (mInstallLock) {
11635                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
11636                            0, 0, null);
11637                    // Scan the package
11638                    if (pkg != null) {
11639                        /*
11640                         * TODO why is the lock being held? doPostInstall is
11641                         * called in other places without the lock. This needs
11642                         * to be straightened out.
11643                         */
11644                        // writer
11645                        synchronized (mPackages) {
11646                            retCode = PackageManager.INSTALL_SUCCEEDED;
11647                            pkgList.add(pkg.packageName);
11648                            // Post process args
11649                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
11650                                    pkg.applicationInfo.uid);
11651                        }
11652                    } else {
11653                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
11654                    }
11655                }
11656
11657            } finally {
11658                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
11659                    // Don't destroy container here. Wait till gc clears things
11660                    // up.
11661                    removeCids.add(args.cid);
11662                }
11663            }
11664        }
11665        // writer
11666        synchronized (mPackages) {
11667            // If the platform SDK has changed since the last time we booted,
11668            // we need to re-grant app permission to catch any new ones that
11669            // appear. This is really a hack, and means that apps can in some
11670            // cases get permissions that the user didn't initially explicitly
11671            // allow... it would be nice to have some better way to handle
11672            // this situation.
11673            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
11674            if (regrantPermissions)
11675                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
11676                        + mSdkVersion + "; regranting permissions for external storage");
11677            mSettings.mExternalSdkPlatform = mSdkVersion;
11678
11679            // Make sure group IDs have been assigned, and any permission
11680            // changes in other apps are accounted for
11681            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
11682                    | (regrantPermissions
11683                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
11684                            : 0));
11685            // can downgrade to reader
11686            // Persist settings
11687            mSettings.writeLPr();
11688        }
11689        // Send a broadcast to let everyone know we are done processing
11690        if (pkgList.size() > 0) {
11691            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11692        }
11693        // Force gc to avoid any stale parser references that we might have.
11694        if (doGc) {
11695            Runtime.getRuntime().gc();
11696        }
11697        // List stale containers and destroy stale temporary containers.
11698        if (removeCids != null) {
11699            for (String cid : removeCids) {
11700                if (cid.startsWith(mTempContainerPrefix)) {
11701                    Log.i(TAG, "Destroying stale temporary container " + cid);
11702                    PackageHelper.destroySdDir(cid);
11703                } else {
11704                    Log.w(TAG, "Container " + cid + " is stale");
11705               }
11706           }
11707        }
11708    }
11709
11710   /*
11711     * Utility method to unload a list of specified containers
11712     */
11713    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
11714        // Just unmount all valid containers.
11715        for (AsecInstallArgs arg : cidArgs) {
11716            synchronized (mInstallLock) {
11717                arg.doPostDeleteLI(false);
11718           }
11719       }
11720   }
11721
11722    /*
11723     * Unload packages mounted on external media. This involves deleting package
11724     * data from internal structures, sending broadcasts about diabled packages,
11725     * gc'ing to free up references, unmounting all secure containers
11726     * corresponding to packages on external media, and posting a
11727     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
11728     * that we always have to post this message if status has been requested no
11729     * matter what.
11730     */
11731    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
11732            final boolean reportStatus) {
11733        if (DEBUG_SD_INSTALL)
11734            Log.i(TAG, "unloading media packages");
11735        ArrayList<String> pkgList = new ArrayList<String>();
11736        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
11737        final Set<AsecInstallArgs> keys = processCids.keySet();
11738        for (AsecInstallArgs args : keys) {
11739            String pkgName = args.getPackageName();
11740            if (DEBUG_SD_INSTALL)
11741                Log.i(TAG, "Trying to unload pkg : " + pkgName);
11742            // Delete package internally
11743            PackageRemovedInfo outInfo = new PackageRemovedInfo();
11744            synchronized (mInstallLock) {
11745                boolean res = deletePackageLI(pkgName, null, false, null, null,
11746                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
11747                if (res) {
11748                    pkgList.add(pkgName);
11749                } else {
11750                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
11751                    failedList.add(args);
11752                }
11753            }
11754        }
11755
11756        // reader
11757        synchronized (mPackages) {
11758            // We didn't update the settings after removing each package;
11759            // write them now for all packages.
11760            mSettings.writeLPr();
11761        }
11762
11763        // We have to absolutely send UPDATED_MEDIA_STATUS only
11764        // after confirming that all the receivers processed the ordered
11765        // broadcast when packages get disabled, force a gc to clean things up.
11766        // and unload all the containers.
11767        if (pkgList.size() > 0) {
11768            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
11769                    new IIntentReceiver.Stub() {
11770                public void performReceive(Intent intent, int resultCode, String data,
11771                        Bundle extras, boolean ordered, boolean sticky,
11772                        int sendingUser) throws RemoteException {
11773                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
11774                            reportStatus ? 1 : 0, 1, keys);
11775                    mHandler.sendMessage(msg);
11776                }
11777            });
11778        } else {
11779            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
11780                    keys);
11781            mHandler.sendMessage(msg);
11782        }
11783    }
11784
11785    /** Binder call */
11786    @Override
11787    public void movePackage(final String packageName, final IPackageMoveObserver observer,
11788            final int flags) {
11789        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
11790        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
11791        int returnCode = PackageManager.MOVE_SUCCEEDED;
11792        int currFlags = 0;
11793        int newFlags = 0;
11794        // reader
11795        synchronized (mPackages) {
11796            PackageParser.Package pkg = mPackages.get(packageName);
11797            if (pkg == null) {
11798                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11799            } else {
11800                // Disable moving fwd locked apps and system packages
11801                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
11802                    Slog.w(TAG, "Cannot move system application");
11803                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
11804                } else if (pkg.mOperationPending) {
11805                    Slog.w(TAG, "Attempt to move package which has pending operations");
11806                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
11807                } else {
11808                    // Find install location first
11809                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
11810                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
11811                        Slog.w(TAG, "Ambigous flags specified for move location.");
11812                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11813                    } else {
11814                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
11815                                : PackageManager.INSTALL_INTERNAL;
11816                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
11817                                : PackageManager.INSTALL_INTERNAL;
11818
11819                        if (newFlags == currFlags) {
11820                            Slog.w(TAG, "No move required. Trying to move to same location");
11821                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
11822                        } else {
11823                            if (isForwardLocked(pkg)) {
11824                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11825                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11826                            }
11827                        }
11828                    }
11829                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11830                        pkg.mOperationPending = true;
11831                    }
11832                }
11833            }
11834
11835            /*
11836             * TODO this next block probably shouldn't be inside the lock. We
11837             * can't guarantee these won't change after this is fired off
11838             * anyway.
11839             */
11840            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11841                processPendingMove(new MoveParams(null, observer, 0, packageName,
11842                        null, -1, user),
11843                        returnCode);
11844            } else {
11845                Message msg = mHandler.obtainMessage(INIT_COPY);
11846                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
11847                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
11848                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
11849                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
11850                msg.obj = mp;
11851                mHandler.sendMessage(msg);
11852            }
11853        }
11854    }
11855
11856    private void processPendingMove(final MoveParams mp, final int currentStatus) {
11857        // Queue up an async operation since the package deletion may take a
11858        // little while.
11859        mHandler.post(new Runnable() {
11860            public void run() {
11861                // TODO fix this; this does nothing.
11862                mHandler.removeCallbacks(this);
11863                int returnCode = currentStatus;
11864                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
11865                    int uidArr[] = null;
11866                    ArrayList<String> pkgList = null;
11867                    synchronized (mPackages) {
11868                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11869                        if (pkg == null) {
11870                            Slog.w(TAG, " Package " + mp.packageName
11871                                    + " doesn't exist. Aborting move");
11872                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11873                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
11874                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
11875                                    + mp.srcArgs.getCodePath() + " to "
11876                                    + pkg.applicationInfo.sourceDir
11877                                    + " Aborting move and returning error");
11878                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11879                        } else {
11880                            uidArr = new int[] {
11881                                pkg.applicationInfo.uid
11882                            };
11883                            pkgList = new ArrayList<String>();
11884                            pkgList.add(mp.packageName);
11885                        }
11886                    }
11887                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11888                        // Send resources unavailable broadcast
11889                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
11890                        // Update package code and resource paths
11891                        synchronized (mInstallLock) {
11892                            synchronized (mPackages) {
11893                                PackageParser.Package pkg = mPackages.get(mp.packageName);
11894                                // Recheck for package again.
11895                                if (pkg == null) {
11896                                    Slog.w(TAG, " Package " + mp.packageName
11897                                            + " doesn't exist. Aborting move");
11898                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
11899                                } else if (!mp.srcArgs.getCodePath().equals(
11900                                        pkg.applicationInfo.sourceDir)) {
11901                                    Slog.w(TAG, "Package " + mp.packageName
11902                                            + " code path changed from " + mp.srcArgs.getCodePath()
11903                                            + " to " + pkg.applicationInfo.sourceDir
11904                                            + " Aborting move and returning error");
11905                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
11906                                } else {
11907                                    final String oldCodePath = pkg.mPath;
11908                                    final String newCodePath = mp.targetArgs.getCodePath();
11909                                    final String newResPath = mp.targetArgs.getResourcePath();
11910                                    final String newNativePath = mp.targetArgs
11911                                            .getNativeLibraryPath();
11912
11913                                    final File newNativeDir = new File(newNativePath);
11914
11915                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
11916                                        // NOTE: We do not report any errors from the APK scan and library
11917                                        // copy at this point.
11918                                        NativeLibraryHelper.ApkHandle handle =
11919                                                new NativeLibraryHelper.ApkHandle(newCodePath);
11920                                        final int abi = NativeLibraryHelper.findSupportedAbi(
11921                                                handle, Build.SUPPORTED_ABIS);
11922                                        if (abi >= 0) {
11923                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
11924                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
11925                                        }
11926                                        handle.close();
11927                                    }
11928                                    final int[] users = sUserManager.getUserIds();
11929                                    for (int user : users) {
11930                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
11931                                                newNativePath, user) < 0) {
11932                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11933                                        }
11934                                    }
11935
11936                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11937                                        pkg.mPath = newCodePath;
11938                                        // Move dex files around
11939                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
11940                                            // Moving of dex files failed. Set
11941                                            // error code and abort move.
11942                                            pkg.mPath = pkg.mScanPath;
11943                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
11944                                        }
11945                                    }
11946
11947                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
11948                                        pkg.mScanPath = newCodePath;
11949                                        pkg.applicationInfo.sourceDir = newCodePath;
11950                                        pkg.applicationInfo.publicSourceDir = newResPath;
11951                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
11952                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
11953                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
11954                                        ps.codePathString = ps.codePath.getPath();
11955                                        ps.resourcePath = new File(
11956                                                pkg.applicationInfo.publicSourceDir);
11957                                        ps.resourcePathString = ps.resourcePath.getPath();
11958                                        ps.nativeLibraryPathString = newNativePath;
11959                                        // Set the application info flag
11960                                        // correctly.
11961                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
11962                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11963                                        } else {
11964                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
11965                                        }
11966                                        ps.setFlags(pkg.applicationInfo.flags);
11967                                        mAppDirs.remove(oldCodePath);
11968                                        mAppDirs.put(newCodePath, pkg);
11969                                        // Persist settings
11970                                        mSettings.writeLPr();
11971                                    }
11972                                }
11973                            }
11974                        }
11975                        // Send resources available broadcast
11976                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
11977                    }
11978                }
11979                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
11980                    // Clean up failed installation
11981                    if (mp.targetArgs != null) {
11982                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
11983                                -1);
11984                    }
11985                } else {
11986                    // Force a gc to clear things up.
11987                    Runtime.getRuntime().gc();
11988                    // Delete older code
11989                    synchronized (mInstallLock) {
11990                        mp.srcArgs.doPostDeleteLI(true);
11991                    }
11992                }
11993
11994                // Allow more operations on this file if we didn't fail because
11995                // an operation was already pending for this package.
11996                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
11997                    synchronized (mPackages) {
11998                        PackageParser.Package pkg = mPackages.get(mp.packageName);
11999                        if (pkg != null) {
12000                            pkg.mOperationPending = false;
12001                       }
12002                   }
12003                }
12004
12005                IPackageMoveObserver observer = mp.observer;
12006                if (observer != null) {
12007                    try {
12008                        observer.packageMoved(mp.packageName, returnCode);
12009                    } catch (RemoteException e) {
12010                        Log.i(TAG, "Observer no longer exists.");
12011                    }
12012                }
12013            }
12014        });
12015    }
12016
12017    public boolean setInstallLocation(int loc) {
12018        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12019                null);
12020        if (getInstallLocation() == loc) {
12021            return true;
12022        }
12023        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12024                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12025            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12026                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12027            return true;
12028        }
12029        return false;
12030   }
12031
12032    public int getInstallLocation() {
12033        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12034                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12035                PackageHelper.APP_INSTALL_AUTO);
12036    }
12037
12038    /** Called by UserManagerService */
12039    void cleanUpUserLILPw(int userHandle) {
12040        mDirtyUsers.remove(userHandle);
12041        mSettings.removeUserLPr(userHandle);
12042        mPendingBroadcasts.remove(userHandle);
12043        if (mInstaller != null) {
12044            // Technically, we shouldn't be doing this with the package lock
12045            // held.  However, this is very rare, and there is already so much
12046            // other disk I/O going on, that we'll let it slide for now.
12047            mInstaller.removeUserDataDirs(userHandle);
12048        }
12049    }
12050
12051    /** Called by UserManagerService */
12052    void createNewUserLILPw(int userHandle, File path) {
12053        if (mInstaller != null) {
12054            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12055        }
12056    }
12057
12058    @Override
12059    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12060        mContext.enforceCallingOrSelfPermission(
12061                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12062                "Only package verification agents can read the verifier device identity");
12063
12064        synchronized (mPackages) {
12065            return mSettings.getVerifierDeviceIdentityLPw();
12066        }
12067    }
12068
12069    @Override
12070    public void setPermissionEnforced(String permission, boolean enforced) {
12071        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12072        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12073            synchronized (mPackages) {
12074                if (mSettings.mReadExternalStorageEnforced == null
12075                        || mSettings.mReadExternalStorageEnforced != enforced) {
12076                    mSettings.mReadExternalStorageEnforced = enforced;
12077                    mSettings.writeLPr();
12078                }
12079            }
12080            // kill any non-foreground processes so we restart them and
12081            // grant/revoke the GID.
12082            final IActivityManager am = ActivityManagerNative.getDefault();
12083            if (am != null) {
12084                final long token = Binder.clearCallingIdentity();
12085                try {
12086                    am.killProcessesBelowForeground("setPermissionEnforcement");
12087                } catch (RemoteException e) {
12088                } finally {
12089                    Binder.restoreCallingIdentity(token);
12090                }
12091            }
12092        } else {
12093            throw new IllegalArgumentException("No selective enforcement for " + permission);
12094        }
12095    }
12096
12097    @Override
12098    @Deprecated
12099    public boolean isPermissionEnforced(String permission) {
12100        return true;
12101    }
12102
12103    @Override
12104    public boolean isStorageLow() {
12105        final long token = Binder.clearCallingIdentity();
12106        try {
12107            final DeviceStorageMonitorInternal
12108                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12109            if (dsm != null) {
12110                return dsm.isMemoryLow();
12111            } else {
12112                return false;
12113            }
12114        } finally {
12115            Binder.restoreCallingIdentity(token);
12116        }
12117    }
12118}
12119