PackageManagerService.java revision e5bcff624fb58b6f95be8ddff7f5b6b3bf5d19c7
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 android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static android.system.OsConstants.S_IRGRP;
52import static android.system.OsConstants.S_IROTH;
53import static android.system.OsConstants.S_IRWXU;
54import static android.system.OsConstants.S_IXGRP;
55import static android.system.OsConstants.S_IXOTH;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.util.ArrayUtils.appendInt;
59import static com.android.internal.util.ArrayUtils.removeInt;
60
61import android.util.ArrayMap;
62
63import com.android.internal.R;
64import com.android.internal.app.IMediaContainerService;
65import com.android.internal.app.ResolverActivity;
66import com.android.internal.content.NativeLibraryHelper;
67import com.android.internal.content.PackageHelper;
68import com.android.internal.os.IParcelFileDescriptorFactory;
69import com.android.internal.util.ArrayUtils;
70import com.android.internal.util.FastPrintWriter;
71import com.android.internal.util.FastXmlSerializer;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.internal.util.Preconditions;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.IActivityManager;
88import android.app.admin.IDevicePolicyManager;
89import android.app.backup.IBackupManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageInstallObserver2;
105import android.content.pm.IPackageInstaller;
106import android.content.pm.IPackageManager;
107import android.content.pm.IPackageMoveObserver;
108import android.content.pm.IPackageStatsObserver;
109import android.content.pm.InstallSessionParams;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.ManifestDigest;
112import android.content.pm.PackageCleanItem;
113import android.content.pm.PackageInfo;
114import android.content.pm.PackageInfoLite;
115import android.content.pm.PackageManager;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageParser;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.FileObserver;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Set;
205import java.util.concurrent.atomic.AtomicBoolean;
206import java.util.concurrent.atomic.AtomicLong;
207
208import dalvik.system.DexFile;
209import dalvik.system.StaleDexCacheError;
210import dalvik.system.VMRuntime;
211
212import libcore.io.IoUtils;
213
214/**
215 * Keep track of all those .apks everywhere.
216 *
217 * This is very central to the platform's security; please run the unit
218 * tests whenever making modifications here:
219 *
220mmm frameworks/base/tests/AndroidTests
221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
223 *
224 * {@hide}
225 */
226public class PackageManagerService extends IPackageManager.Stub {
227    static final String TAG = "PackageManager";
228    static final boolean DEBUG_SETTINGS = false;
229    static final boolean DEBUG_PREFERRED = false;
230    static final boolean DEBUG_UPGRADE = false;
231    private static final boolean DEBUG_INSTALL = false;
232    private static final boolean DEBUG_REMOVE = false;
233    private static final boolean DEBUG_BROADCASTS = false;
234    private static final boolean DEBUG_SHOW_INFO = false;
235    private static final boolean DEBUG_PACKAGE_INFO = false;
236    private static final boolean DEBUG_INTENT_MATCHING = false;
237    private static final boolean DEBUG_PACKAGE_SCANNING = false;
238    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
252    private static final int REMOVE_EVENTS =
253        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
254    private static final int ADD_EVENTS =
255        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
256
257    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
258    // Suffix used during package installation when copying/moving
259    // package apks to install directory.
260    private static final String INSTALL_PACKAGE_SUFFIX = "-";
261
262    static final int SCAN_MONITOR = 1<<0;
263    static final int SCAN_NO_DEX = 1<<1;
264    static final int SCAN_FORCE_DEX = 1<<2;
265    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
266    static final int SCAN_NEW_INSTALL = 1<<4;
267    static final int SCAN_NO_PATHS = 1<<5;
268    static final int SCAN_UPDATE_TIME = 1<<6;
269    static final int SCAN_DEFER_DEX = 1<<7;
270    static final int SCAN_BOOTING = 1<<8;
271    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
272    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
273
274    static final int REMOVE_CHATTY = 1<<16;
275
276    /**
277     * Timeout (in milliseconds) after which the watchdog should declare that
278     * our handler thread is wedged.  The usual default for such things is one
279     * minute but we sometimes do very lengthy I/O operations on this thread,
280     * such as installing multi-gigabyte applications, so ours needs to be longer.
281     */
282    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
283
284    /**
285     * Whether verification is enabled by default.
286     */
287    private static final boolean DEFAULT_VERIFY_ENABLE = true;
288
289    /**
290     * The default maximum time to wait for the verification agent to return in
291     * milliseconds.
292     */
293    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
294
295    /**
296     * The default response for package verification timeout.
297     *
298     * This can be either PackageManager.VERIFICATION_ALLOW or
299     * PackageManager.VERIFICATION_REJECT.
300     */
301    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
302
303    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
304
305    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
306            DEFAULT_CONTAINER_PACKAGE,
307            "com.android.defcontainer.DefaultContainerService");
308
309    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
310
311    private static final String LIB_DIR_NAME = "lib";
312    private static final String LIB64_DIR_NAME = "lib64";
313
314    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
315
316    static final String mTempContainerPrefix = "smdl2tmp";
317
318    private static String sPreferredInstructionSet;
319
320    final ServiceThread mHandlerThread;
321
322    private static final String IDMAP_PREFIX = "/data/resource-cache/";
323    private static final String IDMAP_SUFFIX = "@idmap";
324
325    final PackageHandler mHandler;
326
327    final int mSdkVersion = Build.VERSION.SDK_INT;
328
329    final Context mContext;
330    final boolean mFactoryTest;
331    final boolean mOnlyCore;
332    final DisplayMetrics mMetrics;
333    final int mDefParseFlags;
334    final String[] mSeparateProcesses;
335
336    // This is where all application persistent data goes.
337    final File mAppDataDir;
338
339    // This is where all application persistent data goes for secondary users.
340    final File mUserAppDataDir;
341
342    /** The location for ASEC container files on internal storage. */
343    final String mAsecInternalPath;
344
345    // This is the object monitoring the framework dir.
346    final FileObserver mFrameworkInstallObserver;
347
348    // This is the object monitoring the system app dir.
349    final FileObserver mSystemInstallObserver;
350
351    // This is the object monitoring the privileged system app dir.
352    final FileObserver mPrivilegedInstallObserver;
353
354    // This is the object monitoring the vendor app dir.
355    final FileObserver mVendorInstallObserver;
356
357    // This is the object monitoring the vendor overlay package dir.
358    final FileObserver mVendorOverlayInstallObserver;
359
360    // This is the object monitoring the OEM app dir.
361    final FileObserver mOemInstallObserver;
362
363    // This is the object monitoring mAppInstallDir.
364    final FileObserver mAppInstallObserver;
365
366    // This is the object monitoring mDrmAppPrivateInstallDir.
367    final FileObserver mDrmAppInstallObserver;
368
369    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
370    // LOCK HELD.  Can be called with mInstallLock held.
371    final Installer mInstaller;
372
373    /** Directory where installed third-party apps stored */
374    final File mAppInstallDir;
375
376    /**
377     * Directory to which applications installed internally have their
378     * 32 bit native libraries copied.
379     */
380    private File mAppLib32InstallDir;
381
382    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
383    // apps.
384    final File mDrmAppPrivateInstallDir;
385
386    // ----------------------------------------------------------------
387
388    // Lock for state used when installing and doing other long running
389    // operations.  Methods that must be called with this lock held have
390    // the suffix "LI".
391    final Object mInstallLock = new Object();
392
393    // These are the directories in the 3rd party applications installed dir
394    // that we have currently loaded packages from.  Keys are the application's
395    // installed zip file (absolute codePath), and values are Package.
396    final HashMap<String, PackageParser.Package> mAppDirs =
397            new HashMap<String, PackageParser.Package>();
398
399    // ----------------------------------------------------------------
400
401    // Keys are String (package name), values are Package.  This also serves
402    // as the lock for the global state.  Methods that must be called with
403    // this lock held have the prefix "LP".
404    final HashMap<String, PackageParser.Package> mPackages =
405            new HashMap<String, PackageParser.Package>();
406
407    // Tracks available target package names -> overlay package paths.
408    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
409        new HashMap<String, HashMap<String, PackageParser.Package>>();
410
411    final Settings mSettings;
412    boolean mRestoredSettings;
413
414    // System configuration read by SystemConfig.
415    final int[] mGlobalGids;
416    final SparseArray<HashSet<String>> mSystemPermissions;
417    final HashMap<String, FeatureInfo> mAvailableFeatures;
418
419    // If mac_permissions.xml was found for seinfo labeling.
420    boolean mFoundPolicyFile;
421
422    // If a recursive restorecon of /data/data/<pkg> is needed.
423    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
424
425    public static final class SharedLibraryEntry {
426        public final String path;
427        public final String apk;
428
429        SharedLibraryEntry(String _path, String _apk) {
430            path = _path;
431            apk = _apk;
432        }
433    }
434
435    // Currently known shared libraries.
436    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
437            new HashMap<String, SharedLibraryEntry>();
438
439    // All available activities, for your resolving pleasure.
440    final ActivityIntentResolver mActivities =
441            new ActivityIntentResolver();
442
443    // All available receivers, for your resolving pleasure.
444    final ActivityIntentResolver mReceivers =
445            new ActivityIntentResolver();
446
447    // All available services, for your resolving pleasure.
448    final ServiceIntentResolver mServices = new ServiceIntentResolver();
449
450    // All available providers, for your resolving pleasure.
451    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
452
453    // Mapping from provider base names (first directory in content URI codePath)
454    // to the provider information.
455    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
456            new HashMap<String, PackageParser.Provider>();
457
458    // Mapping from instrumentation class names to info about them.
459    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
460            new HashMap<ComponentName, PackageParser.Instrumentation>();
461
462    // Mapping from permission names to info about them.
463    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
464            new HashMap<String, PackageParser.PermissionGroup>();
465
466    // Packages whose data we have transfered into another package, thus
467    // should no longer exist.
468    final HashSet<String> mTransferedPackages = new HashSet<String>();
469
470    // Broadcast actions that are only available to the system.
471    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
472
473    /** List of packages waiting for verification. */
474    final SparseArray<PackageVerificationState> mPendingVerification
475            = new SparseArray<PackageVerificationState>();
476
477    final PackageInstallerService mInstallerService;
478
479    HashSet<PackageParser.Package> mDeferredDexOpt = null;
480
481    // Cache of users who need badging.
482    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
483
484    /** Token for keys in mPendingVerification. */
485    private int mPendingVerificationToken = 0;
486
487    boolean mSystemReady;
488    boolean mSafeMode;
489    boolean mHasSystemUidErrors;
490
491    ApplicationInfo mAndroidApplication;
492    final ActivityInfo mResolveActivity = new ActivityInfo();
493    final ResolveInfo mResolveInfo = new ResolveInfo();
494    ComponentName mResolveComponentName;
495    PackageParser.Package mPlatformPackage;
496    ComponentName mCustomResolverComponentName;
497
498    boolean mResolverReplaced = false;
499
500    // Set of pending broadcasts for aggregating enable/disable of components.
501    static class PendingPackageBroadcasts {
502        // for each user id, a map of <package name -> components within that package>
503        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
504
505        public PendingPackageBroadcasts() {
506            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
507        }
508
509        public ArrayList<String> get(int userId, String packageName) {
510            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
511            return packages.get(packageName);
512        }
513
514        public void put(int userId, String packageName, ArrayList<String> components) {
515            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
516            packages.put(packageName, components);
517        }
518
519        public void remove(int userId, String packageName) {
520            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
521            if (packages != null) {
522                packages.remove(packageName);
523            }
524        }
525
526        public void remove(int userId) {
527            mUidMap.remove(userId);
528        }
529
530        public int userIdCount() {
531            return mUidMap.size();
532        }
533
534        public int userIdAt(int n) {
535            return mUidMap.keyAt(n);
536        }
537
538        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
539            return mUidMap.get(userId);
540        }
541
542        public int size() {
543            // total number of pending broadcast entries across all userIds
544            int num = 0;
545            for (int i = 0; i< mUidMap.size(); i++) {
546                num += mUidMap.valueAt(i).size();
547            }
548            return num;
549        }
550
551        public void clear() {
552            mUidMap.clear();
553        }
554
555        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
556            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
557            if (map == null) {
558                map = new HashMap<String, ArrayList<String>>();
559                mUidMap.put(userId, map);
560            }
561            return map;
562        }
563    }
564    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
565
566    // Service Connection to remote media container service to copy
567    // package uri's from external media onto secure containers
568    // or internal storage.
569    private IMediaContainerService mContainerService = null;
570
571    static final int SEND_PENDING_BROADCAST = 1;
572    static final int MCS_BOUND = 3;
573    static final int END_COPY = 4;
574    static final int INIT_COPY = 5;
575    static final int MCS_UNBIND = 6;
576    static final int START_CLEANING_PACKAGE = 7;
577    static final int FIND_INSTALL_LOC = 8;
578    static final int POST_INSTALL = 9;
579    static final int MCS_RECONNECT = 10;
580    static final int MCS_GIVE_UP = 11;
581    static final int UPDATED_MEDIA_STATUS = 12;
582    static final int WRITE_SETTINGS = 13;
583    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
584    static final int PACKAGE_VERIFIED = 15;
585    static final int CHECK_PENDING_VERIFICATION = 16;
586
587    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
588
589    // Delay time in millisecs
590    static final int BROADCAST_DELAY = 10 * 1000;
591
592    static UserManagerService sUserManager;
593
594    // Stores a list of users whose package restrictions file needs to be updated
595    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
596
597    final private DefaultContainerConnection mDefContainerConn =
598            new DefaultContainerConnection();
599    class DefaultContainerConnection implements ServiceConnection {
600        public void onServiceConnected(ComponentName name, IBinder service) {
601            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
602            IMediaContainerService imcs =
603                IMediaContainerService.Stub.asInterface(service);
604            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
605        }
606
607        public void onServiceDisconnected(ComponentName name) {
608            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
609        }
610    };
611
612    // Recordkeeping of restore-after-install operations that are currently in flight
613    // between the Package Manager and the Backup Manager
614    class PostInstallData {
615        public InstallArgs args;
616        public PackageInstalledInfo res;
617
618        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
619            args = _a;
620            res = _r;
621        }
622    };
623    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
624    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
625
626    private final String mRequiredVerifierPackage;
627
628    private final PackageUsage mPackageUsage = new PackageUsage();
629
630    private class PackageUsage {
631        private static final int WRITE_INTERVAL
632            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
633
634        private final Object mFileLock = new Object();
635        private final AtomicLong mLastWritten = new AtomicLong(0);
636        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
637
638        private boolean mIsHistoricalPackageUsageAvailable = true;
639
640        boolean isHistoricalPackageUsageAvailable() {
641            return mIsHistoricalPackageUsageAvailable;
642        }
643
644        void write(boolean force) {
645            if (force) {
646                writeInternal();
647                return;
648            }
649            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
650                && !DEBUG_DEXOPT) {
651                return;
652            }
653            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
654                new Thread("PackageUsage_DiskWriter") {
655                    @Override
656                    public void run() {
657                        try {
658                            writeInternal();
659                        } finally {
660                            mBackgroundWriteRunning.set(false);
661                        }
662                    }
663                }.start();
664            }
665        }
666
667        private void writeInternal() {
668            synchronized (mPackages) {
669                synchronized (mFileLock) {
670                    AtomicFile file = getFile();
671                    FileOutputStream f = null;
672                    try {
673                        f = file.startWrite();
674                        BufferedOutputStream out = new BufferedOutputStream(f);
675                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
676                        StringBuilder sb = new StringBuilder();
677                        for (PackageParser.Package pkg : mPackages.values()) {
678                            if (pkg.mLastPackageUsageTimeInMills == 0) {
679                                continue;
680                            }
681                            sb.setLength(0);
682                            sb.append(pkg.packageName);
683                            sb.append(' ');
684                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
685                            sb.append('\n');
686                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
687                        }
688                        out.flush();
689                        file.finishWrite(f);
690                    } catch (IOException e) {
691                        if (f != null) {
692                            file.failWrite(f);
693                        }
694                        Log.e(TAG, "Failed to write package usage times", e);
695                    }
696                }
697            }
698            mLastWritten.set(SystemClock.elapsedRealtime());
699        }
700
701        void readLP() {
702            synchronized (mFileLock) {
703                AtomicFile file = getFile();
704                BufferedInputStream in = null;
705                try {
706                    in = new BufferedInputStream(file.openRead());
707                    StringBuffer sb = new StringBuffer();
708                    while (true) {
709                        String packageName = readToken(in, sb, ' ');
710                        if (packageName == null) {
711                            break;
712                        }
713                        String timeInMillisString = readToken(in, sb, '\n');
714                        if (timeInMillisString == null) {
715                            throw new IOException("Failed to find last usage time for package "
716                                                  + packageName);
717                        }
718                        PackageParser.Package pkg = mPackages.get(packageName);
719                        if (pkg == null) {
720                            continue;
721                        }
722                        long timeInMillis;
723                        try {
724                            timeInMillis = Long.parseLong(timeInMillisString.toString());
725                        } catch (NumberFormatException e) {
726                            throw new IOException("Failed to parse " + timeInMillisString
727                                                  + " as a long.", e);
728                        }
729                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
730                    }
731                } catch (FileNotFoundException expected) {
732                    mIsHistoricalPackageUsageAvailable = false;
733                } catch (IOException e) {
734                    Log.w(TAG, "Failed to read package usage times", e);
735                } finally {
736                    IoUtils.closeQuietly(in);
737                }
738            }
739            mLastWritten.set(SystemClock.elapsedRealtime());
740        }
741
742        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
743                throws IOException {
744            sb.setLength(0);
745            while (true) {
746                int ch = in.read();
747                if (ch == -1) {
748                    if (sb.length() == 0) {
749                        return null;
750                    }
751                    throw new IOException("Unexpected EOF");
752                }
753                if (ch == endOfToken) {
754                    return sb.toString();
755                }
756                sb.append((char)ch);
757            }
758        }
759
760        private AtomicFile getFile() {
761            File dataDir = Environment.getDataDirectory();
762            File systemDir = new File(dataDir, "system");
763            File fname = new File(systemDir, "package-usage.list");
764            return new AtomicFile(fname);
765        }
766    }
767
768    class PackageHandler extends Handler {
769        private boolean mBound = false;
770        final ArrayList<HandlerParams> mPendingInstalls =
771            new ArrayList<HandlerParams>();
772
773        private boolean connectToService() {
774            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
775                    " DefaultContainerService");
776            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            if (mContext.bindServiceAsUser(service, mDefContainerConn,
779                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
780                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781                mBound = true;
782                return true;
783            }
784            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
785            return false;
786        }
787
788        private void disconnectService() {
789            mContainerService = null;
790            mBound = false;
791            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
792            mContext.unbindService(mDefContainerConn);
793            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
794        }
795
796        PackageHandler(Looper looper) {
797            super(looper);
798        }
799
800        public void handleMessage(Message msg) {
801            try {
802                doHandleMessage(msg);
803            } finally {
804                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
805            }
806        }
807
808        void doHandleMessage(Message msg) {
809            switch (msg.what) {
810                case INIT_COPY: {
811                    HandlerParams params = (HandlerParams) msg.obj;
812                    int idx = mPendingInstalls.size();
813                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
814                    // If a bind was already initiated we dont really
815                    // need to do anything. The pending install
816                    // will be processed later on.
817                    if (!mBound) {
818                        // If this is the only one pending we might
819                        // have to bind to the service again.
820                        if (!connectToService()) {
821                            Slog.e(TAG, "Failed to bind to media container service");
822                            params.serviceError();
823                            return;
824                        } else {
825                            // Once we bind to the service, the first
826                            // pending request will be processed.
827                            mPendingInstalls.add(idx, params);
828                        }
829                    } else {
830                        mPendingInstalls.add(idx, params);
831                        // Already bound to the service. Just make
832                        // sure we trigger off processing the first request.
833                        if (idx == 0) {
834                            mHandler.sendEmptyMessage(MCS_BOUND);
835                        }
836                    }
837                    break;
838                }
839                case MCS_BOUND: {
840                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
841                    if (msg.obj != null) {
842                        mContainerService = (IMediaContainerService) msg.obj;
843                    }
844                    if (mContainerService == null) {
845                        // Something seriously wrong. Bail out
846                        Slog.e(TAG, "Cannot bind to media container service");
847                        for (HandlerParams params : mPendingInstalls) {
848                            // Indicate service bind error
849                            params.serviceError();
850                        }
851                        mPendingInstalls.clear();
852                    } else if (mPendingInstalls.size() > 0) {
853                        HandlerParams params = mPendingInstalls.get(0);
854                        if (params != null) {
855                            if (params.startCopy()) {
856                                // We are done...  look for more work or to
857                                // go idle.
858                                if (DEBUG_SD_INSTALL) Log.i(TAG,
859                                        "Checking for more work or unbind...");
860                                // Delete pending install
861                                if (mPendingInstalls.size() > 0) {
862                                    mPendingInstalls.remove(0);
863                                }
864                                if (mPendingInstalls.size() == 0) {
865                                    if (mBound) {
866                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
867                                                "Posting delayed MCS_UNBIND");
868                                        removeMessages(MCS_UNBIND);
869                                        Message ubmsg = obtainMessage(MCS_UNBIND);
870                                        // Unbind after a little delay, to avoid
871                                        // continual thrashing.
872                                        sendMessageDelayed(ubmsg, 10000);
873                                    }
874                                } else {
875                                    // There are more pending requests in queue.
876                                    // Just post MCS_BOUND message to trigger processing
877                                    // of next pending install.
878                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
879                                            "Posting MCS_BOUND for next work");
880                                    mHandler.sendEmptyMessage(MCS_BOUND);
881                                }
882                            }
883                        }
884                    } else {
885                        // Should never happen ideally.
886                        Slog.w(TAG, "Empty queue");
887                    }
888                    break;
889                }
890                case MCS_RECONNECT: {
891                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
892                    if (mPendingInstalls.size() > 0) {
893                        if (mBound) {
894                            disconnectService();
895                        }
896                        if (!connectToService()) {
897                            Slog.e(TAG, "Failed to bind to media container service");
898                            for (HandlerParams params : mPendingInstalls) {
899                                // Indicate service bind error
900                                params.serviceError();
901                            }
902                            mPendingInstalls.clear();
903                        }
904                    }
905                    break;
906                }
907                case MCS_UNBIND: {
908                    // If there is no actual work left, then time to unbind.
909                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
910
911                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
912                        if (mBound) {
913                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
914
915                            disconnectService();
916                        }
917                    } else if (mPendingInstalls.size() > 0) {
918                        // There are more pending requests in queue.
919                        // Just post MCS_BOUND message to trigger processing
920                        // of next pending install.
921                        mHandler.sendEmptyMessage(MCS_BOUND);
922                    }
923
924                    break;
925                }
926                case MCS_GIVE_UP: {
927                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
928                    mPendingInstalls.remove(0);
929                    break;
930                }
931                case SEND_PENDING_BROADCAST: {
932                    String packages[];
933                    ArrayList<String> components[];
934                    int size = 0;
935                    int uids[];
936                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
937                    synchronized (mPackages) {
938                        if (mPendingBroadcasts == null) {
939                            return;
940                        }
941                        size = mPendingBroadcasts.size();
942                        if (size <= 0) {
943                            // Nothing to be done. Just return
944                            return;
945                        }
946                        packages = new String[size];
947                        components = new ArrayList[size];
948                        uids = new int[size];
949                        int i = 0;  // filling out the above arrays
950
951                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
952                            int packageUserId = mPendingBroadcasts.userIdAt(n);
953                            Iterator<Map.Entry<String, ArrayList<String>>> it
954                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
955                                            .entrySet().iterator();
956                            while (it.hasNext() && i < size) {
957                                Map.Entry<String, ArrayList<String>> ent = it.next();
958                                packages[i] = ent.getKey();
959                                components[i] = ent.getValue();
960                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
961                                uids[i] = (ps != null)
962                                        ? UserHandle.getUid(packageUserId, ps.appId)
963                                        : -1;
964                                i++;
965                            }
966                        }
967                        size = i;
968                        mPendingBroadcasts.clear();
969                    }
970                    // Send broadcasts
971                    for (int i = 0; i < size; i++) {
972                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
973                    }
974                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
975                    break;
976                }
977                case START_CLEANING_PACKAGE: {
978                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
979                    final String packageName = (String)msg.obj;
980                    final int userId = msg.arg1;
981                    final boolean andCode = msg.arg2 != 0;
982                    synchronized (mPackages) {
983                        if (userId == UserHandle.USER_ALL) {
984                            int[] users = sUserManager.getUserIds();
985                            for (int user : users) {
986                                mSettings.addPackageToCleanLPw(
987                                        new PackageCleanItem(user, packageName, andCode));
988                            }
989                        } else {
990                            mSettings.addPackageToCleanLPw(
991                                    new PackageCleanItem(userId, packageName, andCode));
992                        }
993                    }
994                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
995                    startCleaningPackages();
996                } break;
997                case POST_INSTALL: {
998                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
999                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1000                    mRunningInstalls.delete(msg.arg1);
1001                    boolean deleteOld = false;
1002
1003                    if (data != null) {
1004                        InstallArgs args = data.args;
1005                        PackageInstalledInfo res = data.res;
1006
1007                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1008                            res.removedInfo.sendBroadcast(false, true, false);
1009                            Bundle extras = new Bundle(1);
1010                            extras.putInt(Intent.EXTRA_UID, res.uid);
1011                            // Determine the set of users who are adding this
1012                            // package for the first time vs. those who are seeing
1013                            // an update.
1014                            int[] firstUsers;
1015                            int[] updateUsers = new int[0];
1016                            if (res.origUsers == null || res.origUsers.length == 0) {
1017                                firstUsers = res.newUsers;
1018                            } else {
1019                                firstUsers = new int[0];
1020                                for (int i=0; i<res.newUsers.length; i++) {
1021                                    int user = res.newUsers[i];
1022                                    boolean isNew = true;
1023                                    for (int j=0; j<res.origUsers.length; j++) {
1024                                        if (res.origUsers[j] == user) {
1025                                            isNew = false;
1026                                            break;
1027                                        }
1028                                    }
1029                                    if (isNew) {
1030                                        int[] newFirst = new int[firstUsers.length+1];
1031                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1032                                                firstUsers.length);
1033                                        newFirst[firstUsers.length] = user;
1034                                        firstUsers = newFirst;
1035                                    } else {
1036                                        int[] newUpdate = new int[updateUsers.length+1];
1037                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1038                                                updateUsers.length);
1039                                        newUpdate[updateUsers.length] = user;
1040                                        updateUsers = newUpdate;
1041                                    }
1042                                }
1043                            }
1044                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1045                                    res.pkg.applicationInfo.packageName,
1046                                    extras, null, null, firstUsers);
1047                            final boolean update = res.removedInfo.removedPackage != null;
1048                            if (update) {
1049                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1050                            }
1051                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1052                                    res.pkg.applicationInfo.packageName,
1053                                    extras, null, null, updateUsers);
1054                            if (update) {
1055                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1056                                        res.pkg.applicationInfo.packageName,
1057                                        extras, null, null, updateUsers);
1058                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1059                                        null, null,
1060                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1061
1062                                // treat asec-hosted packages like removable media on upgrade
1063                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1064                                    if (DEBUG_INSTALL) {
1065                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1066                                                + " is ASEC-hosted -> AVAILABLE");
1067                                    }
1068                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1069                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1070                                    pkgList.add(res.pkg.applicationInfo.packageName);
1071                                    sendResourcesChangedBroadcast(true, true,
1072                                            pkgList,uidArray, null);
1073                                }
1074                            }
1075                            if (res.removedInfo.args != null) {
1076                                // Remove the replaced package's older resources safely now
1077                                deleteOld = true;
1078                            }
1079
1080                            // Log current value of "unknown sources" setting
1081                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1082                                getUnknownSourcesSettings());
1083                        }
1084                        // Force a gc to clear up things
1085                        Runtime.getRuntime().gc();
1086                        // We delete after a gc for applications  on sdcard.
1087                        if (deleteOld) {
1088                            synchronized (mInstallLock) {
1089                                res.removedInfo.args.doPostDeleteLI(true);
1090                            }
1091                        }
1092                        if (args.observer != null) {
1093                            try {
1094                                Bundle extras = extrasForInstallResult(res);
1095                                args.observer.packageInstalled(res.name, extras, res.returnCode,
1096                                        res.returnMsg);
1097                            } catch (RemoteException e) {
1098                                Slog.i(TAG, "Observer no longer exists.");
1099                            }
1100                        }
1101                    } else {
1102                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1103                    }
1104                } break;
1105                case UPDATED_MEDIA_STATUS: {
1106                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1107                    boolean reportStatus = msg.arg1 == 1;
1108                    boolean doGc = msg.arg2 == 1;
1109                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1110                    if (doGc) {
1111                        // Force a gc to clear up stale containers.
1112                        Runtime.getRuntime().gc();
1113                    }
1114                    if (msg.obj != null) {
1115                        @SuppressWarnings("unchecked")
1116                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1117                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1118                        // Unload containers
1119                        unloadAllContainers(args);
1120                    }
1121                    if (reportStatus) {
1122                        try {
1123                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1124                            PackageHelper.getMountService().finishMediaUpdate();
1125                        } catch (RemoteException e) {
1126                            Log.e(TAG, "MountService not running?");
1127                        }
1128                    }
1129                } break;
1130                case WRITE_SETTINGS: {
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1132                    synchronized (mPackages) {
1133                        removeMessages(WRITE_SETTINGS);
1134                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1135                        mSettings.writeLPr();
1136                        mDirtyUsers.clear();
1137                    }
1138                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139                } break;
1140                case WRITE_PACKAGE_RESTRICTIONS: {
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1142                    synchronized (mPackages) {
1143                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1144                        for (int userId : mDirtyUsers) {
1145                            mSettings.writePackageRestrictionsLPr(userId);
1146                        }
1147                        mDirtyUsers.clear();
1148                    }
1149                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150                } break;
1151                case CHECK_PENDING_VERIFICATION: {
1152                    final int verificationId = msg.arg1;
1153                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1154
1155                    if ((state != null) && !state.timeoutExtended()) {
1156                        final InstallArgs args = state.getInstallArgs();
1157                        final Uri originUri = Uri.fromFile(args.originFile);
1158
1159                        Slog.i(TAG, "Verification timed out for " + originUri);
1160                        mPendingVerification.remove(verificationId);
1161
1162                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1163
1164                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1165                            Slog.i(TAG, "Continuing with installation of " + originUri);
1166                            state.setVerifierResponse(Binder.getCallingUid(),
1167                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1168                            broadcastPackageVerified(verificationId, originUri,
1169                                    PackageManager.VERIFICATION_ALLOW,
1170                                    state.getInstallArgs().getUser());
1171                            try {
1172                                ret = args.copyApk(mContainerService, true);
1173                            } catch (RemoteException e) {
1174                                Slog.e(TAG, "Could not contact the ContainerService");
1175                            }
1176                        } else {
1177                            broadcastPackageVerified(verificationId, originUri,
1178                                    PackageManager.VERIFICATION_REJECT,
1179                                    state.getInstallArgs().getUser());
1180                        }
1181
1182                        processPendingInstall(args, ret);
1183                        mHandler.sendEmptyMessage(MCS_UNBIND);
1184                    }
1185                    break;
1186                }
1187                case PACKAGE_VERIFIED: {
1188                    final int verificationId = msg.arg1;
1189
1190                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1191                    if (state == null) {
1192                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1193                        break;
1194                    }
1195
1196                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1197
1198                    state.setVerifierResponse(response.callerUid, response.code);
1199
1200                    if (state.isVerificationComplete()) {
1201                        mPendingVerification.remove(verificationId);
1202
1203                        final InstallArgs args = state.getInstallArgs();
1204                        final Uri originUri = Uri.fromFile(args.originFile);
1205
1206                        int ret;
1207                        if (state.isInstallAllowed()) {
1208                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1209                            broadcastPackageVerified(verificationId, originUri,
1210                                    response.code, state.getInstallArgs().getUser());
1211                            try {
1212                                ret = args.copyApk(mContainerService, true);
1213                            } catch (RemoteException e) {
1214                                Slog.e(TAG, "Could not contact the ContainerService");
1215                            }
1216                        } else {
1217                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1218                        }
1219
1220                        processPendingInstall(args, ret);
1221
1222                        mHandler.sendEmptyMessage(MCS_UNBIND);
1223                    }
1224
1225                    break;
1226                }
1227            }
1228        }
1229    }
1230
1231    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1232        Bundle extras = null;
1233        switch (res.returnCode) {
1234            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1235                extras = new Bundle();
1236                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1237                        res.origPermission);
1238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1239                        res.origPackage);
1240                break;
1241            }
1242        }
1243        return extras;
1244    }
1245
1246    void scheduleWriteSettingsLocked() {
1247        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1248            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1249        }
1250    }
1251
1252    void scheduleWritePackageRestrictionsLocked(int userId) {
1253        if (!sUserManager.exists(userId)) return;
1254        mDirtyUsers.add(userId);
1255        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1256            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1257        }
1258    }
1259
1260    public static final PackageManagerService main(Context context, Installer installer,
1261            boolean factoryTest, boolean onlyCore) {
1262        PackageManagerService m = new PackageManagerService(context, installer,
1263                factoryTest, onlyCore);
1264        ServiceManager.addService("package", m);
1265        return m;
1266    }
1267
1268    static String[] splitString(String str, char sep) {
1269        int count = 1;
1270        int i = 0;
1271        while ((i=str.indexOf(sep, i)) >= 0) {
1272            count++;
1273            i++;
1274        }
1275
1276        String[] res = new String[count];
1277        i=0;
1278        count = 0;
1279        int lastI=0;
1280        while ((i=str.indexOf(sep, i)) >= 0) {
1281            res[count] = str.substring(lastI, i);
1282            count++;
1283            i++;
1284            lastI = i;
1285        }
1286        res[count] = str.substring(lastI, str.length());
1287        return res;
1288    }
1289
1290    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1291        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1292                Context.DISPLAY_SERVICE);
1293        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1294    }
1295
1296    public PackageManagerService(Context context, Installer installer,
1297            boolean factoryTest, boolean onlyCore) {
1298        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1299                SystemClock.uptimeMillis());
1300
1301        if (mSdkVersion <= 0) {
1302            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1303        }
1304
1305        mContext = context;
1306        mFactoryTest = factoryTest;
1307        mOnlyCore = onlyCore;
1308        mMetrics = new DisplayMetrics();
1309        mSettings = new Settings(context);
1310        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1313                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1314        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1315                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1316        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1317                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1318        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1319                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1320        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1321                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1322
1323        String separateProcesses = SystemProperties.get("debug.separate_processes");
1324        if (separateProcesses != null && separateProcesses.length() > 0) {
1325            if ("*".equals(separateProcesses)) {
1326                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1327                mSeparateProcesses = null;
1328                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1329            } else {
1330                mDefParseFlags = 0;
1331                mSeparateProcesses = separateProcesses.split(",");
1332                Slog.w(TAG, "Running with debug.separate_processes: "
1333                        + separateProcesses);
1334            }
1335        } else {
1336            mDefParseFlags = 0;
1337            mSeparateProcesses = null;
1338        }
1339
1340        mInstaller = installer;
1341
1342        getDefaultDisplayMetrics(context, mMetrics);
1343
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        mGlobalGids = systemConfig.getGlobalGids();
1346        mSystemPermissions = systemConfig.getSystemPermissions();
1347        mAvailableFeatures = systemConfig.getAvailableFeatures();
1348
1349        synchronized (mInstallLock) {
1350        // writer
1351        synchronized (mPackages) {
1352            mHandlerThread = new ServiceThread(TAG,
1353                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1354            mHandlerThread.start();
1355            mHandler = new PackageHandler(mHandlerThread.getLooper());
1356            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1357
1358            File dataDir = Environment.getDataDirectory();
1359            mAppDataDir = new File(dataDir, "data");
1360            mAppInstallDir = new File(dataDir, "app");
1361            mAppLib32InstallDir = new File(dataDir, "app-lib");
1362            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1363            mUserAppDataDir = new File(dataDir, "user");
1364            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1365
1366            sUserManager = new UserManagerService(context, this,
1367                    mInstallLock, mPackages);
1368
1369            // Propagate permission configuration in to package manager.
1370            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1371                    = systemConfig.getPermissions();
1372            for (int i=0; i<permConfig.size(); i++) {
1373                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1374                BasePermission bp = mSettings.mPermissions.get(perm.name);
1375                if (bp == null) {
1376                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1377                    mSettings.mPermissions.put(perm.name, bp);
1378                }
1379                if (perm.gids != null) {
1380                    bp.gids = appendInts(bp.gids, perm.gids);
1381                }
1382            }
1383
1384            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1385            for (int i=0; i<libConfig.size(); i++) {
1386                mSharedLibraries.put(libConfig.keyAt(i),
1387                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1388            }
1389
1390            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1391
1392            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1393                    mSdkVersion, mOnlyCore);
1394
1395            String customResolverActivity = Resources.getSystem().getString(
1396                    R.string.config_customResolverActivity);
1397            if (TextUtils.isEmpty(customResolverActivity)) {
1398                customResolverActivity = null;
1399            } else {
1400                mCustomResolverComponentName = ComponentName.unflattenFromString(
1401                        customResolverActivity);
1402            }
1403
1404            long startTime = SystemClock.uptimeMillis();
1405
1406            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1407                    startTime);
1408
1409            // Set flag to monitor and not change apk file paths when
1410            // scanning install directories.
1411            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1412
1413            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1414
1415            /**
1416             * Add everything in the in the boot class path to the
1417             * list of process files because dexopt will have been run
1418             * if necessary during zygote startup.
1419             */
1420            String bootClassPath = System.getProperty("java.boot.class.path");
1421            if (bootClassPath != null) {
1422                String[] paths = splitString(bootClassPath, ':');
1423                for (int i=0; i<paths.length; i++) {
1424                    alreadyDexOpted.add(paths[i]);
1425                }
1426            } else {
1427                Slog.w(TAG, "No BOOTCLASSPATH found!");
1428            }
1429
1430            boolean didDexOptLibraryOrTool = false;
1431
1432            final List<String> instructionSets = getAllInstructionSets();
1433
1434            /**
1435             * Ensure all external libraries have had dexopt run on them.
1436             */
1437            if (mSharedLibraries.size() > 0) {
1438                // NOTE: For now, we're compiling these system "shared libraries"
1439                // (and framework jars) into all available architectures. It's possible
1440                // to compile them only when we come across an app that uses them (there's
1441                // already logic for that in scanPackageLI) but that adds some complexity.
1442                for (String instructionSet : instructionSets) {
1443                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1444                        final String lib = libEntry.path;
1445                        if (lib == null) {
1446                            continue;
1447                        }
1448
1449                        try {
1450                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1451                                alreadyDexOpted.add(lib);
1452
1453                                // The list of "shared libraries" we have at this point is
1454                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1455                                didDexOptLibraryOrTool = true;
1456                            }
1457                        } catch (FileNotFoundException e) {
1458                            Slog.w(TAG, "Library not found: " + lib);
1459                        } catch (IOException e) {
1460                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1461                                    + e.getMessage());
1462                        }
1463                    }
1464                }
1465            }
1466
1467            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1468
1469            // Gross hack for now: we know this file doesn't contain any
1470            // code, so don't dexopt it to avoid the resulting log spew.
1471            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1472
1473            // Gross hack for now: we know this file is only part of
1474            // the boot class path for art, so don't dexopt it to
1475            // avoid the resulting log spew.
1476            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1477
1478            /**
1479             * And there are a number of commands implemented in Java, which
1480             * we currently need to do the dexopt on so that they can be
1481             * run from a non-root shell.
1482             */
1483            String[] frameworkFiles = frameworkDir.list();
1484            if (frameworkFiles != null) {
1485                // TODO: We could compile these only for the most preferred ABI. We should
1486                // first double check that the dex files for these commands are not referenced
1487                // by other system apps.
1488                for (String instructionSet : instructionSets) {
1489                    for (int i=0; i<frameworkFiles.length; i++) {
1490                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1491                        String path = libPath.getPath();
1492                        // Skip the file if we already did it.
1493                        if (alreadyDexOpted.contains(path)) {
1494                            continue;
1495                        }
1496                        // Skip the file if it is not a type we want to dexopt.
1497                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1498                            continue;
1499                        }
1500                        try {
1501                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1502                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1503                                didDexOptLibraryOrTool = true;
1504                            }
1505                        } catch (FileNotFoundException e) {
1506                            Slog.w(TAG, "Jar not found: " + path);
1507                        } catch (IOException e) {
1508                            Slog.w(TAG, "Exception reading jar: " + path, e);
1509                        }
1510                    }
1511                }
1512            }
1513
1514            if (didDexOptLibraryOrTool) {
1515                // If we dexopted a library or tool, then something on the system has
1516                // changed. Consider this significant, and wipe away all other
1517                // existing dexopt files to ensure we don't leave any dangling around.
1518                //
1519                // TODO: This should be revisited because it isn't as good an indicator
1520                // as it used to be. It used to include the boot classpath but at some point
1521                // DexFile.isDexOptNeeded started returning false for the boot
1522                // class path files in all cases. It is very possible in a
1523                // small maintenance release update that the library and tool
1524                // jars may be unchanged but APK could be removed resulting in
1525                // unused dalvik-cache files.
1526                for (String instructionSet : instructionSets) {
1527                    mInstaller.pruneDexCache(instructionSet);
1528                }
1529
1530                // Additionally, delete all dex files from the root directory
1531                // since there shouldn't be any there anyway, unless we're upgrading
1532                // from an older OS version or a build that contained the "old" style
1533                // flat scheme.
1534                mInstaller.pruneDexCache(".");
1535            }
1536
1537            // Collect vendor overlay packages.
1538            // (Do this before scanning any apps.)
1539            // For security and version matching reason, only consider
1540            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1541            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1542            mVendorOverlayInstallObserver = new AppDirObserver(
1543                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1544            mVendorOverlayInstallObserver.startWatching();
1545            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1547
1548            // Find base frameworks (resource packages without code).
1549            mFrameworkInstallObserver = new AppDirObserver(
1550                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1551            mFrameworkInstallObserver.startWatching();
1552            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1553                    | PackageParser.PARSE_IS_SYSTEM_DIR
1554                    | PackageParser.PARSE_IS_PRIVILEGED,
1555                    scanMode | SCAN_NO_DEX, 0);
1556
1557            // Collected privileged system packages.
1558            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1559            mPrivilegedInstallObserver = new AppDirObserver(
1560                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1561            mPrivilegedInstallObserver.startWatching();
1562            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1563                    | PackageParser.PARSE_IS_SYSTEM_DIR
1564                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1565
1566            // Collect ordinary system packages.
1567            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1568            mSystemInstallObserver = new AppDirObserver(
1569                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1570            mSystemInstallObserver.startWatching();
1571            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1572                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1573
1574            // Collect all vendor packages.
1575            File vendorAppDir = new File("/vendor/app");
1576            try {
1577                vendorAppDir = vendorAppDir.getCanonicalFile();
1578            } catch (IOException e) {
1579                // failed to look up canonical path, continue with original one
1580            }
1581            mVendorInstallObserver = new AppDirObserver(
1582                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1583            mVendorInstallObserver.startWatching();
1584            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1585                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1586
1587            // Collect all OEM packages.
1588            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1589            mOemInstallObserver = new AppDirObserver(
1590                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1591            mOemInstallObserver.startWatching();
1592            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1593                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1594
1595            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1596            mInstaller.moveFiles();
1597
1598            // Prune any system packages that no longer exist.
1599            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1600            if (!mOnlyCore) {
1601                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1602                while (psit.hasNext()) {
1603                    PackageSetting ps = psit.next();
1604
1605                    /*
1606                     * If this is not a system app, it can't be a
1607                     * disable system app.
1608                     */
1609                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1610                        continue;
1611                    }
1612
1613                    /*
1614                     * If the package is scanned, it's not erased.
1615                     */
1616                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1617                    if (scannedPkg != null) {
1618                        /*
1619                         * If the system app is both scanned and in the
1620                         * disabled packages list, then it must have been
1621                         * added via OTA. Remove it from the currently
1622                         * scanned package so the previously user-installed
1623                         * application can be scanned.
1624                         */
1625                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1626                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1627                                    + "; removing system app");
1628                            removePackageLI(ps, true);
1629                        }
1630
1631                        continue;
1632                    }
1633
1634                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1635                        psit.remove();
1636                        String msg = "System package " + ps.name
1637                                + " no longer exists; wiping its data";
1638                        reportSettingsProblem(Log.WARN, msg);
1639                        removeDataDirsLI(ps.name);
1640                    } else {
1641                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1642                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1643                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1644                        }
1645                    }
1646                }
1647            }
1648
1649            //look for any incomplete package installations
1650            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1651            //clean up list
1652            for(int i = 0; i < deletePkgsList.size(); i++) {
1653                //clean up here
1654                cleanupInstallFailedPackage(deletePkgsList.get(i));
1655            }
1656            //delete tmp files
1657            deleteTempPackageFiles();
1658
1659            // Remove any shared userIDs that have no associated packages
1660            mSettings.pruneSharedUsersLPw();
1661
1662            if (!mOnlyCore) {
1663                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1664                        SystemClock.uptimeMillis());
1665                mAppInstallObserver = new AppDirObserver(
1666                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1667                mAppInstallObserver.startWatching();
1668                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1669
1670                mDrmAppInstallObserver = new AppDirObserver(
1671                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1672                mDrmAppInstallObserver.startWatching();
1673                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1674                        scanMode, 0);
1675
1676                /**
1677                 * Remove disable package settings for any updated system
1678                 * apps that were removed via an OTA. If they're not a
1679                 * previously-updated app, remove them completely.
1680                 * Otherwise, just revoke their system-level permissions.
1681                 */
1682                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1683                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1684                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1685
1686                    String msg;
1687                    if (deletedPkg == null) {
1688                        msg = "Updated system package " + deletedAppName
1689                                + " no longer exists; wiping its data";
1690                        removeDataDirsLI(deletedAppName);
1691                    } else {
1692                        msg = "Updated system app + " + deletedAppName
1693                                + " no longer present; removing system privileges for "
1694                                + deletedAppName;
1695
1696                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1697
1698                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1699                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1700                    }
1701                    reportSettingsProblem(Log.WARN, msg);
1702                }
1703            } else {
1704                mAppInstallObserver = null;
1705                mDrmAppInstallObserver = null;
1706            }
1707
1708            // Now that we know all of the shared libraries, update all clients to have
1709            // the correct library paths.
1710            updateAllSharedLibrariesLPw();
1711
1712            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1713                // NOTE: We ignore potential failures here during a system scan (like
1714                // the rest of the commands above) because there's precious little we
1715                // can do about it. A settings error is reported, though.
1716                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1717                        false /* force dexopt */, false /* defer dexopt */);
1718            }
1719
1720            // Now that we know all the packages we are keeping,
1721            // read and update their last usage times.
1722            mPackageUsage.readLP();
1723
1724            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1725                    SystemClock.uptimeMillis());
1726            Slog.i(TAG, "Time to scan packages: "
1727                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1728                    + " seconds");
1729
1730            // If the platform SDK has changed since the last time we booted,
1731            // we need to re-grant app permission to catch any new ones that
1732            // appear.  This is really a hack, and means that apps can in some
1733            // cases get permissions that the user didn't initially explicitly
1734            // allow...  it would be nice to have some better way to handle
1735            // this situation.
1736            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1737                    != mSdkVersion;
1738            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1739                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1740                    + "; regranting permissions for internal storage");
1741            mSettings.mInternalSdkPlatform = mSdkVersion;
1742
1743            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1744                    | (regrantPermissions
1745                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1746                            : 0));
1747
1748            // If this is the first boot, and it is a normal boot, then
1749            // we need to initialize the default preferred apps.
1750            if (!mRestoredSettings && !onlyCore) {
1751                mSettings.readDefaultPreferredAppsLPw(this, 0);
1752            }
1753
1754            // If this is first boot after an OTA, and a normal boot, then
1755            // we need to clear code cache directories.
1756            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1757                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1758                for (String pkgName : mSettings.mPackages.keySet()) {
1759                    deleteCodeCacheDirsLI(pkgName);
1760                }
1761                mSettings.mFingerprint = Build.FINGERPRINT;
1762            }
1763
1764            // All the changes are done during package scanning.
1765            mSettings.updateInternalDatabaseVersion();
1766
1767            // can downgrade to reader
1768            mSettings.writeLPr();
1769
1770            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1771                    SystemClock.uptimeMillis());
1772
1773
1774            mRequiredVerifierPackage = getRequiredVerifierLPr();
1775        } // synchronized (mPackages)
1776        } // synchronized (mInstallLock)
1777
1778        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1779
1780        // Now after opening every single application zip, make sure they
1781        // are all flushed.  Not really needed, but keeps things nice and
1782        // tidy.
1783        Runtime.getRuntime().gc();
1784    }
1785
1786    @Override
1787    public boolean isFirstBoot() {
1788        return !mRestoredSettings;
1789    }
1790
1791    @Override
1792    public boolean isOnlyCoreApps() {
1793        return mOnlyCore;
1794    }
1795
1796    private String getRequiredVerifierLPr() {
1797        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1798        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1799                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1800
1801        String requiredVerifier = null;
1802
1803        final int N = receivers.size();
1804        for (int i = 0; i < N; i++) {
1805            final ResolveInfo info = receivers.get(i);
1806
1807            if (info.activityInfo == null) {
1808                continue;
1809            }
1810
1811            final String packageName = info.activityInfo.packageName;
1812
1813            final PackageSetting ps = mSettings.mPackages.get(packageName);
1814            if (ps == null) {
1815                continue;
1816            }
1817
1818            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1819            if (!gp.grantedPermissions
1820                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1821                continue;
1822            }
1823
1824            if (requiredVerifier != null) {
1825                throw new RuntimeException("There can be only one required verifier");
1826            }
1827
1828            requiredVerifier = packageName;
1829        }
1830
1831        return requiredVerifier;
1832    }
1833
1834    @Override
1835    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1836            throws RemoteException {
1837        try {
1838            return super.onTransact(code, data, reply, flags);
1839        } catch (RuntimeException e) {
1840            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1841                Slog.wtf(TAG, "Package Manager Crash", e);
1842            }
1843            throw e;
1844        }
1845    }
1846
1847    void cleanupInstallFailedPackage(PackageSetting ps) {
1848        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1849        removeDataDirsLI(ps.name);
1850
1851        // TODO: try cleaning up codePath directory contents first, since it
1852        // might be a cluster
1853
1854        if (ps.codePath != null) {
1855            if (!ps.codePath.delete()) {
1856                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1857            }
1858        }
1859        if (ps.resourcePath != null) {
1860            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1861                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1862            }
1863        }
1864        mSettings.removePackageLPw(ps.name);
1865    }
1866
1867    static int[] appendInts(int[] cur, int[] add) {
1868        if (add == null) return cur;
1869        if (cur == null) return add;
1870        final int N = add.length;
1871        for (int i=0; i<N; i++) {
1872            cur = appendInt(cur, add[i]);
1873        }
1874        return cur;
1875    }
1876
1877    static int[] removeInts(int[] cur, int[] rem) {
1878        if (rem == null) return cur;
1879        if (cur == null) return cur;
1880        final int N = rem.length;
1881        for (int i=0; i<N; i++) {
1882            cur = removeInt(cur, rem[i]);
1883        }
1884        return cur;
1885    }
1886
1887    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1888        if (!sUserManager.exists(userId)) return null;
1889        final PackageSetting ps = (PackageSetting) p.mExtras;
1890        if (ps == null) {
1891            return null;
1892        }
1893        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1894        final PackageUserState state = ps.readUserState(userId);
1895        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1896                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1897                state, userId);
1898    }
1899
1900    @Override
1901    public boolean isPackageAvailable(String packageName, int userId) {
1902        if (!sUserManager.exists(userId)) return false;
1903        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1904        synchronized (mPackages) {
1905            PackageParser.Package p = mPackages.get(packageName);
1906            if (p != null) {
1907                final PackageSetting ps = (PackageSetting) p.mExtras;
1908                if (ps != null) {
1909                    final PackageUserState state = ps.readUserState(userId);
1910                    if (state != null) {
1911                        return PackageParser.isAvailable(state);
1912                    }
1913                }
1914            }
1915        }
1916        return false;
1917    }
1918
1919    @Override
1920    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1921        if (!sUserManager.exists(userId)) return null;
1922        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1923        // reader
1924        synchronized (mPackages) {
1925            PackageParser.Package p = mPackages.get(packageName);
1926            if (DEBUG_PACKAGE_INFO)
1927                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1928            if (p != null) {
1929                return generatePackageInfo(p, flags, userId);
1930            }
1931            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1932                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1933            }
1934        }
1935        return null;
1936    }
1937
1938    @Override
1939    public String[] currentToCanonicalPackageNames(String[] names) {
1940        String[] out = new String[names.length];
1941        // reader
1942        synchronized (mPackages) {
1943            for (int i=names.length-1; i>=0; i--) {
1944                PackageSetting ps = mSettings.mPackages.get(names[i]);
1945                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1946            }
1947        }
1948        return out;
1949    }
1950
1951    @Override
1952    public String[] canonicalToCurrentPackageNames(String[] names) {
1953        String[] out = new String[names.length];
1954        // reader
1955        synchronized (mPackages) {
1956            for (int i=names.length-1; i>=0; i--) {
1957                String cur = mSettings.mRenamedPackages.get(names[i]);
1958                out[i] = cur != null ? cur : names[i];
1959            }
1960        }
1961        return out;
1962    }
1963
1964    @Override
1965    public int getPackageUid(String packageName, int userId) {
1966        if (!sUserManager.exists(userId)) return -1;
1967        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1968        // reader
1969        synchronized (mPackages) {
1970            PackageParser.Package p = mPackages.get(packageName);
1971            if(p != null) {
1972                return UserHandle.getUid(userId, p.applicationInfo.uid);
1973            }
1974            PackageSetting ps = mSettings.mPackages.get(packageName);
1975            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1976                return -1;
1977            }
1978            p = ps.pkg;
1979            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1980        }
1981    }
1982
1983    @Override
1984    public int[] getPackageGids(String packageName) {
1985        // reader
1986        synchronized (mPackages) {
1987            PackageParser.Package p = mPackages.get(packageName);
1988            if (DEBUG_PACKAGE_INFO)
1989                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1990            if (p != null) {
1991                final PackageSetting ps = (PackageSetting)p.mExtras;
1992                return ps.getGids();
1993            }
1994        }
1995        // stupid thing to indicate an error.
1996        return new int[0];
1997    }
1998
1999    static final PermissionInfo generatePermissionInfo(
2000            BasePermission bp, int flags) {
2001        if (bp.perm != null) {
2002            return PackageParser.generatePermissionInfo(bp.perm, flags);
2003        }
2004        PermissionInfo pi = new PermissionInfo();
2005        pi.name = bp.name;
2006        pi.packageName = bp.sourcePackage;
2007        pi.nonLocalizedLabel = bp.name;
2008        pi.protectionLevel = bp.protectionLevel;
2009        return pi;
2010    }
2011
2012    @Override
2013    public PermissionInfo getPermissionInfo(String name, int flags) {
2014        // reader
2015        synchronized (mPackages) {
2016            final BasePermission p = mSettings.mPermissions.get(name);
2017            if (p != null) {
2018                return generatePermissionInfo(p, flags);
2019            }
2020            return null;
2021        }
2022    }
2023
2024    @Override
2025    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2026        // reader
2027        synchronized (mPackages) {
2028            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2029            for (BasePermission p : mSettings.mPermissions.values()) {
2030                if (group == null) {
2031                    if (p.perm == null || p.perm.info.group == null) {
2032                        out.add(generatePermissionInfo(p, flags));
2033                    }
2034                } else {
2035                    if (p.perm != null && group.equals(p.perm.info.group)) {
2036                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2037                    }
2038                }
2039            }
2040
2041            if (out.size() > 0) {
2042                return out;
2043            }
2044            return mPermissionGroups.containsKey(group) ? out : null;
2045        }
2046    }
2047
2048    @Override
2049    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2050        // reader
2051        synchronized (mPackages) {
2052            return PackageParser.generatePermissionGroupInfo(
2053                    mPermissionGroups.get(name), flags);
2054        }
2055    }
2056
2057    @Override
2058    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2059        // reader
2060        synchronized (mPackages) {
2061            final int N = mPermissionGroups.size();
2062            ArrayList<PermissionGroupInfo> out
2063                    = new ArrayList<PermissionGroupInfo>(N);
2064            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2065                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2066            }
2067            return out;
2068        }
2069    }
2070
2071    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2072            int userId) {
2073        if (!sUserManager.exists(userId)) return null;
2074        PackageSetting ps = mSettings.mPackages.get(packageName);
2075        if (ps != null) {
2076            if (ps.pkg == null) {
2077                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2078                        flags, userId);
2079                if (pInfo != null) {
2080                    return pInfo.applicationInfo;
2081                }
2082                return null;
2083            }
2084            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2085                    ps.readUserState(userId), userId);
2086        }
2087        return null;
2088    }
2089
2090    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2091            int userId) {
2092        if (!sUserManager.exists(userId)) return null;
2093        PackageSetting ps = mSettings.mPackages.get(packageName);
2094        if (ps != null) {
2095            PackageParser.Package pkg = ps.pkg;
2096            if (pkg == null) {
2097                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2098                    return null;
2099                }
2100                // Only data remains, so we aren't worried about code paths
2101                pkg = new PackageParser.Package(packageName);
2102                pkg.applicationInfo.packageName = packageName;
2103                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2104                pkg.applicationInfo.dataDir =
2105                        getDataPathForPackage(packageName, 0).getPath();
2106                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2107                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2108            }
2109            return generatePackageInfo(pkg, flags, userId);
2110        }
2111        return null;
2112    }
2113
2114    @Override
2115    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2116        if (!sUserManager.exists(userId)) return null;
2117        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2118        // writer
2119        synchronized (mPackages) {
2120            PackageParser.Package p = mPackages.get(packageName);
2121            if (DEBUG_PACKAGE_INFO) Log.v(
2122                    TAG, "getApplicationInfo " + packageName
2123                    + ": " + p);
2124            if (p != null) {
2125                PackageSetting ps = mSettings.mPackages.get(packageName);
2126                if (ps == null) return null;
2127                // Note: isEnabledLP() does not apply here - always return info
2128                return PackageParser.generateApplicationInfo(
2129                        p, flags, ps.readUserState(userId), userId);
2130            }
2131            if ("android".equals(packageName)||"system".equals(packageName)) {
2132                return mAndroidApplication;
2133            }
2134            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2135                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2136            }
2137        }
2138        return null;
2139    }
2140
2141
2142    @Override
2143    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2144        mContext.enforceCallingOrSelfPermission(
2145                android.Manifest.permission.CLEAR_APP_CACHE, null);
2146        // Queue up an async operation since clearing cache may take a little while.
2147        mHandler.post(new Runnable() {
2148            public void run() {
2149                mHandler.removeCallbacks(this);
2150                int retCode = -1;
2151                synchronized (mInstallLock) {
2152                    retCode = mInstaller.freeCache(freeStorageSize);
2153                    if (retCode < 0) {
2154                        Slog.w(TAG, "Couldn't clear application caches");
2155                    }
2156                }
2157                if (observer != null) {
2158                    try {
2159                        observer.onRemoveCompleted(null, (retCode >= 0));
2160                    } catch (RemoteException e) {
2161                        Slog.w(TAG, "RemoveException when invoking call back");
2162                    }
2163                }
2164            }
2165        });
2166    }
2167
2168    @Override
2169    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2170        mContext.enforceCallingOrSelfPermission(
2171                android.Manifest.permission.CLEAR_APP_CACHE, null);
2172        // Queue up an async operation since clearing cache may take a little while.
2173        mHandler.post(new Runnable() {
2174            public void run() {
2175                mHandler.removeCallbacks(this);
2176                int retCode = -1;
2177                synchronized (mInstallLock) {
2178                    retCode = mInstaller.freeCache(freeStorageSize);
2179                    if (retCode < 0) {
2180                        Slog.w(TAG, "Couldn't clear application caches");
2181                    }
2182                }
2183                if(pi != null) {
2184                    try {
2185                        // Callback via pending intent
2186                        int code = (retCode >= 0) ? 1 : 0;
2187                        pi.sendIntent(null, code, null,
2188                                null, null);
2189                    } catch (SendIntentException e1) {
2190                        Slog.i(TAG, "Failed to send pending intent");
2191                    }
2192                }
2193            }
2194        });
2195    }
2196
2197    void freeStorage(long freeStorageSize) throws IOException {
2198        synchronized (mInstallLock) {
2199            if (mInstaller.freeCache(freeStorageSize) < 0) {
2200                throw new IOException("Failed to free enough space");
2201            }
2202        }
2203    }
2204
2205    @Override
2206    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2207        if (!sUserManager.exists(userId)) return null;
2208        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2209        synchronized (mPackages) {
2210            PackageParser.Activity a = mActivities.mActivities.get(component);
2211
2212            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2213            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2214                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2215                if (ps == null) return null;
2216                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2217                        userId);
2218            }
2219            if (mResolveComponentName.equals(component)) {
2220                return mResolveActivity;
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2228            String resolvedType) {
2229        synchronized (mPackages) {
2230            PackageParser.Activity a = mActivities.mActivities.get(component);
2231            if (a == null) {
2232                return false;
2233            }
2234            for (int i=0; i<a.intents.size(); i++) {
2235                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2236                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2237                    return true;
2238                }
2239            }
2240            return false;
2241        }
2242    }
2243
2244    @Override
2245    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2246        if (!sUserManager.exists(userId)) return null;
2247        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2248        synchronized (mPackages) {
2249            PackageParser.Activity a = mReceivers.mActivities.get(component);
2250            if (DEBUG_PACKAGE_INFO) Log.v(
2251                TAG, "getReceiverInfo " + component + ": " + a);
2252            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2253                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2254                if (ps == null) return null;
2255                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2256                        userId);
2257            }
2258        }
2259        return null;
2260    }
2261
2262    @Override
2263    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2264        if (!sUserManager.exists(userId)) return null;
2265        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2266        synchronized (mPackages) {
2267            PackageParser.Service s = mServices.mServices.get(component);
2268            if (DEBUG_PACKAGE_INFO) Log.v(
2269                TAG, "getServiceInfo " + component + ": " + s);
2270            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2271                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2272                if (ps == null) return null;
2273                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2274                        userId);
2275            }
2276        }
2277        return null;
2278    }
2279
2280    @Override
2281    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2282        if (!sUserManager.exists(userId)) return null;
2283        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2284        synchronized (mPackages) {
2285            PackageParser.Provider p = mProviders.mProviders.get(component);
2286            if (DEBUG_PACKAGE_INFO) Log.v(
2287                TAG, "getProviderInfo " + component + ": " + p);
2288            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2289                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2290                if (ps == null) return null;
2291                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2292                        userId);
2293            }
2294        }
2295        return null;
2296    }
2297
2298    @Override
2299    public String[] getSystemSharedLibraryNames() {
2300        Set<String> libSet;
2301        synchronized (mPackages) {
2302            libSet = mSharedLibraries.keySet();
2303            int size = libSet.size();
2304            if (size > 0) {
2305                String[] libs = new String[size];
2306                libSet.toArray(libs);
2307                return libs;
2308            }
2309        }
2310        return null;
2311    }
2312
2313    @Override
2314    public FeatureInfo[] getSystemAvailableFeatures() {
2315        Collection<FeatureInfo> featSet;
2316        synchronized (mPackages) {
2317            featSet = mAvailableFeatures.values();
2318            int size = featSet.size();
2319            if (size > 0) {
2320                FeatureInfo[] features = new FeatureInfo[size+1];
2321                featSet.toArray(features);
2322                FeatureInfo fi = new FeatureInfo();
2323                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2324                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2325                features[size] = fi;
2326                return features;
2327            }
2328        }
2329        return null;
2330    }
2331
2332    @Override
2333    public boolean hasSystemFeature(String name) {
2334        synchronized (mPackages) {
2335            return mAvailableFeatures.containsKey(name);
2336        }
2337    }
2338
2339    private void checkValidCaller(int uid, int userId) {
2340        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2341            return;
2342
2343        throw new SecurityException("Caller uid=" + uid
2344                + " is not privileged to communicate with user=" + userId);
2345    }
2346
2347    @Override
2348    public int checkPermission(String permName, String pkgName) {
2349        synchronized (mPackages) {
2350            PackageParser.Package p = mPackages.get(pkgName);
2351            if (p != null && p.mExtras != null) {
2352                PackageSetting ps = (PackageSetting)p.mExtras;
2353                if (ps.sharedUser != null) {
2354                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2355                        return PackageManager.PERMISSION_GRANTED;
2356                    }
2357                } else if (ps.grantedPermissions.contains(permName)) {
2358                    return PackageManager.PERMISSION_GRANTED;
2359                }
2360            }
2361        }
2362        return PackageManager.PERMISSION_DENIED;
2363    }
2364
2365    @Override
2366    public int checkUidPermission(String permName, int uid) {
2367        synchronized (mPackages) {
2368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2369            if (obj != null) {
2370                GrantedPermissions gp = (GrantedPermissions)obj;
2371                if (gp.grantedPermissions.contains(permName)) {
2372                    return PackageManager.PERMISSION_GRANTED;
2373                }
2374            } else {
2375                HashSet<String> perms = mSystemPermissions.get(uid);
2376                if (perms != null && perms.contains(permName)) {
2377                    return PackageManager.PERMISSION_GRANTED;
2378                }
2379            }
2380        }
2381        return PackageManager.PERMISSION_DENIED;
2382    }
2383
2384    /**
2385     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2386     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2387     * @param message the message to log on security exception
2388     */
2389    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2390            String message) {
2391        if (userId < 0) {
2392            throw new IllegalArgumentException("Invalid userId " + userId);
2393        }
2394        if (userId == UserHandle.getUserId(callingUid)) return;
2395        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2396            if (requireFullPermission) {
2397                mContext.enforceCallingOrSelfPermission(
2398                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2399            } else {
2400                try {
2401                    mContext.enforceCallingOrSelfPermission(
2402                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2403                } catch (SecurityException se) {
2404                    mContext.enforceCallingOrSelfPermission(
2405                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2406                }
2407            }
2408        }
2409    }
2410
2411    private BasePermission findPermissionTreeLP(String permName) {
2412        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2413            if (permName.startsWith(bp.name) &&
2414                    permName.length() > bp.name.length() &&
2415                    permName.charAt(bp.name.length()) == '.') {
2416                return bp;
2417            }
2418        }
2419        return null;
2420    }
2421
2422    private BasePermission checkPermissionTreeLP(String permName) {
2423        if (permName != null) {
2424            BasePermission bp = findPermissionTreeLP(permName);
2425            if (bp != null) {
2426                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2427                    return bp;
2428                }
2429                throw new SecurityException("Calling uid "
2430                        + Binder.getCallingUid()
2431                        + " is not allowed to add to permission tree "
2432                        + bp.name + " owned by uid " + bp.uid);
2433            }
2434        }
2435        throw new SecurityException("No permission tree found for " + permName);
2436    }
2437
2438    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2439        if (s1 == null) {
2440            return s2 == null;
2441        }
2442        if (s2 == null) {
2443            return false;
2444        }
2445        if (s1.getClass() != s2.getClass()) {
2446            return false;
2447        }
2448        return s1.equals(s2);
2449    }
2450
2451    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2452        if (pi1.icon != pi2.icon) return false;
2453        if (pi1.logo != pi2.logo) return false;
2454        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2455        if (!compareStrings(pi1.name, pi2.name)) return false;
2456        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2457        // We'll take care of setting this one.
2458        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2459        // These are not currently stored in settings.
2460        //if (!compareStrings(pi1.group, pi2.group)) return false;
2461        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2462        //if (pi1.labelRes != pi2.labelRes) return false;
2463        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2464        return true;
2465    }
2466
2467    int permissionInfoFootprint(PermissionInfo info) {
2468        int size = info.name.length();
2469        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2470        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2471        return size;
2472    }
2473
2474    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2475        int size = 0;
2476        for (BasePermission perm : mSettings.mPermissions.values()) {
2477            if (perm.uid == tree.uid) {
2478                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2479            }
2480        }
2481        return size;
2482    }
2483
2484    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2485        // We calculate the max size of permissions defined by this uid and throw
2486        // if that plus the size of 'info' would exceed our stated maximum.
2487        if (tree.uid != Process.SYSTEM_UID) {
2488            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2489            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2490                throw new SecurityException("Permission tree size cap exceeded");
2491            }
2492        }
2493    }
2494
2495    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2496        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2497            throw new SecurityException("Label must be specified in permission");
2498        }
2499        BasePermission tree = checkPermissionTreeLP(info.name);
2500        BasePermission bp = mSettings.mPermissions.get(info.name);
2501        boolean added = bp == null;
2502        boolean changed = true;
2503        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2504        if (added) {
2505            enforcePermissionCapLocked(info, tree);
2506            bp = new BasePermission(info.name, tree.sourcePackage,
2507                    BasePermission.TYPE_DYNAMIC);
2508        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2509            throw new SecurityException(
2510                    "Not allowed to modify non-dynamic permission "
2511                    + info.name);
2512        } else {
2513            if (bp.protectionLevel == fixedLevel
2514                    && bp.perm.owner.equals(tree.perm.owner)
2515                    && bp.uid == tree.uid
2516                    && comparePermissionInfos(bp.perm.info, info)) {
2517                changed = false;
2518            }
2519        }
2520        bp.protectionLevel = fixedLevel;
2521        info = new PermissionInfo(info);
2522        info.protectionLevel = fixedLevel;
2523        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2524        bp.perm.info.packageName = tree.perm.info.packageName;
2525        bp.uid = tree.uid;
2526        if (added) {
2527            mSettings.mPermissions.put(info.name, bp);
2528        }
2529        if (changed) {
2530            if (!async) {
2531                mSettings.writeLPr();
2532            } else {
2533                scheduleWriteSettingsLocked();
2534            }
2535        }
2536        return added;
2537    }
2538
2539    @Override
2540    public boolean addPermission(PermissionInfo info) {
2541        synchronized (mPackages) {
2542            return addPermissionLocked(info, false);
2543        }
2544    }
2545
2546    @Override
2547    public boolean addPermissionAsync(PermissionInfo info) {
2548        synchronized (mPackages) {
2549            return addPermissionLocked(info, true);
2550        }
2551    }
2552
2553    @Override
2554    public void removePermission(String name) {
2555        synchronized (mPackages) {
2556            checkPermissionTreeLP(name);
2557            BasePermission bp = mSettings.mPermissions.get(name);
2558            if (bp != null) {
2559                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2560                    throw new SecurityException(
2561                            "Not allowed to modify non-dynamic permission "
2562                            + name);
2563                }
2564                mSettings.mPermissions.remove(name);
2565                mSettings.writeLPr();
2566            }
2567        }
2568    }
2569
2570    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2571        int index = pkg.requestedPermissions.indexOf(bp.name);
2572        if (index == -1) {
2573            throw new SecurityException("Package " + pkg.packageName
2574                    + " has not requested permission " + bp.name);
2575        }
2576        boolean isNormal =
2577                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2578                        == PermissionInfo.PROTECTION_NORMAL);
2579        boolean isDangerous =
2580                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2581                        == PermissionInfo.PROTECTION_DANGEROUS);
2582        boolean isDevelopment =
2583                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2584
2585        if (!isNormal && !isDangerous && !isDevelopment) {
2586            throw new SecurityException("Permission " + bp.name
2587                    + " is not a changeable permission type");
2588        }
2589
2590        if (isNormal || isDangerous) {
2591            if (pkg.requestedPermissionsRequired.get(index)) {
2592                throw new SecurityException("Can't change " + bp.name
2593                        + ". It is required by the application");
2594            }
2595        }
2596    }
2597
2598    @Override
2599    public void grantPermission(String packageName, String permissionName) {
2600        mContext.enforceCallingOrSelfPermission(
2601                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2602        synchronized (mPackages) {
2603            final PackageParser.Package pkg = mPackages.get(packageName);
2604            if (pkg == null) {
2605                throw new IllegalArgumentException("Unknown package: " + packageName);
2606            }
2607            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2608            if (bp == null) {
2609                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2610            }
2611
2612            checkGrantRevokePermissions(pkg, bp);
2613
2614            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2615            if (ps == null) {
2616                return;
2617            }
2618            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2619            if (gp.grantedPermissions.add(permissionName)) {
2620                if (ps.haveGids) {
2621                    gp.gids = appendInts(gp.gids, bp.gids);
2622                }
2623                mSettings.writeLPr();
2624            }
2625        }
2626    }
2627
2628    @Override
2629    public void revokePermission(String packageName, String permissionName) {
2630        int changedAppId = -1;
2631
2632        synchronized (mPackages) {
2633            final PackageParser.Package pkg = mPackages.get(packageName);
2634            if (pkg == null) {
2635                throw new IllegalArgumentException("Unknown package: " + packageName);
2636            }
2637            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2638                mContext.enforceCallingOrSelfPermission(
2639                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2640            }
2641            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2642            if (bp == null) {
2643                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2644            }
2645
2646            checkGrantRevokePermissions(pkg, bp);
2647
2648            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2649            if (ps == null) {
2650                return;
2651            }
2652            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2653            if (gp.grantedPermissions.remove(permissionName)) {
2654                gp.grantedPermissions.remove(permissionName);
2655                if (ps.haveGids) {
2656                    gp.gids = removeInts(gp.gids, bp.gids);
2657                }
2658                mSettings.writeLPr();
2659                changedAppId = ps.appId;
2660            }
2661        }
2662
2663        if (changedAppId >= 0) {
2664            // We changed the perm on someone, kill its processes.
2665            IActivityManager am = ActivityManagerNative.getDefault();
2666            if (am != null) {
2667                final int callingUserId = UserHandle.getCallingUserId();
2668                final long ident = Binder.clearCallingIdentity();
2669                try {
2670                    //XXX we should only revoke for the calling user's app permissions,
2671                    // but for now we impact all users.
2672                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2673                    //        "revoke " + permissionName);
2674                    int[] users = sUserManager.getUserIds();
2675                    for (int user : users) {
2676                        am.killUid(UserHandle.getUid(user, changedAppId),
2677                                "revoke " + permissionName);
2678                    }
2679                } catch (RemoteException e) {
2680                } finally {
2681                    Binder.restoreCallingIdentity(ident);
2682                }
2683            }
2684        }
2685    }
2686
2687    @Override
2688    public boolean isProtectedBroadcast(String actionName) {
2689        synchronized (mPackages) {
2690            return mProtectedBroadcasts.contains(actionName);
2691        }
2692    }
2693
2694    @Override
2695    public int checkSignatures(String pkg1, String pkg2) {
2696        synchronized (mPackages) {
2697            final PackageParser.Package p1 = mPackages.get(pkg1);
2698            final PackageParser.Package p2 = mPackages.get(pkg2);
2699            if (p1 == null || p1.mExtras == null
2700                    || p2 == null || p2.mExtras == null) {
2701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2702            }
2703            return compareSignatures(p1.mSignatures, p2.mSignatures);
2704        }
2705    }
2706
2707    @Override
2708    public int checkUidSignatures(int uid1, int uid2) {
2709        // Map to base uids.
2710        uid1 = UserHandle.getAppId(uid1);
2711        uid2 = UserHandle.getAppId(uid2);
2712        // reader
2713        synchronized (mPackages) {
2714            Signature[] s1;
2715            Signature[] s2;
2716            Object obj = mSettings.getUserIdLPr(uid1);
2717            if (obj != null) {
2718                if (obj instanceof SharedUserSetting) {
2719                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2720                } else if (obj instanceof PackageSetting) {
2721                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2722                } else {
2723                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2724                }
2725            } else {
2726                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2727            }
2728            obj = mSettings.getUserIdLPr(uid2);
2729            if (obj != null) {
2730                if (obj instanceof SharedUserSetting) {
2731                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2732                } else if (obj instanceof PackageSetting) {
2733                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2734                } else {
2735                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2736                }
2737            } else {
2738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2739            }
2740            return compareSignatures(s1, s2);
2741        }
2742    }
2743
2744    /**
2745     * Compares two sets of signatures. Returns:
2746     * <br />
2747     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2748     * <br />
2749     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2750     * <br />
2751     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2752     * <br />
2753     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2754     * <br />
2755     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2756     */
2757    static int compareSignatures(Signature[] s1, Signature[] s2) {
2758        if (s1 == null) {
2759            return s2 == null
2760                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2761                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2762        }
2763
2764        if (s2 == null) {
2765            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2766        }
2767
2768        if (s1.length != s2.length) {
2769            return PackageManager.SIGNATURE_NO_MATCH;
2770        }
2771
2772        // Since both signature sets are of size 1, we can compare without HashSets.
2773        if (s1.length == 1) {
2774            return s1[0].equals(s2[0]) ?
2775                    PackageManager.SIGNATURE_MATCH :
2776                    PackageManager.SIGNATURE_NO_MATCH;
2777        }
2778
2779        HashSet<Signature> set1 = new HashSet<Signature>();
2780        for (Signature sig : s1) {
2781            set1.add(sig);
2782        }
2783        HashSet<Signature> set2 = new HashSet<Signature>();
2784        for (Signature sig : s2) {
2785            set2.add(sig);
2786        }
2787        // Make sure s2 contains all signatures in s1.
2788        if (set1.equals(set2)) {
2789            return PackageManager.SIGNATURE_MATCH;
2790        }
2791        return PackageManager.SIGNATURE_NO_MATCH;
2792    }
2793
2794    /**
2795     * If the database version for this type of package (internal storage or
2796     * external storage) is less than the version where package signatures
2797     * were updated, return true.
2798     */
2799    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2800        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2801                DatabaseVersion.SIGNATURE_END_ENTITY))
2802                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2803                        DatabaseVersion.SIGNATURE_END_ENTITY));
2804    }
2805
2806    /**
2807     * Used for backward compatibility to make sure any packages with
2808     * certificate chains get upgraded to the new style. {@code existingSigs}
2809     * will be in the old format (since they were stored on disk from before the
2810     * system upgrade) and {@code scannedSigs} will be in the newer format.
2811     */
2812    private int compareSignaturesCompat(PackageSignatures existingSigs,
2813            PackageParser.Package scannedPkg) {
2814        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2815            return PackageManager.SIGNATURE_NO_MATCH;
2816        }
2817
2818        HashSet<Signature> existingSet = new HashSet<Signature>();
2819        for (Signature sig : existingSigs.mSignatures) {
2820            existingSet.add(sig);
2821        }
2822        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2823        for (Signature sig : scannedPkg.mSignatures) {
2824            try {
2825                Signature[] chainSignatures = sig.getChainSignatures();
2826                for (Signature chainSig : chainSignatures) {
2827                    scannedCompatSet.add(chainSig);
2828                }
2829            } catch (CertificateEncodingException e) {
2830                scannedCompatSet.add(sig);
2831            }
2832        }
2833        /*
2834         * Make sure the expanded scanned set contains all signatures in the
2835         * existing one.
2836         */
2837        if (scannedCompatSet.equals(existingSet)) {
2838            // Migrate the old signatures to the new scheme.
2839            existingSigs.assignSignatures(scannedPkg.mSignatures);
2840            // The new KeySets will be re-added later in the scanning process.
2841            synchronized (mPackages) {
2842                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2843            }
2844            return PackageManager.SIGNATURE_MATCH;
2845        }
2846        return PackageManager.SIGNATURE_NO_MATCH;
2847    }
2848
2849    @Override
2850    public String[] getPackagesForUid(int uid) {
2851        uid = UserHandle.getAppId(uid);
2852        // reader
2853        synchronized (mPackages) {
2854            Object obj = mSettings.getUserIdLPr(uid);
2855            if (obj instanceof SharedUserSetting) {
2856                final SharedUserSetting sus = (SharedUserSetting) obj;
2857                final int N = sus.packages.size();
2858                final String[] res = new String[N];
2859                final Iterator<PackageSetting> it = sus.packages.iterator();
2860                int i = 0;
2861                while (it.hasNext()) {
2862                    res[i++] = it.next().name;
2863                }
2864                return res;
2865            } else if (obj instanceof PackageSetting) {
2866                final PackageSetting ps = (PackageSetting) obj;
2867                return new String[] { ps.name };
2868            }
2869        }
2870        return null;
2871    }
2872
2873    @Override
2874    public String getNameForUid(int uid) {
2875        // reader
2876        synchronized (mPackages) {
2877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2878            if (obj instanceof SharedUserSetting) {
2879                final SharedUserSetting sus = (SharedUserSetting) obj;
2880                return sus.name + ":" + sus.userId;
2881            } else if (obj instanceof PackageSetting) {
2882                final PackageSetting ps = (PackageSetting) obj;
2883                return ps.name;
2884            }
2885        }
2886        return null;
2887    }
2888
2889    @Override
2890    public int getUidForSharedUser(String sharedUserName) {
2891        if(sharedUserName == null) {
2892            return -1;
2893        }
2894        // reader
2895        synchronized (mPackages) {
2896            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2897            if (suid == null) {
2898                return -1;
2899            }
2900            return suid.userId;
2901        }
2902    }
2903
2904    @Override
2905    public int getFlagsForUid(int uid) {
2906        synchronized (mPackages) {
2907            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2908            if (obj instanceof SharedUserSetting) {
2909                final SharedUserSetting sus = (SharedUserSetting) obj;
2910                return sus.pkgFlags;
2911            } else if (obj instanceof PackageSetting) {
2912                final PackageSetting ps = (PackageSetting) obj;
2913                return ps.pkgFlags;
2914            }
2915        }
2916        return 0;
2917    }
2918
2919    @Override
2920    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2921            int flags, int userId) {
2922        if (!sUserManager.exists(userId)) return null;
2923        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2924        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2925        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2926    }
2927
2928    @Override
2929    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2930            IntentFilter filter, int match, ComponentName activity) {
2931        final int userId = UserHandle.getCallingUserId();
2932        if (DEBUG_PREFERRED) {
2933            Log.v(TAG, "setLastChosenActivity intent=" + intent
2934                + " resolvedType=" + resolvedType
2935                + " flags=" + flags
2936                + " filter=" + filter
2937                + " match=" + match
2938                + " activity=" + activity);
2939            filter.dump(new PrintStreamPrinter(System.out), "    ");
2940        }
2941        intent.setComponent(null);
2942        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2943        // Find any earlier preferred or last chosen entries and nuke them
2944        findPreferredActivity(intent, resolvedType,
2945                flags, query, 0, false, true, false, userId);
2946        // Add the new activity as the last chosen for this filter
2947        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2948    }
2949
2950    @Override
2951    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2952        final int userId = UserHandle.getCallingUserId();
2953        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2954        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2955        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2956                false, false, false, userId);
2957    }
2958
2959    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2960            int flags, List<ResolveInfo> query, int userId) {
2961        if (query != null) {
2962            final int N = query.size();
2963            if (N == 1) {
2964                return query.get(0);
2965            } else if (N > 1) {
2966                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2967                // If there is more than one activity with the same priority,
2968                // then let the user decide between them.
2969                ResolveInfo r0 = query.get(0);
2970                ResolveInfo r1 = query.get(1);
2971                if (DEBUG_INTENT_MATCHING || debug) {
2972                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2973                            + r1.activityInfo.name + "=" + r1.priority);
2974                }
2975                // If the first activity has a higher priority, or a different
2976                // default, then it is always desireable to pick it.
2977                if (r0.priority != r1.priority
2978                        || r0.preferredOrder != r1.preferredOrder
2979                        || r0.isDefault != r1.isDefault) {
2980                    return query.get(0);
2981                }
2982                // If we have saved a preference for a preferred activity for
2983                // this Intent, use that.
2984                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2985                        flags, query, r0.priority, true, false, debug, userId);
2986                if (ri != null) {
2987                    return ri;
2988                }
2989                if (userId != 0) {
2990                    ri = new ResolveInfo(mResolveInfo);
2991                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2992                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2993                            ri.activityInfo.applicationInfo);
2994                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2995                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2996                    return ri;
2997                }
2998                return mResolveInfo;
2999            }
3000        }
3001        return null;
3002    }
3003
3004    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3005            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3006        final int N = query.size();
3007        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3008                .get(userId);
3009        // Get the list of persistent preferred activities that handle the intent
3010        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3011        List<PersistentPreferredActivity> pprefs = ppir != null
3012                ? ppir.queryIntent(intent, resolvedType,
3013                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3014                : null;
3015        if (pprefs != null && pprefs.size() > 0) {
3016            final int M = pprefs.size();
3017            for (int i=0; i<M; i++) {
3018                final PersistentPreferredActivity ppa = pprefs.get(i);
3019                if (DEBUG_PREFERRED || debug) {
3020                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3021                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3022                            + "\n  component=" + ppa.mComponent);
3023                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3024                }
3025                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3026                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3027                if (DEBUG_PREFERRED || debug) {
3028                    Slog.v(TAG, "Found persistent preferred activity:");
3029                    if (ai != null) {
3030                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3031                    } else {
3032                        Slog.v(TAG, "  null");
3033                    }
3034                }
3035                if (ai == null) {
3036                    // This previously registered persistent preferred activity
3037                    // component is no longer known. Ignore it and do NOT remove it.
3038                    continue;
3039                }
3040                for (int j=0; j<N; j++) {
3041                    final ResolveInfo ri = query.get(j);
3042                    if (!ri.activityInfo.applicationInfo.packageName
3043                            .equals(ai.applicationInfo.packageName)) {
3044                        continue;
3045                    }
3046                    if (!ri.activityInfo.name.equals(ai.name)) {
3047                        continue;
3048                    }
3049                    //  Found a persistent preference that can handle the intent.
3050                    if (DEBUG_PREFERRED || debug) {
3051                        Slog.v(TAG, "Returning persistent preferred activity: " +
3052                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3053                    }
3054                    return ri;
3055                }
3056            }
3057        }
3058        return null;
3059    }
3060
3061    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3062            List<ResolveInfo> query, int priority, boolean always,
3063            boolean removeMatches, boolean debug, int userId) {
3064        if (!sUserManager.exists(userId)) return null;
3065        // writer
3066        synchronized (mPackages) {
3067            if (intent.getSelector() != null) {
3068                intent = intent.getSelector();
3069            }
3070            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3071
3072            // Try to find a matching persistent preferred activity.
3073            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3074                    debug, userId);
3075
3076            // If a persistent preferred activity matched, use it.
3077            if (pri != null) {
3078                return pri;
3079            }
3080
3081            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3082            // Get the list of preferred activities that handle the intent
3083            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3084            List<PreferredActivity> prefs = pir != null
3085                    ? pir.queryIntent(intent, resolvedType,
3086                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3087                    : null;
3088            if (prefs != null && prefs.size() > 0) {
3089                // First figure out how good the original match set is.
3090                // We will only allow preferred activities that came
3091                // from the same match quality.
3092                int match = 0;
3093
3094                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3095
3096                final int N = query.size();
3097                for (int j=0; j<N; j++) {
3098                    final ResolveInfo ri = query.get(j);
3099                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3100                            + ": 0x" + Integer.toHexString(match));
3101                    if (ri.match > match) {
3102                        match = ri.match;
3103                    }
3104                }
3105
3106                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3107                        + Integer.toHexString(match));
3108
3109                match &= IntentFilter.MATCH_CATEGORY_MASK;
3110                final int M = prefs.size();
3111                for (int i=0; i<M; i++) {
3112                    final PreferredActivity pa = prefs.get(i);
3113                    if (DEBUG_PREFERRED || debug) {
3114                        Slog.v(TAG, "Checking PreferredActivity ds="
3115                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3116                                + "\n  component=" + pa.mPref.mComponent);
3117                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3118                    }
3119                    if (pa.mPref.mMatch != match) {
3120                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3121                                + Integer.toHexString(pa.mPref.mMatch));
3122                        continue;
3123                    }
3124                    // If it's not an "always" type preferred activity and that's what we're
3125                    // looking for, skip it.
3126                    if (always && !pa.mPref.mAlways) {
3127                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3128                        continue;
3129                    }
3130                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3131                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3132                    if (DEBUG_PREFERRED || debug) {
3133                        Slog.v(TAG, "Found preferred activity:");
3134                        if (ai != null) {
3135                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3136                        } else {
3137                            Slog.v(TAG, "  null");
3138                        }
3139                    }
3140                    if (ai == null) {
3141                        // This previously registered preferred activity
3142                        // component is no longer known.  Most likely an update
3143                        // to the app was installed and in the new version this
3144                        // component no longer exists.  Clean it up by removing
3145                        // it from the preferred activities list, and skip it.
3146                        Slog.w(TAG, "Removing dangling preferred activity: "
3147                                + pa.mPref.mComponent);
3148                        pir.removeFilter(pa);
3149                        continue;
3150                    }
3151                    for (int j=0; j<N; j++) {
3152                        final ResolveInfo ri = query.get(j);
3153                        if (!ri.activityInfo.applicationInfo.packageName
3154                                .equals(ai.applicationInfo.packageName)) {
3155                            continue;
3156                        }
3157                        if (!ri.activityInfo.name.equals(ai.name)) {
3158                            continue;
3159                        }
3160
3161                        if (removeMatches) {
3162                            pir.removeFilter(pa);
3163                            if (DEBUG_PREFERRED) {
3164                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3165                            }
3166                            break;
3167                        }
3168
3169                        // Okay we found a previously set preferred or last chosen app.
3170                        // If the result set is different from when this
3171                        // was created, we need to clear it and re-ask the
3172                        // user their preference, if we're looking for an "always" type entry.
3173                        if (always && !pa.mPref.sameSet(query, priority)) {
3174                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3175                                    + intent + " type " + resolvedType);
3176                            if (DEBUG_PREFERRED) {
3177                                Slog.v(TAG, "Removing preferred activity since set changed "
3178                                        + pa.mPref.mComponent);
3179                            }
3180                            pir.removeFilter(pa);
3181                            // Re-add the filter as a "last chosen" entry (!always)
3182                            PreferredActivity lastChosen = new PreferredActivity(
3183                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3184                            pir.addFilter(lastChosen);
3185                            mSettings.writePackageRestrictionsLPr(userId);
3186                            return null;
3187                        }
3188
3189                        // Yay! Either the set matched or we're looking for the last chosen
3190                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3191                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3192                        mSettings.writePackageRestrictionsLPr(userId);
3193                        return ri;
3194                    }
3195                }
3196            }
3197            mSettings.writePackageRestrictionsLPr(userId);
3198        }
3199        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3200        return null;
3201    }
3202
3203    /*
3204     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3205     */
3206    @Override
3207    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3208            int targetUserId) {
3209        mContext.enforceCallingOrSelfPermission(
3210                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3211        List<CrossProfileIntentFilter> matches =
3212                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3213        if (matches != null) {
3214            int size = matches.size();
3215            for (int i = 0; i < size; i++) {
3216                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3217            }
3218        }
3219
3220        ArrayList<String> packageNames = null;
3221        SparseArray<ArrayList<String>> fromSource =
3222                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3223        if (fromSource != null) {
3224            packageNames = fromSource.get(targetUserId);
3225        }
3226        if (packageNames.contains(intent.getPackage())) {
3227            return true;
3228        }
3229        // We need the package name, so we try to resolve with the loosest flags possible
3230        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3231                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3232        int count = resolveInfos.size();
3233        for (int i = 0; i < count; i++) {
3234            ResolveInfo resolveInfo = resolveInfos.get(i);
3235            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3236                return true;
3237            }
3238        }
3239        return false;
3240    }
3241
3242    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3243            String resolvedType, int userId) {
3244        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3245        if (resolver != null) {
3246            return resolver.queryIntent(intent, resolvedType, false, userId);
3247        }
3248        return null;
3249    }
3250
3251    @Override
3252    public List<ResolveInfo> queryIntentActivities(Intent intent,
3253            String resolvedType, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return Collections.emptyList();
3255        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3256        ComponentName comp = intent.getComponent();
3257        if (comp == null) {
3258            if (intent.getSelector() != null) {
3259                intent = intent.getSelector();
3260                comp = intent.getComponent();
3261            }
3262        }
3263
3264        if (comp != null) {
3265            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3266            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3267            if (ai != null) {
3268                final ResolveInfo ri = new ResolveInfo();
3269                ri.activityInfo = ai;
3270                list.add(ri);
3271            }
3272            return list;
3273        }
3274
3275        // reader
3276        synchronized (mPackages) {
3277            final String pkgName = intent.getPackage();
3278            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3279            if (pkgName == null) {
3280                ResolveInfo resolveInfo = null;
3281                if (queryCrossProfile) {
3282                    // Check if the intent needs to be forwarded to another user for this package
3283                    ArrayList<ResolveInfo> crossProfileResult =
3284                            queryIntentActivitiesCrossProfilePackage(
3285                                    intent, resolvedType, flags, userId);
3286                    if (!crossProfileResult.isEmpty()) {
3287                        // Skip the current profile
3288                        return crossProfileResult;
3289                    }
3290                    List<CrossProfileIntentFilter> matchingFilters =
3291                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3292                    // Check for results that need to skip the current profile.
3293                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3294                            resolvedType, flags, userId);
3295                    if (resolveInfo != null) {
3296                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3297                        result.add(resolveInfo);
3298                        return result;
3299                    }
3300                    // Check for cross profile results.
3301                    resolveInfo = queryCrossProfileIntents(
3302                            matchingFilters, intent, resolvedType, flags, userId);
3303                }
3304                // Check for results in the current profile.
3305                List<ResolveInfo> result = mActivities.queryIntent(
3306                        intent, resolvedType, flags, userId);
3307                if (resolveInfo != null) {
3308                    result.add(resolveInfo);
3309                }
3310                return result;
3311            }
3312            final PackageParser.Package pkg = mPackages.get(pkgName);
3313            if (pkg != null) {
3314                if (queryCrossProfile) {
3315                    ArrayList<ResolveInfo> crossProfileResult =
3316                            queryIntentActivitiesCrossProfilePackage(
3317                                    intent, resolvedType, flags, userId, pkg, pkgName);
3318                    if (!crossProfileResult.isEmpty()) {
3319                        // Skip the current profile
3320                        return crossProfileResult;
3321                    }
3322                }
3323                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3324                        pkg.activities, userId);
3325            }
3326            return new ArrayList<ResolveInfo>();
3327        }
3328    }
3329
3330    private ResolveInfo querySkipCurrentProfileIntents(
3331            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3332            int flags, int sourceUserId) {
3333        if (matchingFilters != null) {
3334            int size = matchingFilters.size();
3335            for (int i = 0; i < size; i ++) {
3336                CrossProfileIntentFilter filter = matchingFilters.get(i);
3337                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3338                    // Checking if there are activities in the target user that can handle the
3339                    // intent.
3340                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3341                            flags, sourceUserId);
3342                    if (resolveInfo != null) {
3343                        return resolveInfo;
3344                    }
3345                }
3346            }
3347        }
3348        return null;
3349    }
3350
3351    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3352            Intent intent, String resolvedType, int flags, int userId) {
3353        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3354        SparseArray<ArrayList<String>> sourceForwardingInfo =
3355                mSettings.mCrossProfilePackageInfo.get(userId);
3356        if (sourceForwardingInfo != null) {
3357            int NI = sourceForwardingInfo.size();
3358            for (int i = 0; i < NI; i++) {
3359                int targetUserId = sourceForwardingInfo.keyAt(i);
3360                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3361                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3362                        intent, resolvedType, flags, targetUserId);
3363                int NJ = resolveInfos.size();
3364                for (int j = 0; j < NJ; j++) {
3365                    ResolveInfo resolveInfo = resolveInfos.get(j);
3366                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3367                        matchingResolveInfos.add(createForwardingResolveInfo(
3368                                resolveInfo.filter, userId, targetUserId));
3369                    }
3370                }
3371            }
3372        }
3373        return matchingResolveInfos;
3374    }
3375
3376    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3377            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3378            String packageName) {
3379        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3380        SparseArray<ArrayList<String>> sourceForwardingInfo =
3381                mSettings.mCrossProfilePackageInfo.get(userId);
3382        if (sourceForwardingInfo != null) {
3383            int NI = sourceForwardingInfo.size();
3384            for (int i = 0; i < NI; i++) {
3385                int targetUserId = sourceForwardingInfo.keyAt(i);
3386                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3387                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3388                            intent, resolvedType, flags, pkg.activities, targetUserId);
3389                    int NJ = resolveInfos.size();
3390                    for (int j = 0; j < NJ; j++) {
3391                        ResolveInfo resolveInfo = resolveInfos.get(j);
3392                        matchingResolveInfos.add(createForwardingResolveInfo(
3393                                resolveInfo.filter, userId, targetUserId));
3394                    }
3395                }
3396            }
3397        }
3398        return matchingResolveInfos;
3399    }
3400
3401    // Return matching ResolveInfo if any for skip current profile intent filters.
3402    private ResolveInfo queryCrossProfileIntents(
3403            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3404            int flags, int sourceUserId) {
3405        if (matchingFilters != null) {
3406            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3407            // match the same intent. For performance reasons, it is better not to
3408            // run queryIntent twice for the same userId
3409            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3410            int size = matchingFilters.size();
3411            for (int i = 0; i < size; i++) {
3412                CrossProfileIntentFilter filter = matchingFilters.get(i);
3413                int targetUserId = filter.getTargetUserId();
3414                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3415                        && !alreadyTriedUserIds.get(targetUserId)) {
3416                    // Checking if there are activities in the target user that can handle the
3417                    // intent.
3418                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3419                            flags, sourceUserId);
3420                    if (resolveInfo != null) return resolveInfo;
3421                    alreadyTriedUserIds.put(targetUserId, true);
3422                }
3423            }
3424        }
3425        return null;
3426    }
3427
3428    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3429            String resolvedType, int flags, int sourceUserId) {
3430        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3431                resolvedType, flags, filter.getTargetUserId());
3432        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3433            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3434        }
3435        return null;
3436    }
3437
3438    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3439            int sourceUserId, int targetUserId) {
3440        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3441        String className;
3442        if (targetUserId == UserHandle.USER_OWNER) {
3443            className = FORWARD_INTENT_TO_USER_OWNER;
3444        } else {
3445            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3446        }
3447        ComponentName forwardingActivityComponentName = new ComponentName(
3448                mAndroidApplication.packageName, className);
3449        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3450                sourceUserId);
3451        if (targetUserId == UserHandle.USER_OWNER) {
3452            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3453            forwardingResolveInfo.noResourceId = true;
3454        }
3455        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3456        forwardingResolveInfo.priority = 0;
3457        forwardingResolveInfo.preferredOrder = 0;
3458        forwardingResolveInfo.match = 0;
3459        forwardingResolveInfo.isDefault = true;
3460        forwardingResolveInfo.filter = filter;
3461        forwardingResolveInfo.targetUserId = targetUserId;
3462        return forwardingResolveInfo;
3463    }
3464
3465    @Override
3466    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3467            Intent[] specifics, String[] specificTypes, Intent intent,
3468            String resolvedType, int flags, int userId) {
3469        if (!sUserManager.exists(userId)) return Collections.emptyList();
3470        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3471                "query intent activity options");
3472        final String resultsAction = intent.getAction();
3473
3474        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3475                | PackageManager.GET_RESOLVED_FILTER, userId);
3476
3477        if (DEBUG_INTENT_MATCHING) {
3478            Log.v(TAG, "Query " + intent + ": " + results);
3479        }
3480
3481        int specificsPos = 0;
3482        int N;
3483
3484        // todo: note that the algorithm used here is O(N^2).  This
3485        // isn't a problem in our current environment, but if we start running
3486        // into situations where we have more than 5 or 10 matches then this
3487        // should probably be changed to something smarter...
3488
3489        // First we go through and resolve each of the specific items
3490        // that were supplied, taking care of removing any corresponding
3491        // duplicate items in the generic resolve list.
3492        if (specifics != null) {
3493            for (int i=0; i<specifics.length; i++) {
3494                final Intent sintent = specifics[i];
3495                if (sintent == null) {
3496                    continue;
3497                }
3498
3499                if (DEBUG_INTENT_MATCHING) {
3500                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3501                }
3502
3503                String action = sintent.getAction();
3504                if (resultsAction != null && resultsAction.equals(action)) {
3505                    // If this action was explicitly requested, then don't
3506                    // remove things that have it.
3507                    action = null;
3508                }
3509
3510                ResolveInfo ri = null;
3511                ActivityInfo ai = null;
3512
3513                ComponentName comp = sintent.getComponent();
3514                if (comp == null) {
3515                    ri = resolveIntent(
3516                        sintent,
3517                        specificTypes != null ? specificTypes[i] : null,
3518                            flags, userId);
3519                    if (ri == null) {
3520                        continue;
3521                    }
3522                    if (ri == mResolveInfo) {
3523                        // ACK!  Must do something better with this.
3524                    }
3525                    ai = ri.activityInfo;
3526                    comp = new ComponentName(ai.applicationInfo.packageName,
3527                            ai.name);
3528                } else {
3529                    ai = getActivityInfo(comp, flags, userId);
3530                    if (ai == null) {
3531                        continue;
3532                    }
3533                }
3534
3535                // Look for any generic query activities that are duplicates
3536                // of this specific one, and remove them from the results.
3537                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3538                N = results.size();
3539                int j;
3540                for (j=specificsPos; j<N; j++) {
3541                    ResolveInfo sri = results.get(j);
3542                    if ((sri.activityInfo.name.equals(comp.getClassName())
3543                            && sri.activityInfo.applicationInfo.packageName.equals(
3544                                    comp.getPackageName()))
3545                        || (action != null && sri.filter.matchAction(action))) {
3546                        results.remove(j);
3547                        if (DEBUG_INTENT_MATCHING) Log.v(
3548                            TAG, "Removing duplicate item from " + j
3549                            + " due to specific " + specificsPos);
3550                        if (ri == null) {
3551                            ri = sri;
3552                        }
3553                        j--;
3554                        N--;
3555                    }
3556                }
3557
3558                // Add this specific item to its proper place.
3559                if (ri == null) {
3560                    ri = new ResolveInfo();
3561                    ri.activityInfo = ai;
3562                }
3563                results.add(specificsPos, ri);
3564                ri.specificIndex = i;
3565                specificsPos++;
3566            }
3567        }
3568
3569        // Now we go through the remaining generic results and remove any
3570        // duplicate actions that are found here.
3571        N = results.size();
3572        for (int i=specificsPos; i<N-1; i++) {
3573            final ResolveInfo rii = results.get(i);
3574            if (rii.filter == null) {
3575                continue;
3576            }
3577
3578            // Iterate over all of the actions of this result's intent
3579            // filter...  typically this should be just one.
3580            final Iterator<String> it = rii.filter.actionsIterator();
3581            if (it == null) {
3582                continue;
3583            }
3584            while (it.hasNext()) {
3585                final String action = it.next();
3586                if (resultsAction != null && resultsAction.equals(action)) {
3587                    // If this action was explicitly requested, then don't
3588                    // remove things that have it.
3589                    continue;
3590                }
3591                for (int j=i+1; j<N; j++) {
3592                    final ResolveInfo rij = results.get(j);
3593                    if (rij.filter != null && rij.filter.hasAction(action)) {
3594                        results.remove(j);
3595                        if (DEBUG_INTENT_MATCHING) Log.v(
3596                            TAG, "Removing duplicate item from " + j
3597                            + " due to action " + action + " at " + i);
3598                        j--;
3599                        N--;
3600                    }
3601                }
3602            }
3603
3604            // If the caller didn't request filter information, drop it now
3605            // so we don't have to marshall/unmarshall it.
3606            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3607                rii.filter = null;
3608            }
3609        }
3610
3611        // Filter out the caller activity if so requested.
3612        if (caller != null) {
3613            N = results.size();
3614            for (int i=0; i<N; i++) {
3615                ActivityInfo ainfo = results.get(i).activityInfo;
3616                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3617                        && caller.getClassName().equals(ainfo.name)) {
3618                    results.remove(i);
3619                    break;
3620                }
3621            }
3622        }
3623
3624        // If the caller didn't request filter information,
3625        // drop them now so we don't have to
3626        // marshall/unmarshall it.
3627        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3628            N = results.size();
3629            for (int i=0; i<N; i++) {
3630                results.get(i).filter = null;
3631            }
3632        }
3633
3634        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3635        return results;
3636    }
3637
3638    @Override
3639    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3640            int userId) {
3641        if (!sUserManager.exists(userId)) return Collections.emptyList();
3642        ComponentName comp = intent.getComponent();
3643        if (comp == null) {
3644            if (intent.getSelector() != null) {
3645                intent = intent.getSelector();
3646                comp = intent.getComponent();
3647            }
3648        }
3649        if (comp != null) {
3650            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3651            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3652            if (ai != null) {
3653                ResolveInfo ri = new ResolveInfo();
3654                ri.activityInfo = ai;
3655                list.add(ri);
3656            }
3657            return list;
3658        }
3659
3660        // reader
3661        synchronized (mPackages) {
3662            String pkgName = intent.getPackage();
3663            if (pkgName == null) {
3664                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3665            }
3666            final PackageParser.Package pkg = mPackages.get(pkgName);
3667            if (pkg != null) {
3668                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3669                        userId);
3670            }
3671            return null;
3672        }
3673    }
3674
3675    @Override
3676    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3677        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3678        if (!sUserManager.exists(userId)) return null;
3679        if (query != null) {
3680            if (query.size() >= 1) {
3681                // If there is more than one service with the same priority,
3682                // just arbitrarily pick the first one.
3683                return query.get(0);
3684            }
3685        }
3686        return null;
3687    }
3688
3689    @Override
3690    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3691            int userId) {
3692        if (!sUserManager.exists(userId)) return Collections.emptyList();
3693        ComponentName comp = intent.getComponent();
3694        if (comp == null) {
3695            if (intent.getSelector() != null) {
3696                intent = intent.getSelector();
3697                comp = intent.getComponent();
3698            }
3699        }
3700        if (comp != null) {
3701            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3702            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3703            if (si != null) {
3704                final ResolveInfo ri = new ResolveInfo();
3705                ri.serviceInfo = si;
3706                list.add(ri);
3707            }
3708            return list;
3709        }
3710
3711        // reader
3712        synchronized (mPackages) {
3713            String pkgName = intent.getPackage();
3714            if (pkgName == null) {
3715                return mServices.queryIntent(intent, resolvedType, flags, userId);
3716            }
3717            final PackageParser.Package pkg = mPackages.get(pkgName);
3718            if (pkg != null) {
3719                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3720                        userId);
3721            }
3722            return null;
3723        }
3724    }
3725
3726    @Override
3727    public List<ResolveInfo> queryIntentContentProviders(
3728            Intent intent, String resolvedType, int flags, int userId) {
3729        if (!sUserManager.exists(userId)) return Collections.emptyList();
3730        ComponentName comp = intent.getComponent();
3731        if (comp == null) {
3732            if (intent.getSelector() != null) {
3733                intent = intent.getSelector();
3734                comp = intent.getComponent();
3735            }
3736        }
3737        if (comp != null) {
3738            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3739            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3740            if (pi != null) {
3741                final ResolveInfo ri = new ResolveInfo();
3742                ri.providerInfo = pi;
3743                list.add(ri);
3744            }
3745            return list;
3746        }
3747
3748        // reader
3749        synchronized (mPackages) {
3750            String pkgName = intent.getPackage();
3751            if (pkgName == null) {
3752                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3753            }
3754            final PackageParser.Package pkg = mPackages.get(pkgName);
3755            if (pkg != null) {
3756                return mProviders.queryIntentForPackage(
3757                        intent, resolvedType, flags, pkg.providers, userId);
3758            }
3759            return null;
3760        }
3761    }
3762
3763    @Override
3764    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3765        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3766
3767        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3768
3769        // writer
3770        synchronized (mPackages) {
3771            ArrayList<PackageInfo> list;
3772            if (listUninstalled) {
3773                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3774                for (PackageSetting ps : mSettings.mPackages.values()) {
3775                    PackageInfo pi;
3776                    if (ps.pkg != null) {
3777                        pi = generatePackageInfo(ps.pkg, flags, userId);
3778                    } else {
3779                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3780                    }
3781                    if (pi != null) {
3782                        list.add(pi);
3783                    }
3784                }
3785            } else {
3786                list = new ArrayList<PackageInfo>(mPackages.size());
3787                for (PackageParser.Package p : mPackages.values()) {
3788                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3789                    if (pi != null) {
3790                        list.add(pi);
3791                    }
3792                }
3793            }
3794
3795            return new ParceledListSlice<PackageInfo>(list);
3796        }
3797    }
3798
3799    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3800            String[] permissions, boolean[] tmp, int flags, int userId) {
3801        int numMatch = 0;
3802        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3803        for (int i=0; i<permissions.length; i++) {
3804            if (gp.grantedPermissions.contains(permissions[i])) {
3805                tmp[i] = true;
3806                numMatch++;
3807            } else {
3808                tmp[i] = false;
3809            }
3810        }
3811        if (numMatch == 0) {
3812            return;
3813        }
3814        PackageInfo pi;
3815        if (ps.pkg != null) {
3816            pi = generatePackageInfo(ps.pkg, flags, userId);
3817        } else {
3818            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3819        }
3820        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3821            if (numMatch == permissions.length) {
3822                pi.requestedPermissions = permissions;
3823            } else {
3824                pi.requestedPermissions = new String[numMatch];
3825                numMatch = 0;
3826                for (int i=0; i<permissions.length; i++) {
3827                    if (tmp[i]) {
3828                        pi.requestedPermissions[numMatch] = permissions[i];
3829                        numMatch++;
3830                    }
3831                }
3832            }
3833        }
3834        list.add(pi);
3835    }
3836
3837    @Override
3838    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3839            String[] permissions, int flags, int userId) {
3840        if (!sUserManager.exists(userId)) return null;
3841        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3842
3843        // writer
3844        synchronized (mPackages) {
3845            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3846            boolean[] tmpBools = new boolean[permissions.length];
3847            if (listUninstalled) {
3848                for (PackageSetting ps : mSettings.mPackages.values()) {
3849                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3850                }
3851            } else {
3852                for (PackageParser.Package pkg : mPackages.values()) {
3853                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3854                    if (ps != null) {
3855                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3856                                userId);
3857                    }
3858                }
3859            }
3860
3861            return new ParceledListSlice<PackageInfo>(list);
3862        }
3863    }
3864
3865    @Override
3866    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3867        if (!sUserManager.exists(userId)) return null;
3868        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3869
3870        // writer
3871        synchronized (mPackages) {
3872            ArrayList<ApplicationInfo> list;
3873            if (listUninstalled) {
3874                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3875                for (PackageSetting ps : mSettings.mPackages.values()) {
3876                    ApplicationInfo ai;
3877                    if (ps.pkg != null) {
3878                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3879                                ps.readUserState(userId), userId);
3880                    } else {
3881                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3882                    }
3883                    if (ai != null) {
3884                        list.add(ai);
3885                    }
3886                }
3887            } else {
3888                list = new ArrayList<ApplicationInfo>(mPackages.size());
3889                for (PackageParser.Package p : mPackages.values()) {
3890                    if (p.mExtras != null) {
3891                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3892                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3893                        if (ai != null) {
3894                            list.add(ai);
3895                        }
3896                    }
3897                }
3898            }
3899
3900            return new ParceledListSlice<ApplicationInfo>(list);
3901        }
3902    }
3903
3904    public List<ApplicationInfo> getPersistentApplications(int flags) {
3905        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3906
3907        // reader
3908        synchronized (mPackages) {
3909            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3910            final int userId = UserHandle.getCallingUserId();
3911            while (i.hasNext()) {
3912                final PackageParser.Package p = i.next();
3913                if (p.applicationInfo != null
3914                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3915                        && (!mSafeMode || isSystemApp(p))) {
3916                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3917                    if (ps != null) {
3918                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3919                                ps.readUserState(userId), userId);
3920                        if (ai != null) {
3921                            finalList.add(ai);
3922                        }
3923                    }
3924                }
3925            }
3926        }
3927
3928        return finalList;
3929    }
3930
3931    @Override
3932    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3933        if (!sUserManager.exists(userId)) return null;
3934        // reader
3935        synchronized (mPackages) {
3936            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3937            PackageSetting ps = provider != null
3938                    ? mSettings.mPackages.get(provider.owner.packageName)
3939                    : null;
3940            return ps != null
3941                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3942                    && (!mSafeMode || (provider.info.applicationInfo.flags
3943                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3944                    ? PackageParser.generateProviderInfo(provider, flags,
3945                            ps.readUserState(userId), userId)
3946                    : null;
3947        }
3948    }
3949
3950    /**
3951     * @deprecated
3952     */
3953    @Deprecated
3954    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3955        // reader
3956        synchronized (mPackages) {
3957            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3958                    .entrySet().iterator();
3959            final int userId = UserHandle.getCallingUserId();
3960            while (i.hasNext()) {
3961                Map.Entry<String, PackageParser.Provider> entry = i.next();
3962                PackageParser.Provider p = entry.getValue();
3963                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3964
3965                if (ps != null && p.syncable
3966                        && (!mSafeMode || (p.info.applicationInfo.flags
3967                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3968                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3969                            ps.readUserState(userId), userId);
3970                    if (info != null) {
3971                        outNames.add(entry.getKey());
3972                        outInfo.add(info);
3973                    }
3974                }
3975            }
3976        }
3977    }
3978
3979    @Override
3980    public List<ProviderInfo> queryContentProviders(String processName,
3981            int uid, int flags) {
3982        ArrayList<ProviderInfo> finalList = null;
3983        // reader
3984        synchronized (mPackages) {
3985            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3986            final int userId = processName != null ?
3987                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3988            while (i.hasNext()) {
3989                final PackageParser.Provider p = i.next();
3990                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3991                if (ps != null && p.info.authority != null
3992                        && (processName == null
3993                                || (p.info.processName.equals(processName)
3994                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3995                        && mSettings.isEnabledLPr(p.info, flags, userId)
3996                        && (!mSafeMode
3997                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3998                    if (finalList == null) {
3999                        finalList = new ArrayList<ProviderInfo>(3);
4000                    }
4001                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4002                            ps.readUserState(userId), userId);
4003                    if (info != null) {
4004                        finalList.add(info);
4005                    }
4006                }
4007            }
4008        }
4009
4010        if (finalList != null) {
4011            Collections.sort(finalList, mProviderInitOrderSorter);
4012        }
4013
4014        return finalList;
4015    }
4016
4017    @Override
4018    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4019            int flags) {
4020        // reader
4021        synchronized (mPackages) {
4022            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4023            return PackageParser.generateInstrumentationInfo(i, flags);
4024        }
4025    }
4026
4027    @Override
4028    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4029            int flags) {
4030        ArrayList<InstrumentationInfo> finalList =
4031            new ArrayList<InstrumentationInfo>();
4032
4033        // reader
4034        synchronized (mPackages) {
4035            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4036            while (i.hasNext()) {
4037                final PackageParser.Instrumentation p = i.next();
4038                if (targetPackage == null
4039                        || targetPackage.equals(p.info.targetPackage)) {
4040                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4041                            flags);
4042                    if (ii != null) {
4043                        finalList.add(ii);
4044                    }
4045                }
4046            }
4047        }
4048
4049        return finalList;
4050    }
4051
4052    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4053        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4054        if (overlays == null) {
4055            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4056            return;
4057        }
4058        for (PackageParser.Package opkg : overlays.values()) {
4059            // Not much to do if idmap fails: we already logged the error
4060            // and we certainly don't want to abort installation of pkg simply
4061            // because an overlay didn't fit properly. For these reasons,
4062            // ignore the return value of createIdmapForPackagePairLI.
4063            createIdmapForPackagePairLI(pkg, opkg);
4064        }
4065    }
4066
4067    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4068            PackageParser.Package opkg) {
4069        if (!opkg.mTrustedOverlay) {
4070            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4071                    opkg.baseCodePath + ": overlay not trusted");
4072            return false;
4073        }
4074        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4075        if (overlaySet == null) {
4076            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4077                    opkg.baseCodePath + " but target package has no known overlays");
4078            return false;
4079        }
4080        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4081        // TODO: generate idmap for split APKs
4082        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4083            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4084                    + opkg.baseCodePath);
4085            return false;
4086        }
4087        PackageParser.Package[] overlayArray =
4088            overlaySet.values().toArray(new PackageParser.Package[0]);
4089        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4090            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4091                return p1.mOverlayPriority - p2.mOverlayPriority;
4092            }
4093        };
4094        Arrays.sort(overlayArray, cmp);
4095
4096        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4097        int i = 0;
4098        for (PackageParser.Package p : overlayArray) {
4099            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4100        }
4101        return true;
4102    }
4103
4104    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4105        final File[] files = dir.listFiles();
4106        if (ArrayUtils.isEmpty(files)) {
4107            Log.d(TAG, "No files in app dir " + dir);
4108            return;
4109        }
4110
4111        if (DEBUG_PACKAGE_SCANNING) {
4112            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4113                    + " flags=0x" + Integer.toHexString(flags));
4114        }
4115
4116        for (File file : files) {
4117            final boolean isPackage = isApkFile(file) || file.isDirectory();
4118            if (!isPackage) {
4119                // Ignore entries which are not apk's
4120                continue;
4121            }
4122            try {
4123                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4124                        null, null);
4125            } catch (PackageManagerException e) {
4126                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4127
4128                // Don't mess around with apps in system partition.
4129                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4130                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4131                    // Delete the apk
4132                    Slog.w(TAG, "Cleaning up failed install of " + file);
4133                    file.delete();
4134                }
4135            }
4136        }
4137    }
4138
4139    private static File getSettingsProblemFile() {
4140        File dataDir = Environment.getDataDirectory();
4141        File systemDir = new File(dataDir, "system");
4142        File fname = new File(systemDir, "uiderrors.txt");
4143        return fname;
4144    }
4145
4146    static void reportSettingsProblem(int priority, String msg) {
4147        try {
4148            File fname = getSettingsProblemFile();
4149            FileOutputStream out = new FileOutputStream(fname, true);
4150            PrintWriter pw = new FastPrintWriter(out);
4151            SimpleDateFormat formatter = new SimpleDateFormat();
4152            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4153            pw.println(dateString + ": " + msg);
4154            pw.close();
4155            FileUtils.setPermissions(
4156                    fname.toString(),
4157                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4158                    -1, -1);
4159        } catch (java.io.IOException e) {
4160        }
4161        Slog.println(priority, TAG, msg);
4162    }
4163
4164    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4165            PackageParser.Package pkg, File srcFile, int parseFlags)
4166            throws PackageManagerException {
4167        if (ps != null
4168                && ps.codePath.equals(srcFile)
4169                && ps.timeStamp == srcFile.lastModified()
4170                && !isCompatSignatureUpdateNeeded(pkg)) {
4171            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4172            if (ps.signatures.mSignatures != null
4173                    && ps.signatures.mSignatures.length != 0
4174                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4175                // Optimization: reuse the existing cached certificates
4176                // if the package appears to be unchanged.
4177                pkg.mSignatures = ps.signatures.mSignatures;
4178                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4179                synchronized (mPackages) {
4180                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4181                }
4182                return;
4183            }
4184
4185            Slog.w(TAG, "PackageSetting for " + ps.name
4186                    + " is missing signatures.  Collecting certs again to recover them.");
4187        } else {
4188            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4189        }
4190
4191        try {
4192            pp.collectCertificates(pkg, parseFlags);
4193            pp.collectManifestDigest(pkg);
4194        } catch (PackageParserException e) {
4195            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4196                    + pkg.packageName + ": " + e.getMessage());
4197        }
4198    }
4199
4200    /*
4201     *  Scan a package and return the newly parsed package.
4202     *  Returns null in case of errors and the error code is stored in mLastScanError
4203     */
4204    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4205            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4206        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4207        parseFlags |= mDefParseFlags;
4208        PackageParser pp = new PackageParser();
4209        pp.setSeparateProcesses(mSeparateProcesses);
4210        pp.setOnlyCoreApps(mOnlyCore);
4211        pp.setDisplayMetrics(mMetrics);
4212
4213        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4214            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4215        }
4216
4217        final PackageParser.Package pkg;
4218        try {
4219            pkg = pp.parsePackage(scanFile, parseFlags);
4220        } catch (PackageParserException e) {
4221            throw new PackageManagerException(e.error,
4222                    "Failed to scan " + scanFile + ": " + e.getMessage());
4223        }
4224
4225        PackageSetting ps = null;
4226        PackageSetting updatedPkg;
4227        // reader
4228        synchronized (mPackages) {
4229            // Look to see if we already know about this package.
4230            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4231            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4232                // This package has been renamed to its original name.  Let's
4233                // use that.
4234                ps = mSettings.peekPackageLPr(oldName);
4235            }
4236            // If there was no original package, see one for the real package name.
4237            if (ps == null) {
4238                ps = mSettings.peekPackageLPr(pkg.packageName);
4239            }
4240            // Check to see if this package could be hiding/updating a system
4241            // package.  Must look for it either under the original or real
4242            // package name depending on our state.
4243            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4244            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4245        }
4246        boolean updatedPkgBetter = false;
4247        // First check if this is a system package that may involve an update
4248        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4249            if (ps != null && !ps.codePath.equals(scanFile)) {
4250                // The path has changed from what was last scanned...  check the
4251                // version of the new path against what we have stored to determine
4252                // what to do.
4253                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4254                if (pkg.mVersionCode < ps.versionCode) {
4255                    // The system package has been updated and the code path does not match
4256                    // Ignore entry. Skip it.
4257                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4258                            + " ignored: updated version " + ps.versionCode
4259                            + " better than this " + pkg.mVersionCode);
4260                    if (!updatedPkg.codePath.equals(scanFile)) {
4261                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4262                                + ps.name + " changing from " + updatedPkg.codePathString
4263                                + " to " + scanFile);
4264                        updatedPkg.codePath = scanFile;
4265                        updatedPkg.codePathString = scanFile.toString();
4266                        // This is the point at which we know that the system-disk APK
4267                        // for this package has moved during a reboot (e.g. due to an OTA),
4268                        // so we need to reevaluate it for privilege policy.
4269                        if (locationIsPrivileged(scanFile)) {
4270                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4271                        }
4272                    }
4273                    updatedPkg.pkg = pkg;
4274                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4275                } else {
4276                    // The current app on the system partition is better than
4277                    // what we have updated to on the data partition; switch
4278                    // back to the system partition version.
4279                    // At this point, its safely assumed that package installation for
4280                    // apps in system partition will go through. If not there won't be a working
4281                    // version of the app
4282                    // writer
4283                    synchronized (mPackages) {
4284                        // Just remove the loaded entries from package lists.
4285                        mPackages.remove(ps.name);
4286                    }
4287                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4288                            + "reverting from " + ps.codePathString
4289                            + ": new version " + pkg.mVersionCode
4290                            + " better than installed " + ps.versionCode);
4291
4292                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4293                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4294                            getAppDexInstructionSets(ps), isMultiArch(ps));
4295                    synchronized (mInstallLock) {
4296                        args.cleanUpResourcesLI();
4297                    }
4298                    synchronized (mPackages) {
4299                        mSettings.enableSystemPackageLPw(ps.name);
4300                    }
4301                    updatedPkgBetter = true;
4302                }
4303            }
4304        }
4305
4306        if (updatedPkg != null) {
4307            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4308            // initially
4309            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4310
4311            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4312            // flag set initially
4313            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4314                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4315            }
4316        }
4317
4318        // Verify certificates against what was last scanned
4319        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4320
4321        /*
4322         * A new system app appeared, but we already had a non-system one of the
4323         * same name installed earlier.
4324         */
4325        boolean shouldHideSystemApp = false;
4326        if (updatedPkg == null && ps != null
4327                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4328            /*
4329             * Check to make sure the signatures match first. If they don't,
4330             * wipe the installed application and its data.
4331             */
4332            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4333                    != PackageManager.SIGNATURE_MATCH) {
4334                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4335                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4336                ps = null;
4337            } else {
4338                /*
4339                 * If the newly-added system app is an older version than the
4340                 * already installed version, hide it. It will be scanned later
4341                 * and re-added like an update.
4342                 */
4343                if (pkg.mVersionCode < ps.versionCode) {
4344                    shouldHideSystemApp = true;
4345                } else {
4346                    /*
4347                     * The newly found system app is a newer version that the
4348                     * one previously installed. Simply remove the
4349                     * already-installed application and replace it with our own
4350                     * while keeping the application data.
4351                     */
4352                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4353                            + ps.codePathString + ": new version " + pkg.mVersionCode
4354                            + " better than installed " + ps.versionCode);
4355                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4356                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4357                            getAppDexInstructionSets(ps), isMultiArch(ps));
4358                    synchronized (mInstallLock) {
4359                        args.cleanUpResourcesLI();
4360                    }
4361                }
4362            }
4363        }
4364
4365        // The apk is forward locked (not public) if its code and resources
4366        // are kept in different files. (except for app in either system or
4367        // vendor path).
4368        // TODO grab this value from PackageSettings
4369        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4370            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4371                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4372            }
4373        }
4374
4375        // TODO: extend to support forward-locked splits
4376        String resourcePath = null;
4377        String baseResourcePath = null;
4378        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4379            if (ps != null && ps.resourcePathString != null) {
4380                resourcePath = ps.resourcePathString;
4381                baseResourcePath = ps.resourcePathString;
4382            } else {
4383                // Should not happen at all. Just log an error.
4384                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4385            }
4386        } else {
4387            resourcePath = pkg.codePath;
4388            baseResourcePath = pkg.baseCodePath;
4389        }
4390
4391        // Set application objects path explicitly.
4392        pkg.applicationInfo.setCodePath(pkg.codePath);
4393        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4394        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4395        pkg.applicationInfo.setResourcePath(resourcePath);
4396        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4397        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4398
4399        // Note that we invoke the following method only if we are about to unpack an application
4400        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4401                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4402
4403        /*
4404         * If the system app should be overridden by a previously installed
4405         * data, hide the system app now and let the /data/app scan pick it up
4406         * again.
4407         */
4408        if (shouldHideSystemApp) {
4409            synchronized (mPackages) {
4410                /*
4411                 * We have to grant systems permissions before we hide, because
4412                 * grantPermissions will assume the package update is trying to
4413                 * expand its permissions.
4414                 */
4415                grantPermissionsLPw(pkg, true);
4416                mSettings.disableSystemPackageLPw(pkg.packageName);
4417            }
4418        }
4419
4420        return scannedPkg;
4421    }
4422
4423    private static String fixProcessName(String defProcessName,
4424            String processName, int uid) {
4425        if (processName == null) {
4426            return defProcessName;
4427        }
4428        return processName;
4429    }
4430
4431    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4432            throws PackageManagerException {
4433        if (pkgSetting.signatures.mSignatures != null) {
4434            // Already existing package. Make sure signatures match
4435            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4436                    == PackageManager.SIGNATURE_MATCH;
4437            if (!match) {
4438                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4439                        == PackageManager.SIGNATURE_MATCH;
4440            }
4441            if (!match) {
4442                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4443                        + pkg.packageName + " signatures do not match the "
4444                        + "previously installed version; ignoring!");
4445            }
4446        }
4447
4448        // Check for shared user signatures
4449        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4450            // Already existing package. Make sure signatures match
4451            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4452                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4453            if (!match) {
4454                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4455                        == PackageManager.SIGNATURE_MATCH;
4456            }
4457            if (!match) {
4458                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4459                        "Package " + pkg.packageName
4460                        + " has no signatures that match those in shared user "
4461                        + pkgSetting.sharedUser.name + "; ignoring!");
4462            }
4463        }
4464    }
4465
4466    /**
4467     * Enforces that only the system UID or root's UID can call a method exposed
4468     * via Binder.
4469     *
4470     * @param message used as message if SecurityException is thrown
4471     * @throws SecurityException if the caller is not system or root
4472     */
4473    private static final void enforceSystemOrRoot(String message) {
4474        final int uid = Binder.getCallingUid();
4475        if (uid != Process.SYSTEM_UID && uid != 0) {
4476            throw new SecurityException(message);
4477        }
4478    }
4479
4480    @Override
4481    public void performBootDexOpt() {
4482        enforceSystemOrRoot("Only the system can request dexopt be performed");
4483
4484        final HashSet<PackageParser.Package> pkgs;
4485        synchronized (mPackages) {
4486            pkgs = mDeferredDexOpt;
4487            mDeferredDexOpt = null;
4488        }
4489
4490        if (pkgs != null) {
4491            // Filter out packages that aren't recently used.
4492            //
4493            // The exception is first boot of a non-eng device, which
4494            // should do a full dexopt.
4495            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4496            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4497                // TODO: add a property to control this?
4498                long dexOptLRUThresholdInMinutes;
4499                if (eng) {
4500                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4501                } else {
4502                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4503                }
4504                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4505
4506                int total = pkgs.size();
4507                int skipped = 0;
4508                long now = System.currentTimeMillis();
4509                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4510                    PackageParser.Package pkg = i.next();
4511                    long then = pkg.mLastPackageUsageTimeInMills;
4512                    if (then + dexOptLRUThresholdInMills < now) {
4513                        if (DEBUG_DEXOPT) {
4514                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4515                                  ((then == 0) ? "never" : new Date(then)));
4516                        }
4517                        i.remove();
4518                        skipped++;
4519                    }
4520                }
4521                if (DEBUG_DEXOPT) {
4522                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4523                }
4524            }
4525
4526            int i = 0;
4527            for (PackageParser.Package pkg : pkgs) {
4528                i++;
4529                if (DEBUG_DEXOPT) {
4530                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4531                          + ": " + pkg.packageName);
4532                }
4533                if (!isFirstBoot()) {
4534                    try {
4535                        ActivityManagerNative.getDefault().showBootMessage(
4536                                mContext.getResources().getString(
4537                                        R.string.android_upgrading_apk,
4538                                        i, pkgs.size()), true);
4539                    } catch (RemoteException e) {
4540                    }
4541                }
4542                PackageParser.Package p = pkg;
4543                synchronized (mInstallLock) {
4544                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4545                            true /* include dependencies */);
4546                }
4547            }
4548        }
4549    }
4550
4551    @Override
4552    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4553        return performDexOpt(packageName, instructionSet, true);
4554    }
4555
4556    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4557        if (info.primaryCpuAbi == null) {
4558            return getPreferredInstructionSet();
4559        }
4560
4561        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4562    }
4563
4564    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4565        PackageParser.Package p;
4566        final String targetInstructionSet;
4567        synchronized (mPackages) {
4568            p = mPackages.get(packageName);
4569            if (p == null) {
4570                return false;
4571            }
4572            if (updateUsage) {
4573                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4574            }
4575            mPackageUsage.write(false);
4576
4577            targetInstructionSet = instructionSet != null ? instructionSet :
4578                    getPrimaryInstructionSet(p.applicationInfo);
4579            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4580                return false;
4581            }
4582        }
4583
4584        synchronized (mInstallLock) {
4585            final String[] instructionSets = new String[] { targetInstructionSet };
4586            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4587                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4588        }
4589    }
4590
4591    public HashSet<String> getPackagesThatNeedDexOpt() {
4592        HashSet<String> pkgs = null;
4593        synchronized (mPackages) {
4594            for (PackageParser.Package p : mPackages.values()) {
4595                if (DEBUG_DEXOPT) {
4596                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4597                }
4598                if (!p.mDexOptPerformed.isEmpty()) {
4599                    continue;
4600                }
4601                if (pkgs == null) {
4602                    pkgs = new HashSet<String>();
4603                }
4604                pkgs.add(p.packageName);
4605            }
4606        }
4607        return pkgs;
4608    }
4609
4610    public void shutdown() {
4611        mPackageUsage.write(true);
4612    }
4613
4614    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4615             boolean forceDex, boolean defer, HashSet<String> done) {
4616        for (int i=0; i<libs.size(); i++) {
4617            PackageParser.Package libPkg;
4618            String libName;
4619            synchronized (mPackages) {
4620                libName = libs.get(i);
4621                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4622                if (lib != null && lib.apk != null) {
4623                    libPkg = mPackages.get(lib.apk);
4624                } else {
4625                    libPkg = null;
4626                }
4627            }
4628            if (libPkg != null && !done.contains(libName)) {
4629                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4630            }
4631        }
4632    }
4633
4634    static final int DEX_OPT_SKIPPED = 0;
4635    static final int DEX_OPT_PERFORMED = 1;
4636    static final int DEX_OPT_DEFERRED = 2;
4637    static final int DEX_OPT_FAILED = -1;
4638
4639    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4640            boolean forceDex, boolean defer, HashSet<String> done) {
4641        final String[] instructionSets = targetInstructionSets != null ?
4642                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4643
4644        if (done != null) {
4645            done.add(pkg.packageName);
4646            if (pkg.usesLibraries != null) {
4647                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4648            }
4649            if (pkg.usesOptionalLibraries != null) {
4650                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4651            }
4652        }
4653
4654        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4655            return DEX_OPT_SKIPPED;
4656        }
4657
4658        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4659        boolean performedDexOpt = false;
4660        // There are three basic cases here:
4661        // 1.) we need to dexopt, either because we are forced or it is needed
4662        // 2.) we are defering a needed dexopt
4663        // 3.) we are skipping an unneeded dexopt
4664        for (String path : paths) {
4665            for (String instructionSet : instructionSets) {
4666                if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) {
4667                    continue;
4668                }
4669
4670                try {
4671                    final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4672                            pkg.packageName, instructionSet, defer);
4673                    if (forceDex || (!defer && isDexOptNeeded)) {
4674                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4675                                + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4676                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4677                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4678                                pkg.packageName, instructionSet);
4679
4680                        if (ret < 0) {
4681                            // Don't bother running dexopt again if we failed, it will probably
4682                            // just result in an error again. Also, don't bother dexopting for other
4683                            // paths & ISAs.
4684                            return DEX_OPT_FAILED;
4685                        } else {
4686                            performedDexOpt = true;
4687                            pkg.mDexOptPerformed.add(instructionSet);
4688                        }
4689                    }
4690
4691                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4692                    // paths and instruction sets. We'll deal with them all together when we process
4693                    // our list of deferred dexopts.
4694                    if (defer && isDexOptNeeded) {
4695                        if (mDeferredDexOpt == null) {
4696                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4697                        }
4698                        mDeferredDexOpt.add(pkg);
4699                        return DEX_OPT_DEFERRED;
4700                    }
4701                } catch (FileNotFoundException e) {
4702                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4703                    return DEX_OPT_FAILED;
4704                } catch (IOException e) {
4705                    Slog.w(TAG, "IOException reading apk: " + path, e);
4706                    return DEX_OPT_FAILED;
4707                } catch (StaleDexCacheError e) {
4708                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4709                    return DEX_OPT_FAILED;
4710                } catch (Exception e) {
4711                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4712                    return DEX_OPT_FAILED;
4713                }
4714            }
4715        }
4716
4717        // If we've gotten here, we're sure that no error occurred and that we haven't
4718        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4719        // we've skipped all of them because they are up to date. In both cases this
4720        // package doesn't need dexopt any longer.
4721        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4722    }
4723
4724    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4725        if (info.primaryCpuAbi != null) {
4726            if (info.secondaryCpuAbi != null) {
4727                return new String[] {
4728                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4729                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4730            } else {
4731                return new String[] {
4732                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4733            }
4734        }
4735
4736        return new String[] { getPreferredInstructionSet() };
4737    }
4738
4739    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4740        if (ps.primaryCpuAbiString != null) {
4741            if (ps.secondaryCpuAbiString != null) {
4742                return new String[] {
4743                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4744                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4745            } else {
4746                return new String[] {
4747                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4748            }
4749        }
4750
4751        return new String[] { getPreferredInstructionSet() };
4752    }
4753
4754    private static String getPreferredInstructionSet() {
4755        if (sPreferredInstructionSet == null) {
4756            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4757        }
4758
4759        return sPreferredInstructionSet;
4760    }
4761
4762    private static List<String> getAllInstructionSets() {
4763        final String[] allAbis = Build.SUPPORTED_ABIS;
4764        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4765
4766        for (String abi : allAbis) {
4767            final String instructionSet = VMRuntime.getInstructionSet(abi);
4768            if (!allInstructionSets.contains(instructionSet)) {
4769                allInstructionSets.add(instructionSet);
4770            }
4771        }
4772
4773        return allInstructionSets;
4774    }
4775
4776    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4777                                boolean forceDex, boolean defer, boolean inclDependencies) {
4778        HashSet<String> done;
4779        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4780            done = new HashSet<String>();
4781            done.add(pkg.packageName);
4782        } else {
4783            done = null;
4784        }
4785        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4786    }
4787
4788    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4789        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4790            Slog.w(TAG, "Unable to update from " + oldPkg.name
4791                    + " to " + newPkg.packageName
4792                    + ": old package not in system partition");
4793            return false;
4794        } else if (mPackages.get(oldPkg.name) != null) {
4795            Slog.w(TAG, "Unable to update from " + oldPkg.name
4796                    + " to " + newPkg.packageName
4797                    + ": old package still exists");
4798            return false;
4799        }
4800        return true;
4801    }
4802
4803    File getDataPathForUser(int userId) {
4804        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4805    }
4806
4807    private File getDataPathForPackage(String packageName, int userId) {
4808        /*
4809         * Until we fully support multiple users, return the directory we
4810         * previously would have. The PackageManagerTests will need to be
4811         * revised when this is changed back..
4812         */
4813        if (userId == 0) {
4814            return new File(mAppDataDir, packageName);
4815        } else {
4816            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4817                + File.separator + packageName);
4818        }
4819    }
4820
4821    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4822        int[] users = sUserManager.getUserIds();
4823        int res = mInstaller.install(packageName, uid, uid, seinfo);
4824        if (res < 0) {
4825            return res;
4826        }
4827        for (int user : users) {
4828            if (user != 0) {
4829                res = mInstaller.createUserData(packageName,
4830                        UserHandle.getUid(user, uid), user, seinfo);
4831                if (res < 0) {
4832                    return res;
4833                }
4834            }
4835        }
4836        return res;
4837    }
4838
4839    private int removeDataDirsLI(String packageName) {
4840        int[] users = sUserManager.getUserIds();
4841        int res = 0;
4842        for (int user : users) {
4843            int resInner = mInstaller.remove(packageName, user);
4844            if (resInner < 0) {
4845                res = resInner;
4846            }
4847        }
4848
4849        return res;
4850    }
4851
4852    private int deleteCodeCacheDirsLI(String packageName) {
4853        int[] users = sUserManager.getUserIds();
4854        int res = 0;
4855        for (int user : users) {
4856            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4857            if (resInner < 0) {
4858                res = resInner;
4859            }
4860        }
4861        return res;
4862    }
4863
4864    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4865            PackageParser.Package changingLib) {
4866        if (file.path != null) {
4867            usesLibraryFiles.add(file.path);
4868            return;
4869        }
4870        PackageParser.Package p = mPackages.get(file.apk);
4871        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4872            // If we are doing this while in the middle of updating a library apk,
4873            // then we need to make sure to use that new apk for determining the
4874            // dependencies here.  (We haven't yet finished committing the new apk
4875            // to the package manager state.)
4876            if (p == null || p.packageName.equals(changingLib.packageName)) {
4877                p = changingLib;
4878            }
4879        }
4880        if (p != null) {
4881            usesLibraryFiles.addAll(p.getAllCodePaths());
4882        }
4883    }
4884
4885    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4886            PackageParser.Package changingLib) throws PackageManagerException {
4887        // We might be upgrading from a version of the platform that did not
4888        // provide per-package native library directories for system apps.
4889        // Fix that up here.
4890        if (isSystemApp(pkg)) {
4891            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4892            if (!isUpdatedSystemApp(pkg)) {
4893                setBundledAppAbisAndRoots(pkg, ps);
4894            }
4895        }
4896
4897        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4898            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4899            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4900            for (int i=0; i<N; i++) {
4901                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4902                if (file == null) {
4903                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4904                            "Package " + pkg.packageName + " requires unavailable shared library "
4905                            + pkg.usesLibraries.get(i) + "; failing!");
4906                }
4907                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4908            }
4909            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4910            for (int i=0; i<N; i++) {
4911                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4912                if (file == null) {
4913                    Slog.w(TAG, "Package " + pkg.packageName
4914                            + " desires unavailable shared library "
4915                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4916                } else {
4917                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4918                }
4919            }
4920            N = usesLibraryFiles.size();
4921            if (N > 0) {
4922                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4923            } else {
4924                pkg.usesLibraryFiles = null;
4925            }
4926        }
4927    }
4928
4929    private static boolean hasString(List<String> list, List<String> which) {
4930        if (list == null) {
4931            return false;
4932        }
4933        for (int i=list.size()-1; i>=0; i--) {
4934            for (int j=which.size()-1; j>=0; j--) {
4935                if (which.get(j).equals(list.get(i))) {
4936                    return true;
4937                }
4938            }
4939        }
4940        return false;
4941    }
4942
4943    private void updateAllSharedLibrariesLPw() {
4944        for (PackageParser.Package pkg : mPackages.values()) {
4945            try {
4946                updateSharedLibrariesLPw(pkg, null);
4947            } catch (PackageManagerException e) {
4948                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4949            }
4950        }
4951    }
4952
4953    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4954            PackageParser.Package changingPkg) {
4955        ArrayList<PackageParser.Package> res = null;
4956        for (PackageParser.Package pkg : mPackages.values()) {
4957            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4958                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4959                if (res == null) {
4960                    res = new ArrayList<PackageParser.Package>();
4961                }
4962                res.add(pkg);
4963                try {
4964                    updateSharedLibrariesLPw(pkg, changingPkg);
4965                } catch (PackageManagerException e) {
4966                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4967                }
4968            }
4969        }
4970        return res;
4971    }
4972
4973    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4974            int scanMode, long currentTime, UserHandle user, String abiOverride)
4975            throws PackageManagerException {
4976        final File scanFile = new File(pkg.codePath);
4977        if (pkg.applicationInfo.getCodePath() == null ||
4978                pkg.applicationInfo.getResourcePath() == null) {
4979            // Bail out. The resource and code paths haven't been set.
4980            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4981                    "Code and resource paths haven't been set correctly");
4982        }
4983
4984        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4985            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4986        }
4987
4988        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4989            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4990        }
4991
4992        if (mCustomResolverComponentName != null &&
4993                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4994            setUpCustomResolverActivity(pkg);
4995        }
4996
4997        if (pkg.packageName.equals("android")) {
4998            synchronized (mPackages) {
4999                if (mAndroidApplication != null) {
5000                    Slog.w(TAG, "*************************************************");
5001                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5002                    Slog.w(TAG, " file=" + scanFile);
5003                    Slog.w(TAG, "*************************************************");
5004                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5005                            "Core android package being redefined.  Skipping.");
5006                }
5007
5008                // Set up information for our fall-back user intent resolution activity.
5009                mPlatformPackage = pkg;
5010                pkg.mVersionCode = mSdkVersion;
5011                mAndroidApplication = pkg.applicationInfo;
5012
5013                if (!mResolverReplaced) {
5014                    mResolveActivity.applicationInfo = mAndroidApplication;
5015                    mResolveActivity.name = ResolverActivity.class.getName();
5016                    mResolveActivity.packageName = mAndroidApplication.packageName;
5017                    mResolveActivity.processName = "system:ui";
5018                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5019                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5020                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5021                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5022                    mResolveActivity.exported = true;
5023                    mResolveActivity.enabled = true;
5024                    mResolveInfo.activityInfo = mResolveActivity;
5025                    mResolveInfo.priority = 0;
5026                    mResolveInfo.preferredOrder = 0;
5027                    mResolveInfo.match = 0;
5028                    mResolveComponentName = new ComponentName(
5029                            mAndroidApplication.packageName, mResolveActivity.name);
5030                }
5031            }
5032        }
5033
5034        if (DEBUG_PACKAGE_SCANNING) {
5035            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5036                Log.d(TAG, "Scanning package " + pkg.packageName);
5037        }
5038
5039        if (mPackages.containsKey(pkg.packageName)
5040                || mSharedLibraries.containsKey(pkg.packageName)) {
5041            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5042                    "Application package " + pkg.packageName
5043                    + " already installed.  Skipping duplicate.");
5044        }
5045
5046        // Initialize package source and resource directories
5047        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5048        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5049
5050        SharedUserSetting suid = null;
5051        PackageSetting pkgSetting = null;
5052
5053        if (!isSystemApp(pkg)) {
5054            // Only system apps can use these features.
5055            pkg.mOriginalPackages = null;
5056            pkg.mRealPackage = null;
5057            pkg.mAdoptPermissions = null;
5058        }
5059
5060        // writer
5061        synchronized (mPackages) {
5062            if (pkg.mSharedUserId != null) {
5063                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5064                if (suid == null) {
5065                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5066                            "Creating application package " + pkg.packageName
5067                            + " for shared user failed");
5068                }
5069                if (DEBUG_PACKAGE_SCANNING) {
5070                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5071                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5072                                + "): packages=" + suid.packages);
5073                }
5074            }
5075
5076            // Check if we are renaming from an original package name.
5077            PackageSetting origPackage = null;
5078            String realName = null;
5079            if (pkg.mOriginalPackages != null) {
5080                // This package may need to be renamed to a previously
5081                // installed name.  Let's check on that...
5082                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5083                if (pkg.mOriginalPackages.contains(renamed)) {
5084                    // This package had originally been installed as the
5085                    // original name, and we have already taken care of
5086                    // transitioning to the new one.  Just update the new
5087                    // one to continue using the old name.
5088                    realName = pkg.mRealPackage;
5089                    if (!pkg.packageName.equals(renamed)) {
5090                        // Callers into this function may have already taken
5091                        // care of renaming the package; only do it here if
5092                        // it is not already done.
5093                        pkg.setPackageName(renamed);
5094                    }
5095
5096                } else {
5097                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5098                        if ((origPackage = mSettings.peekPackageLPr(
5099                                pkg.mOriginalPackages.get(i))) != null) {
5100                            // We do have the package already installed under its
5101                            // original name...  should we use it?
5102                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5103                                // New package is not compatible with original.
5104                                origPackage = null;
5105                                continue;
5106                            } else if (origPackage.sharedUser != null) {
5107                                // Make sure uid is compatible between packages.
5108                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5109                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5110                                            + " to " + pkg.packageName + ": old uid "
5111                                            + origPackage.sharedUser.name
5112                                            + " differs from " + pkg.mSharedUserId);
5113                                    origPackage = null;
5114                                    continue;
5115                                }
5116                            } else {
5117                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5118                                        + pkg.packageName + " to old name " + origPackage.name);
5119                            }
5120                            break;
5121                        }
5122                    }
5123                }
5124            }
5125
5126            if (mTransferedPackages.contains(pkg.packageName)) {
5127                Slog.w(TAG, "Package " + pkg.packageName
5128                        + " was transferred to another, but its .apk remains");
5129            }
5130
5131            // Just create the setting, don't add it yet. For already existing packages
5132            // the PkgSetting exists already and doesn't have to be created.
5133            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5134                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5135                    pkg.applicationInfo.primaryCpuAbi,
5136                    pkg.applicationInfo.secondaryCpuAbi,
5137                    pkg.applicationInfo.flags, user, false);
5138            if (pkgSetting == null) {
5139                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5140                        "Creating application package " + pkg.packageName + " failed");
5141            }
5142
5143            if (pkgSetting.origPackage != null) {
5144                // If we are first transitioning from an original package,
5145                // fix up the new package's name now.  We need to do this after
5146                // looking up the package under its new name, so getPackageLP
5147                // can take care of fiddling things correctly.
5148                pkg.setPackageName(origPackage.name);
5149
5150                // File a report about this.
5151                String msg = "New package " + pkgSetting.realName
5152                        + " renamed to replace old package " + pkgSetting.name;
5153                reportSettingsProblem(Log.WARN, msg);
5154
5155                // Make a note of it.
5156                mTransferedPackages.add(origPackage.name);
5157
5158                // No longer need to retain this.
5159                pkgSetting.origPackage = null;
5160            }
5161
5162            if (realName != null) {
5163                // Make a note of it.
5164                mTransferedPackages.add(pkg.packageName);
5165            }
5166
5167            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5168                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5169            }
5170
5171            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5172                // Check all shared libraries and map to their actual file path.
5173                // We only do this here for apps not on a system dir, because those
5174                // are the only ones that can fail an install due to this.  We
5175                // will take care of the system apps by updating all of their
5176                // library paths after the scan is done.
5177                updateSharedLibrariesLPw(pkg, null);
5178            }
5179
5180            if (mFoundPolicyFile) {
5181                SELinuxMMAC.assignSeinfoValue(pkg);
5182            }
5183
5184            pkg.applicationInfo.uid = pkgSetting.appId;
5185            pkg.mExtras = pkgSetting;
5186            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5187                try {
5188                    verifySignaturesLP(pkgSetting, pkg);
5189                } catch (PackageManagerException e) {
5190                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5191                        throw e;
5192                    }
5193                    // The signature has changed, but this package is in the system
5194                    // image...  let's recover!
5195                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5196                    // However...  if this package is part of a shared user, but it
5197                    // doesn't match the signature of the shared user, let's fail.
5198                    // What this means is that you can't change the signatures
5199                    // associated with an overall shared user, which doesn't seem all
5200                    // that unreasonable.
5201                    if (pkgSetting.sharedUser != null) {
5202                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5203                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5204                            throw new PackageManagerException(
5205                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5206                                            "Signature mismatch for shared user : "
5207                                            + pkgSetting.sharedUser);
5208                        }
5209                    }
5210                    // File a report about this.
5211                    String msg = "System package " + pkg.packageName
5212                        + " signature changed; retaining data.";
5213                    reportSettingsProblem(Log.WARN, msg);
5214                }
5215            } else {
5216                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5217                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5218                            + pkg.packageName + " upgrade keys do not match the "
5219                            + "previously installed version");
5220                } else {
5221                    // signatures may have changed as result of upgrade
5222                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5223                }
5224            }
5225            // Verify that this new package doesn't have any content providers
5226            // that conflict with existing packages.  Only do this if the
5227            // package isn't already installed, since we don't want to break
5228            // things that are installed.
5229            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5230                final int N = pkg.providers.size();
5231                int i;
5232                for (i=0; i<N; i++) {
5233                    PackageParser.Provider p = pkg.providers.get(i);
5234                    if (p.info.authority != null) {
5235                        String names[] = p.info.authority.split(";");
5236                        for (int j = 0; j < names.length; j++) {
5237                            if (mProvidersByAuthority.containsKey(names[j])) {
5238                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5239                                final String otherPackageName =
5240                                        ((other != null && other.getComponentName() != null) ?
5241                                                other.getComponentName().getPackageName() : "?");
5242                                throw new PackageManagerException(
5243                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5244                                                "Can't install because provider name " + names[j]
5245                                                + " (in package " + pkg.applicationInfo.packageName
5246                                                + ") is already used by " + otherPackageName);
5247                            }
5248                        }
5249                    }
5250                }
5251            }
5252
5253            if (pkg.mAdoptPermissions != null) {
5254                // This package wants to adopt ownership of permissions from
5255                // another package.
5256                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5257                    final String origName = pkg.mAdoptPermissions.get(i);
5258                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5259                    if (orig != null) {
5260                        if (verifyPackageUpdateLPr(orig, pkg)) {
5261                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5262                                    + pkg.packageName);
5263                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5264                        }
5265                    }
5266                }
5267            }
5268        }
5269
5270        final String pkgName = pkg.packageName;
5271
5272        final long scanFileTime = scanFile.lastModified();
5273        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5274        pkg.applicationInfo.processName = fixProcessName(
5275                pkg.applicationInfo.packageName,
5276                pkg.applicationInfo.processName,
5277                pkg.applicationInfo.uid);
5278
5279        File dataPath;
5280        if (mPlatformPackage == pkg) {
5281            // The system package is special.
5282            dataPath = new File (Environment.getDataDirectory(), "system");
5283            pkg.applicationInfo.dataDir = dataPath.getPath();
5284        } else {
5285            // This is a normal package, need to make its data directory.
5286            dataPath = getDataPathForPackage(pkg.packageName, 0);
5287
5288            boolean uidError = false;
5289
5290            if (dataPath.exists()) {
5291                int currentUid = 0;
5292                try {
5293                    StructStat stat = Os.stat(dataPath.getPath());
5294                    currentUid = stat.st_uid;
5295                } catch (ErrnoException e) {
5296                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5297                }
5298
5299                // If we have mismatched owners for the data path, we have a problem.
5300                if (currentUid != pkg.applicationInfo.uid) {
5301                    boolean recovered = false;
5302                    if (currentUid == 0) {
5303                        // The directory somehow became owned by root.  Wow.
5304                        // This is probably because the system was stopped while
5305                        // installd was in the middle of messing with its libs
5306                        // directory.  Ask installd to fix that.
5307                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5308                                pkg.applicationInfo.uid);
5309                        if (ret >= 0) {
5310                            recovered = true;
5311                            String msg = "Package " + pkg.packageName
5312                                    + " unexpectedly changed to uid 0; recovered to " +
5313                                    + pkg.applicationInfo.uid;
5314                            reportSettingsProblem(Log.WARN, msg);
5315                        }
5316                    }
5317                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5318                            || (scanMode&SCAN_BOOTING) != 0)) {
5319                        // If this is a system app, we can at least delete its
5320                        // current data so the application will still work.
5321                        int ret = removeDataDirsLI(pkgName);
5322                        if (ret >= 0) {
5323                            // TODO: Kill the processes first
5324                            // Old data gone!
5325                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5326                                    ? "System package " : "Third party package ";
5327                            String msg = prefix + pkg.packageName
5328                                    + " has changed from uid: "
5329                                    + currentUid + " to "
5330                                    + pkg.applicationInfo.uid + "; old data erased";
5331                            reportSettingsProblem(Log.WARN, msg);
5332                            recovered = true;
5333
5334                            // And now re-install the app.
5335                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5336                                                   pkg.applicationInfo.seinfo);
5337                            if (ret == -1) {
5338                                // Ack should not happen!
5339                                msg = prefix + pkg.packageName
5340                                        + " could not have data directory re-created after delete.";
5341                                reportSettingsProblem(Log.WARN, msg);
5342                                throw new PackageManagerException(
5343                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5344                            }
5345                        }
5346                        if (!recovered) {
5347                            mHasSystemUidErrors = true;
5348                        }
5349                    } else if (!recovered) {
5350                        // If we allow this install to proceed, we will be broken.
5351                        // Abort, abort!
5352                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5353                                "scanPackageLI");
5354                    }
5355                    if (!recovered) {
5356                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5357                            + pkg.applicationInfo.uid + "/fs_"
5358                            + currentUid;
5359                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5360                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5361                        String msg = "Package " + pkg.packageName
5362                                + " has mismatched uid: "
5363                                + currentUid + " on disk, "
5364                                + pkg.applicationInfo.uid + " in settings";
5365                        // writer
5366                        synchronized (mPackages) {
5367                            mSettings.mReadMessages.append(msg);
5368                            mSettings.mReadMessages.append('\n');
5369                            uidError = true;
5370                            if (!pkgSetting.uidError) {
5371                                reportSettingsProblem(Log.ERROR, msg);
5372                            }
5373                        }
5374                    }
5375                }
5376                pkg.applicationInfo.dataDir = dataPath.getPath();
5377                if (mShouldRestoreconData) {
5378                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5379                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5380                                pkg.applicationInfo.uid);
5381                }
5382            } else {
5383                if (DEBUG_PACKAGE_SCANNING) {
5384                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5385                        Log.v(TAG, "Want this data dir: " + dataPath);
5386                }
5387                //invoke installer to do the actual installation
5388                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5389                                           pkg.applicationInfo.seinfo);
5390                if (ret < 0) {
5391                    // Error from installer
5392                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5393                            "Unable to create data dirs [errorCode=" + ret + "]");
5394                }
5395
5396                if (dataPath.exists()) {
5397                    pkg.applicationInfo.dataDir = dataPath.getPath();
5398                } else {
5399                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5400                    pkg.applicationInfo.dataDir = null;
5401                }
5402            }
5403
5404            pkgSetting.uidError = uidError;
5405        }
5406
5407        final String path = scanFile.getPath();
5408        final String codePath = pkg.applicationInfo.getCodePath();
5409        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5410            // For the case where we had previously uninstalled an update, get rid
5411            // of any native binaries we might have unpackaged. Note that this assumes
5412            // that system app updates were not installed via ASEC.
5413            //
5414            // TODO(multiArch): Is this cleanup really necessary ?
5415            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5416                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5417            setBundledAppAbisAndRoots(pkg, pkgSetting);
5418            setNativeLibraryPaths(pkg);
5419        } else {
5420            // TODO: We can probably be smarter about this stuff. For installed apps,
5421            // we can calculate this information at install time once and for all. For
5422            // system apps, we can probably assume that this information doesn't change
5423            // after the first boot scan. As things stand, we do lots of unnecessary work.
5424
5425            // Give ourselves some initial paths; we'll come back for another
5426            // pass once we've determined ABI below.
5427            setNativeLibraryPaths(pkg);
5428
5429            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5430            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5431            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5432
5433            NativeLibraryHelper.Handle handle = null;
5434            try {
5435                handle = NativeLibraryHelper.Handle.create(scanFile);
5436                // TODO(multiArch): This can be null for apps that didn't go through the
5437                // usual installation process. We can calculate it again, like we
5438                // do during install time.
5439                //
5440                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5441                // unnecessary.
5442                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5443
5444                // Null out the abis so that they can be recalculated.
5445                pkg.applicationInfo.primaryCpuAbi = null;
5446                pkg.applicationInfo.secondaryCpuAbi = null;
5447                if (isMultiArch(pkg.applicationInfo)) {
5448                    // Warn if we've set an abiOverride for multi-lib packages..
5449                    // By definition, we need to copy both 32 and 64 bit libraries for
5450                    // such packages.
5451                    if (abiOverride != null) {
5452                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5453                    }
5454
5455                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5456                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5457                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5458                        if (isAsec) {
5459                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5460                        } else {
5461                            abi32 = copyNativeLibrariesForInternalApp(handle,
5462                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5463                        }
5464                    }
5465
5466                    maybeThrowExceptionForMultiArchCopy(
5467                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5468
5469                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5470                        if (isAsec) {
5471                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5472                        } else {
5473                            abi64 = copyNativeLibrariesForInternalApp(handle,
5474                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5475                        }
5476                    }
5477
5478                    maybeThrowExceptionForMultiArchCopy(
5479                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5480
5481                    if (abi64 >= 0) {
5482                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5483                    }
5484
5485                    if (abi32 >= 0) {
5486                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5487                        if (abi64 >= 0) {
5488                            pkg.applicationInfo.secondaryCpuAbi = abi;
5489                        } else {
5490                            pkg.applicationInfo.primaryCpuAbi = abi;
5491                        }
5492                    }
5493                } else {
5494                    String[] abiList = (abiOverride != null) ?
5495                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5496
5497                    // Enable gross and lame hacks for apps that are built with old
5498                    // SDK tools. We must scan their APKs for renderscript bitcode and
5499                    // not launch them if it's present. Don't bother checking on devices
5500                    // that don't have 64 bit support.
5501                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5502                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5503                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5504                    }
5505
5506                    final int copyRet;
5507                    if (isAsec) {
5508                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5509                    } else {
5510                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5511                                useIsaSpecificSubdirs);
5512                    }
5513
5514                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5515                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5516                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5517                    }
5518
5519                    if (copyRet >= 0) {
5520                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5521                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) {
5522                        pkg.applicationInfo.primaryCpuAbi = abiOverride;
5523                    }
5524                }
5525            } catch (IOException ioe) {
5526                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5527            } finally {
5528                IoUtils.closeQuietly(handle);
5529            }
5530
5531            // Now that we've calculated the ABIs and determined if it's an internal app,
5532            // we will go ahead and populate the nativeLibraryPath.
5533            setNativeLibraryPaths(pkg);
5534
5535            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5536            final int[] userIds = sUserManager.getUserIds();
5537            synchronized (mInstallLock) {
5538                // Create a native library symlink only if we have native libraries
5539                // and if the native libraries are 32 bit libraries. We do not provide
5540                // this symlink for 64 bit libraries.
5541                if (pkg.applicationInfo.primaryCpuAbi != null &&
5542                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5543                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5544                    for (int userId : userIds) {
5545                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5546                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5547                                    "Failed linking native library dir (user=" + userId + ")");
5548                        }
5549                    }
5550                }
5551            }
5552
5553            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5554            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5555        }
5556
5557        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5558                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5559                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5560
5561        // Push the derived path down into PackageSettings so we know what to
5562        // clean up at uninstall time.
5563        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5564
5565        if (DEBUG_ABI_SELECTION) {
5566            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5567                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5568                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5569        }
5570
5571        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5572            // We don't do this here during boot because we can do it all
5573            // at once after scanning all existing packages.
5574            //
5575            // We also do this *before* we perform dexopt on this package, so that
5576            // we can avoid redundant dexopts, and also to make sure we've got the
5577            // code and package path correct.
5578            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5579                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5580        }
5581
5582        if ((scanMode&SCAN_NO_DEX) == 0) {
5583            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5584                    == DEX_OPT_FAILED) {
5585                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5586                    removeDataDirsLI(pkg.packageName);
5587                }
5588
5589                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5590            }
5591        }
5592
5593        if (mFactoryTest && pkg.requestedPermissions.contains(
5594                android.Manifest.permission.FACTORY_TEST)) {
5595            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5596        }
5597
5598        ArrayList<PackageParser.Package> clientLibPkgs = null;
5599
5600        // writer
5601        synchronized (mPackages) {
5602            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5603                // Only system apps can add new shared libraries.
5604                if (pkg.libraryNames != null) {
5605                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5606                        String name = pkg.libraryNames.get(i);
5607                        boolean allowed = false;
5608                        if (isUpdatedSystemApp(pkg)) {
5609                            // New library entries can only be added through the
5610                            // system image.  This is important to get rid of a lot
5611                            // of nasty edge cases: for example if we allowed a non-
5612                            // system update of the app to add a library, then uninstalling
5613                            // the update would make the library go away, and assumptions
5614                            // we made such as through app install filtering would now
5615                            // have allowed apps on the device which aren't compatible
5616                            // with it.  Better to just have the restriction here, be
5617                            // conservative, and create many fewer cases that can negatively
5618                            // impact the user experience.
5619                            final PackageSetting sysPs = mSettings
5620                                    .getDisabledSystemPkgLPr(pkg.packageName);
5621                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5622                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5623                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5624                                        allowed = true;
5625                                        allowed = true;
5626                                        break;
5627                                    }
5628                                }
5629                            }
5630                        } else {
5631                            allowed = true;
5632                        }
5633                        if (allowed) {
5634                            if (!mSharedLibraries.containsKey(name)) {
5635                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5636                            } else if (!name.equals(pkg.packageName)) {
5637                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5638                                        + name + " already exists; skipping");
5639                            }
5640                        } else {
5641                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5642                                    + name + " that is not declared on system image; skipping");
5643                        }
5644                    }
5645                    if ((scanMode&SCAN_BOOTING) == 0) {
5646                        // If we are not booting, we need to update any applications
5647                        // that are clients of our shared library.  If we are booting,
5648                        // this will all be done once the scan is complete.
5649                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5650                    }
5651                }
5652            }
5653        }
5654
5655        // We also need to dexopt any apps that are dependent on this library.  Note that
5656        // if these fail, we should abort the install since installing the library will
5657        // result in some apps being broken.
5658        if (clientLibPkgs != null) {
5659            if ((scanMode&SCAN_NO_DEX) == 0) {
5660                for (int i=0; i<clientLibPkgs.size(); i++) {
5661                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5662                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5663                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5664                            == DEX_OPT_FAILED) {
5665                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5666                            removeDataDirsLI(pkg.packageName);
5667                        }
5668
5669                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5670                                "scanPackageLI failed to dexopt clientLibPkgs");
5671                    }
5672                }
5673            }
5674        }
5675
5676        // Request the ActivityManager to kill the process(only for existing packages)
5677        // so that we do not end up in a confused state while the user is still using the older
5678        // version of the application while the new one gets installed.
5679        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5680            // If the package lives in an asec, tell everyone that the container is going
5681            // away so they can clean up any references to its resources (which would prevent
5682            // vold from being able to unmount the asec)
5683            if (isForwardLocked(pkg) || isExternal(pkg)) {
5684                if (DEBUG_INSTALL) {
5685                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5686                }
5687                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5688                final ArrayList<String> pkgList = new ArrayList<String>(1);
5689                pkgList.add(pkg.applicationInfo.packageName);
5690                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5691            }
5692
5693            // Post the request that it be killed now that the going-away broadcast is en route
5694            killApplication(pkg.applicationInfo.packageName,
5695                        pkg.applicationInfo.uid, "update pkg");
5696        }
5697
5698        // Also need to kill any apps that are dependent on the library.
5699        if (clientLibPkgs != null) {
5700            for (int i=0; i<clientLibPkgs.size(); i++) {
5701                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5702                killApplication(clientPkg.applicationInfo.packageName,
5703                        clientPkg.applicationInfo.uid, "update lib");
5704            }
5705        }
5706
5707        // writer
5708        synchronized (mPackages) {
5709            // We don't expect installation to fail beyond this point,
5710            if ((scanMode&SCAN_MONITOR) != 0) {
5711                mAppDirs.put(pkg.codePath, pkg);
5712            }
5713            // Add the new setting to mSettings
5714            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5715            // Add the new setting to mPackages
5716            mPackages.put(pkg.applicationInfo.packageName, pkg);
5717            // Make sure we don't accidentally delete its data.
5718            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5719            while (iter.hasNext()) {
5720                PackageCleanItem item = iter.next();
5721                if (pkgName.equals(item.packageName)) {
5722                    iter.remove();
5723                }
5724            }
5725
5726            // Take care of first install / last update times.
5727            if (currentTime != 0) {
5728                if (pkgSetting.firstInstallTime == 0) {
5729                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5730                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5731                    pkgSetting.lastUpdateTime = currentTime;
5732                }
5733            } else if (pkgSetting.firstInstallTime == 0) {
5734                // We need *something*.  Take time time stamp of the file.
5735                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5736            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5737                if (scanFileTime != pkgSetting.timeStamp) {
5738                    // A package on the system image has changed; consider this
5739                    // to be an update.
5740                    pkgSetting.lastUpdateTime = scanFileTime;
5741                }
5742            }
5743
5744            // Add the package's KeySets to the global KeySetManagerService
5745            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5746            try {
5747                // Old KeySetData no longer valid.
5748                ksms.removeAppKeySetDataLPw(pkg.packageName);
5749                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5750                if (pkg.mKeySetMapping != null) {
5751                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5752                            pkg.mKeySetMapping.entrySet()) {
5753                        if (entry.getValue() != null) {
5754                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5755                                                          entry.getValue(), entry.getKey());
5756                        }
5757                    }
5758                    if (pkg.mUpgradeKeySets != null) {
5759                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5760                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5761                        }
5762                    }
5763                }
5764            } catch (NullPointerException e) {
5765                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5766            } catch (IllegalArgumentException e) {
5767                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5768            }
5769
5770            int N = pkg.providers.size();
5771            StringBuilder r = null;
5772            int i;
5773            for (i=0; i<N; i++) {
5774                PackageParser.Provider p = pkg.providers.get(i);
5775                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5776                        p.info.processName, pkg.applicationInfo.uid);
5777                mProviders.addProvider(p);
5778                p.syncable = p.info.isSyncable;
5779                if (p.info.authority != null) {
5780                    String names[] = p.info.authority.split(";");
5781                    p.info.authority = null;
5782                    for (int j = 0; j < names.length; j++) {
5783                        if (j == 1 && p.syncable) {
5784                            // We only want the first authority for a provider to possibly be
5785                            // syncable, so if we already added this provider using a different
5786                            // authority clear the syncable flag. We copy the provider before
5787                            // changing it because the mProviders object contains a reference
5788                            // to a provider that we don't want to change.
5789                            // Only do this for the second authority since the resulting provider
5790                            // object can be the same for all future authorities for this provider.
5791                            p = new PackageParser.Provider(p);
5792                            p.syncable = false;
5793                        }
5794                        if (!mProvidersByAuthority.containsKey(names[j])) {
5795                            mProvidersByAuthority.put(names[j], p);
5796                            if (p.info.authority == null) {
5797                                p.info.authority = names[j];
5798                            } else {
5799                                p.info.authority = p.info.authority + ";" + names[j];
5800                            }
5801                            if (DEBUG_PACKAGE_SCANNING) {
5802                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5803                                    Log.d(TAG, "Registered content provider: " + names[j]
5804                                            + ", className = " + p.info.name + ", isSyncable = "
5805                                            + p.info.isSyncable);
5806                            }
5807                        } else {
5808                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5809                            Slog.w(TAG, "Skipping provider name " + names[j] +
5810                                    " (in package " + pkg.applicationInfo.packageName +
5811                                    "): name already used by "
5812                                    + ((other != null && other.getComponentName() != null)
5813                                            ? other.getComponentName().getPackageName() : "?"));
5814                        }
5815                    }
5816                }
5817                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5818                    if (r == null) {
5819                        r = new StringBuilder(256);
5820                    } else {
5821                        r.append(' ');
5822                    }
5823                    r.append(p.info.name);
5824                }
5825            }
5826            if (r != null) {
5827                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5828            }
5829
5830            N = pkg.services.size();
5831            r = null;
5832            for (i=0; i<N; i++) {
5833                PackageParser.Service s = pkg.services.get(i);
5834                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5835                        s.info.processName, pkg.applicationInfo.uid);
5836                mServices.addService(s);
5837                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5838                    if (r == null) {
5839                        r = new StringBuilder(256);
5840                    } else {
5841                        r.append(' ');
5842                    }
5843                    r.append(s.info.name);
5844                }
5845            }
5846            if (r != null) {
5847                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5848            }
5849
5850            N = pkg.receivers.size();
5851            r = null;
5852            for (i=0; i<N; i++) {
5853                PackageParser.Activity a = pkg.receivers.get(i);
5854                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5855                        a.info.processName, pkg.applicationInfo.uid);
5856                mReceivers.addActivity(a, "receiver");
5857                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5858                    if (r == null) {
5859                        r = new StringBuilder(256);
5860                    } else {
5861                        r.append(' ');
5862                    }
5863                    r.append(a.info.name);
5864                }
5865            }
5866            if (r != null) {
5867                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5868            }
5869
5870            N = pkg.activities.size();
5871            r = null;
5872            for (i=0; i<N; i++) {
5873                PackageParser.Activity a = pkg.activities.get(i);
5874                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5875                        a.info.processName, pkg.applicationInfo.uid);
5876                mActivities.addActivity(a, "activity");
5877                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5878                    if (r == null) {
5879                        r = new StringBuilder(256);
5880                    } else {
5881                        r.append(' ');
5882                    }
5883                    r.append(a.info.name);
5884                }
5885            }
5886            if (r != null) {
5887                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5888            }
5889
5890            N = pkg.permissionGroups.size();
5891            r = null;
5892            for (i=0; i<N; i++) {
5893                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5894                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5895                if (cur == null) {
5896                    mPermissionGroups.put(pg.info.name, pg);
5897                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5898                        if (r == null) {
5899                            r = new StringBuilder(256);
5900                        } else {
5901                            r.append(' ');
5902                        }
5903                        r.append(pg.info.name);
5904                    }
5905                } else {
5906                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5907                            + pg.info.packageName + " ignored: original from "
5908                            + cur.info.packageName);
5909                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5910                        if (r == null) {
5911                            r = new StringBuilder(256);
5912                        } else {
5913                            r.append(' ');
5914                        }
5915                        r.append("DUP:");
5916                        r.append(pg.info.name);
5917                    }
5918                }
5919            }
5920            if (r != null) {
5921                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5922            }
5923
5924            N = pkg.permissions.size();
5925            r = null;
5926            for (i=0; i<N; i++) {
5927                PackageParser.Permission p = pkg.permissions.get(i);
5928                HashMap<String, BasePermission> permissionMap =
5929                        p.tree ? mSettings.mPermissionTrees
5930                        : mSettings.mPermissions;
5931                p.group = mPermissionGroups.get(p.info.group);
5932                if (p.info.group == null || p.group != null) {
5933                    BasePermission bp = permissionMap.get(p.info.name);
5934                    if (bp == null) {
5935                        bp = new BasePermission(p.info.name, p.info.packageName,
5936                                BasePermission.TYPE_NORMAL);
5937                        permissionMap.put(p.info.name, bp);
5938                    }
5939                    if (bp.perm == null) {
5940                        if (bp.sourcePackage != null
5941                                && !bp.sourcePackage.equals(p.info.packageName)) {
5942                            // If this is a permission that was formerly defined by a non-system
5943                            // app, but is now defined by a system app (following an upgrade),
5944                            // discard the previous declaration and consider the system's to be
5945                            // canonical.
5946                            if (isSystemApp(p.owner)) {
5947                                String msg = "New decl " + p.owner + " of permission  "
5948                                        + p.info.name + " is system";
5949                                reportSettingsProblem(Log.WARN, msg);
5950                                bp.sourcePackage = null;
5951                            }
5952                        }
5953                        if (bp.sourcePackage == null
5954                                || bp.sourcePackage.equals(p.info.packageName)) {
5955                            BasePermission tree = findPermissionTreeLP(p.info.name);
5956                            if (tree == null
5957                                    || tree.sourcePackage.equals(p.info.packageName)) {
5958                                bp.packageSetting = pkgSetting;
5959                                bp.perm = p;
5960                                bp.uid = pkg.applicationInfo.uid;
5961                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5962                                    if (r == null) {
5963                                        r = new StringBuilder(256);
5964                                    } else {
5965                                        r.append(' ');
5966                                    }
5967                                    r.append(p.info.name);
5968                                }
5969                            } else {
5970                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5971                                        + p.info.packageName + " ignored: base tree "
5972                                        + tree.name + " is from package "
5973                                        + tree.sourcePackage);
5974                            }
5975                        } else {
5976                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5977                                    + p.info.packageName + " ignored: original from "
5978                                    + bp.sourcePackage);
5979                        }
5980                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5981                        if (r == null) {
5982                            r = new StringBuilder(256);
5983                        } else {
5984                            r.append(' ');
5985                        }
5986                        r.append("DUP:");
5987                        r.append(p.info.name);
5988                    }
5989                    if (bp.perm == p) {
5990                        bp.protectionLevel = p.info.protectionLevel;
5991                    }
5992                } else {
5993                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5994                            + p.info.packageName + " ignored: no group "
5995                            + p.group);
5996                }
5997            }
5998            if (r != null) {
5999                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6000            }
6001
6002            N = pkg.instrumentation.size();
6003            r = null;
6004            for (i=0; i<N; i++) {
6005                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6006                a.info.packageName = pkg.applicationInfo.packageName;
6007                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6008                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6009                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6010                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6011                a.info.dataDir = pkg.applicationInfo.dataDir;
6012
6013                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6014                // need other information about the application, like the ABI and what not ?
6015                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6016                mInstrumentation.put(a.getComponentName(), a);
6017                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6018                    if (r == null) {
6019                        r = new StringBuilder(256);
6020                    } else {
6021                        r.append(' ');
6022                    }
6023                    r.append(a.info.name);
6024                }
6025            }
6026            if (r != null) {
6027                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6028            }
6029
6030            if (pkg.protectedBroadcasts != null) {
6031                N = pkg.protectedBroadcasts.size();
6032                for (i=0; i<N; i++) {
6033                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6034                }
6035            }
6036
6037            pkgSetting.setTimeStamp(scanFileTime);
6038
6039            // Create idmap files for pairs of (packages, overlay packages).
6040            // Note: "android", ie framework-res.apk, is handled by native layers.
6041            if (pkg.mOverlayTarget != null) {
6042                // This is an overlay package.
6043                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6044                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6045                        mOverlays.put(pkg.mOverlayTarget,
6046                                new HashMap<String, PackageParser.Package>());
6047                    }
6048                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6049                    map.put(pkg.packageName, pkg);
6050                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6051                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6052                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6053                                "scanPackageLI failed to createIdmap");
6054                    }
6055                }
6056            } else if (mOverlays.containsKey(pkg.packageName) &&
6057                    !pkg.packageName.equals("android")) {
6058                // This is a regular package, with one or more known overlay packages.
6059                createIdmapsForPackageLI(pkg);
6060            }
6061        }
6062
6063        return pkg;
6064    }
6065
6066    /**
6067     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6068     * i.e, so that all packages can be run inside a single process if required.
6069     *
6070     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6071     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6072     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6073     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6074     * updating a package that belongs to a shared user.
6075     *
6076     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6077     * adds unnecessary complexity.
6078     */
6079    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6080            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6081        String requiredInstructionSet = null;
6082        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6083            requiredInstructionSet = VMRuntime.getInstructionSet(
6084                     scannedPackage.applicationInfo.primaryCpuAbi);
6085        }
6086
6087        PackageSetting requirer = null;
6088        for (PackageSetting ps : packagesForUser) {
6089            // If packagesForUser contains scannedPackage, we skip it. This will happen
6090            // when scannedPackage is an update of an existing package. Without this check,
6091            // we will never be able to change the ABI of any package belonging to a shared
6092            // user, even if it's compatible with other packages.
6093            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6094                if (ps.primaryCpuAbiString == null) {
6095                    continue;
6096                }
6097
6098                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6099                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6100                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6101                    // this but there's not much we can do.
6102                    String errorMessage = "Instruction set mismatch, "
6103                            + ((requirer == null) ? "[caller]" : requirer)
6104                            + " requires " + requiredInstructionSet + " whereas " + ps
6105                            + " requires " + instructionSet;
6106                    Slog.w(TAG, errorMessage);
6107                }
6108
6109                if (requiredInstructionSet == null) {
6110                    requiredInstructionSet = instructionSet;
6111                    requirer = ps;
6112                }
6113            }
6114        }
6115
6116        if (requiredInstructionSet != null) {
6117            String adjustedAbi;
6118            if (requirer != null) {
6119                // requirer != null implies that either scannedPackage was null or that scannedPackage
6120                // did not require an ABI, in which case we have to adjust scannedPackage to match
6121                // the ABI of the set (which is the same as requirer's ABI)
6122                adjustedAbi = requirer.primaryCpuAbiString;
6123                if (scannedPackage != null) {
6124                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6125                }
6126            } else {
6127                // requirer == null implies that we're updating all ABIs in the set to
6128                // match scannedPackage.
6129                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6130            }
6131
6132            for (PackageSetting ps : packagesForUser) {
6133                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6134                    if (ps.primaryCpuAbiString != null) {
6135                        continue;
6136                    }
6137
6138                    ps.primaryCpuAbiString = adjustedAbi;
6139                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6140                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6141                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6142
6143                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6144                                deferDexOpt, true) == DEX_OPT_FAILED) {
6145                            ps.primaryCpuAbiString = null;
6146                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6147                            return;
6148                        } else {
6149                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6150                        }
6151                    }
6152                }
6153            }
6154        }
6155    }
6156
6157    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6158        synchronized (mPackages) {
6159            mResolverReplaced = true;
6160            // Set up information for custom user intent resolution activity.
6161            mResolveActivity.applicationInfo = pkg.applicationInfo;
6162            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6163            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6164            mResolveActivity.processName = null;
6165            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6166            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6167                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6168            mResolveActivity.theme = 0;
6169            mResolveActivity.exported = true;
6170            mResolveActivity.enabled = true;
6171            mResolveInfo.activityInfo = mResolveActivity;
6172            mResolveInfo.priority = 0;
6173            mResolveInfo.preferredOrder = 0;
6174            mResolveInfo.match = 0;
6175            mResolveComponentName = mCustomResolverComponentName;
6176            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6177                    mResolveComponentName);
6178        }
6179    }
6180
6181    private static String calculateApkRoot(final String codePathString) {
6182        final File codePath = new File(codePathString);
6183        final File codeRoot;
6184        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6185            codeRoot = Environment.getRootDirectory();
6186        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6187            codeRoot = Environment.getOemDirectory();
6188        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6189            codeRoot = Environment.getVendorDirectory();
6190        } else {
6191            // Unrecognized code path; take its top real segment as the apk root:
6192            // e.g. /something/app/blah.apk => /something
6193            try {
6194                File f = codePath.getCanonicalFile();
6195                File parent = f.getParentFile();    // non-null because codePath is a file
6196                File tmp;
6197                while ((tmp = parent.getParentFile()) != null) {
6198                    f = parent;
6199                    parent = tmp;
6200                }
6201                codeRoot = f;
6202                Slog.w(TAG, "Unrecognized code path "
6203                        + codePath + " - using " + codeRoot);
6204            } catch (IOException e) {
6205                // Can't canonicalize the code path -- shenanigans?
6206                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6207                return Environment.getRootDirectory().getPath();
6208            }
6209        }
6210        return codeRoot.getPath();
6211    }
6212
6213    /**
6214     * Derive and set the location of native libraries for the given package,
6215     * which varies depending on where and how the package was installed.
6216     */
6217    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6218        final ApplicationInfo info = pkg.applicationInfo;
6219        final String codePath = pkg.codePath;
6220        final File codeFile = new File(codePath);
6221        // If "/system/lib64/apkname" exists, assume that is the per-package
6222        // native library directory to use; otherwise use "/system/lib/apkname".
6223        final String apkRoot = calculateApkRoot(info.sourceDir);
6224
6225        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6226        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6227
6228
6229        info.nativeLibraryRootDir = null;
6230        info.nativeLibraryRootRequiresIsa = false;
6231        info.nativeLibraryDir = null;
6232        info.secondaryNativeLibraryDir = null;
6233
6234        if (isApkFile(codeFile)) {
6235            // Monolithic install
6236            if (bundledApp) {
6237                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6238                        getPrimaryInstructionSet(info));
6239
6240                // This is a bundled system app so choose the path based on the ABI.
6241                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6242                // is just the default path.
6243                final String apkName = deriveCodePathName(codePath);
6244                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6245                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6246                        apkName).getAbsolutePath();
6247
6248                if (info.secondaryCpuAbi != null) {
6249                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6250                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6251                            secondaryLibDir, apkName).getAbsolutePath();
6252                }
6253            } else if (asecApp) {
6254                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6255                        .getAbsolutePath();
6256            } else {
6257                final String apkName = deriveCodePathName(codePath);
6258                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6259                        .getAbsolutePath();
6260            }
6261
6262            info.nativeLibraryRootRequiresIsa = false;
6263            info.nativeLibraryDir = info.nativeLibraryRootDir;
6264        } else {
6265            // Cluster install
6266            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6267            info.nativeLibraryRootRequiresIsa = true;
6268
6269            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6270                    getPrimaryInstructionSet(info)).getAbsolutePath();
6271
6272            if (info.secondaryCpuAbi != null) {
6273                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6274                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6275            }
6276        }
6277    }
6278
6279    /**
6280     * Calculate the abis and roots for a bundled app. These can uniquely
6281     * be determined from the contents of the system partition, i.e whether
6282     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6283     * of this information, and instead assume that the system was built
6284     * sensibly.
6285     */
6286    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6287                                           PackageSetting pkgSetting) {
6288        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6289
6290        // If "/system/lib64/apkname" exists, assume that is the per-package
6291        // native library directory to use; otherwise use "/system/lib/apkname".
6292        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6293        setBundledAppAbi(pkg, apkRoot, apkName);
6294        // pkgSetting might be null during rescan following uninstall of updates
6295        // to a bundled app, so accommodate that possibility.  The settings in
6296        // that case will be established later from the parsed package.
6297        //
6298        // If the settings aren't null, sync them up with what we've just derived.
6299        // note that apkRoot isn't stored in the package settings.
6300        if (pkgSetting != null) {
6301            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6302            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6303        }
6304    }
6305
6306    /**
6307     * Deduces the ABI of a bundled app and sets the relevant fields on the
6308     * parsed pkg object.
6309     *
6310     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6311     *        under which system libraries are installed.
6312     * @param apkName the name of the installed package.
6313     */
6314    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6315        final File codeFile = new File(pkg.codePath);
6316
6317        final boolean has64BitLibs;
6318        final boolean has32BitLibs;
6319        if (isApkFile(codeFile)) {
6320            // Monolithic install
6321            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6322            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6323        } else {
6324            // Cluster install
6325            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6326            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6327                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6328                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6329                has64BitLibs = (new File(rootDir, isa)).exists();
6330            } else {
6331                has64BitLibs = false;
6332            }
6333            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6334                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6335                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6336                has32BitLibs = (new File(rootDir, isa)).exists();
6337            } else {
6338                has32BitLibs = false;
6339            }
6340        }
6341
6342        if (has64BitLibs && !has32BitLibs) {
6343            // The package has 64 bit libs, but not 32 bit libs. Its primary
6344            // ABI should be 64 bit. We can safely assume here that the bundled
6345            // native libraries correspond to the most preferred ABI in the list.
6346
6347            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6348            pkg.applicationInfo.secondaryCpuAbi = null;
6349        } else if (has32BitLibs && !has64BitLibs) {
6350            // The package has 32 bit libs but not 64 bit libs. Its primary
6351            // ABI should be 32 bit.
6352
6353            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6354            pkg.applicationInfo.secondaryCpuAbi = null;
6355        } else if (has32BitLibs && has64BitLibs) {
6356            // The application has both 64 and 32 bit bundled libraries. We check
6357            // here that the app declares multiArch support, and warn if it doesn't.
6358            //
6359            // We will be lenient here and record both ABIs. The primary will be the
6360            // ABI that's higher on the list, i.e, a device that's configured to prefer
6361            // 64 bit apps will see a 64 bit primary ABI,
6362
6363            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6364                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6365            }
6366
6367            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6368                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6369                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6370            } else {
6371                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6372                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6373            }
6374        } else {
6375            pkg.applicationInfo.primaryCpuAbi = null;
6376            pkg.applicationInfo.secondaryCpuAbi = null;
6377        }
6378    }
6379
6380    private static void createNativeLibrarySubdir(File path) throws IOException {
6381        if (!path.isDirectory()) {
6382            path.delete();
6383
6384            if (!path.mkdir()) {
6385                throw new IOException("Cannot create " + path.getPath());
6386            }
6387
6388            try {
6389                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6390            } catch (ErrnoException e) {
6391                throw new IOException("Cannot chmod native library directory "
6392                        + path.getPath(), e);
6393            }
6394        } else if (!SELinux.restorecon(path)) {
6395            throw new IOException("Cannot set SELinux context for " + path.getPath());
6396        }
6397    }
6398
6399    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6400            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6401        createNativeLibrarySubdir(nativeLibraryRoot);
6402
6403        /*
6404         * If this is an internal application or our nativeLibraryPath points to
6405         * the app-lib directory, unpack the libraries if necessary.
6406         */
6407        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6408        if (abi >= 0) {
6409            /*
6410             * If we have a matching instruction set, construct a subdir under the native
6411             * library root that corresponds to this instruction set.
6412             */
6413            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6414            final File subDir;
6415            if (useIsaSubdir) {
6416                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6417                createNativeLibrarySubdir(isaSubdir);
6418                subDir = isaSubdir;
6419            } else {
6420                subDir = nativeLibraryRoot;
6421            }
6422
6423            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6424            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6425                return copyRet;
6426            }
6427        }
6428
6429        return abi;
6430    }
6431
6432    private void killApplication(String pkgName, int appId, String reason) {
6433        // Request the ActivityManager to kill the process(only for existing packages)
6434        // so that we do not end up in a confused state while the user is still using the older
6435        // version of the application while the new one gets installed.
6436        IActivityManager am = ActivityManagerNative.getDefault();
6437        if (am != null) {
6438            try {
6439                am.killApplicationWithAppId(pkgName, appId, reason);
6440            } catch (RemoteException e) {
6441            }
6442        }
6443    }
6444
6445    void removePackageLI(PackageSetting ps, boolean chatty) {
6446        if (DEBUG_INSTALL) {
6447            if (chatty)
6448                Log.d(TAG, "Removing package " + ps.name);
6449        }
6450
6451        // writer
6452        synchronized (mPackages) {
6453            mPackages.remove(ps.name);
6454            if (ps.codePathString != null) {
6455                mAppDirs.remove(ps.codePathString);
6456            }
6457
6458            final PackageParser.Package pkg = ps.pkg;
6459            if (pkg != null) {
6460                cleanPackageDataStructuresLILPw(pkg, chatty);
6461            }
6462        }
6463    }
6464
6465    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6466        if (DEBUG_INSTALL) {
6467            if (chatty)
6468                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6469        }
6470
6471        // writer
6472        synchronized (mPackages) {
6473            mPackages.remove(pkg.applicationInfo.packageName);
6474            if (pkg.codePath != null) {
6475                mAppDirs.remove(pkg.codePath);
6476            }
6477            cleanPackageDataStructuresLILPw(pkg, chatty);
6478        }
6479    }
6480
6481    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6482        int N = pkg.providers.size();
6483        StringBuilder r = null;
6484        int i;
6485        for (i=0; i<N; i++) {
6486            PackageParser.Provider p = pkg.providers.get(i);
6487            mProviders.removeProvider(p);
6488            if (p.info.authority == null) {
6489
6490                /* There was another ContentProvider with this authority when
6491                 * this app was installed so this authority is null,
6492                 * Ignore it as we don't have to unregister the provider.
6493                 */
6494                continue;
6495            }
6496            String names[] = p.info.authority.split(";");
6497            for (int j = 0; j < names.length; j++) {
6498                if (mProvidersByAuthority.get(names[j]) == p) {
6499                    mProvidersByAuthority.remove(names[j]);
6500                    if (DEBUG_REMOVE) {
6501                        if (chatty)
6502                            Log.d(TAG, "Unregistered content provider: " + names[j]
6503                                    + ", className = " + p.info.name + ", isSyncable = "
6504                                    + p.info.isSyncable);
6505                    }
6506                }
6507            }
6508            if (DEBUG_REMOVE && chatty) {
6509                if (r == null) {
6510                    r = new StringBuilder(256);
6511                } else {
6512                    r.append(' ');
6513                }
6514                r.append(p.info.name);
6515            }
6516        }
6517        if (r != null) {
6518            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6519        }
6520
6521        N = pkg.services.size();
6522        r = null;
6523        for (i=0; i<N; i++) {
6524            PackageParser.Service s = pkg.services.get(i);
6525            mServices.removeService(s);
6526            if (chatty) {
6527                if (r == null) {
6528                    r = new StringBuilder(256);
6529                } else {
6530                    r.append(' ');
6531                }
6532                r.append(s.info.name);
6533            }
6534        }
6535        if (r != null) {
6536            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6537        }
6538
6539        N = pkg.receivers.size();
6540        r = null;
6541        for (i=0; i<N; i++) {
6542            PackageParser.Activity a = pkg.receivers.get(i);
6543            mReceivers.removeActivity(a, "receiver");
6544            if (DEBUG_REMOVE && chatty) {
6545                if (r == null) {
6546                    r = new StringBuilder(256);
6547                } else {
6548                    r.append(' ');
6549                }
6550                r.append(a.info.name);
6551            }
6552        }
6553        if (r != null) {
6554            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6555        }
6556
6557        N = pkg.activities.size();
6558        r = null;
6559        for (i=0; i<N; i++) {
6560            PackageParser.Activity a = pkg.activities.get(i);
6561            mActivities.removeActivity(a, "activity");
6562            if (DEBUG_REMOVE && chatty) {
6563                if (r == null) {
6564                    r = new StringBuilder(256);
6565                } else {
6566                    r.append(' ');
6567                }
6568                r.append(a.info.name);
6569            }
6570        }
6571        if (r != null) {
6572            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6573        }
6574
6575        N = pkg.permissions.size();
6576        r = null;
6577        for (i=0; i<N; i++) {
6578            PackageParser.Permission p = pkg.permissions.get(i);
6579            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6580            if (bp == null) {
6581                bp = mSettings.mPermissionTrees.get(p.info.name);
6582            }
6583            if (bp != null && bp.perm == p) {
6584                bp.perm = null;
6585                if (DEBUG_REMOVE && chatty) {
6586                    if (r == null) {
6587                        r = new StringBuilder(256);
6588                    } else {
6589                        r.append(' ');
6590                    }
6591                    r.append(p.info.name);
6592                }
6593            }
6594        }
6595        if (r != null) {
6596            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6597        }
6598
6599        N = pkg.instrumentation.size();
6600        r = null;
6601        for (i=0; i<N; i++) {
6602            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6603            mInstrumentation.remove(a.getComponentName());
6604            if (DEBUG_REMOVE && chatty) {
6605                if (r == null) {
6606                    r = new StringBuilder(256);
6607                } else {
6608                    r.append(' ');
6609                }
6610                r.append(a.info.name);
6611            }
6612        }
6613        if (r != null) {
6614            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6615        }
6616
6617        r = null;
6618        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6619            // Only system apps can hold shared libraries.
6620            if (pkg.libraryNames != null) {
6621                for (i=0; i<pkg.libraryNames.size(); i++) {
6622                    String name = pkg.libraryNames.get(i);
6623                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6624                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6625                        mSharedLibraries.remove(name);
6626                        if (DEBUG_REMOVE && chatty) {
6627                            if (r == null) {
6628                                r = new StringBuilder(256);
6629                            } else {
6630                                r.append(' ');
6631                            }
6632                            r.append(name);
6633                        }
6634                    }
6635                }
6636            }
6637        }
6638        if (r != null) {
6639            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6640        }
6641    }
6642
6643    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6644        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6645            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6646                return true;
6647            }
6648        }
6649        return false;
6650    }
6651
6652    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6653    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6654    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6655
6656    private void updatePermissionsLPw(String changingPkg,
6657            PackageParser.Package pkgInfo, int flags) {
6658        // Make sure there are no dangling permission trees.
6659        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6660        while (it.hasNext()) {
6661            final BasePermission bp = it.next();
6662            if (bp.packageSetting == null) {
6663                // We may not yet have parsed the package, so just see if
6664                // we still know about its settings.
6665                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6666            }
6667            if (bp.packageSetting == null) {
6668                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6669                        + " from package " + bp.sourcePackage);
6670                it.remove();
6671            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6672                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6673                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6674                            + " from package " + bp.sourcePackage);
6675                    flags |= UPDATE_PERMISSIONS_ALL;
6676                    it.remove();
6677                }
6678            }
6679        }
6680
6681        // Make sure all dynamic permissions have been assigned to a package,
6682        // and make sure there are no dangling permissions.
6683        it = mSettings.mPermissions.values().iterator();
6684        while (it.hasNext()) {
6685            final BasePermission bp = it.next();
6686            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6687                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6688                        + bp.name + " pkg=" + bp.sourcePackage
6689                        + " info=" + bp.pendingInfo);
6690                if (bp.packageSetting == null && bp.pendingInfo != null) {
6691                    final BasePermission tree = findPermissionTreeLP(bp.name);
6692                    if (tree != null && tree.perm != null) {
6693                        bp.packageSetting = tree.packageSetting;
6694                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6695                                new PermissionInfo(bp.pendingInfo));
6696                        bp.perm.info.packageName = tree.perm.info.packageName;
6697                        bp.perm.info.name = bp.name;
6698                        bp.uid = tree.uid;
6699                    }
6700                }
6701            }
6702            if (bp.packageSetting == null) {
6703                // We may not yet have parsed the package, so just see if
6704                // we still know about its settings.
6705                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6706            }
6707            if (bp.packageSetting == null) {
6708                Slog.w(TAG, "Removing dangling permission: " + bp.name
6709                        + " from package " + bp.sourcePackage);
6710                it.remove();
6711            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6712                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6713                    Slog.i(TAG, "Removing old permission: " + bp.name
6714                            + " from package " + bp.sourcePackage);
6715                    flags |= UPDATE_PERMISSIONS_ALL;
6716                    it.remove();
6717                }
6718            }
6719        }
6720
6721        // Now update the permissions for all packages, in particular
6722        // replace the granted permissions of the system packages.
6723        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6724            for (PackageParser.Package pkg : mPackages.values()) {
6725                if (pkg != pkgInfo) {
6726                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6727                }
6728            }
6729        }
6730
6731        if (pkgInfo != null) {
6732            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6733        }
6734    }
6735
6736    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6737        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6738        if (ps == null) {
6739            return;
6740        }
6741        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6742        HashSet<String> origPermissions = gp.grantedPermissions;
6743        boolean changedPermission = false;
6744
6745        if (replace) {
6746            ps.permissionsFixed = false;
6747            if (gp == ps) {
6748                origPermissions = new HashSet<String>(gp.grantedPermissions);
6749                gp.grantedPermissions.clear();
6750                gp.gids = mGlobalGids;
6751            }
6752        }
6753
6754        if (gp.gids == null) {
6755            gp.gids = mGlobalGids;
6756        }
6757
6758        final int N = pkg.requestedPermissions.size();
6759        for (int i=0; i<N; i++) {
6760            final String name = pkg.requestedPermissions.get(i);
6761            final boolean required = pkg.requestedPermissionsRequired.get(i);
6762            final BasePermission bp = mSettings.mPermissions.get(name);
6763            if (DEBUG_INSTALL) {
6764                if (gp != ps) {
6765                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6766                }
6767            }
6768
6769            if (bp == null || bp.packageSetting == null) {
6770                Slog.w(TAG, "Unknown permission " + name
6771                        + " in package " + pkg.packageName);
6772                continue;
6773            }
6774
6775            final String perm = bp.name;
6776            boolean allowed;
6777            boolean allowedSig = false;
6778            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6779            if (level == PermissionInfo.PROTECTION_NORMAL
6780                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6781                // We grant a normal or dangerous permission if any of the following
6782                // are true:
6783                // 1) The permission is required
6784                // 2) The permission is optional, but was granted in the past
6785                // 3) The permission is optional, but was requested by an
6786                //    app in /system (not /data)
6787                //
6788                // Otherwise, reject the permission.
6789                allowed = (required || origPermissions.contains(perm)
6790                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6791            } else if (bp.packageSetting == null) {
6792                // This permission is invalid; skip it.
6793                allowed = false;
6794            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6795                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6796                if (allowed) {
6797                    allowedSig = true;
6798                }
6799            } else {
6800                allowed = false;
6801            }
6802            if (DEBUG_INSTALL) {
6803                if (gp != ps) {
6804                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6805                }
6806            }
6807            if (allowed) {
6808                if (!isSystemApp(ps) && ps.permissionsFixed) {
6809                    // If this is an existing, non-system package, then
6810                    // we can't add any new permissions to it.
6811                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6812                        // Except...  if this is a permission that was added
6813                        // to the platform (note: need to only do this when
6814                        // updating the platform).
6815                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6816                    }
6817                }
6818                if (allowed) {
6819                    if (!gp.grantedPermissions.contains(perm)) {
6820                        changedPermission = true;
6821                        gp.grantedPermissions.add(perm);
6822                        gp.gids = appendInts(gp.gids, bp.gids);
6823                    } else if (!ps.haveGids) {
6824                        gp.gids = appendInts(gp.gids, bp.gids);
6825                    }
6826                } else {
6827                    Slog.w(TAG, "Not granting permission " + perm
6828                            + " to package " + pkg.packageName
6829                            + " because it was previously installed without");
6830                }
6831            } else {
6832                if (gp.grantedPermissions.remove(perm)) {
6833                    changedPermission = true;
6834                    gp.gids = removeInts(gp.gids, bp.gids);
6835                    Slog.i(TAG, "Un-granting permission " + perm
6836                            + " from package " + pkg.packageName
6837                            + " (protectionLevel=" + bp.protectionLevel
6838                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6839                            + ")");
6840                } else {
6841                    Slog.w(TAG, "Not granting permission " + perm
6842                            + " to package " + pkg.packageName
6843                            + " (protectionLevel=" + bp.protectionLevel
6844                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6845                            + ")");
6846                }
6847            }
6848        }
6849
6850        if ((changedPermission || replace) && !ps.permissionsFixed &&
6851                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6852            // This is the first that we have heard about this package, so the
6853            // permissions we have now selected are fixed until explicitly
6854            // changed.
6855            ps.permissionsFixed = true;
6856        }
6857        ps.haveGids = true;
6858    }
6859
6860    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6861        boolean allowed = false;
6862        final int NP = PackageParser.NEW_PERMISSIONS.length;
6863        for (int ip=0; ip<NP; ip++) {
6864            final PackageParser.NewPermissionInfo npi
6865                    = PackageParser.NEW_PERMISSIONS[ip];
6866            if (npi.name.equals(perm)
6867                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6868                allowed = true;
6869                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6870                        + pkg.packageName);
6871                break;
6872            }
6873        }
6874        return allowed;
6875    }
6876
6877    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6878                                          BasePermission bp, HashSet<String> origPermissions) {
6879        boolean allowed;
6880        allowed = (compareSignatures(
6881                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6882                        == PackageManager.SIGNATURE_MATCH)
6883                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6884                        == PackageManager.SIGNATURE_MATCH);
6885        if (!allowed && (bp.protectionLevel
6886                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6887            if (isSystemApp(pkg)) {
6888                // For updated system applications, a system permission
6889                // is granted only if it had been defined by the original application.
6890                if (isUpdatedSystemApp(pkg)) {
6891                    final PackageSetting sysPs = mSettings
6892                            .getDisabledSystemPkgLPr(pkg.packageName);
6893                    final GrantedPermissions origGp = sysPs.sharedUser != null
6894                            ? sysPs.sharedUser : sysPs;
6895
6896                    if (origGp.grantedPermissions.contains(perm)) {
6897                        // If the original was granted this permission, we take
6898                        // that grant decision as read and propagate it to the
6899                        // update.
6900                        allowed = true;
6901                    } else {
6902                        // The system apk may have been updated with an older
6903                        // version of the one on the data partition, but which
6904                        // granted a new system permission that it didn't have
6905                        // before.  In this case we do want to allow the app to
6906                        // now get the new permission if the ancestral apk is
6907                        // privileged to get it.
6908                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6909                            for (int j=0;
6910                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6911                                if (perm.equals(
6912                                        sysPs.pkg.requestedPermissions.get(j))) {
6913                                    allowed = true;
6914                                    break;
6915                                }
6916                            }
6917                        }
6918                    }
6919                } else {
6920                    allowed = isPrivilegedApp(pkg);
6921                }
6922            }
6923        }
6924        if (!allowed && (bp.protectionLevel
6925                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6926            // For development permissions, a development permission
6927            // is granted only if it was already granted.
6928            allowed = origPermissions.contains(perm);
6929        }
6930        return allowed;
6931    }
6932
6933    final class ActivityIntentResolver
6934            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6935        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6936                boolean defaultOnly, int userId) {
6937            if (!sUserManager.exists(userId)) return null;
6938            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6939            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6940        }
6941
6942        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6943                int userId) {
6944            if (!sUserManager.exists(userId)) return null;
6945            mFlags = flags;
6946            return super.queryIntent(intent, resolvedType,
6947                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6948        }
6949
6950        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6951                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6952            if (!sUserManager.exists(userId)) return null;
6953            if (packageActivities == null) {
6954                return null;
6955            }
6956            mFlags = flags;
6957            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6958            final int N = packageActivities.size();
6959            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6960                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6961
6962            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6963            for (int i = 0; i < N; ++i) {
6964                intentFilters = packageActivities.get(i).intents;
6965                if (intentFilters != null && intentFilters.size() > 0) {
6966                    PackageParser.ActivityIntentInfo[] array =
6967                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6968                    intentFilters.toArray(array);
6969                    listCut.add(array);
6970                }
6971            }
6972            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6973        }
6974
6975        public final void addActivity(PackageParser.Activity a, String type) {
6976            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6977            mActivities.put(a.getComponentName(), a);
6978            if (DEBUG_SHOW_INFO)
6979                Log.v(
6980                TAG, "  " + type + " " +
6981                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6982            if (DEBUG_SHOW_INFO)
6983                Log.v(TAG, "    Class=" + a.info.name);
6984            final int NI = a.intents.size();
6985            for (int j=0; j<NI; j++) {
6986                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6987                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6988                    intent.setPriority(0);
6989                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6990                            + a.className + " with priority > 0, forcing to 0");
6991                }
6992                if (DEBUG_SHOW_INFO) {
6993                    Log.v(TAG, "    IntentFilter:");
6994                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6995                }
6996                if (!intent.debugCheck()) {
6997                    Log.w(TAG, "==> For Activity " + a.info.name);
6998                }
6999                addFilter(intent);
7000            }
7001        }
7002
7003        public final void removeActivity(PackageParser.Activity a, String type) {
7004            mActivities.remove(a.getComponentName());
7005            if (DEBUG_SHOW_INFO) {
7006                Log.v(TAG, "  " + type + " "
7007                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7008                                : a.info.name) + ":");
7009                Log.v(TAG, "    Class=" + a.info.name);
7010            }
7011            final int NI = a.intents.size();
7012            for (int j=0; j<NI; j++) {
7013                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7014                if (DEBUG_SHOW_INFO) {
7015                    Log.v(TAG, "    IntentFilter:");
7016                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7017                }
7018                removeFilter(intent);
7019            }
7020        }
7021
7022        @Override
7023        protected boolean allowFilterResult(
7024                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7025            ActivityInfo filterAi = filter.activity.info;
7026            for (int i=dest.size()-1; i>=0; i--) {
7027                ActivityInfo destAi = dest.get(i).activityInfo;
7028                if (destAi.name == filterAi.name
7029                        && destAi.packageName == filterAi.packageName) {
7030                    return false;
7031                }
7032            }
7033            return true;
7034        }
7035
7036        @Override
7037        protected ActivityIntentInfo[] newArray(int size) {
7038            return new ActivityIntentInfo[size];
7039        }
7040
7041        @Override
7042        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7043            if (!sUserManager.exists(userId)) return true;
7044            PackageParser.Package p = filter.activity.owner;
7045            if (p != null) {
7046                PackageSetting ps = (PackageSetting)p.mExtras;
7047                if (ps != null) {
7048                    // System apps are never considered stopped for purposes of
7049                    // filtering, because there may be no way for the user to
7050                    // actually re-launch them.
7051                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7052                            && ps.getStopped(userId);
7053                }
7054            }
7055            return false;
7056        }
7057
7058        @Override
7059        protected boolean isPackageForFilter(String packageName,
7060                PackageParser.ActivityIntentInfo info) {
7061            return packageName.equals(info.activity.owner.packageName);
7062        }
7063
7064        @Override
7065        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7066                int match, int userId) {
7067            if (!sUserManager.exists(userId)) return null;
7068            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7069                return null;
7070            }
7071            final PackageParser.Activity activity = info.activity;
7072            if (mSafeMode && (activity.info.applicationInfo.flags
7073                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7074                return null;
7075            }
7076            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7077            if (ps == null) {
7078                return null;
7079            }
7080            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7081                    ps.readUserState(userId), userId);
7082            if (ai == null) {
7083                return null;
7084            }
7085            final ResolveInfo res = new ResolveInfo();
7086            res.activityInfo = ai;
7087            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7088                res.filter = info;
7089            }
7090            res.priority = info.getPriority();
7091            res.preferredOrder = activity.owner.mPreferredOrder;
7092            //System.out.println("Result: " + res.activityInfo.className +
7093            //                   " = " + res.priority);
7094            res.match = match;
7095            res.isDefault = info.hasDefault;
7096            res.labelRes = info.labelRes;
7097            res.nonLocalizedLabel = info.nonLocalizedLabel;
7098            if (userNeedsBadging(userId)) {
7099                res.noResourceId = true;
7100            } else {
7101                res.icon = info.icon;
7102            }
7103            res.system = isSystemApp(res.activityInfo.applicationInfo);
7104            return res;
7105        }
7106
7107        @Override
7108        protected void sortResults(List<ResolveInfo> results) {
7109            Collections.sort(results, mResolvePrioritySorter);
7110        }
7111
7112        @Override
7113        protected void dumpFilter(PrintWriter out, String prefix,
7114                PackageParser.ActivityIntentInfo filter) {
7115            out.print(prefix); out.print(
7116                    Integer.toHexString(System.identityHashCode(filter.activity)));
7117                    out.print(' ');
7118                    filter.activity.printComponentShortName(out);
7119                    out.print(" filter ");
7120                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7121        }
7122
7123//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7124//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7125//            final List<ResolveInfo> retList = Lists.newArrayList();
7126//            while (i.hasNext()) {
7127//                final ResolveInfo resolveInfo = i.next();
7128//                if (isEnabledLP(resolveInfo.activityInfo)) {
7129//                    retList.add(resolveInfo);
7130//                }
7131//            }
7132//            return retList;
7133//        }
7134
7135        // Keys are String (activity class name), values are Activity.
7136        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7137                = new HashMap<ComponentName, PackageParser.Activity>();
7138        private int mFlags;
7139    }
7140
7141    private final class ServiceIntentResolver
7142            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7143        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7144                boolean defaultOnly, int userId) {
7145            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7146            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7147        }
7148
7149        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7150                int userId) {
7151            if (!sUserManager.exists(userId)) return null;
7152            mFlags = flags;
7153            return super.queryIntent(intent, resolvedType,
7154                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7155        }
7156
7157        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7158                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7159            if (!sUserManager.exists(userId)) return null;
7160            if (packageServices == null) {
7161                return null;
7162            }
7163            mFlags = flags;
7164            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7165            final int N = packageServices.size();
7166            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7167                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7168
7169            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7170            for (int i = 0; i < N; ++i) {
7171                intentFilters = packageServices.get(i).intents;
7172                if (intentFilters != null && intentFilters.size() > 0) {
7173                    PackageParser.ServiceIntentInfo[] array =
7174                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7175                    intentFilters.toArray(array);
7176                    listCut.add(array);
7177                }
7178            }
7179            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7180        }
7181
7182        public final void addService(PackageParser.Service s) {
7183            mServices.put(s.getComponentName(), s);
7184            if (DEBUG_SHOW_INFO) {
7185                Log.v(TAG, "  "
7186                        + (s.info.nonLocalizedLabel != null
7187                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7188                Log.v(TAG, "    Class=" + s.info.name);
7189            }
7190            final int NI = s.intents.size();
7191            int j;
7192            for (j=0; j<NI; j++) {
7193                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7194                if (DEBUG_SHOW_INFO) {
7195                    Log.v(TAG, "    IntentFilter:");
7196                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7197                }
7198                if (!intent.debugCheck()) {
7199                    Log.w(TAG, "==> For Service " + s.info.name);
7200                }
7201                addFilter(intent);
7202            }
7203        }
7204
7205        public final void removeService(PackageParser.Service s) {
7206            mServices.remove(s.getComponentName());
7207            if (DEBUG_SHOW_INFO) {
7208                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7209                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7210                Log.v(TAG, "    Class=" + s.info.name);
7211            }
7212            final int NI = s.intents.size();
7213            int j;
7214            for (j=0; j<NI; j++) {
7215                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7216                if (DEBUG_SHOW_INFO) {
7217                    Log.v(TAG, "    IntentFilter:");
7218                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7219                }
7220                removeFilter(intent);
7221            }
7222        }
7223
7224        @Override
7225        protected boolean allowFilterResult(
7226                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7227            ServiceInfo filterSi = filter.service.info;
7228            for (int i=dest.size()-1; i>=0; i--) {
7229                ServiceInfo destAi = dest.get(i).serviceInfo;
7230                if (destAi.name == filterSi.name
7231                        && destAi.packageName == filterSi.packageName) {
7232                    return false;
7233                }
7234            }
7235            return true;
7236        }
7237
7238        @Override
7239        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7240            return new PackageParser.ServiceIntentInfo[size];
7241        }
7242
7243        @Override
7244        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7245            if (!sUserManager.exists(userId)) return true;
7246            PackageParser.Package p = filter.service.owner;
7247            if (p != null) {
7248                PackageSetting ps = (PackageSetting)p.mExtras;
7249                if (ps != null) {
7250                    // System apps are never considered stopped for purposes of
7251                    // filtering, because there may be no way for the user to
7252                    // actually re-launch them.
7253                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7254                            && ps.getStopped(userId);
7255                }
7256            }
7257            return false;
7258        }
7259
7260        @Override
7261        protected boolean isPackageForFilter(String packageName,
7262                PackageParser.ServiceIntentInfo info) {
7263            return packageName.equals(info.service.owner.packageName);
7264        }
7265
7266        @Override
7267        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7268                int match, int userId) {
7269            if (!sUserManager.exists(userId)) return null;
7270            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7271            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7272                return null;
7273            }
7274            final PackageParser.Service service = info.service;
7275            if (mSafeMode && (service.info.applicationInfo.flags
7276                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7277                return null;
7278            }
7279            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7280            if (ps == null) {
7281                return null;
7282            }
7283            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7284                    ps.readUserState(userId), userId);
7285            if (si == null) {
7286                return null;
7287            }
7288            final ResolveInfo res = new ResolveInfo();
7289            res.serviceInfo = si;
7290            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7291                res.filter = filter;
7292            }
7293            res.priority = info.getPriority();
7294            res.preferredOrder = service.owner.mPreferredOrder;
7295            //System.out.println("Result: " + res.activityInfo.className +
7296            //                   " = " + res.priority);
7297            res.match = match;
7298            res.isDefault = info.hasDefault;
7299            res.labelRes = info.labelRes;
7300            res.nonLocalizedLabel = info.nonLocalizedLabel;
7301            res.icon = info.icon;
7302            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7303            return res;
7304        }
7305
7306        @Override
7307        protected void sortResults(List<ResolveInfo> results) {
7308            Collections.sort(results, mResolvePrioritySorter);
7309        }
7310
7311        @Override
7312        protected void dumpFilter(PrintWriter out, String prefix,
7313                PackageParser.ServiceIntentInfo filter) {
7314            out.print(prefix); out.print(
7315                    Integer.toHexString(System.identityHashCode(filter.service)));
7316                    out.print(' ');
7317                    filter.service.printComponentShortName(out);
7318                    out.print(" filter ");
7319                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7320        }
7321
7322//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7323//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7324//            final List<ResolveInfo> retList = Lists.newArrayList();
7325//            while (i.hasNext()) {
7326//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7327//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7328//                    retList.add(resolveInfo);
7329//                }
7330//            }
7331//            return retList;
7332//        }
7333
7334        // Keys are String (activity class name), values are Activity.
7335        private final HashMap<ComponentName, PackageParser.Service> mServices
7336                = new HashMap<ComponentName, PackageParser.Service>();
7337        private int mFlags;
7338    };
7339
7340    private final class ProviderIntentResolver
7341            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7342        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7343                boolean defaultOnly, int userId) {
7344            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7345            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7346        }
7347
7348        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7349                int userId) {
7350            if (!sUserManager.exists(userId))
7351                return null;
7352            mFlags = flags;
7353            return super.queryIntent(intent, resolvedType,
7354                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7355        }
7356
7357        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7358                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7359            if (!sUserManager.exists(userId))
7360                return null;
7361            if (packageProviders == null) {
7362                return null;
7363            }
7364            mFlags = flags;
7365            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7366            final int N = packageProviders.size();
7367            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7368                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7369
7370            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7371            for (int i = 0; i < N; ++i) {
7372                intentFilters = packageProviders.get(i).intents;
7373                if (intentFilters != null && intentFilters.size() > 0) {
7374                    PackageParser.ProviderIntentInfo[] array =
7375                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7376                    intentFilters.toArray(array);
7377                    listCut.add(array);
7378                }
7379            }
7380            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7381        }
7382
7383        public final void addProvider(PackageParser.Provider p) {
7384            if (mProviders.containsKey(p.getComponentName())) {
7385                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7386                return;
7387            }
7388
7389            mProviders.put(p.getComponentName(), p);
7390            if (DEBUG_SHOW_INFO) {
7391                Log.v(TAG, "  "
7392                        + (p.info.nonLocalizedLabel != null
7393                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7394                Log.v(TAG, "    Class=" + p.info.name);
7395            }
7396            final int NI = p.intents.size();
7397            int j;
7398            for (j = 0; j < NI; j++) {
7399                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7400                if (DEBUG_SHOW_INFO) {
7401                    Log.v(TAG, "    IntentFilter:");
7402                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7403                }
7404                if (!intent.debugCheck()) {
7405                    Log.w(TAG, "==> For Provider " + p.info.name);
7406                }
7407                addFilter(intent);
7408            }
7409        }
7410
7411        public final void removeProvider(PackageParser.Provider p) {
7412            mProviders.remove(p.getComponentName());
7413            if (DEBUG_SHOW_INFO) {
7414                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7415                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7416                Log.v(TAG, "    Class=" + p.info.name);
7417            }
7418            final int NI = p.intents.size();
7419            int j;
7420            for (j = 0; j < NI; j++) {
7421                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7422                if (DEBUG_SHOW_INFO) {
7423                    Log.v(TAG, "    IntentFilter:");
7424                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7425                }
7426                removeFilter(intent);
7427            }
7428        }
7429
7430        @Override
7431        protected boolean allowFilterResult(
7432                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7433            ProviderInfo filterPi = filter.provider.info;
7434            for (int i = dest.size() - 1; i >= 0; i--) {
7435                ProviderInfo destPi = dest.get(i).providerInfo;
7436                if (destPi.name == filterPi.name
7437                        && destPi.packageName == filterPi.packageName) {
7438                    return false;
7439                }
7440            }
7441            return true;
7442        }
7443
7444        @Override
7445        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7446            return new PackageParser.ProviderIntentInfo[size];
7447        }
7448
7449        @Override
7450        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7451            if (!sUserManager.exists(userId))
7452                return true;
7453            PackageParser.Package p = filter.provider.owner;
7454            if (p != null) {
7455                PackageSetting ps = (PackageSetting) p.mExtras;
7456                if (ps != null) {
7457                    // System apps are never considered stopped for purposes of
7458                    // filtering, because there may be no way for the user to
7459                    // actually re-launch them.
7460                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7461                            && ps.getStopped(userId);
7462                }
7463            }
7464            return false;
7465        }
7466
7467        @Override
7468        protected boolean isPackageForFilter(String packageName,
7469                PackageParser.ProviderIntentInfo info) {
7470            return packageName.equals(info.provider.owner.packageName);
7471        }
7472
7473        @Override
7474        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7475                int match, int userId) {
7476            if (!sUserManager.exists(userId))
7477                return null;
7478            final PackageParser.ProviderIntentInfo info = filter;
7479            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7480                return null;
7481            }
7482            final PackageParser.Provider provider = info.provider;
7483            if (mSafeMode && (provider.info.applicationInfo.flags
7484                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7485                return null;
7486            }
7487            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7488            if (ps == null) {
7489                return null;
7490            }
7491            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7492                    ps.readUserState(userId), userId);
7493            if (pi == null) {
7494                return null;
7495            }
7496            final ResolveInfo res = new ResolveInfo();
7497            res.providerInfo = pi;
7498            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7499                res.filter = filter;
7500            }
7501            res.priority = info.getPriority();
7502            res.preferredOrder = provider.owner.mPreferredOrder;
7503            res.match = match;
7504            res.isDefault = info.hasDefault;
7505            res.labelRes = info.labelRes;
7506            res.nonLocalizedLabel = info.nonLocalizedLabel;
7507            res.icon = info.icon;
7508            res.system = isSystemApp(res.providerInfo.applicationInfo);
7509            return res;
7510        }
7511
7512        @Override
7513        protected void sortResults(List<ResolveInfo> results) {
7514            Collections.sort(results, mResolvePrioritySorter);
7515        }
7516
7517        @Override
7518        protected void dumpFilter(PrintWriter out, String prefix,
7519                PackageParser.ProviderIntentInfo filter) {
7520            out.print(prefix);
7521            out.print(
7522                    Integer.toHexString(System.identityHashCode(filter.provider)));
7523            out.print(' ');
7524            filter.provider.printComponentShortName(out);
7525            out.print(" filter ");
7526            out.println(Integer.toHexString(System.identityHashCode(filter)));
7527        }
7528
7529        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7530                = new HashMap<ComponentName, PackageParser.Provider>();
7531        private int mFlags;
7532    };
7533
7534    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7535            new Comparator<ResolveInfo>() {
7536        public int compare(ResolveInfo r1, ResolveInfo r2) {
7537            int v1 = r1.priority;
7538            int v2 = r2.priority;
7539            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7540            if (v1 != v2) {
7541                return (v1 > v2) ? -1 : 1;
7542            }
7543            v1 = r1.preferredOrder;
7544            v2 = r2.preferredOrder;
7545            if (v1 != v2) {
7546                return (v1 > v2) ? -1 : 1;
7547            }
7548            if (r1.isDefault != r2.isDefault) {
7549                return r1.isDefault ? -1 : 1;
7550            }
7551            v1 = r1.match;
7552            v2 = r2.match;
7553            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7554            if (v1 != v2) {
7555                return (v1 > v2) ? -1 : 1;
7556            }
7557            if (r1.system != r2.system) {
7558                return r1.system ? -1 : 1;
7559            }
7560            return 0;
7561        }
7562    };
7563
7564    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7565            new Comparator<ProviderInfo>() {
7566        public int compare(ProviderInfo p1, ProviderInfo p2) {
7567            final int v1 = p1.initOrder;
7568            final int v2 = p2.initOrder;
7569            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7570        }
7571    };
7572
7573    static final void sendPackageBroadcast(String action, String pkg,
7574            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7575            int[] userIds) {
7576        IActivityManager am = ActivityManagerNative.getDefault();
7577        if (am != null) {
7578            try {
7579                if (userIds == null) {
7580                    userIds = am.getRunningUserIds();
7581                }
7582                for (int id : userIds) {
7583                    final Intent intent = new Intent(action,
7584                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7585                    if (extras != null) {
7586                        intent.putExtras(extras);
7587                    }
7588                    if (targetPkg != null) {
7589                        intent.setPackage(targetPkg);
7590                    }
7591                    // Modify the UID when posting to other users
7592                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7593                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7594                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7595                        intent.putExtra(Intent.EXTRA_UID, uid);
7596                    }
7597                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7598                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7599                    if (DEBUG_BROADCASTS) {
7600                        RuntimeException here = new RuntimeException("here");
7601                        here.fillInStackTrace();
7602                        Slog.d(TAG, "Sending to user " + id + ": "
7603                                + intent.toShortString(false, true, false, false)
7604                                + " " + intent.getExtras(), here);
7605                    }
7606                    am.broadcastIntent(null, intent, null, finishedReceiver,
7607                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7608                            finishedReceiver != null, false, id);
7609                }
7610            } catch (RemoteException ex) {
7611            }
7612        }
7613    }
7614
7615    /**
7616     * Check if the external storage media is available. This is true if there
7617     * is a mounted external storage medium or if the external storage is
7618     * emulated.
7619     */
7620    private boolean isExternalMediaAvailable() {
7621        return mMediaMounted || Environment.isExternalStorageEmulated();
7622    }
7623
7624    @Override
7625    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7626        // writer
7627        synchronized (mPackages) {
7628            if (!isExternalMediaAvailable()) {
7629                // If the external storage is no longer mounted at this point,
7630                // the caller may not have been able to delete all of this
7631                // packages files and can not delete any more.  Bail.
7632                return null;
7633            }
7634            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7635            if (lastPackage != null) {
7636                pkgs.remove(lastPackage);
7637            }
7638            if (pkgs.size() > 0) {
7639                return pkgs.get(0);
7640            }
7641        }
7642        return null;
7643    }
7644
7645    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7646        if (false) {
7647            RuntimeException here = new RuntimeException("here");
7648            here.fillInStackTrace();
7649            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7650                    + " andCode=" + andCode, here);
7651        }
7652        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7653                userId, andCode ? 1 : 0, packageName));
7654    }
7655
7656    void startCleaningPackages() {
7657        // reader
7658        synchronized (mPackages) {
7659            if (!isExternalMediaAvailable()) {
7660                return;
7661            }
7662            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7663                return;
7664            }
7665        }
7666        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7667        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7668        IActivityManager am = ActivityManagerNative.getDefault();
7669        if (am != null) {
7670            try {
7671                am.startService(null, intent, null, UserHandle.USER_OWNER);
7672            } catch (RemoteException e) {
7673            }
7674        }
7675    }
7676
7677    private final class AppDirObserver extends FileObserver {
7678        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7679            super(path, mask);
7680            mRootDir = path;
7681            mIsRom = isrom;
7682            mIsPrivileged = isPrivileged;
7683        }
7684
7685        public void onEvent(int event, String path) {
7686            String removedPackage = null;
7687            int removedAppId = -1;
7688            int[] removedUsers = null;
7689            String addedPackage = null;
7690            int addedAppId = -1;
7691            int[] addedUsers = null;
7692
7693            // TODO post a message to the handler to obtain serial ordering
7694            synchronized (mInstallLock) {
7695                String fullPathStr = null;
7696                File fullPath = null;
7697                if (path != null) {
7698                    fullPath = new File(mRootDir, path);
7699                    fullPathStr = fullPath.getPath();
7700                }
7701
7702                if (DEBUG_APP_DIR_OBSERVER)
7703                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7704
7705                if (!isApkFile(fullPath)) {
7706                    if (DEBUG_APP_DIR_OBSERVER)
7707                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7708                    return;
7709                }
7710
7711                // Ignore packages that are being installed or
7712                // have just been installed.
7713                if (ignoreCodePath(fullPathStr)) {
7714                    return;
7715                }
7716                PackageParser.Package p = null;
7717                PackageSetting ps = null;
7718                // reader
7719                synchronized (mPackages) {
7720                    p = mAppDirs.get(fullPathStr);
7721                    if (p != null) {
7722                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7723                        if (ps != null) {
7724                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7725                        } else {
7726                            removedUsers = sUserManager.getUserIds();
7727                        }
7728                    }
7729                    addedUsers = sUserManager.getUserIds();
7730                }
7731                if ((event&REMOVE_EVENTS) != 0) {
7732                    if (ps != null) {
7733                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7734                        removePackageLI(ps, true);
7735                        removedPackage = ps.name;
7736                        removedAppId = ps.appId;
7737                    }
7738                }
7739
7740                if ((event&ADD_EVENTS) != 0) {
7741                    if (p == null) {
7742                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7743                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7744                        if (mIsRom) {
7745                            flags |= PackageParser.PARSE_IS_SYSTEM
7746                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7747                            if (mIsPrivileged) {
7748                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7749                            }
7750                        }
7751                        try {
7752                            p = scanPackageLI(fullPath, flags,
7753                                    SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7754                                    System.currentTimeMillis(), UserHandle.ALL, null);
7755                        } catch (PackageManagerException e) {
7756                            Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage());
7757                            p = null;
7758                        }
7759                        if (p != null) {
7760                            /*
7761                             * TODO this seems dangerous as the package may have
7762                             * changed since we last acquired the mPackages
7763                             * lock.
7764                             */
7765                            // writer
7766                            synchronized (mPackages) {
7767                                updatePermissionsLPw(p.packageName, p,
7768                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7769                            }
7770                            addedPackage = p.applicationInfo.packageName;
7771                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7772                        }
7773                    }
7774                }
7775
7776                // reader
7777                synchronized (mPackages) {
7778                    mSettings.writeLPr();
7779                }
7780            }
7781
7782            if (removedPackage != null) {
7783                Bundle extras = new Bundle(1);
7784                extras.putInt(Intent.EXTRA_UID, removedAppId);
7785                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7786                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7787                        extras, null, null, removedUsers);
7788            }
7789            if (addedPackage != null) {
7790                Bundle extras = new Bundle(1);
7791                extras.putInt(Intent.EXTRA_UID, addedAppId);
7792                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7793                        extras, null, null, addedUsers);
7794            }
7795        }
7796
7797        private final String mRootDir;
7798        private final boolean mIsRom;
7799        private final boolean mIsPrivileged;
7800    }
7801
7802    @Override
7803    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7804            String installerPackageName, VerificationParams verificationParams,
7805            String packageAbiOverride) {
7806        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7807                null);
7808
7809        final File originFile = new File(originPath);
7810        final int uid = Binder.getCallingUid();
7811        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7812            try {
7813                if (observer != null) {
7814                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null);
7815                }
7816            } catch (RemoteException re) {
7817            }
7818            return;
7819        }
7820
7821        UserHandle user;
7822        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7823            user = UserHandle.ALL;
7824        } else {
7825            user = new UserHandle(UserHandle.getUserId(uid));
7826        }
7827
7828        final int filteredFlags;
7829        if (uid == Process.SHELL_UID || uid == 0) {
7830            if (DEBUG_INSTALL) {
7831                Slog.v(TAG, "Install from ADB");
7832            }
7833            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7834        } else {
7835            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7836        }
7837
7838        verificationParams.setInstallerUid(uid);
7839
7840        final Message msg = mHandler.obtainMessage(INIT_COPY);
7841        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7842                installerPackageName, verificationParams, user, packageAbiOverride);
7843        mHandler.sendMessage(msg);
7844    }
7845
7846    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7847            InstallSessionParams params, String installerPackageName, int installerUid,
7848            UserHandle user) {
7849        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7850                params.referrerUri, installerUid, null);
7851
7852        final Message msg = mHandler.obtainMessage(INIT_COPY);
7853        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7854                installerPackageName, verifParams, user, params.abiOverride);
7855        mHandler.sendMessage(msg);
7856    }
7857
7858    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7859        Bundle extras = new Bundle(1);
7860        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7861
7862        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7863                packageName, extras, null, null, new int[] {userId});
7864        try {
7865            IActivityManager am = ActivityManagerNative.getDefault();
7866            final boolean isSystem =
7867                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7868            if (isSystem && am.isUserRunning(userId, false)) {
7869                // The just-installed/enabled app is bundled on the system, so presumed
7870                // to be able to run automatically without needing an explicit launch.
7871                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7872                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7873                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7874                        .setPackage(packageName);
7875                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7876                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7877            }
7878        } catch (RemoteException e) {
7879            // shouldn't happen
7880            Slog.w(TAG, "Unable to bootstrap installed package", e);
7881        }
7882    }
7883
7884    @Override
7885    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7886            int userId) {
7887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7888        PackageSetting pkgSetting;
7889        final int uid = Binder.getCallingUid();
7890        if (UserHandle.getUserId(uid) != userId) {
7891            mContext.enforceCallingOrSelfPermission(
7892                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7893                    "setApplicationHiddenSetting for user " + userId);
7894        }
7895
7896        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7897            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7898            return false;
7899        }
7900
7901        long callingId = Binder.clearCallingIdentity();
7902        try {
7903            boolean sendAdded = false;
7904            boolean sendRemoved = false;
7905            // writer
7906            synchronized (mPackages) {
7907                pkgSetting = mSettings.mPackages.get(packageName);
7908                if (pkgSetting == null) {
7909                    return false;
7910                }
7911                if (pkgSetting.getHidden(userId) != hidden) {
7912                    pkgSetting.setHidden(hidden, userId);
7913                    mSettings.writePackageRestrictionsLPr(userId);
7914                    if (hidden) {
7915                        sendRemoved = true;
7916                    } else {
7917                        sendAdded = true;
7918                    }
7919                }
7920            }
7921            if (sendAdded) {
7922                sendPackageAddedForUser(packageName, pkgSetting, userId);
7923                return true;
7924            }
7925            if (sendRemoved) {
7926                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7927                        "hiding pkg");
7928                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7929            }
7930        } finally {
7931            Binder.restoreCallingIdentity(callingId);
7932        }
7933        return false;
7934    }
7935
7936    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7937            int userId) {
7938        final PackageRemovedInfo info = new PackageRemovedInfo();
7939        info.removedPackage = packageName;
7940        info.removedUsers = new int[] {userId};
7941        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7942        info.sendBroadcast(false, false, false);
7943    }
7944
7945    /**
7946     * Returns true if application is not found or there was an error. Otherwise it returns
7947     * the hidden state of the package for the given user.
7948     */
7949    @Override
7950    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7952        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7953                "getApplicationHidden for user " + userId);
7954        PackageSetting pkgSetting;
7955        long callingId = Binder.clearCallingIdentity();
7956        try {
7957            // writer
7958            synchronized (mPackages) {
7959                pkgSetting = mSettings.mPackages.get(packageName);
7960                if (pkgSetting == null) {
7961                    return true;
7962                }
7963                return pkgSetting.getHidden(userId);
7964            }
7965        } finally {
7966            Binder.restoreCallingIdentity(callingId);
7967        }
7968    }
7969
7970    /**
7971     * @hide
7972     */
7973    @Override
7974    public int installExistingPackageAsUser(String packageName, int userId) {
7975        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7976                null);
7977        PackageSetting pkgSetting;
7978        final int uid = Binder.getCallingUid();
7979        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7980        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7981            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7982        }
7983
7984        long callingId = Binder.clearCallingIdentity();
7985        try {
7986            boolean sendAdded = false;
7987            Bundle extras = new Bundle(1);
7988
7989            // writer
7990            synchronized (mPackages) {
7991                pkgSetting = mSettings.mPackages.get(packageName);
7992                if (pkgSetting == null) {
7993                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7994                }
7995                if (!pkgSetting.getInstalled(userId)) {
7996                    pkgSetting.setInstalled(true, userId);
7997                    pkgSetting.setHidden(false, userId);
7998                    mSettings.writePackageRestrictionsLPr(userId);
7999                    sendAdded = true;
8000                }
8001            }
8002
8003            if (sendAdded) {
8004                sendPackageAddedForUser(packageName, pkgSetting, userId);
8005            }
8006        } finally {
8007            Binder.restoreCallingIdentity(callingId);
8008        }
8009
8010        return PackageManager.INSTALL_SUCCEEDED;
8011    }
8012
8013    boolean isUserRestricted(int userId, String restrictionKey) {
8014        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8015        if (restrictions.getBoolean(restrictionKey, false)) {
8016            Log.w(TAG, "User is restricted: " + restrictionKey);
8017            return true;
8018        }
8019        return false;
8020    }
8021
8022    @Override
8023    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8024        mContext.enforceCallingOrSelfPermission(
8025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8026                "Only package verification agents can verify applications");
8027
8028        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8029        final PackageVerificationResponse response = new PackageVerificationResponse(
8030                verificationCode, Binder.getCallingUid());
8031        msg.arg1 = id;
8032        msg.obj = response;
8033        mHandler.sendMessage(msg);
8034    }
8035
8036    @Override
8037    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8038            long millisecondsToDelay) {
8039        mContext.enforceCallingOrSelfPermission(
8040                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8041                "Only package verification agents can extend verification timeouts");
8042
8043        final PackageVerificationState state = mPendingVerification.get(id);
8044        final PackageVerificationResponse response = new PackageVerificationResponse(
8045                verificationCodeAtTimeout, Binder.getCallingUid());
8046
8047        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8048            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8049        }
8050        if (millisecondsToDelay < 0) {
8051            millisecondsToDelay = 0;
8052        }
8053        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8054                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8055            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8056        }
8057
8058        if ((state != null) && !state.timeoutExtended()) {
8059            state.extendTimeout();
8060
8061            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8062            msg.arg1 = id;
8063            msg.obj = response;
8064            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8065        }
8066    }
8067
8068    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8069            int verificationCode, UserHandle user) {
8070        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8071        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8072        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8073        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8074        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8075
8076        mContext.sendBroadcastAsUser(intent, user,
8077                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8078    }
8079
8080    private ComponentName matchComponentForVerifier(String packageName,
8081            List<ResolveInfo> receivers) {
8082        ActivityInfo targetReceiver = null;
8083
8084        final int NR = receivers.size();
8085        for (int i = 0; i < NR; i++) {
8086            final ResolveInfo info = receivers.get(i);
8087            if (info.activityInfo == null) {
8088                continue;
8089            }
8090
8091            if (packageName.equals(info.activityInfo.packageName)) {
8092                targetReceiver = info.activityInfo;
8093                break;
8094            }
8095        }
8096
8097        if (targetReceiver == null) {
8098            return null;
8099        }
8100
8101        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8102    }
8103
8104    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8105            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8106        if (pkgInfo.verifiers.length == 0) {
8107            return null;
8108        }
8109
8110        final int N = pkgInfo.verifiers.length;
8111        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8112        for (int i = 0; i < N; i++) {
8113            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8114
8115            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8116                    receivers);
8117            if (comp == null) {
8118                continue;
8119            }
8120
8121            final int verifierUid = getUidForVerifier(verifierInfo);
8122            if (verifierUid == -1) {
8123                continue;
8124            }
8125
8126            if (DEBUG_VERIFY) {
8127                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8128                        + " with the correct signature");
8129            }
8130            sufficientVerifiers.add(comp);
8131            verificationState.addSufficientVerifier(verifierUid);
8132        }
8133
8134        return sufficientVerifiers;
8135    }
8136
8137    private int getUidForVerifier(VerifierInfo verifierInfo) {
8138        synchronized (mPackages) {
8139            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8140            if (pkg == null) {
8141                return -1;
8142            } else if (pkg.mSignatures.length != 1) {
8143                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8144                        + " has more than one signature; ignoring");
8145                return -1;
8146            }
8147
8148            /*
8149             * If the public key of the package's signature does not match
8150             * our expected public key, then this is a different package and
8151             * we should skip.
8152             */
8153
8154            final byte[] expectedPublicKey;
8155            try {
8156                final Signature verifierSig = pkg.mSignatures[0];
8157                final PublicKey publicKey = verifierSig.getPublicKey();
8158                expectedPublicKey = publicKey.getEncoded();
8159            } catch (CertificateException e) {
8160                return -1;
8161            }
8162
8163            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8164
8165            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8166                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8167                        + " does not have the expected public key; ignoring");
8168                return -1;
8169            }
8170
8171            return pkg.applicationInfo.uid;
8172        }
8173    }
8174
8175    @Override
8176    public void finishPackageInstall(int token) {
8177        enforceSystemOrRoot("Only the system is allowed to finish installs");
8178
8179        if (DEBUG_INSTALL) {
8180            Slog.v(TAG, "BM finishing package install for " + token);
8181        }
8182
8183        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8184        mHandler.sendMessage(msg);
8185    }
8186
8187    /**
8188     * Get the verification agent timeout.
8189     *
8190     * @return verification timeout in milliseconds
8191     */
8192    private long getVerificationTimeout() {
8193        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8194                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8195                DEFAULT_VERIFICATION_TIMEOUT);
8196    }
8197
8198    /**
8199     * Get the default verification agent response code.
8200     *
8201     * @return default verification response code
8202     */
8203    private int getDefaultVerificationResponse() {
8204        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8205                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8206                DEFAULT_VERIFICATION_RESPONSE);
8207    }
8208
8209    /**
8210     * Check whether or not package verification has been enabled.
8211     *
8212     * @return true if verification should be performed
8213     */
8214    private boolean isVerificationEnabled(int userId, int flags) {
8215        if (!DEFAULT_VERIFY_ENABLE) {
8216            return false;
8217        }
8218
8219        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8220
8221        // Check if installing from ADB
8222        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8223            // Do not run verification in a test harness environment
8224            if (ActivityManager.isRunningInTestHarness()) {
8225                return false;
8226            }
8227            if (ensureVerifyAppsEnabled) {
8228                return true;
8229            }
8230            // Check if the developer does not want package verification for ADB installs
8231            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8232                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8233                return false;
8234            }
8235        }
8236
8237        if (ensureVerifyAppsEnabled) {
8238            return true;
8239        }
8240
8241        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8242                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8243    }
8244
8245    /**
8246     * Get the "allow unknown sources" setting.
8247     *
8248     * @return the current "allow unknown sources" setting
8249     */
8250    private int getUnknownSourcesSettings() {
8251        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8252                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8253                -1);
8254    }
8255
8256    @Override
8257    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8258        final int uid = Binder.getCallingUid();
8259        // writer
8260        synchronized (mPackages) {
8261            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8262            if (targetPackageSetting == null) {
8263                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8264            }
8265
8266            PackageSetting installerPackageSetting;
8267            if (installerPackageName != null) {
8268                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8269                if (installerPackageSetting == null) {
8270                    throw new IllegalArgumentException("Unknown installer package: "
8271                            + installerPackageName);
8272                }
8273            } else {
8274                installerPackageSetting = null;
8275            }
8276
8277            Signature[] callerSignature;
8278            Object obj = mSettings.getUserIdLPr(uid);
8279            if (obj != null) {
8280                if (obj instanceof SharedUserSetting) {
8281                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8282                } else if (obj instanceof PackageSetting) {
8283                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8284                } else {
8285                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8286                }
8287            } else {
8288                throw new SecurityException("Unknown calling uid " + uid);
8289            }
8290
8291            // Verify: can't set installerPackageName to a package that is
8292            // not signed with the same cert as the caller.
8293            if (installerPackageSetting != null) {
8294                if (compareSignatures(callerSignature,
8295                        installerPackageSetting.signatures.mSignatures)
8296                        != PackageManager.SIGNATURE_MATCH) {
8297                    throw new SecurityException(
8298                            "Caller does not have same cert as new installer package "
8299                            + installerPackageName);
8300                }
8301            }
8302
8303            // Verify: if target already has an installer package, it must
8304            // be signed with the same cert as the caller.
8305            if (targetPackageSetting.installerPackageName != null) {
8306                PackageSetting setting = mSettings.mPackages.get(
8307                        targetPackageSetting.installerPackageName);
8308                // If the currently set package isn't valid, then it's always
8309                // okay to change it.
8310                if (setting != null) {
8311                    if (compareSignatures(callerSignature,
8312                            setting.signatures.mSignatures)
8313                            != PackageManager.SIGNATURE_MATCH) {
8314                        throw new SecurityException(
8315                                "Caller does not have same cert as old installer package "
8316                                + targetPackageSetting.installerPackageName);
8317                    }
8318                }
8319            }
8320
8321            // Okay!
8322            targetPackageSetting.installerPackageName = installerPackageName;
8323            scheduleWriteSettingsLocked();
8324        }
8325    }
8326
8327    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8328        // Queue up an async operation since the package installation may take a little while.
8329        mHandler.post(new Runnable() {
8330            public void run() {
8331                mHandler.removeCallbacks(this);
8332                 // Result object to be returned
8333                PackageInstalledInfo res = new PackageInstalledInfo();
8334                res.returnCode = currentStatus;
8335                res.uid = -1;
8336                res.pkg = null;
8337                res.removedInfo = new PackageRemovedInfo();
8338                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8339                    args.doPreInstall(res.returnCode);
8340                    synchronized (mInstallLock) {
8341                        installPackageLI(args, true, res);
8342                    }
8343                    args.doPostInstall(res.returnCode, res.uid);
8344                }
8345
8346                // A restore should be performed at this point if (a) the install
8347                // succeeded, (b) the operation is not an update, and (c) the new
8348                // package has a backupAgent defined.
8349                final boolean update = res.removedInfo.removedPackage != null;
8350                boolean doRestore = (!update
8351                        && res.pkg != null
8352                        && res.pkg.applicationInfo.backupAgentName != null);
8353
8354                // Set up the post-install work request bookkeeping.  This will be used
8355                // and cleaned up by the post-install event handling regardless of whether
8356                // there's a restore pass performed.  Token values are >= 1.
8357                int token;
8358                if (mNextInstallToken < 0) mNextInstallToken = 1;
8359                token = mNextInstallToken++;
8360
8361                PostInstallData data = new PostInstallData(args, res);
8362                mRunningInstalls.put(token, data);
8363                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8364
8365                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8366                    // Pass responsibility to the Backup Manager.  It will perform a
8367                    // restore if appropriate, then pass responsibility back to the
8368                    // Package Manager to run the post-install observer callbacks
8369                    // and broadcasts.
8370                    IBackupManager bm = IBackupManager.Stub.asInterface(
8371                            ServiceManager.getService(Context.BACKUP_SERVICE));
8372                    if (bm != null) {
8373                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8374                                + " to BM for possible restore");
8375                        try {
8376                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8377                        } catch (RemoteException e) {
8378                            // can't happen; the backup manager is local
8379                        } catch (Exception e) {
8380                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8381                            doRestore = false;
8382                        }
8383                    } else {
8384                        Slog.e(TAG, "Backup Manager not found!");
8385                        doRestore = false;
8386                    }
8387                }
8388
8389                if (!doRestore) {
8390                    // No restore possible, or the Backup Manager was mysteriously not
8391                    // available -- just fire the post-install work request directly.
8392                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8393                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8394                    mHandler.sendMessage(msg);
8395                }
8396            }
8397        });
8398    }
8399
8400    private abstract class HandlerParams {
8401        private static final int MAX_RETRIES = 4;
8402
8403        /**
8404         * Number of times startCopy() has been attempted and had a non-fatal
8405         * error.
8406         */
8407        private int mRetries = 0;
8408
8409        /** User handle for the user requesting the information or installation. */
8410        private final UserHandle mUser;
8411
8412        HandlerParams(UserHandle user) {
8413            mUser = user;
8414        }
8415
8416        UserHandle getUser() {
8417            return mUser;
8418        }
8419
8420        final boolean startCopy() {
8421            boolean res;
8422            try {
8423                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8424
8425                if (++mRetries > MAX_RETRIES) {
8426                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8427                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8428                    handleServiceError();
8429                    return false;
8430                } else {
8431                    handleStartCopy();
8432                    res = true;
8433                }
8434            } catch (RemoteException e) {
8435                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8436                mHandler.sendEmptyMessage(MCS_RECONNECT);
8437                res = false;
8438            }
8439            handleReturnCode();
8440            return res;
8441        }
8442
8443        final void serviceError() {
8444            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8445            handleServiceError();
8446            handleReturnCode();
8447        }
8448
8449        abstract void handleStartCopy() throws RemoteException;
8450        abstract void handleServiceError();
8451        abstract void handleReturnCode();
8452    }
8453
8454    class MeasureParams extends HandlerParams {
8455        private final PackageStats mStats;
8456        private boolean mSuccess;
8457
8458        private final IPackageStatsObserver mObserver;
8459
8460        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8461            super(new UserHandle(stats.userHandle));
8462            mObserver = observer;
8463            mStats = stats;
8464        }
8465
8466        @Override
8467        public String toString() {
8468            return "MeasureParams{"
8469                + Integer.toHexString(System.identityHashCode(this))
8470                + " " + mStats.packageName + "}";
8471        }
8472
8473        @Override
8474        void handleStartCopy() throws RemoteException {
8475            synchronized (mInstallLock) {
8476                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8477            }
8478
8479            if (mSuccess) {
8480                final boolean mounted;
8481                if (Environment.isExternalStorageEmulated()) {
8482                    mounted = true;
8483                } else {
8484                    final String status = Environment.getExternalStorageState();
8485                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8486                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8487                }
8488
8489                if (mounted) {
8490                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8491
8492                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8493                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8494
8495                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8496                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8497
8498                    // Always subtract cache size, since it's a subdirectory
8499                    mStats.externalDataSize -= mStats.externalCacheSize;
8500
8501                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8502                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8503
8504                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8505                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8506                }
8507            }
8508        }
8509
8510        @Override
8511        void handleReturnCode() {
8512            if (mObserver != null) {
8513                try {
8514                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8515                } catch (RemoteException e) {
8516                    Slog.i(TAG, "Observer no longer exists.");
8517                }
8518            }
8519        }
8520
8521        @Override
8522        void handleServiceError() {
8523            Slog.e(TAG, "Could not measure application " + mStats.packageName
8524                            + " external storage");
8525        }
8526    }
8527
8528    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8529            throws RemoteException {
8530        long result = 0;
8531        for (File path : paths) {
8532            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8533        }
8534        return result;
8535    }
8536
8537    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8538        for (File path : paths) {
8539            try {
8540                mcs.clearDirectory(path.getAbsolutePath());
8541            } catch (RemoteException e) {
8542            }
8543        }
8544    }
8545
8546    class InstallParams extends HandlerParams {
8547        /**
8548         * Location where install is coming from, before it has been
8549         * copied/renamed into place. This could be a single monolithic APK
8550         * file, or a cluster directory. This location may be untrusted.
8551         */
8552        final File originFile;
8553
8554        /**
8555         * Flag indicating that {@link #originFile} has already been staged,
8556         * meaning downstream users don't need to defensively copy the contents.
8557         */
8558        boolean originStaged;
8559
8560        final IPackageInstallObserver2 observer;
8561        int flags;
8562        final String installerPackageName;
8563        final VerificationParams verificationParams;
8564        private InstallArgs mArgs;
8565        private int mRet;
8566        final String packageAbiOverride;
8567        boolean multiArch;
8568
8569        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8570                int flags, String installerPackageName, VerificationParams verificationParams,
8571                UserHandle user, String packageAbiOverride) {
8572            super(user);
8573            this.originFile = Preconditions.checkNotNull(originFile);
8574            this.originStaged = originStaged;
8575            this.observer = observer;
8576            this.flags = flags;
8577            this.installerPackageName = installerPackageName;
8578            this.verificationParams = verificationParams;
8579            this.packageAbiOverride = packageAbiOverride;
8580        }
8581
8582        @Override
8583        public String toString() {
8584            return "InstallParams{"
8585                + Integer.toHexString(System.identityHashCode(this))
8586                + " " + originFile + "}";
8587        }
8588
8589        public ManifestDigest getManifestDigest() {
8590            if (verificationParams == null) {
8591                return null;
8592            }
8593            return verificationParams.getManifestDigest();
8594        }
8595
8596        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8597            String packageName = pkgLite.packageName;
8598            int installLocation = pkgLite.installLocation;
8599            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8600            // reader
8601            synchronized (mPackages) {
8602                PackageParser.Package pkg = mPackages.get(packageName);
8603                if (pkg != null) {
8604                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8605                        // Check for downgrading.
8606                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8607                            if (pkgLite.versionCode < pkg.mVersionCode) {
8608                                Slog.w(TAG, "Can't install update of " + packageName
8609                                        + " update version " + pkgLite.versionCode
8610                                        + " is older than installed version "
8611                                        + pkg.mVersionCode);
8612                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8613                            }
8614                        }
8615                        // Check for updated system application.
8616                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8617                            if (onSd) {
8618                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8619                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8620                            }
8621                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8622                        } else {
8623                            if (onSd) {
8624                                // Install flag overrides everything.
8625                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8626                            }
8627                            // If current upgrade specifies particular preference
8628                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8629                                // Application explicitly specified internal.
8630                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8631                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8632                                // App explictly prefers external. Let policy decide
8633                            } else {
8634                                // Prefer previous location
8635                                if (isExternal(pkg)) {
8636                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8637                                }
8638                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8639                            }
8640                        }
8641                    } else {
8642                        // Invalid install. Return error code
8643                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8644                    }
8645                }
8646            }
8647            // All the special cases have been taken care of.
8648            // Return result based on recommended install location.
8649            if (onSd) {
8650                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8651            }
8652            return pkgLite.recommendedInstallLocation;
8653        }
8654
8655        private long getMemoryLowThreshold() {
8656            final DeviceStorageMonitorInternal
8657                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8658            if (dsm == null) {
8659                return 0L;
8660            }
8661            return dsm.getMemoryLowThreshold();
8662        }
8663
8664        /*
8665         * Invoke remote method to get package information and install
8666         * location values. Override install location based on default
8667         * policy if needed and then create install arguments based
8668         * on the install location.
8669         */
8670        public void handleStartCopy() throws RemoteException {
8671            int ret = PackageManager.INSTALL_SUCCEEDED;
8672            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8673            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8674            PackageInfoLite pkgLite = null;
8675
8676            if (onInt && onSd) {
8677                // Check if both bits are set.
8678                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8679                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8680            } else {
8681                final long lowThreshold = getMemoryLowThreshold();
8682                if (lowThreshold == 0L) {
8683                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8684                }
8685
8686                // Remote call to find out default install location
8687                final String originPath = originFile.getAbsolutePath();
8688                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8689                        packageAbiOverride);
8690                // Keep track of whether this package is a multiArch package until
8691                // we perform a full scan of it. We need to do this because we might
8692                // end up extracting the package shared libraries before we perform
8693                // a full scan.
8694                multiArch = pkgLite.multiArch;
8695
8696                /*
8697                 * If we have too little free space, try to free cache
8698                 * before giving up.
8699                 */
8700                if (pkgLite.recommendedInstallLocation
8701                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8702                    final long size = mContainerService.calculateInstalledSize(
8703                            originPath, isForwardLocked(), packageAbiOverride);
8704                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8705                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8706                                lowThreshold, packageAbiOverride);
8707                    }
8708                    /*
8709                     * The cache free must have deleted the file we
8710                     * downloaded to install.
8711                     *
8712                     * TODO: fix the "freeCache" call to not delete
8713                     *       the file we care about.
8714                     */
8715                    if (pkgLite.recommendedInstallLocation
8716                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8717                        pkgLite.recommendedInstallLocation
8718                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8719                    }
8720                }
8721            }
8722
8723            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8724                int loc = pkgLite.recommendedInstallLocation;
8725                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8726                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8727                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8728                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8729                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8730                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8731                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8732                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8733                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8734                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8735                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8736                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8737                } else {
8738                    // Override with defaults if needed.
8739                    loc = installLocationPolicy(pkgLite, flags);
8740                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8741                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8742                    } else if (!onSd && !onInt) {
8743                        // Override install location with flags
8744                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8745                            // Set the flag to install on external media.
8746                            flags |= PackageManager.INSTALL_EXTERNAL;
8747                            flags &= ~PackageManager.INSTALL_INTERNAL;
8748                        } else {
8749                            // Make sure the flag for installing on external
8750                            // media is unset
8751                            flags |= PackageManager.INSTALL_INTERNAL;
8752                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8753                        }
8754                    }
8755                }
8756            }
8757
8758            final InstallArgs args = createInstallArgs(this);
8759            mArgs = args;
8760
8761            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8762                 /*
8763                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8764                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8765                 */
8766                int userIdentifier = getUser().getIdentifier();
8767                if (userIdentifier == UserHandle.USER_ALL
8768                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8769                    userIdentifier = UserHandle.USER_OWNER;
8770                }
8771
8772                /*
8773                 * Determine if we have any installed package verifiers. If we
8774                 * do, then we'll defer to them to verify the packages.
8775                 */
8776                final int requiredUid = mRequiredVerifierPackage == null ? -1
8777                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8778                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8779                    // TODO: send verifier the install session instead of uri
8780                    final Intent verification = new Intent(
8781                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8782                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8783                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8784
8785                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8786                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8787                            0 /* TODO: Which userId? */);
8788
8789                    if (DEBUG_VERIFY) {
8790                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8791                                + verification.toString() + " with " + pkgLite.verifiers.length
8792                                + " optional verifiers");
8793                    }
8794
8795                    final int verificationId = mPendingVerificationToken++;
8796
8797                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8798
8799                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8800                            installerPackageName);
8801
8802                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8803
8804                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8805                            pkgLite.packageName);
8806
8807                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8808                            pkgLite.versionCode);
8809
8810                    if (verificationParams != null) {
8811                        if (verificationParams.getVerificationURI() != null) {
8812                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8813                                 verificationParams.getVerificationURI());
8814                        }
8815                        if (verificationParams.getOriginatingURI() != null) {
8816                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8817                                  verificationParams.getOriginatingURI());
8818                        }
8819                        if (verificationParams.getReferrer() != null) {
8820                            verification.putExtra(Intent.EXTRA_REFERRER,
8821                                  verificationParams.getReferrer());
8822                        }
8823                        if (verificationParams.getOriginatingUid() >= 0) {
8824                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8825                                  verificationParams.getOriginatingUid());
8826                        }
8827                        if (verificationParams.getInstallerUid() >= 0) {
8828                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8829                                  verificationParams.getInstallerUid());
8830                        }
8831                    }
8832
8833                    final PackageVerificationState verificationState = new PackageVerificationState(
8834                            requiredUid, args);
8835
8836                    mPendingVerification.append(verificationId, verificationState);
8837
8838                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8839                            receivers, verificationState);
8840
8841                    /*
8842                     * If any sufficient verifiers were listed in the package
8843                     * manifest, attempt to ask them.
8844                     */
8845                    if (sufficientVerifiers != null) {
8846                        final int N = sufficientVerifiers.size();
8847                        if (N == 0) {
8848                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8849                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8850                        } else {
8851                            for (int i = 0; i < N; i++) {
8852                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8853
8854                                final Intent sufficientIntent = new Intent(verification);
8855                                sufficientIntent.setComponent(verifierComponent);
8856
8857                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8858                            }
8859                        }
8860                    }
8861
8862                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8863                            mRequiredVerifierPackage, receivers);
8864                    if (ret == PackageManager.INSTALL_SUCCEEDED
8865                            && mRequiredVerifierPackage != null) {
8866                        /*
8867                         * Send the intent to the required verification agent,
8868                         * but only start the verification timeout after the
8869                         * target BroadcastReceivers have run.
8870                         */
8871                        verification.setComponent(requiredVerifierComponent);
8872                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8873                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8874                                new BroadcastReceiver() {
8875                                    @Override
8876                                    public void onReceive(Context context, Intent intent) {
8877                                        final Message msg = mHandler
8878                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8879                                        msg.arg1 = verificationId;
8880                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8881                                    }
8882                                }, null, 0, null, null);
8883
8884                        /*
8885                         * We don't want the copy to proceed until verification
8886                         * succeeds, so null out this field.
8887                         */
8888                        mArgs = null;
8889                    }
8890                } else {
8891                    /*
8892                     * No package verification is enabled, so immediately start
8893                     * the remote call to initiate copy using temporary file.
8894                     */
8895                    ret = args.copyApk(mContainerService, true);
8896                }
8897            }
8898
8899            mRet = ret;
8900        }
8901
8902        @Override
8903        void handleReturnCode() {
8904            // If mArgs is null, then MCS couldn't be reached. When it
8905            // reconnects, it will try again to install. At that point, this
8906            // will succeed.
8907            if (mArgs != null) {
8908                processPendingInstall(mArgs, mRet);
8909            }
8910        }
8911
8912        @Override
8913        void handleServiceError() {
8914            mArgs = createInstallArgs(this);
8915            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8916        }
8917
8918        public boolean isForwardLocked() {
8919            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8920        }
8921    }
8922
8923    /*
8924     * Utility class used in movePackage api.
8925     * srcArgs and targetArgs are not set for invalid flags and make
8926     * sure to do null checks when invoking methods on them.
8927     * We probably want to return ErrorPrams for both failed installs
8928     * and moves.
8929     */
8930    class MoveParams extends HandlerParams {
8931        final IPackageMoveObserver observer;
8932        final int flags;
8933        final String packageName;
8934        final InstallArgs srcArgs;
8935        final InstallArgs targetArgs;
8936        int uid;
8937        int mRet;
8938
8939        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8940                String packageName, String[] instructionSets, int uid, UserHandle user,
8941                boolean isMultiArch) {
8942            super(user);
8943            this.srcArgs = srcArgs;
8944            this.observer = observer;
8945            this.flags = flags;
8946            this.packageName = packageName;
8947            this.uid = uid;
8948            if (srcArgs != null) {
8949                final String codePath = srcArgs.getCodePath();
8950                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8951                        instructionSets, isMultiArch);
8952            } else {
8953                targetArgs = null;
8954            }
8955        }
8956
8957        @Override
8958        public String toString() {
8959            return "MoveParams{"
8960                + Integer.toHexString(System.identityHashCode(this))
8961                + " " + packageName + "}";
8962        }
8963
8964        public void handleStartCopy() throws RemoteException {
8965            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8966            // Check for storage space on target medium
8967            if (!targetArgs.checkFreeStorage(mContainerService)) {
8968                Log.w(TAG, "Insufficient storage to install");
8969                return;
8970            }
8971
8972            mRet = srcArgs.doPreCopy();
8973            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8974                return;
8975            }
8976
8977            mRet = targetArgs.copyApk(mContainerService, false);
8978            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8979                srcArgs.doPostCopy(uid);
8980                return;
8981            }
8982
8983            mRet = srcArgs.doPostCopy(uid);
8984            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8985                return;
8986            }
8987
8988            mRet = targetArgs.doPreInstall(mRet);
8989            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8990                return;
8991            }
8992
8993            if (DEBUG_SD_INSTALL) {
8994                StringBuilder builder = new StringBuilder();
8995                if (srcArgs != null) {
8996                    builder.append("src: ");
8997                    builder.append(srcArgs.getCodePath());
8998                }
8999                if (targetArgs != null) {
9000                    builder.append(" target : ");
9001                    builder.append(targetArgs.getCodePath());
9002                }
9003                Log.i(TAG, builder.toString());
9004            }
9005        }
9006
9007        @Override
9008        void handleReturnCode() {
9009            targetArgs.doPostInstall(mRet, uid);
9010            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9011            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9012                currentStatus = PackageManager.MOVE_SUCCEEDED;
9013            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9014                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9015            }
9016            processPendingMove(this, currentStatus);
9017        }
9018
9019        @Override
9020        void handleServiceError() {
9021            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9022        }
9023    }
9024
9025    /**
9026     * Used during creation of InstallArgs
9027     *
9028     * @param flags package installation flags
9029     * @return true if should be installed on external storage
9030     */
9031    private static boolean installOnSd(int flags) {
9032        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9033            return false;
9034        }
9035        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9036            return true;
9037        }
9038        return false;
9039    }
9040
9041    /**
9042     * Used during creation of InstallArgs
9043     *
9044     * @param flags package installation flags
9045     * @return true if should be installed as forward locked
9046     */
9047    private static boolean installForwardLocked(int flags) {
9048        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9049    }
9050
9051    private InstallArgs createInstallArgs(InstallParams params) {
9052        // TODO: extend to support incoming zero-copy locations
9053
9054        if (installOnSd(params.flags) || params.isForwardLocked()) {
9055            return new AsecInstallArgs(params);
9056        } else {
9057            return new FileInstallArgs(params);
9058        }
9059    }
9060
9061    /**
9062     * Create args that describe an existing installed package. Typically used
9063     * when cleaning up old installs, or used as a move source.
9064     */
9065    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9066            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9067            boolean isMultiArch) {
9068        final boolean isInAsec;
9069        if (installOnSd(flags)) {
9070            /* Apps on SD card are always in ASEC containers. */
9071            isInAsec = true;
9072        } else if (installForwardLocked(flags)
9073                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9074            /*
9075             * Forward-locked apps are only in ASEC containers if they're the
9076             * new style
9077             */
9078            isInAsec = true;
9079        } else {
9080            isInAsec = false;
9081        }
9082
9083        if (isInAsec) {
9084            return new AsecInstallArgs(codePath, instructionSets,
9085                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9086        } else {
9087            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9088                    instructionSets, isMultiArch);
9089        }
9090    }
9091
9092    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9093            String[] instructionSets, boolean isMultiArch) {
9094        final File codeFile = new File(codePath);
9095        if (installOnSd(flags) || installForwardLocked(flags)) {
9096            String cid = getNextCodePath(codePath, pkgName, "/"
9097                    + AsecInstallArgs.RES_FILE_NAME);
9098            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9099                    installForwardLocked(flags), isMultiArch);
9100        } else {
9101            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9102        }
9103    }
9104
9105    static abstract class InstallArgs {
9106        /** @see InstallParams#originFile */
9107        final File originFile;
9108        /** @see InstallParams#originStaged */
9109        final boolean originStaged;
9110
9111        // TODO: define inherit location
9112
9113        final IPackageInstallObserver2 observer;
9114        // Always refers to PackageManager flags only
9115        final int flags;
9116        final String installerPackageName;
9117        final ManifestDigest manifestDigest;
9118        final UserHandle user;
9119        final String abiOverride;
9120        final boolean multiArch;
9121
9122        // The list of instruction sets supported by this app. This is currently
9123        // only used during the rmdex() phase to clean up resources. We can get rid of this
9124        // if we move dex files under the common app path.
9125        /* nullable */ String[] instructionSets;
9126
9127        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9128                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9129                    UserHandle user, String[] instructionSets,
9130                    String abiOverride, boolean multiArch) {
9131            this.originFile = originFile;
9132            this.originStaged = originStaged;
9133            this.flags = flags;
9134            this.observer = observer;
9135            this.installerPackageName = installerPackageName;
9136            this.manifestDigest = manifestDigest;
9137            this.user = user;
9138            this.instructionSets = instructionSets;
9139            this.abiOverride = abiOverride;
9140            this.multiArch = multiArch;
9141        }
9142
9143        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9144        abstract int doPreInstall(int status);
9145
9146        /**
9147         * Rename package into final resting place. All paths on the given
9148         * scanned package should be updated to reflect the rename.
9149         */
9150        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9151        abstract int doPostInstall(int status, int uid);
9152
9153        /** @see PackageSettingBase#codePathString */
9154        abstract String getCodePath();
9155        /** @see PackageSettingBase#resourcePathString */
9156        abstract String getResourcePath();
9157        abstract String getLegacyNativeLibraryPath();
9158
9159        // Need installer lock especially for dex file removal.
9160        abstract void cleanUpResourcesLI();
9161        abstract boolean doPostDeleteLI(boolean delete);
9162        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9163
9164        /**
9165         * Called before the source arguments are copied. This is used mostly
9166         * for MoveParams when it needs to read the source file to put it in the
9167         * destination.
9168         */
9169        int doPreCopy() {
9170            return PackageManager.INSTALL_SUCCEEDED;
9171        }
9172
9173        /**
9174         * Called after the source arguments are copied. This is used mostly for
9175         * MoveParams when it needs to read the source file to put it in the
9176         * destination.
9177         *
9178         * @return
9179         */
9180        int doPostCopy(int uid) {
9181            return PackageManager.INSTALL_SUCCEEDED;
9182        }
9183
9184        protected boolean isFwdLocked() {
9185            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9186        }
9187
9188        UserHandle getUser() {
9189            return user;
9190        }
9191    }
9192
9193    /**
9194     * Logic to handle installation of non-ASEC applications, including copying
9195     * and renaming logic.
9196     */
9197    class FileInstallArgs extends InstallArgs {
9198        private File codeFile;
9199        private File resourceFile;
9200        private File legacyNativeLibraryPath;
9201
9202        // Example topology:
9203        // /data/app/com.example/base.apk
9204        // /data/app/com.example/split_foo.apk
9205        // /data/app/com.example/lib/arm/libfoo.so
9206        // /data/app/com.example/lib/arm64/libfoo.so
9207        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9208
9209        /** New install */
9210        FileInstallArgs(InstallParams params) {
9211            super(params.originFile, params.originStaged, params.observer, params.flags,
9212                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9213                    null /* instruction sets */, params.packageAbiOverride,
9214                    params.multiArch);
9215            if (isFwdLocked()) {
9216                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9217            }
9218        }
9219
9220        /** Existing install */
9221        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9222                String[] instructionSets, boolean isMultiArch) {
9223            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9224            this.codeFile = (codePath != null) ? new File(codePath) : null;
9225            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9226            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9227                    new File(legacyNativeLibraryPath) : null;
9228        }
9229
9230        /** New install from existing */
9231        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9232            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9233                    isMultiArch);
9234        }
9235
9236        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9237            final long lowThreshold;
9238
9239            final DeviceStorageMonitorInternal
9240                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9241            if (dsm == null) {
9242                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9243                lowThreshold = 0L;
9244            } else {
9245                if (dsm.isMemoryLow()) {
9246                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9247                    return false;
9248                }
9249
9250                lowThreshold = dsm.getMemoryLowThreshold();
9251            }
9252
9253            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9254                    lowThreshold);
9255        }
9256
9257        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9258            int ret = PackageManager.INSTALL_SUCCEEDED;
9259
9260            if (originStaged) {
9261                Slog.d(TAG, originFile + " already staged; skipping copy");
9262                codeFile = originFile;
9263                resourceFile = originFile;
9264            } else {
9265                try {
9266                    final File tempDir = mInstallerService.allocateSessionDir();
9267                    codeFile = tempDir;
9268                    resourceFile = tempDir;
9269                } catch (IOException e) {
9270                    Slog.w(TAG, "Failed to create copy file: " + e);
9271                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9272                }
9273
9274                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9275                    @Override
9276                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9277                        if (!FileUtils.isValidExtFilename(name)) {
9278                            throw new IllegalArgumentException("Invalid filename: " + name);
9279                        }
9280                        try {
9281                            final File file = new File(codeFile, name);
9282                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9283                                    O_RDWR | O_CREAT, 0644);
9284                            Os.chmod(file.getAbsolutePath(), 0644);
9285                            return new ParcelFileDescriptor(fd);
9286                        } catch (ErrnoException e) {
9287                            throw new RemoteException("Failed to open: " + e.getMessage());
9288                        }
9289                    }
9290                };
9291
9292                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9293                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9294                    Slog.e(TAG, "Failed to copy package");
9295                    return ret;
9296                }
9297            }
9298
9299            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9300            NativeLibraryHelper.Handle handle = null;
9301            try {
9302                handle = NativeLibraryHelper.Handle.create(codeFile);
9303                if (multiArch) {
9304                    // Warn if we've set an abiOverride for multi-lib packages..
9305                    // By definition, we need to copy both 32 and 64 bit libraries for
9306                    // such packages.
9307                    if (abiOverride != null) {
9308                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9309                    }
9310
9311                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9312                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9313                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9314                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9315                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9316                    }
9317
9318                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9319                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9320                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9321                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9322                    }
9323                } else {
9324                    String[] abiList = (abiOverride != null) ?
9325                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9326
9327                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9328                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9329                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9330                    }
9331
9332                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9333                            true /* use isa specific subdirs */);
9334                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9335                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9336                        return copyRet;
9337                    }
9338                }
9339            } catch (IOException e) {
9340                Slog.e(TAG, "Copying native libraries failed", e);
9341                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9342            } catch (PackageManagerException pme) {
9343                Slog.e(TAG, "Copying native libraries failed", pme);
9344                ret = pme.error;
9345            } finally {
9346                IoUtils.closeQuietly(handle);
9347            }
9348
9349            return ret;
9350        }
9351
9352        int doPreInstall(int status) {
9353            if (status != PackageManager.INSTALL_SUCCEEDED) {
9354                cleanUp();
9355            }
9356            return status;
9357        }
9358
9359        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9360            if (status != PackageManager.INSTALL_SUCCEEDED) {
9361                cleanUp();
9362                return false;
9363            } else {
9364                final File beforeCodeFile = codeFile;
9365                final File afterCodeFile = getNextCodePath(pkg.packageName);
9366
9367                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9368                try {
9369                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9370                } catch (ErrnoException e) {
9371                    Slog.d(TAG, "Failed to rename", e);
9372                    return false;
9373                }
9374
9375                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9376                    Slog.d(TAG, "Failed to restorecon");
9377                    return false;
9378                }
9379
9380                // Reflect the rename internally
9381                codeFile = afterCodeFile;
9382                resourceFile = afterCodeFile;
9383
9384                // Reflect the rename in scanned details
9385                pkg.codePath = afterCodeFile.getAbsolutePath();
9386                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9387                        pkg.baseCodePath);
9388                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9389                        pkg.splitCodePaths);
9390
9391                // Reflect the rename in app info
9392                pkg.applicationInfo.setCodePath(pkg.codePath);
9393                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9394                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9395                pkg.applicationInfo.setResourcePath(pkg.codePath);
9396                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9397                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9398
9399                return true;
9400            }
9401        }
9402
9403        int doPostInstall(int status, int uid) {
9404            if (status != PackageManager.INSTALL_SUCCEEDED) {
9405                cleanUp();
9406            }
9407            return status;
9408        }
9409
9410        @Override
9411        String getCodePath() {
9412            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9413        }
9414
9415        @Override
9416        String getResourcePath() {
9417            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9418        }
9419
9420        @Override
9421        String getLegacyNativeLibraryPath() {
9422            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9423        }
9424
9425        private boolean cleanUp() {
9426            if (codeFile == null || !codeFile.exists()) {
9427                return false;
9428            }
9429
9430            if (codeFile.isDirectory()) {
9431                FileUtils.deleteContents(codeFile);
9432            }
9433            codeFile.delete();
9434
9435            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9436                resourceFile.delete();
9437            }
9438
9439            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9440                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9441                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9442                }
9443                legacyNativeLibraryPath.delete();
9444            }
9445
9446            return true;
9447        }
9448
9449        void cleanUpResourcesLI() {
9450            // Try enumerating all code paths before deleting
9451            List<String> allCodePaths = Collections.EMPTY_LIST;
9452            if (codeFile != null && codeFile.exists()) {
9453                try {
9454                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9455                    allCodePaths = pkg.getAllCodePaths();
9456                } catch (PackageParserException e) {
9457                    // Ignored; we tried our best
9458                }
9459            }
9460
9461            cleanUp();
9462
9463            if (!allCodePaths.isEmpty()) {
9464                if (instructionSets == null) {
9465                    throw new IllegalStateException("instructionSet == null");
9466                }
9467
9468                for (String codePath : allCodePaths) {
9469                    for (String instructionSet : instructionSets) {
9470                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9471                        if (retCode < 0) {
9472                            Slog.w(TAG, "Couldn't remove dex file for package: "
9473                                    + " at location " + codePath + ", retcode=" + retCode);
9474                            // we don't consider this to be a failure of the core package deletion
9475                        }
9476                    }
9477                }
9478            }
9479        }
9480
9481        boolean doPostDeleteLI(boolean delete) {
9482            // XXX err, shouldn't we respect the delete flag?
9483            cleanUpResourcesLI();
9484            return true;
9485        }
9486    }
9487
9488    private boolean isAsecExternal(String cid) {
9489        final String asecPath = PackageHelper.getSdFilesystem(cid);
9490        return !asecPath.startsWith(mAsecInternalPath);
9491    }
9492
9493    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9494            PackageManagerException {
9495        if (copyRet < 0) {
9496            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9497                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9498                throw new PackageManagerException(copyRet, message);
9499            }
9500        }
9501    }
9502
9503    /**
9504     * Extract the MountService "container ID" from the full code path of an
9505     * .apk.
9506     */
9507    static String cidFromCodePath(String fullCodePath) {
9508        int eidx = fullCodePath.lastIndexOf("/");
9509        String subStr1 = fullCodePath.substring(0, eidx);
9510        int sidx = subStr1.lastIndexOf("/");
9511        return subStr1.substring(sidx+1, eidx);
9512    }
9513
9514    /**
9515     * Logic to handle installation of ASEC applications, including copying and
9516     * renaming logic.
9517     */
9518    class AsecInstallArgs extends InstallArgs {
9519        // TODO: teach about handling cluster directories
9520
9521        static final String RES_FILE_NAME = "pkg.apk";
9522        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9523
9524        String cid;
9525        String packagePath;
9526        String resourcePath;
9527        String legacyNativeLibraryDir;
9528
9529        /** New install */
9530        AsecInstallArgs(InstallParams params) {
9531            super(params.originFile, params.originStaged, params.observer, params.flags,
9532                    params.installerPackageName, params.getManifestDigest(),
9533                    params.getUser(), null /* instruction sets */,
9534                    params.packageAbiOverride, params.multiArch);
9535        }
9536
9537        /** Existing install */
9538        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9539                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9540            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9541                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9542                    instructionSets, null, isMultiArch);
9543            // Extract cid from fullCodePath
9544            int eidx = fullCodePath.lastIndexOf("/");
9545            String subStr1 = fullCodePath.substring(0, eidx);
9546            int sidx = subStr1.lastIndexOf("/");
9547            cid = subStr1.substring(sidx+1, eidx);
9548            setCachePath(subStr1);
9549        }
9550
9551        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9552                        boolean isMultiArch) {
9553            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9554                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9555                    instructionSets, null, isMultiArch);
9556            this.cid = cid;
9557            setCachePath(PackageHelper.getSdDir(cid));
9558        }
9559
9560        /** New install from existing */
9561        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9562                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9563            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9564                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9565                    instructionSets, null, isMultiArch);
9566            this.cid = cid;
9567        }
9568
9569        void createCopyFile() {
9570            cid = getTempContainerId();
9571        }
9572
9573        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9574            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9575                    abiOverride);
9576        }
9577
9578        private final boolean isExternal() {
9579            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9580        }
9581
9582        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9583            if (temp) {
9584                createCopyFile();
9585            } else {
9586                /*
9587                 * Pre-emptively destroy the container since it's destroyed if
9588                 * copying fails due to it existing anyway.
9589                 */
9590                PackageHelper.destroySdDir(cid);
9591            }
9592
9593            final String newCachePath = imcs.copyPackageToContainer(
9594                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9595                    isFwdLocked(), abiOverride);
9596
9597            if (newCachePath != null) {
9598                setCachePath(newCachePath);
9599                return PackageManager.INSTALL_SUCCEEDED;
9600            } else {
9601                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9602            }
9603        }
9604
9605        @Override
9606        String getCodePath() {
9607            return packagePath;
9608        }
9609
9610        @Override
9611        String getResourcePath() {
9612            return resourcePath;
9613        }
9614
9615        @Override
9616        String getLegacyNativeLibraryPath() {
9617            return legacyNativeLibraryDir;
9618        }
9619
9620        int doPreInstall(int status) {
9621            if (status != PackageManager.INSTALL_SUCCEEDED) {
9622                // Destroy container
9623                PackageHelper.destroySdDir(cid);
9624            } else {
9625                boolean mounted = PackageHelper.isContainerMounted(cid);
9626                if (!mounted) {
9627                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9628                            Process.SYSTEM_UID);
9629                    if (newCachePath != null) {
9630                        setCachePath(newCachePath);
9631                    } else {
9632                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9633                    }
9634                }
9635            }
9636            return status;
9637        }
9638
9639        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9640            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9641            String newCachePath = null;
9642            if (PackageHelper.isContainerMounted(cid)) {
9643                // Unmount the container
9644                if (!PackageHelper.unMountSdDir(cid)) {
9645                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9646                    return false;
9647                }
9648            }
9649            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9650                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9651                        " which might be stale. Will try to clean up.");
9652                // Clean up the stale container and proceed to recreate.
9653                if (!PackageHelper.destroySdDir(newCacheId)) {
9654                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9655                    return false;
9656                }
9657                // Successfully cleaned up stale container. Try to rename again.
9658                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9659                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9660                            + " inspite of cleaning it up.");
9661                    return false;
9662                }
9663            }
9664            if (!PackageHelper.isContainerMounted(newCacheId)) {
9665                Slog.w(TAG, "Mounting container " + newCacheId);
9666                newCachePath = PackageHelper.mountSdDir(newCacheId,
9667                        getEncryptKey(), Process.SYSTEM_UID);
9668            } else {
9669                newCachePath = PackageHelper.getSdDir(newCacheId);
9670            }
9671            if (newCachePath == null) {
9672                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9673                return false;
9674            }
9675            Log.i(TAG, "Succesfully renamed " + cid +
9676                    " to " + newCacheId +
9677                    " at new path: " + newCachePath);
9678            cid = newCacheId;
9679            setCachePath(newCachePath);
9680
9681            // TODO: extend to support split APKs
9682            pkg.codePath = getCodePath();
9683            pkg.baseCodePath = getCodePath();
9684            pkg.splitCodePaths = null;
9685
9686            pkg.applicationInfo.setCodePath(getCodePath());
9687            pkg.applicationInfo.setBaseCodePath(getCodePath());
9688            pkg.applicationInfo.setSplitCodePaths(null);
9689            pkg.applicationInfo.setResourcePath(getResourcePath());
9690            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9691            pkg.applicationInfo.setSplitResourcePaths(null);
9692
9693            return true;
9694        }
9695
9696        private void setCachePath(String newCachePath) {
9697            File cachePath = new File(newCachePath);
9698            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9699            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9700
9701            if (isFwdLocked()) {
9702                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9703            } else {
9704                resourcePath = packagePath;
9705            }
9706        }
9707
9708        int doPostInstall(int status, int uid) {
9709            if (status != PackageManager.INSTALL_SUCCEEDED) {
9710                cleanUp();
9711            } else {
9712                final int groupOwner;
9713                final String protectedFile;
9714                if (isFwdLocked()) {
9715                    groupOwner = UserHandle.getSharedAppGid(uid);
9716                    protectedFile = RES_FILE_NAME;
9717                } else {
9718                    groupOwner = -1;
9719                    protectedFile = null;
9720                }
9721
9722                if (uid < Process.FIRST_APPLICATION_UID
9723                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9724                    Slog.e(TAG, "Failed to finalize " + cid);
9725                    PackageHelper.destroySdDir(cid);
9726                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9727                }
9728
9729                boolean mounted = PackageHelper.isContainerMounted(cid);
9730                if (!mounted) {
9731                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9732                }
9733            }
9734            return status;
9735        }
9736
9737        private void cleanUp() {
9738            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9739
9740            // Destroy secure container
9741            PackageHelper.destroySdDir(cid);
9742        }
9743
9744        void cleanUpResourcesLI() {
9745            String sourceFile = getCodePath();
9746            // Remove dex file
9747            if (instructionSets == null) {
9748                throw new IllegalStateException("instructionSet == null");
9749            }
9750            for (String instructionSet : instructionSets) {
9751                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9752                if (retCode < 0) {
9753                    Slog.w(TAG, "Couldn't remove dex file for package: "
9754                            + " at location "
9755                            + sourceFile.toString() + ", retcode=" + retCode);
9756                    // we don't consider this to be a failure of the core package deletion
9757                }
9758            }
9759            cleanUp();
9760        }
9761
9762        boolean matchContainer(String app) {
9763            if (cid.startsWith(app)) {
9764                return true;
9765            }
9766            return false;
9767        }
9768
9769        String getPackageName() {
9770            return getAsecPackageName(cid);
9771        }
9772
9773        boolean doPostDeleteLI(boolean delete) {
9774            boolean ret = false;
9775            boolean mounted = PackageHelper.isContainerMounted(cid);
9776            if (mounted) {
9777                // Unmount first
9778                ret = PackageHelper.unMountSdDir(cid);
9779            }
9780            if (ret && delete) {
9781                cleanUpResourcesLI();
9782            }
9783            return ret;
9784        }
9785
9786        @Override
9787        int doPreCopy() {
9788            if (isFwdLocked()) {
9789                if (!PackageHelper.fixSdPermissions(cid,
9790                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9791                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9792                }
9793            }
9794
9795            return PackageManager.INSTALL_SUCCEEDED;
9796        }
9797
9798        @Override
9799        int doPostCopy(int uid) {
9800            if (isFwdLocked()) {
9801                if (uid < Process.FIRST_APPLICATION_UID
9802                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9803                                RES_FILE_NAME)) {
9804                    Slog.e(TAG, "Failed to finalize " + cid);
9805                    PackageHelper.destroySdDir(cid);
9806                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9807                }
9808            }
9809
9810            return PackageManager.INSTALL_SUCCEEDED;
9811        }
9812    }
9813
9814    static String getAsecPackageName(String packageCid) {
9815        int idx = packageCid.lastIndexOf("-");
9816        if (idx == -1) {
9817            return packageCid;
9818        }
9819        return packageCid.substring(0, idx);
9820    }
9821
9822    // Utility method used to create code paths based on package name and available index.
9823    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9824        String idxStr = "";
9825        int idx = 1;
9826        // Fall back to default value of idx=1 if prefix is not
9827        // part of oldCodePath
9828        if (oldCodePath != null) {
9829            String subStr = oldCodePath;
9830            // Drop the suffix right away
9831            if (suffix != null && subStr.endsWith(suffix)) {
9832                subStr = subStr.substring(0, subStr.length() - suffix.length());
9833            }
9834            // If oldCodePath already contains prefix find out the
9835            // ending index to either increment or decrement.
9836            int sidx = subStr.lastIndexOf(prefix);
9837            if (sidx != -1) {
9838                subStr = subStr.substring(sidx + prefix.length());
9839                if (subStr != null) {
9840                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9841                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9842                    }
9843                    try {
9844                        idx = Integer.parseInt(subStr);
9845                        if (idx <= 1) {
9846                            idx++;
9847                        } else {
9848                            idx--;
9849                        }
9850                    } catch(NumberFormatException e) {
9851                    }
9852                }
9853            }
9854        }
9855        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9856        return prefix + idxStr;
9857    }
9858
9859    private File getNextCodePath(String packageName) {
9860        int suffix = 1;
9861        File result;
9862        do {
9863            result = new File(mAppInstallDir, packageName + "-" + suffix);
9864            suffix++;
9865        } while (result.exists());
9866        return result;
9867    }
9868
9869    // Utility method used to ignore ADD/REMOVE events
9870    // by directory observer.
9871    private static boolean ignoreCodePath(String fullPathStr) {
9872        String apkName = deriveCodePathName(fullPathStr);
9873        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9874        if (idx != -1 && ((idx+1) < apkName.length())) {
9875            // Make sure the package ends with a numeral
9876            String version = apkName.substring(idx+1);
9877            try {
9878                Integer.parseInt(version);
9879                return true;
9880            } catch (NumberFormatException e) {}
9881        }
9882        return false;
9883    }
9884
9885    // Utility method that returns the relative package path with respect
9886    // to the installation directory. Like say for /data/data/com.test-1.apk
9887    // string com.test-1 is returned.
9888    static String deriveCodePathName(String codePath) {
9889        if (codePath == null) {
9890            return null;
9891        }
9892        final File codeFile = new File(codePath);
9893        final String name = codeFile.getName();
9894        if (codeFile.isDirectory()) {
9895            return name;
9896        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9897            final int lastDot = name.lastIndexOf('.');
9898            return name.substring(0, lastDot);
9899        } else {
9900            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9901            return null;
9902        }
9903    }
9904
9905    class PackageInstalledInfo {
9906        String name;
9907        int uid;
9908        // The set of users that originally had this package installed.
9909        int[] origUsers;
9910        // The set of users that now have this package installed.
9911        int[] newUsers;
9912        PackageParser.Package pkg;
9913        int returnCode;
9914        String returnMsg;
9915        PackageRemovedInfo removedInfo;
9916
9917        public void setError(int code, String msg) {
9918            returnCode = code;
9919            returnMsg = msg;
9920            Slog.w(TAG, msg);
9921        }
9922
9923        public void setError(String msg, PackageParserException e) {
9924            returnCode = e.error;
9925            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9926            Slog.w(TAG, msg, e);
9927        }
9928
9929        public void setError(String msg, PackageManagerException e) {
9930            returnCode = e.error;
9931            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9932            Slog.w(TAG, msg, e);
9933        }
9934
9935        // In some error cases we want to convey more info back to the observer
9936        String origPackage;
9937        String origPermission;
9938    }
9939
9940    /*
9941     * Install a non-existing package.
9942     */
9943    private void installNewPackageLI(PackageParser.Package pkg,
9944            int parseFlags, int scanMode, UserHandle user,
9945            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9946        // Remember this for later, in case we need to rollback this install
9947        String pkgName = pkg.packageName;
9948
9949        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9950        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9951        synchronized(mPackages) {
9952            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9953                // A package with the same name is already installed, though
9954                // it has been renamed to an older name.  The package we
9955                // are trying to install should be installed as an update to
9956                // the existing one, but that has not been requested, so bail.
9957                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9958                        + " without first uninstalling package running as "
9959                        + mSettings.mRenamedPackages.get(pkgName));
9960                return;
9961            }
9962            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9963                // Don't allow installation over an existing package with the same name.
9964                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9965                        + " without first uninstalling.");
9966                return;
9967            }
9968        }
9969
9970        try {
9971            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9972                    System.currentTimeMillis(), user, abiOverride);
9973
9974            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9975            // delete the partially installed application. the data directory will have to be
9976            // restored if it was already existing
9977            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9978                // remove package from internal structures.  Note that we want deletePackageX to
9979                // delete the package data and cache directories that it created in
9980                // scanPackageLocked, unless those directories existed before we even tried to
9981                // install.
9982                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9983                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9984                                res.removedInfo, true);
9985            }
9986
9987        } catch (PackageManagerException e) {
9988            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9989        }
9990    }
9991
9992    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9993        // Upgrade keysets are being used.  Determine if new package has a superset of the
9994        // required keys.
9995        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9996        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9997        for (int i = 0; i < upgradeKeySets.length; i++) {
9998            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9999            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10000                return true;
10001            }
10002        }
10003        return false;
10004    }
10005
10006    private void replacePackageLI(PackageParser.Package pkg,
10007            int parseFlags, int scanMode, UserHandle user,
10008            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10009        PackageParser.Package oldPackage;
10010        String pkgName = pkg.packageName;
10011        int[] allUsers;
10012        boolean[] perUserInstalled;
10013
10014        // First find the old package info and check signatures
10015        synchronized(mPackages) {
10016            oldPackage = mPackages.get(pkgName);
10017            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10018            PackageSetting ps = mSettings.mPackages.get(pkgName);
10019            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10020                // default to original signature matching
10021                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10022                    != PackageManager.SIGNATURE_MATCH) {
10023                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10024                            "New package has a different signature: " + pkgName);
10025                    return;
10026                }
10027            } else {
10028                if(!checkUpgradeKeySetLP(ps, pkg)) {
10029                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10030                            "New package not signed by keys specified by upgrade-keysets: "
10031                            + pkgName);
10032                    return;
10033                }
10034            }
10035
10036            // In case of rollback, remember per-user/profile install state
10037            allUsers = sUserManager.getUserIds();
10038            perUserInstalled = new boolean[allUsers.length];
10039            for (int i = 0; i < allUsers.length; i++) {
10040                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10041            }
10042        }
10043
10044        boolean sysPkg = (isSystemApp(oldPackage));
10045        if (sysPkg) {
10046            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10047                    user, allUsers, perUserInstalled, installerPackageName, res,
10048                    abiOverride);
10049        } else {
10050            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10051                    user, allUsers, perUserInstalled, installerPackageName, res,
10052                    abiOverride);
10053        }
10054    }
10055
10056    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10057            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10058            int[] allUsers, boolean[] perUserInstalled,
10059            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10060        String pkgName = deletedPackage.packageName;
10061        boolean deletedPkg = true;
10062        boolean updatedSettings = false;
10063
10064        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10065                + deletedPackage);
10066        long origUpdateTime;
10067        if (pkg.mExtras != null) {
10068            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10069        } else {
10070            origUpdateTime = 0;
10071        }
10072
10073        // First delete the existing package while retaining the data directory
10074        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10075                res.removedInfo, true)) {
10076            // If the existing package wasn't successfully deleted
10077            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10078            deletedPkg = false;
10079        } else {
10080            // Successfully deleted the old package. Now proceed with re-installation
10081            deleteCodeCacheDirsLI(pkgName);
10082            try {
10083                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10084                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
10085                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10086                updatedSettings = true;
10087            } catch (PackageManagerException e) {
10088                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10089            }
10090        }
10091
10092        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10093            // remove package from internal structures.  Note that we want deletePackageX to
10094            // delete the package data and cache directories that it created in
10095            // scanPackageLocked, unless those directories existed before we even tried to
10096            // install.
10097            if(updatedSettings) {
10098                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10099                deletePackageLI(
10100                        pkgName, null, true, allUsers, perUserInstalled,
10101                        PackageManager.DELETE_KEEP_DATA,
10102                                res.removedInfo, true);
10103            }
10104            // Since we failed to install the new package we need to restore the old
10105            // package that we deleted.
10106            if (deletedPkg) {
10107                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10108                File restoreFile = new File(deletedPackage.codePath);
10109                // Parse old package
10110                boolean oldOnSd = isExternal(deletedPackage);
10111                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10112                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10113                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10114                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10115                        | SCAN_UPDATE_TIME;
10116                try {
10117                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10118                            null);
10119                } catch (PackageManagerException e) {
10120                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10121                            + e.getMessage());
10122                    return;
10123                }
10124                // Restore of old package succeeded. Update permissions.
10125                // writer
10126                synchronized (mPackages) {
10127                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10128                            UPDATE_PERMISSIONS_ALL);
10129                    // can downgrade to reader
10130                    mSettings.writeLPr();
10131                }
10132                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10133            }
10134        }
10135    }
10136
10137    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10138            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10139            int[] allUsers, boolean[] perUserInstalled,
10140            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10141        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10142                + ", old=" + deletedPackage);
10143        boolean updatedSettings = false;
10144        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10145                PackageParser.PARSE_IS_SYSTEM;
10146        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10147            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10148        }
10149        String packageName = deletedPackage.packageName;
10150        if (packageName == null) {
10151            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10152                    "Attempt to delete null packageName.");
10153            return;
10154        }
10155        PackageParser.Package oldPkg;
10156        PackageSetting oldPkgSetting;
10157        // reader
10158        synchronized (mPackages) {
10159            oldPkg = mPackages.get(packageName);
10160            oldPkgSetting = mSettings.mPackages.get(packageName);
10161            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10162                    (oldPkgSetting == null)) {
10163                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10164                        "Couldn't find package:" + packageName + " information");
10165                return;
10166            }
10167        }
10168
10169        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10170
10171        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10172        res.removedInfo.removedPackage = packageName;
10173        // Remove existing system package
10174        removePackageLI(oldPkgSetting, true);
10175        // writer
10176        synchronized (mPackages) {
10177            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10178                // We didn't need to disable the .apk as a current system package,
10179                // which means we are replacing another update that is already
10180                // installed.  We need to make sure to delete the older one's .apk.
10181                res.removedInfo.args = createInstallArgsForExisting(0,
10182                        deletedPackage.applicationInfo.getCodePath(),
10183                        deletedPackage.applicationInfo.getResourcePath(),
10184                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10185                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10186                        isMultiArch(deletedPackage.applicationInfo));
10187            } else {
10188                res.removedInfo.args = null;
10189            }
10190        }
10191
10192        // Successfully disabled the old package. Now proceed with re-installation
10193        deleteCodeCacheDirsLI(packageName);
10194
10195        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10196        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10197
10198        PackageParser.Package newPackage = null;
10199        try {
10200            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10201            if (newPackage.mExtras != null) {
10202                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10203                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10204                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10205
10206                // is the update attempting to change shared user? that isn't going to work...
10207                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10208                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10209                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10210                            + " to " + newPkgSetting.sharedUser);
10211                    updatedSettings = true;
10212                }
10213            }
10214
10215            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10216                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10217                updatedSettings = true;
10218            }
10219
10220        } catch (PackageManagerException e) {
10221            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10222        }
10223
10224        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10225            // Re installation failed. Restore old information
10226            // Remove new pkg information
10227            if (newPackage != null) {
10228                removeInstalledPackageLI(newPackage, true);
10229            }
10230            // Add back the old system package
10231            try {
10232                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10233                        null);
10234            } catch (PackageManagerException e) {
10235                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10236            }
10237            // Restore the old system information in Settings
10238            synchronized(mPackages) {
10239                if (updatedSettings) {
10240                    mSettings.enableSystemPackageLPw(packageName);
10241                    mSettings.setInstallerPackageName(packageName,
10242                            oldPkgSetting.installerPackageName);
10243                }
10244                mSettings.writeLPr();
10245            }
10246        }
10247    }
10248
10249    // Utility method used to move dex files during install.
10250    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10251        // TODO: extend to move split APK dex files
10252        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10253            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10254            for (String instructionSet : instructionSets) {
10255                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10256                        instructionSet);
10257                if (retCode != 0) {
10258                /*
10259                 * Programs may be lazily run through dexopt, so the
10260                 * source may not exist. However, something seems to
10261                 * have gone wrong, so note that dexopt needs to be
10262                 * run again and remove the source file. In addition,
10263                 * remove the target to make sure there isn't a stale
10264                 * file from a previous version of the package.
10265                 */
10266                    newPackage.mDexOptPerformed.clear();
10267                    mInstaller.rmdex(oldCodePath, instructionSet);
10268                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10269                }
10270            }
10271        }
10272        return PackageManager.INSTALL_SUCCEEDED;
10273    }
10274
10275    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10276            int[] allUsers, boolean[] perUserInstalled,
10277            PackageInstalledInfo res) {
10278        String pkgName = newPackage.packageName;
10279        synchronized (mPackages) {
10280            //write settings. the installStatus will be incomplete at this stage.
10281            //note that the new package setting would have already been
10282            //added to mPackages. It hasn't been persisted yet.
10283            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10284            mSettings.writeLPr();
10285        }
10286
10287        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10288
10289        synchronized (mPackages) {
10290            updatePermissionsLPw(newPackage.packageName, newPackage,
10291                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10292                            ? UPDATE_PERMISSIONS_ALL : 0));
10293            // For system-bundled packages, we assume that installing an upgraded version
10294            // of the package implies that the user actually wants to run that new code,
10295            // so we enable the package.
10296            if (isSystemApp(newPackage)) {
10297                // NB: implicit assumption that system package upgrades apply to all users
10298                if (DEBUG_INSTALL) {
10299                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10300                }
10301                PackageSetting ps = mSettings.mPackages.get(pkgName);
10302                if (ps != null) {
10303                    if (res.origUsers != null) {
10304                        for (int userHandle : res.origUsers) {
10305                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10306                                    userHandle, installerPackageName);
10307                        }
10308                    }
10309                    // Also convey the prior install/uninstall state
10310                    if (allUsers != null && perUserInstalled != null) {
10311                        for (int i = 0; i < allUsers.length; i++) {
10312                            if (DEBUG_INSTALL) {
10313                                Slog.d(TAG, "    user " + allUsers[i]
10314                                        + " => " + perUserInstalled[i]);
10315                            }
10316                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10317                        }
10318                        // these install state changes will be persisted in the
10319                        // upcoming call to mSettings.writeLPr().
10320                    }
10321                }
10322            }
10323            res.name = pkgName;
10324            res.uid = newPackage.applicationInfo.uid;
10325            res.pkg = newPackage;
10326            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10327            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10328            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10329            //to update install status
10330            mSettings.writeLPr();
10331        }
10332    }
10333
10334    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10335        int pFlags = args.flags;
10336        String installerPackageName = args.installerPackageName;
10337        File tmpPackageFile = new File(args.getCodePath());
10338        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10339        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10340        boolean replace = false;
10341        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10342                | (newInstall ? SCAN_NEW_INSTALL : 0);
10343        // Result object to be returned
10344        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10345
10346        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10347        // Retrieve PackageSettings and parse package
10348        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10349                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10350                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10351        PackageParser pp = new PackageParser();
10352        pp.setSeparateProcesses(mSeparateProcesses);
10353        pp.setDisplayMetrics(mMetrics);
10354
10355        final PackageParser.Package pkg;
10356        try {
10357            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10358        } catch (PackageParserException e) {
10359            res.setError("Failed parse during installPackageLI", e);
10360            return;
10361        }
10362
10363        String pkgName = res.name = pkg.packageName;
10364        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10365            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10366                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10367                return;
10368            }
10369        }
10370
10371        try {
10372            pp.collectCertificates(pkg, parseFlags);
10373            pp.collectManifestDigest(pkg);
10374        } catch (PackageParserException e) {
10375            res.setError("Failed collect during installPackageLI", e);
10376            return;
10377        }
10378
10379        /* If the installer passed in a manifest digest, compare it now. */
10380        if (args.manifestDigest != null) {
10381            if (DEBUG_INSTALL) {
10382                final String parsedManifest = pkg.manifestDigest == null ? "null"
10383                        : pkg.manifestDigest.toString();
10384                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10385                        + parsedManifest);
10386            }
10387
10388            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10389                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10390                return;
10391            }
10392        } else if (DEBUG_INSTALL) {
10393            final String parsedManifest = pkg.manifestDigest == null
10394                    ? "null" : pkg.manifestDigest.toString();
10395            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10396        }
10397
10398        // Get rid of all references to package scan path via parser.
10399        pp = null;
10400        String oldCodePath = null;
10401        boolean systemApp = false;
10402        synchronized (mPackages) {
10403            // Check whether the newly-scanned package wants to define an already-defined perm
10404            int N = pkg.permissions.size();
10405            for (int i = N-1; i >= 0; i--) {
10406                PackageParser.Permission perm = pkg.permissions.get(i);
10407                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10408                if (bp != null) {
10409                    // If the defining package is signed with our cert, it's okay.  This
10410                    // also includes the "updating the same package" case, of course.
10411                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10412                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10413                        // If the owning package is the system itself, we log but allow
10414                        // install to proceed; we fail the install on all other permission
10415                        // redefinitions.
10416                        if (!bp.sourcePackage.equals("android")) {
10417                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10418                                    + pkg.packageName + " attempting to redeclare permission "
10419                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10420                            res.origPermission = perm.info.name;
10421                            res.origPackage = bp.sourcePackage;
10422                            return;
10423                        } else {
10424                            Slog.w(TAG, "Package " + pkg.packageName
10425                                    + " attempting to redeclare system permission "
10426                                    + perm.info.name + "; ignoring new declaration");
10427                            pkg.permissions.remove(i);
10428                        }
10429                    }
10430                }
10431            }
10432
10433            // Check if installing already existing package
10434            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10435                String oldName = mSettings.mRenamedPackages.get(pkgName);
10436                if (pkg.mOriginalPackages != null
10437                        && pkg.mOriginalPackages.contains(oldName)
10438                        && mPackages.containsKey(oldName)) {
10439                    // This package is derived from an original package,
10440                    // and this device has been updating from that original
10441                    // name.  We must continue using the original name, so
10442                    // rename the new package here.
10443                    pkg.setPackageName(oldName);
10444                    pkgName = pkg.packageName;
10445                    replace = true;
10446                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10447                            + oldName + " pkgName=" + pkgName);
10448                } else if (mPackages.containsKey(pkgName)) {
10449                    // This package, under its official name, already exists
10450                    // on the device; we should replace it.
10451                    replace = true;
10452                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10453                }
10454            }
10455            PackageSetting ps = mSettings.mPackages.get(pkgName);
10456            if (ps != null) {
10457                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10458                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10459                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10460                    systemApp = (ps.pkg.applicationInfo.flags &
10461                            ApplicationInfo.FLAG_SYSTEM) != 0;
10462                }
10463                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10464            }
10465        }
10466
10467        if (systemApp && onSd) {
10468            // Disable updates to system apps on sdcard
10469            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10470                    "Cannot install updates to system apps on sdcard");
10471            return;
10472        }
10473
10474        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10475            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10476            return;
10477        }
10478
10479        if (replace) {
10480            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10481                    installerPackageName, res, args.abiOverride);
10482        } else {
10483            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10484                    installerPackageName, res, args.abiOverride);
10485        }
10486        synchronized (mPackages) {
10487            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10488            if (ps != null) {
10489                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10490            }
10491        }
10492    }
10493
10494    private static boolean isForwardLocked(PackageParser.Package pkg) {
10495        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10496    }
10497
10498    private static boolean isForwardLocked(ApplicationInfo info) {
10499        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10500    }
10501
10502    private boolean isForwardLocked(PackageSetting ps) {
10503        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10504    }
10505
10506    private static boolean isMultiArch(PackageSetting ps) {
10507        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10508    }
10509
10510    private static boolean isMultiArch(ApplicationInfo info) {
10511        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10512    }
10513
10514    private static boolean isExternal(PackageParser.Package pkg) {
10515        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10516    }
10517
10518    private static boolean isExternal(PackageSetting ps) {
10519        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10520    }
10521
10522    private static boolean isExternal(ApplicationInfo info) {
10523        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10524    }
10525
10526    private static boolean isSystemApp(PackageParser.Package pkg) {
10527        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10528    }
10529
10530    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10531        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10532    }
10533
10534    private static boolean isSystemApp(ApplicationInfo info) {
10535        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10536    }
10537
10538    private static boolean isSystemApp(PackageSetting ps) {
10539        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10540    }
10541
10542    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10543        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10544    }
10545
10546    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10547        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10548    }
10549
10550    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10551        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10552    }
10553
10554    private int packageFlagsToInstallFlags(PackageSetting ps) {
10555        int installFlags = 0;
10556        if (isExternal(ps)) {
10557            installFlags |= PackageManager.INSTALL_EXTERNAL;
10558        }
10559        if (isForwardLocked(ps)) {
10560            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10561        }
10562        return installFlags;
10563    }
10564
10565    private void deleteTempPackageFiles() {
10566        final FilenameFilter filter = new FilenameFilter() {
10567            public boolean accept(File dir, String name) {
10568                return name.startsWith("vmdl") && name.endsWith(".tmp");
10569            }
10570        };
10571        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10572            file.delete();
10573        }
10574    }
10575
10576    @Override
10577    public void deletePackageAsUser(final String packageName,
10578                                    final IPackageDeleteObserver observer,
10579                                    final int userId, final int flags) {
10580        mContext.enforceCallingOrSelfPermission(
10581                android.Manifest.permission.DELETE_PACKAGES, null);
10582        final int uid = Binder.getCallingUid();
10583        if (UserHandle.getUserId(uid) != userId) {
10584            mContext.enforceCallingPermission(
10585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10586                    "deletePackage for user " + userId);
10587        }
10588        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10589            try {
10590                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10591            } catch (RemoteException re) {
10592            }
10593            return;
10594        }
10595
10596        boolean uninstallBlocked = false;
10597        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10598            int[] users = sUserManager.getUserIds();
10599            for (int i = 0; i < users.length; ++i) {
10600                if (getBlockUninstallForUser(packageName, users[i])) {
10601                    uninstallBlocked = true;
10602                    break;
10603                }
10604            }
10605        } else {
10606            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10607        }
10608        if (uninstallBlocked) {
10609            try {
10610                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED);
10611            } catch (RemoteException re) {
10612            }
10613            return;
10614        }
10615
10616        if (DEBUG_REMOVE) {
10617            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10618        }
10619        // Queue up an async operation since the package deletion may take a little while.
10620        mHandler.post(new Runnable() {
10621            public void run() {
10622                mHandler.removeCallbacks(this);
10623                final int returnCode = deletePackageX(packageName, userId, flags);
10624                if (observer != null) {
10625                    try {
10626                        observer.packageDeleted(packageName, returnCode);
10627                    } catch (RemoteException e) {
10628                        Log.i(TAG, "Observer no longer exists.");
10629                    } //end catch
10630                } //end if
10631            } //end run
10632        });
10633    }
10634
10635    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10636        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10637                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10638        try {
10639            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10640                    || dpm.isDeviceOwner(packageName))) {
10641                return true;
10642            }
10643        } catch (RemoteException e) {
10644        }
10645        return false;
10646    }
10647
10648    /**
10649     *  This method is an internal method that could be get invoked either
10650     *  to delete an installed package or to clean up a failed installation.
10651     *  After deleting an installed package, a broadcast is sent to notify any
10652     *  listeners that the package has been installed. For cleaning up a failed
10653     *  installation, the broadcast is not necessary since the package's
10654     *  installation wouldn't have sent the initial broadcast either
10655     *  The key steps in deleting a package are
10656     *  deleting the package information in internal structures like mPackages,
10657     *  deleting the packages base directories through installd
10658     *  updating mSettings to reflect current status
10659     *  persisting settings for later use
10660     *  sending a broadcast if necessary
10661     */
10662    private int deletePackageX(String packageName, int userId, int flags) {
10663        final PackageRemovedInfo info = new PackageRemovedInfo();
10664        final boolean res;
10665
10666        if (isPackageDeviceAdmin(packageName, userId)) {
10667            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10668            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10669        }
10670
10671        boolean removedForAllUsers = false;
10672        boolean systemUpdate = false;
10673
10674        // for the uninstall-updates case and restricted profiles, remember the per-
10675        // userhandle installed state
10676        int[] allUsers;
10677        boolean[] perUserInstalled;
10678        synchronized (mPackages) {
10679            PackageSetting ps = mSettings.mPackages.get(packageName);
10680            allUsers = sUserManager.getUserIds();
10681            perUserInstalled = new boolean[allUsers.length];
10682            for (int i = 0; i < allUsers.length; i++) {
10683                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10684            }
10685        }
10686
10687        synchronized (mInstallLock) {
10688            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10689            res = deletePackageLI(packageName,
10690                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10691                            ? UserHandle.ALL : new UserHandle(userId),
10692                    true, allUsers, perUserInstalled,
10693                    flags | REMOVE_CHATTY, info, true);
10694            systemUpdate = info.isRemovedPackageSystemUpdate;
10695            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10696                removedForAllUsers = true;
10697            }
10698            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10699                    + " removedForAllUsers=" + removedForAllUsers);
10700        }
10701
10702        if (res) {
10703            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10704
10705            // If the removed package was a system update, the old system package
10706            // was re-enabled; we need to broadcast this information
10707            if (systemUpdate) {
10708                Bundle extras = new Bundle(1);
10709                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10710                        ? info.removedAppId : info.uid);
10711                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10712
10713                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10714                        extras, null, null, null);
10715                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10716                        extras, null, null, null);
10717                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10718                        null, packageName, null, null);
10719            }
10720        }
10721        // Force a gc here.
10722        Runtime.getRuntime().gc();
10723        // Delete the resources here after sending the broadcast to let
10724        // other processes clean up before deleting resources.
10725        if (info.args != null) {
10726            synchronized (mInstallLock) {
10727                info.args.doPostDeleteLI(true);
10728            }
10729        }
10730
10731        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10732    }
10733
10734    static class PackageRemovedInfo {
10735        String removedPackage;
10736        int uid = -1;
10737        int removedAppId = -1;
10738        int[] removedUsers = null;
10739        boolean isRemovedPackageSystemUpdate = false;
10740        // Clean up resources deleted packages.
10741        InstallArgs args = null;
10742
10743        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10744            Bundle extras = new Bundle(1);
10745            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10746            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10747            if (replacing) {
10748                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10749            }
10750            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10751            if (removedPackage != null) {
10752                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10753                        extras, null, null, removedUsers);
10754                if (fullRemove && !replacing) {
10755                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10756                            extras, null, null, removedUsers);
10757                }
10758            }
10759            if (removedAppId >= 0) {
10760                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10761                        removedUsers);
10762            }
10763        }
10764    }
10765
10766    /*
10767     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10768     * flag is not set, the data directory is removed as well.
10769     * make sure this flag is set for partially installed apps. If not its meaningless to
10770     * delete a partially installed application.
10771     */
10772    private void removePackageDataLI(PackageSetting ps,
10773            int[] allUserHandles, boolean[] perUserInstalled,
10774            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10775        String packageName = ps.name;
10776        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10777        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10778        // Retrieve object to delete permissions for shared user later on
10779        final PackageSetting deletedPs;
10780        // reader
10781        synchronized (mPackages) {
10782            deletedPs = mSettings.mPackages.get(packageName);
10783            if (outInfo != null) {
10784                outInfo.removedPackage = packageName;
10785                outInfo.removedUsers = deletedPs != null
10786                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10787                        : null;
10788            }
10789        }
10790        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10791            removeDataDirsLI(packageName);
10792            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10793        }
10794        // writer
10795        synchronized (mPackages) {
10796            if (deletedPs != null) {
10797                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10798                    if (outInfo != null) {
10799                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10800                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10801                    }
10802                    if (deletedPs != null) {
10803                        updatePermissionsLPw(deletedPs.name, null, 0);
10804                        if (deletedPs.sharedUser != null) {
10805                            // remove permissions associated with package
10806                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10807                        }
10808                    }
10809                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10810                }
10811                // make sure to preserve per-user disabled state if this removal was just
10812                // a downgrade of a system app to the factory package
10813                if (allUserHandles != null && perUserInstalled != null) {
10814                    if (DEBUG_REMOVE) {
10815                        Slog.d(TAG, "Propagating install state across downgrade");
10816                    }
10817                    for (int i = 0; i < allUserHandles.length; i++) {
10818                        if (DEBUG_REMOVE) {
10819                            Slog.d(TAG, "    user " + allUserHandles[i]
10820                                    + " => " + perUserInstalled[i]);
10821                        }
10822                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10823                    }
10824                }
10825            }
10826            // can downgrade to reader
10827            if (writeSettings) {
10828                // Save settings now
10829                mSettings.writeLPr();
10830            }
10831        }
10832        if (outInfo != null) {
10833            // A user ID was deleted here. Go through all users and remove it
10834            // from KeyStore.
10835            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10836        }
10837    }
10838
10839    static boolean locationIsPrivileged(File path) {
10840        try {
10841            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10842                    .getCanonicalPath();
10843            return path.getCanonicalPath().startsWith(privilegedAppDir);
10844        } catch (IOException e) {
10845            Slog.e(TAG, "Unable to access code path " + path);
10846        }
10847        return false;
10848    }
10849
10850    /*
10851     * Tries to delete system package.
10852     */
10853    private boolean deleteSystemPackageLI(PackageSetting newPs,
10854            int[] allUserHandles, boolean[] perUserInstalled,
10855            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10856        final boolean applyUserRestrictions
10857                = (allUserHandles != null) && (perUserInstalled != null);
10858        PackageSetting disabledPs = null;
10859        // Confirm if the system package has been updated
10860        // An updated system app can be deleted. This will also have to restore
10861        // the system pkg from system partition
10862        // reader
10863        synchronized (mPackages) {
10864            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10865        }
10866        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10867                + " disabledPs=" + disabledPs);
10868        if (disabledPs == null) {
10869            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10870            return false;
10871        } else if (DEBUG_REMOVE) {
10872            Slog.d(TAG, "Deleting system pkg from data partition");
10873        }
10874        if (DEBUG_REMOVE) {
10875            if (applyUserRestrictions) {
10876                Slog.d(TAG, "Remembering install states:");
10877                for (int i = 0; i < allUserHandles.length; i++) {
10878                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10879                }
10880            }
10881        }
10882        // Delete the updated package
10883        outInfo.isRemovedPackageSystemUpdate = true;
10884        if (disabledPs.versionCode < newPs.versionCode) {
10885            // Delete data for downgrades
10886            flags &= ~PackageManager.DELETE_KEEP_DATA;
10887        } else {
10888            // Preserve data by setting flag
10889            flags |= PackageManager.DELETE_KEEP_DATA;
10890        }
10891        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10892                allUserHandles, perUserInstalled, outInfo, writeSettings);
10893        if (!ret) {
10894            return false;
10895        }
10896        // writer
10897        synchronized (mPackages) {
10898            // Reinstate the old system package
10899            mSettings.enableSystemPackageLPw(newPs.name);
10900            // Remove any native libraries from the upgraded package.
10901            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10902        }
10903        // Install the system package
10904        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10905        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10906        if (locationIsPrivileged(disabledPs.codePath)) {
10907            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10908        }
10909
10910        final PackageParser.Package newPkg;
10911        try {
10912            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10913                    null, null);
10914        } catch (PackageManagerException e) {
10915            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10916            return false;
10917        }
10918
10919        // writer
10920        synchronized (mPackages) {
10921            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10922            setBundledAppAbisAndRoots(newPkg, ps);
10923            updatePermissionsLPw(newPkg.packageName, newPkg,
10924                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10925            if (applyUserRestrictions) {
10926                if (DEBUG_REMOVE) {
10927                    Slog.d(TAG, "Propagating install state across reinstall");
10928                }
10929                for (int i = 0; i < allUserHandles.length; i++) {
10930                    if (DEBUG_REMOVE) {
10931                        Slog.d(TAG, "    user " + allUserHandles[i]
10932                                + " => " + perUserInstalled[i]);
10933                    }
10934                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10935                }
10936                // Regardless of writeSettings we need to ensure that this restriction
10937                // state propagation is persisted
10938                mSettings.writeAllUsersPackageRestrictionsLPr();
10939            }
10940            // can downgrade to reader here
10941            if (writeSettings) {
10942                mSettings.writeLPr();
10943            }
10944        }
10945        return true;
10946    }
10947
10948    private boolean deleteInstalledPackageLI(PackageSetting ps,
10949            boolean deleteCodeAndResources, int flags,
10950            int[] allUserHandles, boolean[] perUserInstalled,
10951            PackageRemovedInfo outInfo, boolean writeSettings) {
10952        if (outInfo != null) {
10953            outInfo.uid = ps.appId;
10954        }
10955
10956        // Delete package data from internal structures and also remove data if flag is set
10957        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10958
10959        // Delete application code and resources
10960        if (deleteCodeAndResources && (outInfo != null)) {
10961            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10962                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10963                    getAppDexInstructionSets(ps), isMultiArch(ps));
10964        }
10965        return true;
10966    }
10967
10968    @Override
10969    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10970            int userId) {
10971        mContext.enforceCallingOrSelfPermission(
10972                android.Manifest.permission.DELETE_PACKAGES, null);
10973        synchronized (mPackages) {
10974            PackageSetting ps = mSettings.mPackages.get(packageName);
10975            if (ps == null) {
10976                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10977                return false;
10978            }
10979            if (!ps.getInstalled(userId)) {
10980                // Can't block uninstall for an app that is not installed or enabled.
10981                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10982                return false;
10983            }
10984            ps.setBlockUninstall(blockUninstall, userId);
10985            mSettings.writePackageRestrictionsLPr(userId);
10986        }
10987        return true;
10988    }
10989
10990    @Override
10991    public boolean getBlockUninstallForUser(String packageName, int userId) {
10992        synchronized (mPackages) {
10993            PackageSetting ps = mSettings.mPackages.get(packageName);
10994            if (ps == null) {
10995                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10996                return false;
10997            }
10998            return ps.getBlockUninstall(userId);
10999        }
11000    }
11001
11002    /*
11003     * This method handles package deletion in general
11004     */
11005    private boolean deletePackageLI(String packageName, UserHandle user,
11006            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11007            int flags, PackageRemovedInfo outInfo,
11008            boolean writeSettings) {
11009        if (packageName == null) {
11010            Slog.w(TAG, "Attempt to delete null packageName.");
11011            return false;
11012        }
11013        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11014        PackageSetting ps;
11015        boolean dataOnly = false;
11016        int removeUser = -1;
11017        int appId = -1;
11018        synchronized (mPackages) {
11019            ps = mSettings.mPackages.get(packageName);
11020            if (ps == null) {
11021                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11022                return false;
11023            }
11024            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11025                    && user.getIdentifier() != UserHandle.USER_ALL) {
11026                // The caller is asking that the package only be deleted for a single
11027                // user.  To do this, we just mark its uninstalled state and delete
11028                // its data.  If this is a system app, we only allow this to happen if
11029                // they have set the special DELETE_SYSTEM_APP which requests different
11030                // semantics than normal for uninstalling system apps.
11031                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11032                ps.setUserState(user.getIdentifier(),
11033                        COMPONENT_ENABLED_STATE_DEFAULT,
11034                        false, //installed
11035                        true,  //stopped
11036                        true,  //notLaunched
11037                        false, //hidden
11038                        null, null, null,
11039                        false // blockUninstall
11040                        );
11041                if (!isSystemApp(ps)) {
11042                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11043                        // Other user still have this package installed, so all
11044                        // we need to do is clear this user's data and save that
11045                        // it is uninstalled.
11046                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11047                        removeUser = user.getIdentifier();
11048                        appId = ps.appId;
11049                        mSettings.writePackageRestrictionsLPr(removeUser);
11050                    } else {
11051                        // We need to set it back to 'installed' so the uninstall
11052                        // broadcasts will be sent correctly.
11053                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11054                        ps.setInstalled(true, user.getIdentifier());
11055                    }
11056                } else {
11057                    // This is a system app, so we assume that the
11058                    // other users still have this package installed, so all
11059                    // we need to do is clear this user's data and save that
11060                    // it is uninstalled.
11061                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11062                    removeUser = user.getIdentifier();
11063                    appId = ps.appId;
11064                    mSettings.writePackageRestrictionsLPr(removeUser);
11065                }
11066            }
11067        }
11068
11069        if (removeUser >= 0) {
11070            // From above, we determined that we are deleting this only
11071            // for a single user.  Continue the work here.
11072            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11073            if (outInfo != null) {
11074                outInfo.removedPackage = packageName;
11075                outInfo.removedAppId = appId;
11076                outInfo.removedUsers = new int[] {removeUser};
11077            }
11078            mInstaller.clearUserData(packageName, removeUser);
11079            removeKeystoreDataIfNeeded(removeUser, appId);
11080            schedulePackageCleaning(packageName, removeUser, false);
11081            return true;
11082        }
11083
11084        if (dataOnly) {
11085            // Delete application data first
11086            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11087            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11088            return true;
11089        }
11090
11091        boolean ret = false;
11092        if (isSystemApp(ps)) {
11093            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11094            // When an updated system application is deleted we delete the existing resources as well and
11095            // fall back to existing code in system partition
11096            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11097                    flags, outInfo, writeSettings);
11098        } else {
11099            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11100            // Kill application pre-emptively especially for apps on sd.
11101            killApplication(packageName, ps.appId, "uninstall pkg");
11102            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11103                    allUserHandles, perUserInstalled,
11104                    outInfo, writeSettings);
11105        }
11106
11107        return ret;
11108    }
11109
11110    private final class ClearStorageConnection implements ServiceConnection {
11111        IMediaContainerService mContainerService;
11112
11113        @Override
11114        public void onServiceConnected(ComponentName name, IBinder service) {
11115            synchronized (this) {
11116                mContainerService = IMediaContainerService.Stub.asInterface(service);
11117                notifyAll();
11118            }
11119        }
11120
11121        @Override
11122        public void onServiceDisconnected(ComponentName name) {
11123        }
11124    }
11125
11126    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11127        final boolean mounted;
11128        if (Environment.isExternalStorageEmulated()) {
11129            mounted = true;
11130        } else {
11131            final String status = Environment.getExternalStorageState();
11132
11133            mounted = status.equals(Environment.MEDIA_MOUNTED)
11134                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11135        }
11136
11137        if (!mounted) {
11138            return;
11139        }
11140
11141        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11142        int[] users;
11143        if (userId == UserHandle.USER_ALL) {
11144            users = sUserManager.getUserIds();
11145        } else {
11146            users = new int[] { userId };
11147        }
11148        final ClearStorageConnection conn = new ClearStorageConnection();
11149        if (mContext.bindServiceAsUser(
11150                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11151            try {
11152                for (int curUser : users) {
11153                    long timeout = SystemClock.uptimeMillis() + 5000;
11154                    synchronized (conn) {
11155                        long now = SystemClock.uptimeMillis();
11156                        while (conn.mContainerService == null && now < timeout) {
11157                            try {
11158                                conn.wait(timeout - now);
11159                            } catch (InterruptedException e) {
11160                            }
11161                        }
11162                    }
11163                    if (conn.mContainerService == null) {
11164                        return;
11165                    }
11166
11167                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11168                    clearDirectory(conn.mContainerService,
11169                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11170                    if (allData) {
11171                        clearDirectory(conn.mContainerService,
11172                                userEnv.buildExternalStorageAppDataDirs(packageName));
11173                        clearDirectory(conn.mContainerService,
11174                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11175                    }
11176                }
11177            } finally {
11178                mContext.unbindService(conn);
11179            }
11180        }
11181    }
11182
11183    @Override
11184    public void clearApplicationUserData(final String packageName,
11185            final IPackageDataObserver observer, final int userId) {
11186        mContext.enforceCallingOrSelfPermission(
11187                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11188        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11189        // Queue up an async operation since the package deletion may take a little while.
11190        mHandler.post(new Runnable() {
11191            public void run() {
11192                mHandler.removeCallbacks(this);
11193                final boolean succeeded;
11194                synchronized (mInstallLock) {
11195                    succeeded = clearApplicationUserDataLI(packageName, userId);
11196                }
11197                clearExternalStorageDataSync(packageName, userId, true);
11198                if (succeeded) {
11199                    // invoke DeviceStorageMonitor's update method to clear any notifications
11200                    DeviceStorageMonitorInternal
11201                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11202                    if (dsm != null) {
11203                        dsm.checkMemory();
11204                    }
11205                }
11206                if(observer != null) {
11207                    try {
11208                        observer.onRemoveCompleted(packageName, succeeded);
11209                    } catch (RemoteException e) {
11210                        Log.i(TAG, "Observer no longer exists.");
11211                    }
11212                } //end if observer
11213            } //end run
11214        });
11215    }
11216
11217    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11218        if (packageName == null) {
11219            Slog.w(TAG, "Attempt to delete null packageName.");
11220            return false;
11221        }
11222        PackageParser.Package p;
11223        boolean dataOnly = false;
11224        final int appId;
11225        synchronized (mPackages) {
11226            p = mPackages.get(packageName);
11227            if (p == null) {
11228                dataOnly = true;
11229                PackageSetting ps = mSettings.mPackages.get(packageName);
11230                if ((ps == null) || (ps.pkg == null)) {
11231                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11232                    return false;
11233                }
11234                p = ps.pkg;
11235            }
11236            if (!dataOnly) {
11237                // need to check this only for fully installed applications
11238                if (p == null) {
11239                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11240                    return false;
11241                }
11242                final ApplicationInfo applicationInfo = p.applicationInfo;
11243                if (applicationInfo == null) {
11244                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11245                    return false;
11246                }
11247            }
11248            if (p != null && p.applicationInfo != null) {
11249                appId = p.applicationInfo.uid;
11250            } else {
11251                appId = -1;
11252            }
11253        }
11254        int retCode = mInstaller.clearUserData(packageName, userId);
11255        if (retCode < 0) {
11256            Slog.w(TAG, "Couldn't remove cache files for package: "
11257                    + packageName);
11258            return false;
11259        }
11260        removeKeystoreDataIfNeeded(userId, appId);
11261        return true;
11262    }
11263
11264    /**
11265     * Remove entries from the keystore daemon. Will only remove it if the
11266     * {@code appId} is valid.
11267     */
11268    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11269        if (appId < 0) {
11270            return;
11271        }
11272
11273        final KeyStore keyStore = KeyStore.getInstance();
11274        if (keyStore != null) {
11275            if (userId == UserHandle.USER_ALL) {
11276                for (final int individual : sUserManager.getUserIds()) {
11277                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11278                }
11279            } else {
11280                keyStore.clearUid(UserHandle.getUid(userId, appId));
11281            }
11282        } else {
11283            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11284        }
11285    }
11286
11287    @Override
11288    public void deleteApplicationCacheFiles(final String packageName,
11289            final IPackageDataObserver observer) {
11290        mContext.enforceCallingOrSelfPermission(
11291                android.Manifest.permission.DELETE_CACHE_FILES, null);
11292        // Queue up an async operation since the package deletion may take a little while.
11293        final int userId = UserHandle.getCallingUserId();
11294        mHandler.post(new Runnable() {
11295            public void run() {
11296                mHandler.removeCallbacks(this);
11297                final boolean succeded;
11298                synchronized (mInstallLock) {
11299                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11300                }
11301                clearExternalStorageDataSync(packageName, userId, false);
11302                if(observer != null) {
11303                    try {
11304                        observer.onRemoveCompleted(packageName, succeded);
11305                    } catch (RemoteException e) {
11306                        Log.i(TAG, "Observer no longer exists.");
11307                    }
11308                } //end if observer
11309            } //end run
11310        });
11311    }
11312
11313    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11314        if (packageName == null) {
11315            Slog.w(TAG, "Attempt to delete null packageName.");
11316            return false;
11317        }
11318        PackageParser.Package p;
11319        synchronized (mPackages) {
11320            p = mPackages.get(packageName);
11321        }
11322        if (p == null) {
11323            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11324            return false;
11325        }
11326        final ApplicationInfo applicationInfo = p.applicationInfo;
11327        if (applicationInfo == null) {
11328            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11329            return false;
11330        }
11331        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11332        if (retCode < 0) {
11333            Slog.w(TAG, "Couldn't remove cache files for package: "
11334                       + packageName + " u" + userId);
11335            return false;
11336        }
11337        return true;
11338    }
11339
11340    @Override
11341    public void getPackageSizeInfo(final String packageName, int userHandle,
11342            final IPackageStatsObserver observer) {
11343        mContext.enforceCallingOrSelfPermission(
11344                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11345        if (packageName == null) {
11346            throw new IllegalArgumentException("Attempt to get size of null packageName");
11347        }
11348
11349        PackageStats stats = new PackageStats(packageName, userHandle);
11350
11351        /*
11352         * Queue up an async operation since the package measurement may take a
11353         * little while.
11354         */
11355        Message msg = mHandler.obtainMessage(INIT_COPY);
11356        msg.obj = new MeasureParams(stats, observer);
11357        mHandler.sendMessage(msg);
11358    }
11359
11360    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11361            PackageStats pStats) {
11362        if (packageName == null) {
11363            Slog.w(TAG, "Attempt to get size of null packageName.");
11364            return false;
11365        }
11366        PackageParser.Package p;
11367        boolean dataOnly = false;
11368        String libDirRoot = null;
11369        String asecPath = null;
11370        PackageSetting ps = null;
11371        synchronized (mPackages) {
11372            p = mPackages.get(packageName);
11373            ps = mSettings.mPackages.get(packageName);
11374            if(p == null) {
11375                dataOnly = true;
11376                if((ps == null) || (ps.pkg == null)) {
11377                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11378                    return false;
11379                }
11380                p = ps.pkg;
11381            }
11382            if (ps != null) {
11383                libDirRoot = ps.legacyNativeLibraryPathString;
11384            }
11385            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11386                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11387                if (secureContainerId != null) {
11388                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11389                }
11390            }
11391        }
11392        String publicSrcDir = null;
11393        if(!dataOnly) {
11394            final ApplicationInfo applicationInfo = p.applicationInfo;
11395            if (applicationInfo == null) {
11396                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11397                return false;
11398            }
11399            if (isForwardLocked(p)) {
11400                publicSrcDir = applicationInfo.getBaseResourcePath();
11401            }
11402        }
11403        // TODO: extend to measure size of split APKs
11404        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11405        // not just the first level.
11406        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11407        // just the primary.
11408        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11409                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11410                pStats);
11411        if (res < 0) {
11412            return false;
11413        }
11414
11415        // Fix-up for forward-locked applications in ASEC containers.
11416        if (!isExternal(p)) {
11417            pStats.codeSize += pStats.externalCodeSize;
11418            pStats.externalCodeSize = 0L;
11419        }
11420
11421        return true;
11422    }
11423
11424
11425    @Override
11426    public void addPackageToPreferred(String packageName) {
11427        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11428    }
11429
11430    @Override
11431    public void removePackageFromPreferred(String packageName) {
11432        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11433    }
11434
11435    @Override
11436    public List<PackageInfo> getPreferredPackages(int flags) {
11437        return new ArrayList<PackageInfo>();
11438    }
11439
11440    private int getUidTargetSdkVersionLockedLPr(int uid) {
11441        Object obj = mSettings.getUserIdLPr(uid);
11442        if (obj instanceof SharedUserSetting) {
11443            final SharedUserSetting sus = (SharedUserSetting) obj;
11444            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11445            final Iterator<PackageSetting> it = sus.packages.iterator();
11446            while (it.hasNext()) {
11447                final PackageSetting ps = it.next();
11448                if (ps.pkg != null) {
11449                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11450                    if (v < vers) vers = v;
11451                }
11452            }
11453            return vers;
11454        } else if (obj instanceof PackageSetting) {
11455            final PackageSetting ps = (PackageSetting) obj;
11456            if (ps.pkg != null) {
11457                return ps.pkg.applicationInfo.targetSdkVersion;
11458            }
11459        }
11460        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11461    }
11462
11463    @Override
11464    public void addPreferredActivity(IntentFilter filter, int match,
11465            ComponentName[] set, ComponentName activity, int userId) {
11466        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11467    }
11468
11469    private void addPreferredActivityInternal(IntentFilter filter, int match,
11470            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11471        // writer
11472        int callingUid = Binder.getCallingUid();
11473        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11474        if (filter.countActions() == 0) {
11475            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11476            return;
11477        }
11478        synchronized (mPackages) {
11479            if (mContext.checkCallingOrSelfPermission(
11480                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11481                    != PackageManager.PERMISSION_GRANTED) {
11482                if (getUidTargetSdkVersionLockedLPr(callingUid)
11483                        < Build.VERSION_CODES.FROYO) {
11484                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11485                            + callingUid);
11486                    return;
11487                }
11488                mContext.enforceCallingOrSelfPermission(
11489                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11490            }
11491
11492            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11493            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11494            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11495                    new PreferredActivity(filter, match, set, activity, always));
11496            mSettings.writePackageRestrictionsLPr(userId);
11497        }
11498    }
11499
11500    @Override
11501    public void replacePreferredActivity(IntentFilter filter, int match,
11502            ComponentName[] set, ComponentName activity) {
11503        if (filter.countActions() != 1) {
11504            throw new IllegalArgumentException(
11505                    "replacePreferredActivity expects filter to have only 1 action.");
11506        }
11507        if (filter.countDataAuthorities() != 0
11508                || filter.countDataPaths() != 0
11509                || filter.countDataSchemes() > 1
11510                || filter.countDataTypes() != 0) {
11511            throw new IllegalArgumentException(
11512                    "replacePreferredActivity expects filter to have no data authorities, " +
11513                    "paths, or types; and at most one scheme.");
11514        }
11515        synchronized (mPackages) {
11516            if (mContext.checkCallingOrSelfPermission(
11517                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11518                    != PackageManager.PERMISSION_GRANTED) {
11519                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11520                        < Build.VERSION_CODES.FROYO) {
11521                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11522                            + Binder.getCallingUid());
11523                    return;
11524                }
11525                mContext.enforceCallingOrSelfPermission(
11526                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11527            }
11528
11529            final int callingUserId = UserHandle.getCallingUserId();
11530            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11531            if (pir != null) {
11532                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11533                if (filter.countDataSchemes() == 1) {
11534                    Uri.Builder builder = new Uri.Builder();
11535                    builder.scheme(filter.getDataScheme(0));
11536                    intent.setData(builder.build());
11537                }
11538                List<PreferredActivity> matches = pir.queryIntent(
11539                        intent, null, true, callingUserId);
11540                if (DEBUG_PREFERRED) {
11541                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11542                }
11543                for (int i = 0; i < matches.size(); i++) {
11544                    PreferredActivity pa = matches.get(i);
11545                    if (DEBUG_PREFERRED) {
11546                        Slog.i(TAG, "Removing preferred activity "
11547                                + pa.mPref.mComponent + ":");
11548                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11549                    }
11550                    pir.removeFilter(pa);
11551                }
11552            }
11553            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11554        }
11555    }
11556
11557    @Override
11558    public void clearPackagePreferredActivities(String packageName) {
11559        final int uid = Binder.getCallingUid();
11560        // writer
11561        synchronized (mPackages) {
11562            PackageParser.Package pkg = mPackages.get(packageName);
11563            if (pkg == null || pkg.applicationInfo.uid != uid) {
11564                if (mContext.checkCallingOrSelfPermission(
11565                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11566                        != PackageManager.PERMISSION_GRANTED) {
11567                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11568                            < Build.VERSION_CODES.FROYO) {
11569                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11570                                + Binder.getCallingUid());
11571                        return;
11572                    }
11573                    mContext.enforceCallingOrSelfPermission(
11574                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11575                }
11576            }
11577
11578            int user = UserHandle.getCallingUserId();
11579            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11580                mSettings.writePackageRestrictionsLPr(user);
11581                scheduleWriteSettingsLocked();
11582            }
11583        }
11584    }
11585
11586    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11587    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11588        ArrayList<PreferredActivity> removed = null;
11589        boolean changed = false;
11590        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11591            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11592            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11593            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11594                continue;
11595            }
11596            Iterator<PreferredActivity> it = pir.filterIterator();
11597            while (it.hasNext()) {
11598                PreferredActivity pa = it.next();
11599                // Mark entry for removal only if it matches the package name
11600                // and the entry is of type "always".
11601                if (packageName == null ||
11602                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11603                                && pa.mPref.mAlways)) {
11604                    if (removed == null) {
11605                        removed = new ArrayList<PreferredActivity>();
11606                    }
11607                    removed.add(pa);
11608                }
11609            }
11610            if (removed != null) {
11611                for (int j=0; j<removed.size(); j++) {
11612                    PreferredActivity pa = removed.get(j);
11613                    pir.removeFilter(pa);
11614                }
11615                changed = true;
11616            }
11617        }
11618        return changed;
11619    }
11620
11621    @Override
11622    public void resetPreferredActivities(int userId) {
11623        mContext.enforceCallingOrSelfPermission(
11624                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11625        // writer
11626        synchronized (mPackages) {
11627            int user = UserHandle.getCallingUserId();
11628            clearPackagePreferredActivitiesLPw(null, user);
11629            mSettings.readDefaultPreferredAppsLPw(this, user);
11630            mSettings.writePackageRestrictionsLPr(user);
11631            scheduleWriteSettingsLocked();
11632        }
11633    }
11634
11635    @Override
11636    public int getPreferredActivities(List<IntentFilter> outFilters,
11637            List<ComponentName> outActivities, String packageName) {
11638
11639        int num = 0;
11640        final int userId = UserHandle.getCallingUserId();
11641        // reader
11642        synchronized (mPackages) {
11643            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11644            if (pir != null) {
11645                final Iterator<PreferredActivity> it = pir.filterIterator();
11646                while (it.hasNext()) {
11647                    final PreferredActivity pa = it.next();
11648                    if (packageName == null
11649                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11650                                    && pa.mPref.mAlways)) {
11651                        if (outFilters != null) {
11652                            outFilters.add(new IntentFilter(pa));
11653                        }
11654                        if (outActivities != null) {
11655                            outActivities.add(pa.mPref.mComponent);
11656                        }
11657                    }
11658                }
11659            }
11660        }
11661
11662        return num;
11663    }
11664
11665    @Override
11666    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11667            int userId) {
11668        int callingUid = Binder.getCallingUid();
11669        if (callingUid != Process.SYSTEM_UID) {
11670            throw new SecurityException(
11671                    "addPersistentPreferredActivity can only be run by the system");
11672        }
11673        if (filter.countActions() == 0) {
11674            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11675            return;
11676        }
11677        synchronized (mPackages) {
11678            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11679                    " :");
11680            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11681            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11682                    new PersistentPreferredActivity(filter, activity));
11683            mSettings.writePackageRestrictionsLPr(userId);
11684        }
11685    }
11686
11687    @Override
11688    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11689        int callingUid = Binder.getCallingUid();
11690        if (callingUid != Process.SYSTEM_UID) {
11691            throw new SecurityException(
11692                    "clearPackagePersistentPreferredActivities can only be run by the system");
11693        }
11694        ArrayList<PersistentPreferredActivity> removed = null;
11695        boolean changed = false;
11696        synchronized (mPackages) {
11697            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11698                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11699                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11700                        .valueAt(i);
11701                if (userId != thisUserId) {
11702                    continue;
11703                }
11704                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11705                while (it.hasNext()) {
11706                    PersistentPreferredActivity ppa = it.next();
11707                    // Mark entry for removal only if it matches the package name.
11708                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11709                        if (removed == null) {
11710                            removed = new ArrayList<PersistentPreferredActivity>();
11711                        }
11712                        removed.add(ppa);
11713                    }
11714                }
11715                if (removed != null) {
11716                    for (int j=0; j<removed.size(); j++) {
11717                        PersistentPreferredActivity ppa = removed.get(j);
11718                        ppir.removeFilter(ppa);
11719                    }
11720                    changed = true;
11721                }
11722            }
11723
11724            if (changed) {
11725                mSettings.writePackageRestrictionsLPr(userId);
11726            }
11727        }
11728    }
11729
11730    @Override
11731    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11732            int targetUserId, int flags) {
11733        mContext.enforceCallingOrSelfPermission(
11734                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11735        if (intentFilter.countActions() == 0) {
11736            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11737            return;
11738        }
11739        synchronized (mPackages) {
11740            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11741                    targetUserId, flags);
11742            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11743            mSettings.writePackageRestrictionsLPr(sourceUserId);
11744        }
11745    }
11746
11747    public void addCrossProfileIntentsForPackage(String packageName,
11748            int sourceUserId, int targetUserId) {
11749        mContext.enforceCallingOrSelfPermission(
11750                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11751        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11752        mSettings.writePackageRestrictionsLPr(sourceUserId);
11753    }
11754
11755    public void removeCrossProfileIntentsForPackage(String packageName,
11756            int sourceUserId, int targetUserId) {
11757        mContext.enforceCallingOrSelfPermission(
11758                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11759        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11760        mSettings.writePackageRestrictionsLPr(sourceUserId);
11761    }
11762
11763    @Override
11764    public void clearCrossProfileIntentFilters(int sourceUserId) {
11765        mContext.enforceCallingOrSelfPermission(
11766                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11767        synchronized (mPackages) {
11768            CrossProfileIntentResolver resolver =
11769                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11770            HashSet<CrossProfileIntentFilter> set =
11771                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11772            for (CrossProfileIntentFilter filter : set) {
11773                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11774                    resolver.removeFilter(filter);
11775                }
11776            }
11777            mSettings.writePackageRestrictionsLPr(sourceUserId);
11778        }
11779    }
11780
11781    @Override
11782    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11783        Intent intent = new Intent(Intent.ACTION_MAIN);
11784        intent.addCategory(Intent.CATEGORY_HOME);
11785
11786        final int callingUserId = UserHandle.getCallingUserId();
11787        List<ResolveInfo> list = queryIntentActivities(intent, null,
11788                PackageManager.GET_META_DATA, callingUserId);
11789        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11790                true, false, false, callingUserId);
11791
11792        allHomeCandidates.clear();
11793        if (list != null) {
11794            for (ResolveInfo ri : list) {
11795                allHomeCandidates.add(ri);
11796            }
11797        }
11798        return (preferred == null || preferred.activityInfo == null)
11799                ? null
11800                : new ComponentName(preferred.activityInfo.packageName,
11801                        preferred.activityInfo.name);
11802    }
11803
11804    @Override
11805    public void setApplicationEnabledSetting(String appPackageName,
11806            int newState, int flags, int userId, String callingPackage) {
11807        if (!sUserManager.exists(userId)) return;
11808        if (callingPackage == null) {
11809            callingPackage = Integer.toString(Binder.getCallingUid());
11810        }
11811        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11812    }
11813
11814    @Override
11815    public void setComponentEnabledSetting(ComponentName componentName,
11816            int newState, int flags, int userId) {
11817        if (!sUserManager.exists(userId)) return;
11818        setEnabledSetting(componentName.getPackageName(),
11819                componentName.getClassName(), newState, flags, userId, null);
11820    }
11821
11822    private void setEnabledSetting(final String packageName, String className, int newState,
11823            final int flags, int userId, String callingPackage) {
11824        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11825              || newState == COMPONENT_ENABLED_STATE_ENABLED
11826              || newState == COMPONENT_ENABLED_STATE_DISABLED
11827              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11828              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11829            throw new IllegalArgumentException("Invalid new component state: "
11830                    + newState);
11831        }
11832        PackageSetting pkgSetting;
11833        final int uid = Binder.getCallingUid();
11834        final int permission = mContext.checkCallingOrSelfPermission(
11835                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11836        enforceCrossUserPermission(uid, userId, false, "set enabled");
11837        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11838        boolean sendNow = false;
11839        boolean isApp = (className == null);
11840        String componentName = isApp ? packageName : className;
11841        int packageUid = -1;
11842        ArrayList<String> components;
11843
11844        // writer
11845        synchronized (mPackages) {
11846            pkgSetting = mSettings.mPackages.get(packageName);
11847            if (pkgSetting == null) {
11848                if (className == null) {
11849                    throw new IllegalArgumentException(
11850                            "Unknown package: " + packageName);
11851                }
11852                throw new IllegalArgumentException(
11853                        "Unknown component: " + packageName
11854                        + "/" + className);
11855            }
11856            // Allow root and verify that userId is not being specified by a different user
11857            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11858                throw new SecurityException(
11859                        "Permission Denial: attempt to change component state from pid="
11860                        + Binder.getCallingPid()
11861                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11862            }
11863            if (className == null) {
11864                // We're dealing with an application/package level state change
11865                if (pkgSetting.getEnabled(userId) == newState) {
11866                    // Nothing to do
11867                    return;
11868                }
11869                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11870                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11871                    // Don't care about who enables an app.
11872                    callingPackage = null;
11873                }
11874                pkgSetting.setEnabled(newState, userId, callingPackage);
11875                // pkgSetting.pkg.mSetEnabled = newState;
11876            } else {
11877                // We're dealing with a component level state change
11878                // First, verify that this is a valid class name.
11879                PackageParser.Package pkg = pkgSetting.pkg;
11880                if (pkg == null || !pkg.hasComponentClassName(className)) {
11881                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11882                        throw new IllegalArgumentException("Component class " + className
11883                                + " does not exist in " + packageName);
11884                    } else {
11885                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11886                                + className + " does not exist in " + packageName);
11887                    }
11888                }
11889                switch (newState) {
11890                case COMPONENT_ENABLED_STATE_ENABLED:
11891                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11892                        return;
11893                    }
11894                    break;
11895                case COMPONENT_ENABLED_STATE_DISABLED:
11896                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11897                        return;
11898                    }
11899                    break;
11900                case COMPONENT_ENABLED_STATE_DEFAULT:
11901                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11902                        return;
11903                    }
11904                    break;
11905                default:
11906                    Slog.e(TAG, "Invalid new component state: " + newState);
11907                    return;
11908                }
11909            }
11910            mSettings.writePackageRestrictionsLPr(userId);
11911            components = mPendingBroadcasts.get(userId, packageName);
11912            final boolean newPackage = components == null;
11913            if (newPackage) {
11914                components = new ArrayList<String>();
11915            }
11916            if (!components.contains(componentName)) {
11917                components.add(componentName);
11918            }
11919            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11920                sendNow = true;
11921                // Purge entry from pending broadcast list if another one exists already
11922                // since we are sending one right away.
11923                mPendingBroadcasts.remove(userId, packageName);
11924            } else {
11925                if (newPackage) {
11926                    mPendingBroadcasts.put(userId, packageName, components);
11927                }
11928                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11929                    // Schedule a message
11930                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11931                }
11932            }
11933        }
11934
11935        long callingId = Binder.clearCallingIdentity();
11936        try {
11937            if (sendNow) {
11938                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11939                sendPackageChangedBroadcast(packageName,
11940                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11941            }
11942        } finally {
11943            Binder.restoreCallingIdentity(callingId);
11944        }
11945    }
11946
11947    private void sendPackageChangedBroadcast(String packageName,
11948            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11949        if (DEBUG_INSTALL)
11950            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11951                    + componentNames);
11952        Bundle extras = new Bundle(4);
11953        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11954        String nameList[] = new String[componentNames.size()];
11955        componentNames.toArray(nameList);
11956        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11957        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11958        extras.putInt(Intent.EXTRA_UID, packageUid);
11959        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11960                new int[] {UserHandle.getUserId(packageUid)});
11961    }
11962
11963    @Override
11964    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11965        if (!sUserManager.exists(userId)) return;
11966        final int uid = Binder.getCallingUid();
11967        final int permission = mContext.checkCallingOrSelfPermission(
11968                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11969        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11970        enforceCrossUserPermission(uid, userId, true, "stop package");
11971        // writer
11972        synchronized (mPackages) {
11973            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11974                    uid, userId)) {
11975                scheduleWritePackageRestrictionsLocked(userId);
11976            }
11977        }
11978    }
11979
11980    @Override
11981    public String getInstallerPackageName(String packageName) {
11982        // reader
11983        synchronized (mPackages) {
11984            return mSettings.getInstallerPackageNameLPr(packageName);
11985        }
11986    }
11987
11988    @Override
11989    public int getApplicationEnabledSetting(String packageName, int userId) {
11990        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11991        int uid = Binder.getCallingUid();
11992        enforceCrossUserPermission(uid, userId, false, "get enabled");
11993        // reader
11994        synchronized (mPackages) {
11995            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11996        }
11997    }
11998
11999    @Override
12000    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12001        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12002        int uid = Binder.getCallingUid();
12003        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12004        // reader
12005        synchronized (mPackages) {
12006            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12007        }
12008    }
12009
12010    @Override
12011    public void enterSafeMode() {
12012        enforceSystemOrRoot("Only the system can request entering safe mode");
12013
12014        if (!mSystemReady) {
12015            mSafeMode = true;
12016        }
12017    }
12018
12019    @Override
12020    public void systemReady() {
12021        mSystemReady = true;
12022
12023        // Read the compatibilty setting when the system is ready.
12024        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12025                mContext.getContentResolver(),
12026                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12027        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12028        if (DEBUG_SETTINGS) {
12029            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12030        }
12031
12032        synchronized (mPackages) {
12033            // Verify that all of the preferred activity components actually
12034            // exist.  It is possible for applications to be updated and at
12035            // that point remove a previously declared activity component that
12036            // had been set as a preferred activity.  We try to clean this up
12037            // the next time we encounter that preferred activity, but it is
12038            // possible for the user flow to never be able to return to that
12039            // situation so here we do a sanity check to make sure we haven't
12040            // left any junk around.
12041            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12042            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12043                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12044                removed.clear();
12045                for (PreferredActivity pa : pir.filterSet()) {
12046                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12047                        removed.add(pa);
12048                    }
12049                }
12050                if (removed.size() > 0) {
12051                    for (int r=0; r<removed.size(); r++) {
12052                        PreferredActivity pa = removed.get(r);
12053                        Slog.w(TAG, "Removing dangling preferred activity: "
12054                                + pa.mPref.mComponent);
12055                        pir.removeFilter(pa);
12056                    }
12057                    mSettings.writePackageRestrictionsLPr(
12058                            mSettings.mPreferredActivities.keyAt(i));
12059                }
12060            }
12061        }
12062        sUserManager.systemReady();
12063    }
12064
12065    @Override
12066    public boolean isSafeMode() {
12067        return mSafeMode;
12068    }
12069
12070    @Override
12071    public boolean hasSystemUidErrors() {
12072        return mHasSystemUidErrors;
12073    }
12074
12075    static String arrayToString(int[] array) {
12076        StringBuffer buf = new StringBuffer(128);
12077        buf.append('[');
12078        if (array != null) {
12079            for (int i=0; i<array.length; i++) {
12080                if (i > 0) buf.append(", ");
12081                buf.append(array[i]);
12082            }
12083        }
12084        buf.append(']');
12085        return buf.toString();
12086    }
12087
12088    static class DumpState {
12089        public static final int DUMP_LIBS = 1 << 0;
12090        public static final int DUMP_FEATURES = 1 << 1;
12091        public static final int DUMP_RESOLVERS = 1 << 2;
12092        public static final int DUMP_PERMISSIONS = 1 << 3;
12093        public static final int DUMP_PACKAGES = 1 << 4;
12094        public static final int DUMP_SHARED_USERS = 1 << 5;
12095        public static final int DUMP_MESSAGES = 1 << 6;
12096        public static final int DUMP_PROVIDERS = 1 << 7;
12097        public static final int DUMP_VERIFIERS = 1 << 8;
12098        public static final int DUMP_PREFERRED = 1 << 9;
12099        public static final int DUMP_PREFERRED_XML = 1 << 10;
12100        public static final int DUMP_KEYSETS = 1 << 11;
12101        public static final int DUMP_VERSION = 1 << 12;
12102        public static final int DUMP_INSTALLS = 1 << 13;
12103
12104        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12105
12106        private int mTypes;
12107
12108        private int mOptions;
12109
12110        private boolean mTitlePrinted;
12111
12112        private SharedUserSetting mSharedUser;
12113
12114        public boolean isDumping(int type) {
12115            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12116                return true;
12117            }
12118
12119            return (mTypes & type) != 0;
12120        }
12121
12122        public void setDump(int type) {
12123            mTypes |= type;
12124        }
12125
12126        public boolean isOptionEnabled(int option) {
12127            return (mOptions & option) != 0;
12128        }
12129
12130        public void setOptionEnabled(int option) {
12131            mOptions |= option;
12132        }
12133
12134        public boolean onTitlePrinted() {
12135            final boolean printed = mTitlePrinted;
12136            mTitlePrinted = true;
12137            return printed;
12138        }
12139
12140        public boolean getTitlePrinted() {
12141            return mTitlePrinted;
12142        }
12143
12144        public void setTitlePrinted(boolean enabled) {
12145            mTitlePrinted = enabled;
12146        }
12147
12148        public SharedUserSetting getSharedUser() {
12149            return mSharedUser;
12150        }
12151
12152        public void setSharedUser(SharedUserSetting user) {
12153            mSharedUser = user;
12154        }
12155    }
12156
12157    @Override
12158    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12159        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12160                != PackageManager.PERMISSION_GRANTED) {
12161            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12162                    + Binder.getCallingPid()
12163                    + ", uid=" + Binder.getCallingUid()
12164                    + " without permission "
12165                    + android.Manifest.permission.DUMP);
12166            return;
12167        }
12168
12169        DumpState dumpState = new DumpState();
12170        boolean fullPreferred = false;
12171        boolean checkin = false;
12172
12173        String packageName = null;
12174
12175        int opti = 0;
12176        while (opti < args.length) {
12177            String opt = args[opti];
12178            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12179                break;
12180            }
12181            opti++;
12182            if ("-a".equals(opt)) {
12183                // Right now we only know how to print all.
12184            } else if ("-h".equals(opt)) {
12185                pw.println("Package manager dump options:");
12186                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12187                pw.println("    --checkin: dump for a checkin");
12188                pw.println("    -f: print details of intent filters");
12189                pw.println("    -h: print this help");
12190                pw.println("  cmd may be one of:");
12191                pw.println("    l[ibraries]: list known shared libraries");
12192                pw.println("    f[ibraries]: list device features");
12193                pw.println("    k[eysets]: print known keysets");
12194                pw.println("    r[esolvers]: dump intent resolvers");
12195                pw.println("    perm[issions]: dump permissions");
12196                pw.println("    pref[erred]: print preferred package settings");
12197                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12198                pw.println("    prov[iders]: dump content providers");
12199                pw.println("    p[ackages]: dump installed packages");
12200                pw.println("    s[hared-users]: dump shared user IDs");
12201                pw.println("    m[essages]: print collected runtime messages");
12202                pw.println("    v[erifiers]: print package verifier info");
12203                pw.println("    version: print database version info");
12204                pw.println("    write: write current settings now");
12205                pw.println("    <package.name>: info about given package");
12206                pw.println("    installs: details about install sessions");
12207                return;
12208            } else if ("--checkin".equals(opt)) {
12209                checkin = true;
12210            } else if ("-f".equals(opt)) {
12211                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12212            } else {
12213                pw.println("Unknown argument: " + opt + "; use -h for help");
12214            }
12215        }
12216
12217        // Is the caller requesting to dump a particular piece of data?
12218        if (opti < args.length) {
12219            String cmd = args[opti];
12220            opti++;
12221            // Is this a package name?
12222            if ("android".equals(cmd) || cmd.contains(".")) {
12223                packageName = cmd;
12224                // When dumping a single package, we always dump all of its
12225                // filter information since the amount of data will be reasonable.
12226                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12227            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12228                dumpState.setDump(DumpState.DUMP_LIBS);
12229            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12230                dumpState.setDump(DumpState.DUMP_FEATURES);
12231            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12232                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12233            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12234                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12235            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12236                dumpState.setDump(DumpState.DUMP_PREFERRED);
12237            } else if ("preferred-xml".equals(cmd)) {
12238                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12239                if (opti < args.length && "--full".equals(args[opti])) {
12240                    fullPreferred = true;
12241                    opti++;
12242                }
12243            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12244                dumpState.setDump(DumpState.DUMP_PACKAGES);
12245            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12246                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12247            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12248                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12249            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12250                dumpState.setDump(DumpState.DUMP_MESSAGES);
12251            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12252                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12253            } else if ("version".equals(cmd)) {
12254                dumpState.setDump(DumpState.DUMP_VERSION);
12255            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12256                dumpState.setDump(DumpState.DUMP_KEYSETS);
12257            } else if ("write".equals(cmd)) {
12258                synchronized (mPackages) {
12259                    mSettings.writeLPr();
12260                    pw.println("Settings written.");
12261                    return;
12262                }
12263            } else if ("installs".equals(cmd)) {
12264                dumpState.setDump(DumpState.DUMP_INSTALLS);
12265            }
12266        }
12267
12268        if (checkin) {
12269            pw.println("vers,1");
12270        }
12271
12272        // reader
12273        synchronized (mPackages) {
12274            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12275                if (!checkin) {
12276                    if (dumpState.onTitlePrinted())
12277                        pw.println();
12278                    pw.println("Database versions:");
12279                    pw.print("  SDK Version:");
12280                    pw.print(" internal=");
12281                    pw.print(mSettings.mInternalSdkPlatform);
12282                    pw.print(" external=");
12283                    pw.println(mSettings.mExternalSdkPlatform);
12284                    pw.print("  DB Version:");
12285                    pw.print(" internal=");
12286                    pw.print(mSettings.mInternalDatabaseVersion);
12287                    pw.print(" external=");
12288                    pw.println(mSettings.mExternalDatabaseVersion);
12289                }
12290            }
12291
12292            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12293                if (!checkin) {
12294                    if (dumpState.onTitlePrinted())
12295                        pw.println();
12296                    pw.println("Verifiers:");
12297                    pw.print("  Required: ");
12298                    pw.print(mRequiredVerifierPackage);
12299                    pw.print(" (uid=");
12300                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12301                    pw.println(")");
12302                } else if (mRequiredVerifierPackage != null) {
12303                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12304                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12305                }
12306            }
12307
12308            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12309                boolean printedHeader = false;
12310                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12311                while (it.hasNext()) {
12312                    String name = it.next();
12313                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12314                    if (!checkin) {
12315                        if (!printedHeader) {
12316                            if (dumpState.onTitlePrinted())
12317                                pw.println();
12318                            pw.println("Libraries:");
12319                            printedHeader = true;
12320                        }
12321                        pw.print("  ");
12322                    } else {
12323                        pw.print("lib,");
12324                    }
12325                    pw.print(name);
12326                    if (!checkin) {
12327                        pw.print(" -> ");
12328                    }
12329                    if (ent.path != null) {
12330                        if (!checkin) {
12331                            pw.print("(jar) ");
12332                            pw.print(ent.path);
12333                        } else {
12334                            pw.print(",jar,");
12335                            pw.print(ent.path);
12336                        }
12337                    } else {
12338                        if (!checkin) {
12339                            pw.print("(apk) ");
12340                            pw.print(ent.apk);
12341                        } else {
12342                            pw.print(",apk,");
12343                            pw.print(ent.apk);
12344                        }
12345                    }
12346                    pw.println();
12347                }
12348            }
12349
12350            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12351                if (dumpState.onTitlePrinted())
12352                    pw.println();
12353                if (!checkin) {
12354                    pw.println("Features:");
12355                }
12356                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12357                while (it.hasNext()) {
12358                    String name = it.next();
12359                    if (!checkin) {
12360                        pw.print("  ");
12361                    } else {
12362                        pw.print("feat,");
12363                    }
12364                    pw.println(name);
12365                }
12366            }
12367
12368            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12369                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12370                        : "Activity Resolver Table:", "  ", packageName,
12371                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12372                    dumpState.setTitlePrinted(true);
12373                }
12374                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12375                        : "Receiver Resolver Table:", "  ", packageName,
12376                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12377                    dumpState.setTitlePrinted(true);
12378                }
12379                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12380                        : "Service Resolver Table:", "  ", packageName,
12381                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12382                    dumpState.setTitlePrinted(true);
12383                }
12384                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12385                        : "Provider Resolver Table:", "  ", packageName,
12386                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12387                    dumpState.setTitlePrinted(true);
12388                }
12389            }
12390
12391            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12392                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12393                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12394                    int user = mSettings.mPreferredActivities.keyAt(i);
12395                    if (pir.dump(pw,
12396                            dumpState.getTitlePrinted()
12397                                ? "\nPreferred Activities User " + user + ":"
12398                                : "Preferred Activities User " + user + ":", "  ",
12399                            packageName, true)) {
12400                        dumpState.setTitlePrinted(true);
12401                    }
12402                }
12403            }
12404
12405            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12406                pw.flush();
12407                FileOutputStream fout = new FileOutputStream(fd);
12408                BufferedOutputStream str = new BufferedOutputStream(fout);
12409                XmlSerializer serializer = new FastXmlSerializer();
12410                try {
12411                    serializer.setOutput(str, "utf-8");
12412                    serializer.startDocument(null, true);
12413                    serializer.setFeature(
12414                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12415                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12416                    serializer.endDocument();
12417                    serializer.flush();
12418                } catch (IllegalArgumentException e) {
12419                    pw.println("Failed writing: " + e);
12420                } catch (IllegalStateException e) {
12421                    pw.println("Failed writing: " + e);
12422                } catch (IOException e) {
12423                    pw.println("Failed writing: " + e);
12424                }
12425            }
12426
12427            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12428                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12429            }
12430
12431            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12432                boolean printedSomething = false;
12433                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12434                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12435                        continue;
12436                    }
12437                    if (!printedSomething) {
12438                        if (dumpState.onTitlePrinted())
12439                            pw.println();
12440                        pw.println("Registered ContentProviders:");
12441                        printedSomething = true;
12442                    }
12443                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12444                    pw.print("    "); pw.println(p.toString());
12445                }
12446                printedSomething = false;
12447                for (Map.Entry<String, PackageParser.Provider> entry :
12448                        mProvidersByAuthority.entrySet()) {
12449                    PackageParser.Provider p = entry.getValue();
12450                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12451                        continue;
12452                    }
12453                    if (!printedSomething) {
12454                        if (dumpState.onTitlePrinted())
12455                            pw.println();
12456                        pw.println("ContentProvider Authorities:");
12457                        printedSomething = true;
12458                    }
12459                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12460                    pw.print("    "); pw.println(p.toString());
12461                    if (p.info != null && p.info.applicationInfo != null) {
12462                        final String appInfo = p.info.applicationInfo.toString();
12463                        pw.print("      applicationInfo="); pw.println(appInfo);
12464                    }
12465                }
12466            }
12467
12468            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12469                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12470            }
12471
12472            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12473                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12474            }
12475
12476            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12477                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12478            }
12479
12480            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12481                if (dumpState.onTitlePrinted()) pw.println();
12482                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12483            }
12484
12485            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12486                if (dumpState.onTitlePrinted()) pw.println();
12487                mSettings.dumpReadMessagesLPr(pw, dumpState);
12488
12489                pw.println();
12490                pw.println("Package warning messages:");
12491                final File fname = getSettingsProblemFile();
12492                FileInputStream in = null;
12493                try {
12494                    in = new FileInputStream(fname);
12495                    final int avail = in.available();
12496                    final byte[] data = new byte[avail];
12497                    in.read(data);
12498                    pw.print(new String(data));
12499                } catch (FileNotFoundException e) {
12500                } catch (IOException e) {
12501                } finally {
12502                    if (in != null) {
12503                        try {
12504                            in.close();
12505                        } catch (IOException e) {
12506                        }
12507                    }
12508                }
12509            }
12510        }
12511    }
12512
12513    // ------- apps on sdcard specific code -------
12514    static final boolean DEBUG_SD_INSTALL = false;
12515
12516    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12517
12518    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12519
12520    private boolean mMediaMounted = false;
12521
12522    private String getEncryptKey() {
12523        try {
12524            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12525                    SD_ENCRYPTION_KEYSTORE_NAME);
12526            if (sdEncKey == null) {
12527                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12528                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12529                if (sdEncKey == null) {
12530                    Slog.e(TAG, "Failed to create encryption keys");
12531                    return null;
12532                }
12533            }
12534            return sdEncKey;
12535        } catch (NoSuchAlgorithmException nsae) {
12536            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12537            return null;
12538        } catch (IOException ioe) {
12539            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12540            return null;
12541        }
12542
12543    }
12544
12545    /* package */static String getTempContainerId() {
12546        int tmpIdx = 1;
12547        String list[] = PackageHelper.getSecureContainerList();
12548        if (list != null) {
12549            for (final String name : list) {
12550                // Ignore null and non-temporary container entries
12551                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12552                    continue;
12553                }
12554
12555                String subStr = name.substring(mTempContainerPrefix.length());
12556                try {
12557                    int cid = Integer.parseInt(subStr);
12558                    if (cid >= tmpIdx) {
12559                        tmpIdx = cid + 1;
12560                    }
12561                } catch (NumberFormatException e) {
12562                }
12563            }
12564        }
12565        return mTempContainerPrefix + tmpIdx;
12566    }
12567
12568    /*
12569     * Update media status on PackageManager.
12570     */
12571    @Override
12572    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12573        int callingUid = Binder.getCallingUid();
12574        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12575            throw new SecurityException("Media status can only be updated by the system");
12576        }
12577        // reader; this apparently protects mMediaMounted, but should probably
12578        // be a different lock in that case.
12579        synchronized (mPackages) {
12580            Log.i(TAG, "Updating external media status from "
12581                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12582                    + (mediaStatus ? "mounted" : "unmounted"));
12583            if (DEBUG_SD_INSTALL)
12584                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12585                        + ", mMediaMounted=" + mMediaMounted);
12586            if (mediaStatus == mMediaMounted) {
12587                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12588                        : 0, -1);
12589                mHandler.sendMessage(msg);
12590                return;
12591            }
12592            mMediaMounted = mediaStatus;
12593        }
12594        // Queue up an async operation since the package installation may take a
12595        // little while.
12596        mHandler.post(new Runnable() {
12597            public void run() {
12598                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12599            }
12600        });
12601    }
12602
12603    /**
12604     * Called by MountService when the initial ASECs to scan are available.
12605     * Should block until all the ASEC containers are finished being scanned.
12606     */
12607    public void scanAvailableAsecs() {
12608        updateExternalMediaStatusInner(true, false, false);
12609        if (mShouldRestoreconData) {
12610            SELinuxMMAC.setRestoreconDone();
12611            mShouldRestoreconData = false;
12612        }
12613    }
12614
12615    /*
12616     * Collect information of applications on external media, map them against
12617     * existing containers and update information based on current mount status.
12618     * Please note that we always have to report status if reportStatus has been
12619     * set to true especially when unloading packages.
12620     */
12621    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12622            boolean externalStorage) {
12623        // Collection of uids
12624        int uidArr[] = null;
12625        // Collection of stale containers
12626        HashSet<String> removeCids = new HashSet<String>();
12627        // Collection of packages on external media with valid containers.
12628        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12629        // Get list of secure containers.
12630        final String list[] = PackageHelper.getSecureContainerList();
12631        if (list == null || list.length == 0) {
12632            Log.i(TAG, "No secure containers on sdcard");
12633        } else {
12634            // Process list of secure containers and categorize them
12635            // as active or stale based on their package internal state.
12636            int uidList[] = new int[list.length];
12637            int num = 0;
12638            // reader
12639            synchronized (mPackages) {
12640                for (String cid : list) {
12641                    if (DEBUG_SD_INSTALL)
12642                        Log.i(TAG, "Processing container " + cid);
12643                    String pkgName = getAsecPackageName(cid);
12644                    if (pkgName == null) {
12645                        if (DEBUG_SD_INSTALL)
12646                            Log.i(TAG, "Container : " + cid + " stale");
12647                        removeCids.add(cid);
12648                        continue;
12649                    }
12650                    if (DEBUG_SD_INSTALL)
12651                        Log.i(TAG, "Looking for pkg : " + pkgName);
12652
12653                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12654                    if (ps == null) {
12655                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12656                        removeCids.add(cid);
12657                        continue;
12658                    }
12659
12660                    /*
12661                     * Skip packages that are not external if we're unmounting
12662                     * external storage.
12663                     */
12664                    if (externalStorage && !isMounted && !isExternal(ps)) {
12665                        continue;
12666                    }
12667
12668                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12669                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12670                    // The package status is changed only if the code path
12671                    // matches between settings and the container id.
12672                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12673                        if (DEBUG_SD_INSTALL) {
12674                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12675                                    + " at code path: " + ps.codePathString);
12676                        }
12677
12678                        // We do have a valid package installed on sdcard
12679                        processCids.put(args, ps.codePathString);
12680                        final int uid = ps.appId;
12681                        if (uid != -1) {
12682                            uidList[num++] = uid;
12683                        }
12684                    } else {
12685                        Log.i(TAG, "Deleting stale container for " + cid);
12686                        removeCids.add(cid);
12687                    }
12688                }
12689            }
12690
12691            if (num > 0) {
12692                // Sort uid list
12693                Arrays.sort(uidList, 0, num);
12694                // Throw away duplicates
12695                uidArr = new int[num];
12696                uidArr[0] = uidList[0];
12697                int di = 0;
12698                for (int i = 1; i < num; i++) {
12699                    if (uidList[i - 1] != uidList[i]) {
12700                        uidArr[di++] = uidList[i];
12701                    }
12702                }
12703            }
12704        }
12705        // Process packages with valid entries.
12706        if (isMounted) {
12707            if (DEBUG_SD_INSTALL)
12708                Log.i(TAG, "Loading packages");
12709            loadMediaPackages(processCids, uidArr, removeCids);
12710            startCleaningPackages();
12711        } else {
12712            if (DEBUG_SD_INSTALL)
12713                Log.i(TAG, "Unloading packages");
12714            unloadMediaPackages(processCids, uidArr, reportStatus);
12715        }
12716    }
12717
12718   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12719           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12720        int size = pkgList.size();
12721        if (size > 0) {
12722            // Send broadcasts here
12723            Bundle extras = new Bundle();
12724            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12725                    .toArray(new String[size]));
12726            if (uidArr != null) {
12727                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12728            }
12729            if (replacing) {
12730                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12731            }
12732            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12733                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12734            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12735        }
12736    }
12737
12738   /*
12739     * Look at potentially valid container ids from processCids If package
12740     * information doesn't match the one on record or package scanning fails,
12741     * the cid is added to list of removeCids. We currently don't delete stale
12742     * containers.
12743     */
12744   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12745            HashSet<String> removeCids) {
12746        ArrayList<String> pkgList = new ArrayList<String>();
12747        Set<AsecInstallArgs> keys = processCids.keySet();
12748        boolean doGc = false;
12749        for (AsecInstallArgs args : keys) {
12750            String codePath = processCids.get(args);
12751            if (DEBUG_SD_INSTALL)
12752                Log.i(TAG, "Loading container : " + args.cid);
12753            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12754            try {
12755                // Make sure there are no container errors first.
12756                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12757                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12758                            + " when installing from sdcard");
12759                    continue;
12760                }
12761                // Check code path here.
12762                if (codePath == null || !codePath.equals(args.getCodePath())) {
12763                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12764                            + " does not match one in settings " + codePath);
12765                    continue;
12766                }
12767                // Parse package
12768                int parseFlags = mDefParseFlags;
12769                if (args.isExternal()) {
12770                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12771                }
12772                if (args.isFwdLocked()) {
12773                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12774                }
12775
12776                doGc = true;
12777                synchronized (mInstallLock) {
12778                    PackageParser.Package pkg = null;
12779                    try {
12780                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12781                    } catch (PackageManagerException e) {
12782                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12783                    }
12784                    // Scan the package
12785                    if (pkg != null) {
12786                        /*
12787                         * TODO why is the lock being held? doPostInstall is
12788                         * called in other places without the lock. This needs
12789                         * to be straightened out.
12790                         */
12791                        // writer
12792                        synchronized (mPackages) {
12793                            retCode = PackageManager.INSTALL_SUCCEEDED;
12794                            pkgList.add(pkg.packageName);
12795                            // Post process args
12796                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12797                                    pkg.applicationInfo.uid);
12798                        }
12799                    } else {
12800                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12801                    }
12802                }
12803
12804            } finally {
12805                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12806                    // Don't destroy container here. Wait till gc clears things
12807                    // up.
12808                    removeCids.add(args.cid);
12809                }
12810            }
12811        }
12812        // writer
12813        synchronized (mPackages) {
12814            // If the platform SDK has changed since the last time we booted,
12815            // we need to re-grant app permission to catch any new ones that
12816            // appear. This is really a hack, and means that apps can in some
12817            // cases get permissions that the user didn't initially explicitly
12818            // allow... it would be nice to have some better way to handle
12819            // this situation.
12820            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12821            if (regrantPermissions)
12822                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12823                        + mSdkVersion + "; regranting permissions for external storage");
12824            mSettings.mExternalSdkPlatform = mSdkVersion;
12825
12826            // Make sure group IDs have been assigned, and any permission
12827            // changes in other apps are accounted for
12828            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12829                    | (regrantPermissions
12830                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12831                            : 0));
12832
12833            mSettings.updateExternalDatabaseVersion();
12834
12835            // can downgrade to reader
12836            // Persist settings
12837            mSettings.writeLPr();
12838        }
12839        // Send a broadcast to let everyone know we are done processing
12840        if (pkgList.size() > 0) {
12841            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12842        }
12843        // Force gc to avoid any stale parser references that we might have.
12844        if (doGc) {
12845            Runtime.getRuntime().gc();
12846        }
12847        // List stale containers and destroy stale temporary containers.
12848        if (removeCids != null) {
12849            for (String cid : removeCids) {
12850                if (cid.startsWith(mTempContainerPrefix)) {
12851                    Log.i(TAG, "Destroying stale temporary container " + cid);
12852                    PackageHelper.destroySdDir(cid);
12853                } else {
12854                    Log.w(TAG, "Container " + cid + " is stale");
12855               }
12856           }
12857        }
12858    }
12859
12860   /*
12861     * Utility method to unload a list of specified containers
12862     */
12863    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12864        // Just unmount all valid containers.
12865        for (AsecInstallArgs arg : cidArgs) {
12866            synchronized (mInstallLock) {
12867                arg.doPostDeleteLI(false);
12868           }
12869       }
12870   }
12871
12872    /*
12873     * Unload packages mounted on external media. This involves deleting package
12874     * data from internal structures, sending broadcasts about diabled packages,
12875     * gc'ing to free up references, unmounting all secure containers
12876     * corresponding to packages on external media, and posting a
12877     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12878     * that we always have to post this message if status has been requested no
12879     * matter what.
12880     */
12881    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12882            final boolean reportStatus) {
12883        if (DEBUG_SD_INSTALL)
12884            Log.i(TAG, "unloading media packages");
12885        ArrayList<String> pkgList = new ArrayList<String>();
12886        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12887        final Set<AsecInstallArgs> keys = processCids.keySet();
12888        for (AsecInstallArgs args : keys) {
12889            String pkgName = args.getPackageName();
12890            if (DEBUG_SD_INSTALL)
12891                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12892            // Delete package internally
12893            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12894            synchronized (mInstallLock) {
12895                boolean res = deletePackageLI(pkgName, null, false, null, null,
12896                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12897                if (res) {
12898                    pkgList.add(pkgName);
12899                } else {
12900                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12901                    failedList.add(args);
12902                }
12903            }
12904        }
12905
12906        // reader
12907        synchronized (mPackages) {
12908            // We didn't update the settings after removing each package;
12909            // write them now for all packages.
12910            mSettings.writeLPr();
12911        }
12912
12913        // We have to absolutely send UPDATED_MEDIA_STATUS only
12914        // after confirming that all the receivers processed the ordered
12915        // broadcast when packages get disabled, force a gc to clean things up.
12916        // and unload all the containers.
12917        if (pkgList.size() > 0) {
12918            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12919                    new IIntentReceiver.Stub() {
12920                public void performReceive(Intent intent, int resultCode, String data,
12921                        Bundle extras, boolean ordered, boolean sticky,
12922                        int sendingUser) throws RemoteException {
12923                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12924                            reportStatus ? 1 : 0, 1, keys);
12925                    mHandler.sendMessage(msg);
12926                }
12927            });
12928        } else {
12929            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12930                    keys);
12931            mHandler.sendMessage(msg);
12932        }
12933    }
12934
12935    /** Binder call */
12936    @Override
12937    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12938            final int flags) {
12939        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12940        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12941        int returnCode = PackageManager.MOVE_SUCCEEDED;
12942        int currFlags = 0;
12943        int newFlags = 0;
12944        // reader
12945        synchronized (mPackages) {
12946            PackageParser.Package pkg = mPackages.get(packageName);
12947            if (pkg == null) {
12948                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12949            } else {
12950                // Disable moving fwd locked apps and system packages
12951                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12952                    Slog.w(TAG, "Cannot move system application");
12953                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12954                } else if (pkg.mOperationPending) {
12955                    Slog.w(TAG, "Attempt to move package which has pending operations");
12956                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12957                } else {
12958                    // Find install location first
12959                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12960                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12961                        Slog.w(TAG, "Ambigous flags specified for move location.");
12962                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12963                    } else {
12964                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12965                                : PackageManager.INSTALL_INTERNAL;
12966                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12967                                : PackageManager.INSTALL_INTERNAL;
12968
12969                        if (newFlags == currFlags) {
12970                            Slog.w(TAG, "No move required. Trying to move to same location");
12971                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12972                        } else {
12973                            if (isForwardLocked(pkg)) {
12974                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12975                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12976                            }
12977                        }
12978                    }
12979                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12980                        pkg.mOperationPending = true;
12981                    }
12982                }
12983            }
12984
12985            /*
12986             * TODO this next block probably shouldn't be inside the lock. We
12987             * can't guarantee these won't change after this is fired off
12988             * anyway.
12989             */
12990            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12991                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
12992                        returnCode);
12993            } else {
12994                Message msg = mHandler.obtainMessage(INIT_COPY);
12995                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
12996                final boolean multiArch = isMultiArch(pkg.applicationInfo);
12997                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12998                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12999                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13000                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13001                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13002                msg.obj = mp;
13003                mHandler.sendMessage(msg);
13004            }
13005        }
13006    }
13007
13008    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13009        // Queue up an async operation since the package deletion may take a
13010        // little while.
13011        mHandler.post(new Runnable() {
13012            public void run() {
13013                // TODO fix this; this does nothing.
13014                mHandler.removeCallbacks(this);
13015                int returnCode = currentStatus;
13016                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13017                    int uidArr[] = null;
13018                    ArrayList<String> pkgList = null;
13019                    synchronized (mPackages) {
13020                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13021                        if (pkg == null) {
13022                            Slog.w(TAG, " Package " + mp.packageName
13023                                    + " doesn't exist. Aborting move");
13024                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13025                        } else if (!mp.srcArgs.getCodePath().equals(
13026                                pkg.applicationInfo.getCodePath())) {
13027                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13028                                    + mp.srcArgs.getCodePath() + " to "
13029                                    + pkg.applicationInfo.getCodePath()
13030                                    + " Aborting move and returning error");
13031                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13032                        } else {
13033                            uidArr = new int[] {
13034                                pkg.applicationInfo.uid
13035                            };
13036                            pkgList = new ArrayList<String>();
13037                            pkgList.add(mp.packageName);
13038                        }
13039                    }
13040                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13041                        // Send resources unavailable broadcast
13042                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13043                        // Update package code and resource paths
13044                        synchronized (mInstallLock) {
13045                            synchronized (mPackages) {
13046                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13047                                // Recheck for package again.
13048                                if (pkg == null) {
13049                                    Slog.w(TAG, " Package " + mp.packageName
13050                                            + " doesn't exist. Aborting move");
13051                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13052                                } else if (!mp.srcArgs.getCodePath().equals(
13053                                        pkg.applicationInfo.getCodePath())) {
13054                                    Slog.w(TAG, "Package " + mp.packageName
13055                                            + " code path changed from " + mp.srcArgs.getCodePath()
13056                                            + " to " + pkg.applicationInfo.getCodePath()
13057                                            + " Aborting move and returning error");
13058                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13059                                } else {
13060                                    final String oldCodePath = pkg.codePath;
13061                                    final String newCodePath = mp.targetArgs.getCodePath();
13062                                    final String newResPath = mp.targetArgs.getResourcePath();
13063                                    // TODO: This assumes the new style of installation.
13064                                    // should we look at legacyNativeLibraryPath ?
13065                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13066                                    final File newNativeDir = new File(newNativeRoot);
13067
13068                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13069                                        // TODO(multiArch): Fix this so that it looks at the existing
13070                                        // recorded CPU abis from the package. There's no need for a separate
13071                                        // round of ABI scanning here.
13072                                        NativeLibraryHelper.Handle handle = null;
13073                                        try {
13074                                            handle = NativeLibraryHelper.Handle.create(
13075                                                    new File(newCodePath));
13076                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13077                                                    handle, Build.SUPPORTED_ABIS);
13078                                            if (abi >= 0) {
13079                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13080                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13081                                            }
13082                                        } catch (IOException ioe) {
13083                                            Slog.w(TAG, "Unable to extract native libs for package :"
13084                                                    + mp.packageName, ioe);
13085                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13086                                        } finally {
13087                                            IoUtils.closeQuietly(handle);
13088                                        }
13089                                    }
13090
13091                                    final int[] users = sUserManager.getUserIds();
13092                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13093                                        for (int user : users) {
13094                                            // TODO(multiArch): Fix this so that it links to the
13095                                            // correct directory. We're currently pointing to root. but we
13096                                            // must point to the arch specific subdirectory (if applicable).
13097                                            //
13098                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13099                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13100                                                    newNativeRoot, user) < 0) {
13101                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13102                                            }
13103                                        }
13104                                    }
13105
13106                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13107                                        pkg.codePath = newCodePath;
13108                                        pkg.baseCodePath = newCodePath;
13109                                        // Move dex files around
13110                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13111                                            // Moving of dex files failed. Set
13112                                            // error code and abort move.
13113                                            pkg.codePath = oldCodePath;
13114                                            pkg.baseCodePath = oldCodePath;
13115                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13116                                        }
13117                                    }
13118
13119                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13120                                        pkg.applicationInfo.setCodePath(newCodePath);
13121                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13122                                        pkg.applicationInfo.setSplitCodePaths(null);
13123                                        pkg.applicationInfo.setResourcePath(newResPath);
13124                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13125                                        pkg.applicationInfo.setSplitResourcePaths(null);
13126
13127                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13128                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13129                                        ps.codePathString = ps.codePath.getPath();
13130                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13131                                        ps.resourcePathString = ps.resourcePath.getPath();
13132
13133                                        // Note that we don't have to recalculate the primary and secondary
13134                                        // CPU ABIs because they must already have been calculated during the
13135                                        // initial install of the app.
13136                                        ps.legacyNativeLibraryPathString = null;
13137
13138                                        // Set the application info flag
13139                                        // correctly.
13140                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13141                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13142                                        } else {
13143                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13144                                        }
13145                                        ps.setFlags(pkg.applicationInfo.flags);
13146                                        mAppDirs.remove(oldCodePath);
13147                                        mAppDirs.put(newCodePath, pkg);
13148                                        // Persist settings
13149                                        mSettings.writeLPr();
13150                                    }
13151                                }
13152                            }
13153                        }
13154                        // Send resources available broadcast
13155                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13156                    }
13157                }
13158                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13159                    // Clean up failed installation
13160                    if (mp.targetArgs != null) {
13161                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13162                                -1);
13163                    }
13164                } else {
13165                    // Force a gc to clear things up.
13166                    Runtime.getRuntime().gc();
13167                    // Delete older code
13168                    synchronized (mInstallLock) {
13169                        mp.srcArgs.doPostDeleteLI(true);
13170                    }
13171                }
13172
13173                // Allow more operations on this file if we didn't fail because
13174                // an operation was already pending for this package.
13175                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13176                    synchronized (mPackages) {
13177                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13178                        if (pkg != null) {
13179                            pkg.mOperationPending = false;
13180                       }
13181                   }
13182                }
13183
13184                IPackageMoveObserver observer = mp.observer;
13185                if (observer != null) {
13186                    try {
13187                        observer.packageMoved(mp.packageName, returnCode);
13188                    } catch (RemoteException e) {
13189                        Log.i(TAG, "Observer no longer exists.");
13190                    }
13191                }
13192            }
13193        });
13194    }
13195
13196    @Override
13197    public boolean setInstallLocation(int loc) {
13198        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13199                null);
13200        if (getInstallLocation() == loc) {
13201            return true;
13202        }
13203        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13204                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13205            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13206                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13207            return true;
13208        }
13209        return false;
13210   }
13211
13212    @Override
13213    public int getInstallLocation() {
13214        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13215                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13216                PackageHelper.APP_INSTALL_AUTO);
13217    }
13218
13219    /** Called by UserManagerService */
13220    void cleanUpUserLILPw(int userHandle) {
13221        mDirtyUsers.remove(userHandle);
13222        mSettings.removeUserLPw(userHandle);
13223        mPendingBroadcasts.remove(userHandle);
13224        if (mInstaller != null) {
13225            // Technically, we shouldn't be doing this with the package lock
13226            // held.  However, this is very rare, and there is already so much
13227            // other disk I/O going on, that we'll let it slide for now.
13228            mInstaller.removeUserDataDirs(userHandle);
13229        }
13230        mUserNeedsBadging.delete(userHandle);
13231    }
13232
13233    /** Called by UserManagerService */
13234    void createNewUserLILPw(int userHandle, File path) {
13235        if (mInstaller != null) {
13236            mInstaller.createUserConfig(userHandle);
13237            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13238        }
13239    }
13240
13241    @Override
13242    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13243        mContext.enforceCallingOrSelfPermission(
13244                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13245                "Only package verification agents can read the verifier device identity");
13246
13247        synchronized (mPackages) {
13248            return mSettings.getVerifierDeviceIdentityLPw();
13249        }
13250    }
13251
13252    @Override
13253    public void setPermissionEnforced(String permission, boolean enforced) {
13254        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13255        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13256            synchronized (mPackages) {
13257                if (mSettings.mReadExternalStorageEnforced == null
13258                        || mSettings.mReadExternalStorageEnforced != enforced) {
13259                    mSettings.mReadExternalStorageEnforced = enforced;
13260                    mSettings.writeLPr();
13261                }
13262            }
13263            // kill any non-foreground processes so we restart them and
13264            // grant/revoke the GID.
13265            final IActivityManager am = ActivityManagerNative.getDefault();
13266            if (am != null) {
13267                final long token = Binder.clearCallingIdentity();
13268                try {
13269                    am.killProcessesBelowForeground("setPermissionEnforcement");
13270                } catch (RemoteException e) {
13271                } finally {
13272                    Binder.restoreCallingIdentity(token);
13273                }
13274            }
13275        } else {
13276            throw new IllegalArgumentException("No selective enforcement for " + permission);
13277        }
13278    }
13279
13280    @Override
13281    @Deprecated
13282    public boolean isPermissionEnforced(String permission) {
13283        return true;
13284    }
13285
13286    @Override
13287    public boolean isStorageLow() {
13288        final long token = Binder.clearCallingIdentity();
13289        try {
13290            final DeviceStorageMonitorInternal
13291                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13292            if (dsm != null) {
13293                return dsm.isMemoryLow();
13294            } else {
13295                return false;
13296            }
13297        } finally {
13298            Binder.restoreCallingIdentity(token);
13299        }
13300    }
13301
13302    @Override
13303    public IPackageInstaller getPackageInstaller() {
13304        return mInstallerService;
13305    }
13306
13307    private boolean userNeedsBadging(int userId) {
13308        int index = mUserNeedsBadging.indexOfKey(userId);
13309        if (index < 0) {
13310            final UserInfo userInfo;
13311            final long token = Binder.clearCallingIdentity();
13312            try {
13313                userInfo = sUserManager.getUserInfo(userId);
13314            } finally {
13315                Binder.restoreCallingIdentity(token);
13316            }
13317            final boolean b;
13318            if (userInfo != null && userInfo.isManagedProfile()) {
13319                b = true;
13320            } else {
13321                b = false;
13322            }
13323            mUserNeedsBadging.put(userId, b);
13324            return b;
13325        }
13326        return mUserNeedsBadging.valueAt(index);
13327    }
13328
13329    @Override
13330    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13331        if (packageName == null || alias == null) {
13332            return null;
13333        }
13334        synchronized(mPackages) {
13335            final PackageParser.Package pkg = mPackages.get(packageName);
13336            if (pkg == null) {
13337                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13338                throw new IllegalArgumentException("Unknown package: " + packageName);
13339            }
13340            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13341                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13342                throw new SecurityException("May not access KeySets defined by"
13343                        + " aliases in other applications.");
13344            }
13345            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13346            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13347        }
13348    }
13349
13350    @Override
13351    public KeySetHandle getSigningKeySet(String packageName) {
13352        if (packageName == null) {
13353            return null;
13354        }
13355        synchronized(mPackages) {
13356            final PackageParser.Package pkg = mPackages.get(packageName);
13357            if (pkg == null) {
13358                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13359                throw new IllegalArgumentException("Unknown package: " + packageName);
13360            }
13361            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13362                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13363                throw new SecurityException("May not access signing KeySet of other apps.");
13364            }
13365            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13366            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13367        }
13368    }
13369
13370    @Override
13371    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13372        if (packageName == null || ks == null) {
13373            return false;
13374        }
13375        synchronized(mPackages) {
13376            final PackageParser.Package pkg = mPackages.get(packageName);
13377            if (pkg == null) {
13378                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13379                throw new IllegalArgumentException("Unknown package: " + packageName);
13380            }
13381            if (ks instanceof KeySetHandle) {
13382                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13383                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13384            }
13385            return false;
13386        }
13387    }
13388
13389    @Override
13390    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13391        if (packageName == null || ks == null) {
13392            return false;
13393        }
13394        synchronized(mPackages) {
13395            final PackageParser.Package pkg = mPackages.get(packageName);
13396            if (pkg == null) {
13397                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13398                throw new IllegalArgumentException("Unknown package: " + packageName);
13399            }
13400            if (ks instanceof KeySetHandle) {
13401                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13402                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13403            }
13404            return false;
13405        }
13406    }
13407}
13408