PackageManagerService.java revision 9a445771f57dd15b06db0dbefd66c368d84eec2d
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 (bundledApp) {
6235            // Monolithic bundled install
6236            // TODO: support cluster bundled installs?
6237
6238            final boolean is64Bit = (info.primaryCpuAbi != null)
6239                    && VMRuntime.is64BitAbi(info.primaryCpuAbi);
6240
6241            // This is a bundled system app so choose the path based on the ABI.
6242            // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6243            // is just the default path.
6244            final String apkName = deriveCodePathName(codePath);
6245            final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6246            info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6247                    apkName).getAbsolutePath();
6248            info.nativeLibraryRootRequiresIsa = false;
6249
6250            info.nativeLibraryDir = info.nativeLibraryRootDir;
6251            if (info.secondaryCpuAbi != null) {
6252                final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6253                info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6254                        secondaryLibDir, apkName).getAbsolutePath();
6255            }
6256        } else if (isApkFile(codeFile)) {
6257            // Monolithic install
6258            if (asecApp) {
6259                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6260                        .getAbsolutePath();
6261            } else {
6262                final String apkName = deriveCodePathName(codePath);
6263                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6264                        .getAbsolutePath();
6265            }
6266
6267            info.nativeLibraryRootRequiresIsa = false;
6268            info.nativeLibraryDir = info.nativeLibraryRootDir;
6269        } else {
6270            // Cluster install
6271            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6272            info.nativeLibraryRootRequiresIsa = true;
6273
6274            if (info.primaryCpuAbi != null) {
6275                info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6276                        VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath();
6277            }
6278
6279            if (info.secondaryCpuAbi != null) {
6280                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6281                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6282            }
6283        }
6284    }
6285
6286    /**
6287     * Calculate the abis and roots for a bundled app. These can uniquely
6288     * be determined from the contents of the system partition, i.e whether
6289     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6290     * of this information, and instead assume that the system was built
6291     * sensibly.
6292     */
6293    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6294                                           PackageSetting pkgSetting) {
6295        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6296
6297        // If "/system/lib64/apkname" exists, assume that is the per-package
6298        // native library directory to use; otherwise use "/system/lib/apkname".
6299        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6300        setBundledAppAbi(pkg, apkRoot, apkName);
6301        // pkgSetting might be null during rescan following uninstall of updates
6302        // to a bundled app, so accommodate that possibility.  The settings in
6303        // that case will be established later from the parsed package.
6304        //
6305        // If the settings aren't null, sync them up with what we've just derived.
6306        // note that apkRoot isn't stored in the package settings.
6307        if (pkgSetting != null) {
6308            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6309            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6310        }
6311    }
6312
6313    /**
6314     * Deduces the ABI of a bundled app and sets the relevant fields on the
6315     * parsed pkg object.
6316     *
6317     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6318     *        under which system libraries are installed.
6319     * @param apkName the name of the installed package.
6320     */
6321    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6322        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6323        // or similar.
6324        final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6325        final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6326
6327        if (has64BitLibs && !has32BitLibs) {
6328            // The package has 64 bit libs, but not 32 bit libs. Its primary
6329            // ABI should be 64 bit. We can safely assume here that the bundled
6330            // native libraries correspond to the most preferred ABI in the list.
6331
6332            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6333            pkg.applicationInfo.secondaryCpuAbi = null;
6334        } else if (has32BitLibs && !has64BitLibs) {
6335            // The package has 32 bit libs but not 64 bit libs. Its primary
6336            // ABI should be 32 bit.
6337
6338            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6339            pkg.applicationInfo.secondaryCpuAbi = null;
6340        } else if (has32BitLibs && has64BitLibs) {
6341            // The application has both 64 and 32 bit bundled libraries. We check
6342            // here that the app declares multiArch support, and warn if it doesn't.
6343            //
6344            // We will be lenient here and record both ABIs. The primary will be the
6345            // ABI that's higher on the list, i.e, a device that's configured to prefer
6346            // 64 bit apps will see a 64 bit primary ABI,
6347
6348            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6349                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6350            }
6351
6352            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6353                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6354                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6355            } else {
6356                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6357                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6358            }
6359        } else {
6360            pkg.applicationInfo.primaryCpuAbi = null;
6361            pkg.applicationInfo.secondaryCpuAbi = null;
6362        }
6363    }
6364
6365    private static void createNativeLibrarySubdir(File path) throws IOException {
6366        if (!path.isDirectory()) {
6367            path.delete();
6368
6369            if (!path.mkdir()) {
6370                throw new IOException("Cannot create " + path.getPath());
6371            }
6372
6373            try {
6374                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6375            } catch (ErrnoException e) {
6376                throw new IOException("Cannot chmod native library directory "
6377                        + path.getPath(), e);
6378            }
6379        } else if (!SELinux.restorecon(path)) {
6380            throw new IOException("Cannot set SELinux context for " + path.getPath());
6381        }
6382    }
6383
6384    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6385            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6386        createNativeLibrarySubdir(nativeLibraryRoot);
6387
6388        /*
6389         * If this is an internal application or our nativeLibraryPath points to
6390         * the app-lib directory, unpack the libraries if necessary.
6391         */
6392        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6393        if (abi >= 0) {
6394            /*
6395             * If we have a matching instruction set, construct a subdir under the native
6396             * library root that corresponds to this instruction set.
6397             */
6398            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6399            final File subDir;
6400            if (useIsaSubdir) {
6401                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6402                createNativeLibrarySubdir(isaSubdir);
6403                subDir = isaSubdir;
6404            } else {
6405                subDir = nativeLibraryRoot;
6406            }
6407
6408            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6409            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6410                return copyRet;
6411            }
6412        }
6413
6414        return abi;
6415    }
6416
6417    private void killApplication(String pkgName, int appId, String reason) {
6418        // Request the ActivityManager to kill the process(only for existing packages)
6419        // so that we do not end up in a confused state while the user is still using the older
6420        // version of the application while the new one gets installed.
6421        IActivityManager am = ActivityManagerNative.getDefault();
6422        if (am != null) {
6423            try {
6424                am.killApplicationWithAppId(pkgName, appId, reason);
6425            } catch (RemoteException e) {
6426            }
6427        }
6428    }
6429
6430    void removePackageLI(PackageSetting ps, boolean chatty) {
6431        if (DEBUG_INSTALL) {
6432            if (chatty)
6433                Log.d(TAG, "Removing package " + ps.name);
6434        }
6435
6436        // writer
6437        synchronized (mPackages) {
6438            mPackages.remove(ps.name);
6439            if (ps.codePathString != null) {
6440                mAppDirs.remove(ps.codePathString);
6441            }
6442
6443            final PackageParser.Package pkg = ps.pkg;
6444            if (pkg != null) {
6445                cleanPackageDataStructuresLILPw(pkg, chatty);
6446            }
6447        }
6448    }
6449
6450    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6451        if (DEBUG_INSTALL) {
6452            if (chatty)
6453                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6454        }
6455
6456        // writer
6457        synchronized (mPackages) {
6458            mPackages.remove(pkg.applicationInfo.packageName);
6459            if (pkg.codePath != null) {
6460                mAppDirs.remove(pkg.codePath);
6461            }
6462            cleanPackageDataStructuresLILPw(pkg, chatty);
6463        }
6464    }
6465
6466    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6467        int N = pkg.providers.size();
6468        StringBuilder r = null;
6469        int i;
6470        for (i=0; i<N; i++) {
6471            PackageParser.Provider p = pkg.providers.get(i);
6472            mProviders.removeProvider(p);
6473            if (p.info.authority == null) {
6474
6475                /* There was another ContentProvider with this authority when
6476                 * this app was installed so this authority is null,
6477                 * Ignore it as we don't have to unregister the provider.
6478                 */
6479                continue;
6480            }
6481            String names[] = p.info.authority.split(";");
6482            for (int j = 0; j < names.length; j++) {
6483                if (mProvidersByAuthority.get(names[j]) == p) {
6484                    mProvidersByAuthority.remove(names[j]);
6485                    if (DEBUG_REMOVE) {
6486                        if (chatty)
6487                            Log.d(TAG, "Unregistered content provider: " + names[j]
6488                                    + ", className = " + p.info.name + ", isSyncable = "
6489                                    + p.info.isSyncable);
6490                    }
6491                }
6492            }
6493            if (DEBUG_REMOVE && chatty) {
6494                if (r == null) {
6495                    r = new StringBuilder(256);
6496                } else {
6497                    r.append(' ');
6498                }
6499                r.append(p.info.name);
6500            }
6501        }
6502        if (r != null) {
6503            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6504        }
6505
6506        N = pkg.services.size();
6507        r = null;
6508        for (i=0; i<N; i++) {
6509            PackageParser.Service s = pkg.services.get(i);
6510            mServices.removeService(s);
6511            if (chatty) {
6512                if (r == null) {
6513                    r = new StringBuilder(256);
6514                } else {
6515                    r.append(' ');
6516                }
6517                r.append(s.info.name);
6518            }
6519        }
6520        if (r != null) {
6521            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6522        }
6523
6524        N = pkg.receivers.size();
6525        r = null;
6526        for (i=0; i<N; i++) {
6527            PackageParser.Activity a = pkg.receivers.get(i);
6528            mReceivers.removeActivity(a, "receiver");
6529            if (DEBUG_REMOVE && chatty) {
6530                if (r == null) {
6531                    r = new StringBuilder(256);
6532                } else {
6533                    r.append(' ');
6534                }
6535                r.append(a.info.name);
6536            }
6537        }
6538        if (r != null) {
6539            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6540        }
6541
6542        N = pkg.activities.size();
6543        r = null;
6544        for (i=0; i<N; i++) {
6545            PackageParser.Activity a = pkg.activities.get(i);
6546            mActivities.removeActivity(a, "activity");
6547            if (DEBUG_REMOVE && chatty) {
6548                if (r == null) {
6549                    r = new StringBuilder(256);
6550                } else {
6551                    r.append(' ');
6552                }
6553                r.append(a.info.name);
6554            }
6555        }
6556        if (r != null) {
6557            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6558        }
6559
6560        N = pkg.permissions.size();
6561        r = null;
6562        for (i=0; i<N; i++) {
6563            PackageParser.Permission p = pkg.permissions.get(i);
6564            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6565            if (bp == null) {
6566                bp = mSettings.mPermissionTrees.get(p.info.name);
6567            }
6568            if (bp != null && bp.perm == p) {
6569                bp.perm = null;
6570                if (DEBUG_REMOVE && chatty) {
6571                    if (r == null) {
6572                        r = new StringBuilder(256);
6573                    } else {
6574                        r.append(' ');
6575                    }
6576                    r.append(p.info.name);
6577                }
6578            }
6579        }
6580        if (r != null) {
6581            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6582        }
6583
6584        N = pkg.instrumentation.size();
6585        r = null;
6586        for (i=0; i<N; i++) {
6587            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6588            mInstrumentation.remove(a.getComponentName());
6589            if (DEBUG_REMOVE && chatty) {
6590                if (r == null) {
6591                    r = new StringBuilder(256);
6592                } else {
6593                    r.append(' ');
6594                }
6595                r.append(a.info.name);
6596            }
6597        }
6598        if (r != null) {
6599            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6600        }
6601
6602        r = null;
6603        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6604            // Only system apps can hold shared libraries.
6605            if (pkg.libraryNames != null) {
6606                for (i=0; i<pkg.libraryNames.size(); i++) {
6607                    String name = pkg.libraryNames.get(i);
6608                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6609                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6610                        mSharedLibraries.remove(name);
6611                        if (DEBUG_REMOVE && chatty) {
6612                            if (r == null) {
6613                                r = new StringBuilder(256);
6614                            } else {
6615                                r.append(' ');
6616                            }
6617                            r.append(name);
6618                        }
6619                    }
6620                }
6621            }
6622        }
6623        if (r != null) {
6624            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6625        }
6626    }
6627
6628    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6629        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6630            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6631                return true;
6632            }
6633        }
6634        return false;
6635    }
6636
6637    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6638    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6639    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6640
6641    private void updatePermissionsLPw(String changingPkg,
6642            PackageParser.Package pkgInfo, int flags) {
6643        // Make sure there are no dangling permission trees.
6644        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6645        while (it.hasNext()) {
6646            final BasePermission bp = it.next();
6647            if (bp.packageSetting == null) {
6648                // We may not yet have parsed the package, so just see if
6649                // we still know about its settings.
6650                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6651            }
6652            if (bp.packageSetting == null) {
6653                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6654                        + " from package " + bp.sourcePackage);
6655                it.remove();
6656            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6657                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6658                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6659                            + " from package " + bp.sourcePackage);
6660                    flags |= UPDATE_PERMISSIONS_ALL;
6661                    it.remove();
6662                }
6663            }
6664        }
6665
6666        // Make sure all dynamic permissions have been assigned to a package,
6667        // and make sure there are no dangling permissions.
6668        it = mSettings.mPermissions.values().iterator();
6669        while (it.hasNext()) {
6670            final BasePermission bp = it.next();
6671            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6672                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6673                        + bp.name + " pkg=" + bp.sourcePackage
6674                        + " info=" + bp.pendingInfo);
6675                if (bp.packageSetting == null && bp.pendingInfo != null) {
6676                    final BasePermission tree = findPermissionTreeLP(bp.name);
6677                    if (tree != null && tree.perm != null) {
6678                        bp.packageSetting = tree.packageSetting;
6679                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6680                                new PermissionInfo(bp.pendingInfo));
6681                        bp.perm.info.packageName = tree.perm.info.packageName;
6682                        bp.perm.info.name = bp.name;
6683                        bp.uid = tree.uid;
6684                    }
6685                }
6686            }
6687            if (bp.packageSetting == null) {
6688                // We may not yet have parsed the package, so just see if
6689                // we still know about its settings.
6690                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6691            }
6692            if (bp.packageSetting == null) {
6693                Slog.w(TAG, "Removing dangling permission: " + bp.name
6694                        + " from package " + bp.sourcePackage);
6695                it.remove();
6696            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6697                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6698                    Slog.i(TAG, "Removing old permission: " + bp.name
6699                            + " from package " + bp.sourcePackage);
6700                    flags |= UPDATE_PERMISSIONS_ALL;
6701                    it.remove();
6702                }
6703            }
6704        }
6705
6706        // Now update the permissions for all packages, in particular
6707        // replace the granted permissions of the system packages.
6708        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6709            for (PackageParser.Package pkg : mPackages.values()) {
6710                if (pkg != pkgInfo) {
6711                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6712                }
6713            }
6714        }
6715
6716        if (pkgInfo != null) {
6717            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6718        }
6719    }
6720
6721    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6722        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6723        if (ps == null) {
6724            return;
6725        }
6726        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6727        HashSet<String> origPermissions = gp.grantedPermissions;
6728        boolean changedPermission = false;
6729
6730        if (replace) {
6731            ps.permissionsFixed = false;
6732            if (gp == ps) {
6733                origPermissions = new HashSet<String>(gp.grantedPermissions);
6734                gp.grantedPermissions.clear();
6735                gp.gids = mGlobalGids;
6736            }
6737        }
6738
6739        if (gp.gids == null) {
6740            gp.gids = mGlobalGids;
6741        }
6742
6743        final int N = pkg.requestedPermissions.size();
6744        for (int i=0; i<N; i++) {
6745            final String name = pkg.requestedPermissions.get(i);
6746            final boolean required = pkg.requestedPermissionsRequired.get(i);
6747            final BasePermission bp = mSettings.mPermissions.get(name);
6748            if (DEBUG_INSTALL) {
6749                if (gp != ps) {
6750                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6751                }
6752            }
6753
6754            if (bp == null || bp.packageSetting == null) {
6755                Slog.w(TAG, "Unknown permission " + name
6756                        + " in package " + pkg.packageName);
6757                continue;
6758            }
6759
6760            final String perm = bp.name;
6761            boolean allowed;
6762            boolean allowedSig = false;
6763            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6764            if (level == PermissionInfo.PROTECTION_NORMAL
6765                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6766                // We grant a normal or dangerous permission if any of the following
6767                // are true:
6768                // 1) The permission is required
6769                // 2) The permission is optional, but was granted in the past
6770                // 3) The permission is optional, but was requested by an
6771                //    app in /system (not /data)
6772                //
6773                // Otherwise, reject the permission.
6774                allowed = (required || origPermissions.contains(perm)
6775                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6776            } else if (bp.packageSetting == null) {
6777                // This permission is invalid; skip it.
6778                allowed = false;
6779            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6780                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6781                if (allowed) {
6782                    allowedSig = true;
6783                }
6784            } else {
6785                allowed = false;
6786            }
6787            if (DEBUG_INSTALL) {
6788                if (gp != ps) {
6789                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6790                }
6791            }
6792            if (allowed) {
6793                if (!isSystemApp(ps) && ps.permissionsFixed) {
6794                    // If this is an existing, non-system package, then
6795                    // we can't add any new permissions to it.
6796                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6797                        // Except...  if this is a permission that was added
6798                        // to the platform (note: need to only do this when
6799                        // updating the platform).
6800                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6801                    }
6802                }
6803                if (allowed) {
6804                    if (!gp.grantedPermissions.contains(perm)) {
6805                        changedPermission = true;
6806                        gp.grantedPermissions.add(perm);
6807                        gp.gids = appendInts(gp.gids, bp.gids);
6808                    } else if (!ps.haveGids) {
6809                        gp.gids = appendInts(gp.gids, bp.gids);
6810                    }
6811                } else {
6812                    Slog.w(TAG, "Not granting permission " + perm
6813                            + " to package " + pkg.packageName
6814                            + " because it was previously installed without");
6815                }
6816            } else {
6817                if (gp.grantedPermissions.remove(perm)) {
6818                    changedPermission = true;
6819                    gp.gids = removeInts(gp.gids, bp.gids);
6820                    Slog.i(TAG, "Un-granting permission " + perm
6821                            + " from package " + pkg.packageName
6822                            + " (protectionLevel=" + bp.protectionLevel
6823                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6824                            + ")");
6825                } else {
6826                    Slog.w(TAG, "Not granting permission " + perm
6827                            + " to package " + pkg.packageName
6828                            + " (protectionLevel=" + bp.protectionLevel
6829                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6830                            + ")");
6831                }
6832            }
6833        }
6834
6835        if ((changedPermission || replace) && !ps.permissionsFixed &&
6836                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6837            // This is the first that we have heard about this package, so the
6838            // permissions we have now selected are fixed until explicitly
6839            // changed.
6840            ps.permissionsFixed = true;
6841        }
6842        ps.haveGids = true;
6843    }
6844
6845    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6846        boolean allowed = false;
6847        final int NP = PackageParser.NEW_PERMISSIONS.length;
6848        for (int ip=0; ip<NP; ip++) {
6849            final PackageParser.NewPermissionInfo npi
6850                    = PackageParser.NEW_PERMISSIONS[ip];
6851            if (npi.name.equals(perm)
6852                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6853                allowed = true;
6854                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6855                        + pkg.packageName);
6856                break;
6857            }
6858        }
6859        return allowed;
6860    }
6861
6862    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6863                                          BasePermission bp, HashSet<String> origPermissions) {
6864        boolean allowed;
6865        allowed = (compareSignatures(
6866                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6867                        == PackageManager.SIGNATURE_MATCH)
6868                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6869                        == PackageManager.SIGNATURE_MATCH);
6870        if (!allowed && (bp.protectionLevel
6871                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6872            if (isSystemApp(pkg)) {
6873                // For updated system applications, a system permission
6874                // is granted only if it had been defined by the original application.
6875                if (isUpdatedSystemApp(pkg)) {
6876                    final PackageSetting sysPs = mSettings
6877                            .getDisabledSystemPkgLPr(pkg.packageName);
6878                    final GrantedPermissions origGp = sysPs.sharedUser != null
6879                            ? sysPs.sharedUser : sysPs;
6880
6881                    if (origGp.grantedPermissions.contains(perm)) {
6882                        // If the original was granted this permission, we take
6883                        // that grant decision as read and propagate it to the
6884                        // update.
6885                        allowed = true;
6886                    } else {
6887                        // The system apk may have been updated with an older
6888                        // version of the one on the data partition, but which
6889                        // granted a new system permission that it didn't have
6890                        // before.  In this case we do want to allow the app to
6891                        // now get the new permission if the ancestral apk is
6892                        // privileged to get it.
6893                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6894                            for (int j=0;
6895                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6896                                if (perm.equals(
6897                                        sysPs.pkg.requestedPermissions.get(j))) {
6898                                    allowed = true;
6899                                    break;
6900                                }
6901                            }
6902                        }
6903                    }
6904                } else {
6905                    allowed = isPrivilegedApp(pkg);
6906                }
6907            }
6908        }
6909        if (!allowed && (bp.protectionLevel
6910                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6911            // For development permissions, a development permission
6912            // is granted only if it was already granted.
6913            allowed = origPermissions.contains(perm);
6914        }
6915        return allowed;
6916    }
6917
6918    final class ActivityIntentResolver
6919            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6920        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6921                boolean defaultOnly, int userId) {
6922            if (!sUserManager.exists(userId)) return null;
6923            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6924            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6925        }
6926
6927        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6928                int userId) {
6929            if (!sUserManager.exists(userId)) return null;
6930            mFlags = flags;
6931            return super.queryIntent(intent, resolvedType,
6932                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6933        }
6934
6935        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6936                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6937            if (!sUserManager.exists(userId)) return null;
6938            if (packageActivities == null) {
6939                return null;
6940            }
6941            mFlags = flags;
6942            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6943            final int N = packageActivities.size();
6944            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6945                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6946
6947            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6948            for (int i = 0; i < N; ++i) {
6949                intentFilters = packageActivities.get(i).intents;
6950                if (intentFilters != null && intentFilters.size() > 0) {
6951                    PackageParser.ActivityIntentInfo[] array =
6952                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6953                    intentFilters.toArray(array);
6954                    listCut.add(array);
6955                }
6956            }
6957            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6958        }
6959
6960        public final void addActivity(PackageParser.Activity a, String type) {
6961            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6962            mActivities.put(a.getComponentName(), a);
6963            if (DEBUG_SHOW_INFO)
6964                Log.v(
6965                TAG, "  " + type + " " +
6966                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6967            if (DEBUG_SHOW_INFO)
6968                Log.v(TAG, "    Class=" + a.info.name);
6969            final int NI = a.intents.size();
6970            for (int j=0; j<NI; j++) {
6971                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6972                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6973                    intent.setPriority(0);
6974                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6975                            + a.className + " with priority > 0, forcing to 0");
6976                }
6977                if (DEBUG_SHOW_INFO) {
6978                    Log.v(TAG, "    IntentFilter:");
6979                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6980                }
6981                if (!intent.debugCheck()) {
6982                    Log.w(TAG, "==> For Activity " + a.info.name);
6983                }
6984                addFilter(intent);
6985            }
6986        }
6987
6988        public final void removeActivity(PackageParser.Activity a, String type) {
6989            mActivities.remove(a.getComponentName());
6990            if (DEBUG_SHOW_INFO) {
6991                Log.v(TAG, "  " + type + " "
6992                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6993                                : a.info.name) + ":");
6994                Log.v(TAG, "    Class=" + a.info.name);
6995            }
6996            final int NI = a.intents.size();
6997            for (int j=0; j<NI; j++) {
6998                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6999                if (DEBUG_SHOW_INFO) {
7000                    Log.v(TAG, "    IntentFilter:");
7001                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7002                }
7003                removeFilter(intent);
7004            }
7005        }
7006
7007        @Override
7008        protected boolean allowFilterResult(
7009                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7010            ActivityInfo filterAi = filter.activity.info;
7011            for (int i=dest.size()-1; i>=0; i--) {
7012                ActivityInfo destAi = dest.get(i).activityInfo;
7013                if (destAi.name == filterAi.name
7014                        && destAi.packageName == filterAi.packageName) {
7015                    return false;
7016                }
7017            }
7018            return true;
7019        }
7020
7021        @Override
7022        protected ActivityIntentInfo[] newArray(int size) {
7023            return new ActivityIntentInfo[size];
7024        }
7025
7026        @Override
7027        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7028            if (!sUserManager.exists(userId)) return true;
7029            PackageParser.Package p = filter.activity.owner;
7030            if (p != null) {
7031                PackageSetting ps = (PackageSetting)p.mExtras;
7032                if (ps != null) {
7033                    // System apps are never considered stopped for purposes of
7034                    // filtering, because there may be no way for the user to
7035                    // actually re-launch them.
7036                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7037                            && ps.getStopped(userId);
7038                }
7039            }
7040            return false;
7041        }
7042
7043        @Override
7044        protected boolean isPackageForFilter(String packageName,
7045                PackageParser.ActivityIntentInfo info) {
7046            return packageName.equals(info.activity.owner.packageName);
7047        }
7048
7049        @Override
7050        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7051                int match, int userId) {
7052            if (!sUserManager.exists(userId)) return null;
7053            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7054                return null;
7055            }
7056            final PackageParser.Activity activity = info.activity;
7057            if (mSafeMode && (activity.info.applicationInfo.flags
7058                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7059                return null;
7060            }
7061            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7062            if (ps == null) {
7063                return null;
7064            }
7065            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7066                    ps.readUserState(userId), userId);
7067            if (ai == null) {
7068                return null;
7069            }
7070            final ResolveInfo res = new ResolveInfo();
7071            res.activityInfo = ai;
7072            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7073                res.filter = info;
7074            }
7075            res.priority = info.getPriority();
7076            res.preferredOrder = activity.owner.mPreferredOrder;
7077            //System.out.println("Result: " + res.activityInfo.className +
7078            //                   " = " + res.priority);
7079            res.match = match;
7080            res.isDefault = info.hasDefault;
7081            res.labelRes = info.labelRes;
7082            res.nonLocalizedLabel = info.nonLocalizedLabel;
7083            if (userNeedsBadging(userId)) {
7084                res.noResourceId = true;
7085            } else {
7086                res.icon = info.icon;
7087            }
7088            res.system = isSystemApp(res.activityInfo.applicationInfo);
7089            return res;
7090        }
7091
7092        @Override
7093        protected void sortResults(List<ResolveInfo> results) {
7094            Collections.sort(results, mResolvePrioritySorter);
7095        }
7096
7097        @Override
7098        protected void dumpFilter(PrintWriter out, String prefix,
7099                PackageParser.ActivityIntentInfo filter) {
7100            out.print(prefix); out.print(
7101                    Integer.toHexString(System.identityHashCode(filter.activity)));
7102                    out.print(' ');
7103                    filter.activity.printComponentShortName(out);
7104                    out.print(" filter ");
7105                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7106        }
7107
7108//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7109//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7110//            final List<ResolveInfo> retList = Lists.newArrayList();
7111//            while (i.hasNext()) {
7112//                final ResolveInfo resolveInfo = i.next();
7113//                if (isEnabledLP(resolveInfo.activityInfo)) {
7114//                    retList.add(resolveInfo);
7115//                }
7116//            }
7117//            return retList;
7118//        }
7119
7120        // Keys are String (activity class name), values are Activity.
7121        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7122                = new HashMap<ComponentName, PackageParser.Activity>();
7123        private int mFlags;
7124    }
7125
7126    private final class ServiceIntentResolver
7127            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7128        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7129                boolean defaultOnly, int userId) {
7130            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7131            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7132        }
7133
7134        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7135                int userId) {
7136            if (!sUserManager.exists(userId)) return null;
7137            mFlags = flags;
7138            return super.queryIntent(intent, resolvedType,
7139                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7140        }
7141
7142        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7143                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7144            if (!sUserManager.exists(userId)) return null;
7145            if (packageServices == null) {
7146                return null;
7147            }
7148            mFlags = flags;
7149            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7150            final int N = packageServices.size();
7151            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7152                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7153
7154            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7155            for (int i = 0; i < N; ++i) {
7156                intentFilters = packageServices.get(i).intents;
7157                if (intentFilters != null && intentFilters.size() > 0) {
7158                    PackageParser.ServiceIntentInfo[] array =
7159                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7160                    intentFilters.toArray(array);
7161                    listCut.add(array);
7162                }
7163            }
7164            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7165        }
7166
7167        public final void addService(PackageParser.Service s) {
7168            mServices.put(s.getComponentName(), s);
7169            if (DEBUG_SHOW_INFO) {
7170                Log.v(TAG, "  "
7171                        + (s.info.nonLocalizedLabel != null
7172                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7173                Log.v(TAG, "    Class=" + s.info.name);
7174            }
7175            final int NI = s.intents.size();
7176            int j;
7177            for (j=0; j<NI; j++) {
7178                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7179                if (DEBUG_SHOW_INFO) {
7180                    Log.v(TAG, "    IntentFilter:");
7181                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7182                }
7183                if (!intent.debugCheck()) {
7184                    Log.w(TAG, "==> For Service " + s.info.name);
7185                }
7186                addFilter(intent);
7187            }
7188        }
7189
7190        public final void removeService(PackageParser.Service s) {
7191            mServices.remove(s.getComponentName());
7192            if (DEBUG_SHOW_INFO) {
7193                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7194                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7195                Log.v(TAG, "    Class=" + s.info.name);
7196            }
7197            final int NI = s.intents.size();
7198            int j;
7199            for (j=0; j<NI; j++) {
7200                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7201                if (DEBUG_SHOW_INFO) {
7202                    Log.v(TAG, "    IntentFilter:");
7203                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7204                }
7205                removeFilter(intent);
7206            }
7207        }
7208
7209        @Override
7210        protected boolean allowFilterResult(
7211                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7212            ServiceInfo filterSi = filter.service.info;
7213            for (int i=dest.size()-1; i>=0; i--) {
7214                ServiceInfo destAi = dest.get(i).serviceInfo;
7215                if (destAi.name == filterSi.name
7216                        && destAi.packageName == filterSi.packageName) {
7217                    return false;
7218                }
7219            }
7220            return true;
7221        }
7222
7223        @Override
7224        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7225            return new PackageParser.ServiceIntentInfo[size];
7226        }
7227
7228        @Override
7229        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7230            if (!sUserManager.exists(userId)) return true;
7231            PackageParser.Package p = filter.service.owner;
7232            if (p != null) {
7233                PackageSetting ps = (PackageSetting)p.mExtras;
7234                if (ps != null) {
7235                    // System apps are never considered stopped for purposes of
7236                    // filtering, because there may be no way for the user to
7237                    // actually re-launch them.
7238                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7239                            && ps.getStopped(userId);
7240                }
7241            }
7242            return false;
7243        }
7244
7245        @Override
7246        protected boolean isPackageForFilter(String packageName,
7247                PackageParser.ServiceIntentInfo info) {
7248            return packageName.equals(info.service.owner.packageName);
7249        }
7250
7251        @Override
7252        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7253                int match, int userId) {
7254            if (!sUserManager.exists(userId)) return null;
7255            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7256            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7257                return null;
7258            }
7259            final PackageParser.Service service = info.service;
7260            if (mSafeMode && (service.info.applicationInfo.flags
7261                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7262                return null;
7263            }
7264            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7265            if (ps == null) {
7266                return null;
7267            }
7268            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7269                    ps.readUserState(userId), userId);
7270            if (si == null) {
7271                return null;
7272            }
7273            final ResolveInfo res = new ResolveInfo();
7274            res.serviceInfo = si;
7275            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7276                res.filter = filter;
7277            }
7278            res.priority = info.getPriority();
7279            res.preferredOrder = service.owner.mPreferredOrder;
7280            //System.out.println("Result: " + res.activityInfo.className +
7281            //                   " = " + res.priority);
7282            res.match = match;
7283            res.isDefault = info.hasDefault;
7284            res.labelRes = info.labelRes;
7285            res.nonLocalizedLabel = info.nonLocalizedLabel;
7286            res.icon = info.icon;
7287            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7288            return res;
7289        }
7290
7291        @Override
7292        protected void sortResults(List<ResolveInfo> results) {
7293            Collections.sort(results, mResolvePrioritySorter);
7294        }
7295
7296        @Override
7297        protected void dumpFilter(PrintWriter out, String prefix,
7298                PackageParser.ServiceIntentInfo filter) {
7299            out.print(prefix); out.print(
7300                    Integer.toHexString(System.identityHashCode(filter.service)));
7301                    out.print(' ');
7302                    filter.service.printComponentShortName(out);
7303                    out.print(" filter ");
7304                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7305        }
7306
7307//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7308//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7309//            final List<ResolveInfo> retList = Lists.newArrayList();
7310//            while (i.hasNext()) {
7311//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7312//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7313//                    retList.add(resolveInfo);
7314//                }
7315//            }
7316//            return retList;
7317//        }
7318
7319        // Keys are String (activity class name), values are Activity.
7320        private final HashMap<ComponentName, PackageParser.Service> mServices
7321                = new HashMap<ComponentName, PackageParser.Service>();
7322        private int mFlags;
7323    };
7324
7325    private final class ProviderIntentResolver
7326            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7327        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7328                boolean defaultOnly, int userId) {
7329            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7330            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7331        }
7332
7333        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7334                int userId) {
7335            if (!sUserManager.exists(userId))
7336                return null;
7337            mFlags = flags;
7338            return super.queryIntent(intent, resolvedType,
7339                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7340        }
7341
7342        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7343                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7344            if (!sUserManager.exists(userId))
7345                return null;
7346            if (packageProviders == null) {
7347                return null;
7348            }
7349            mFlags = flags;
7350            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7351            final int N = packageProviders.size();
7352            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7353                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7354
7355            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7356            for (int i = 0; i < N; ++i) {
7357                intentFilters = packageProviders.get(i).intents;
7358                if (intentFilters != null && intentFilters.size() > 0) {
7359                    PackageParser.ProviderIntentInfo[] array =
7360                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7361                    intentFilters.toArray(array);
7362                    listCut.add(array);
7363                }
7364            }
7365            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7366        }
7367
7368        public final void addProvider(PackageParser.Provider p) {
7369            if (mProviders.containsKey(p.getComponentName())) {
7370                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7371                return;
7372            }
7373
7374            mProviders.put(p.getComponentName(), p);
7375            if (DEBUG_SHOW_INFO) {
7376                Log.v(TAG, "  "
7377                        + (p.info.nonLocalizedLabel != null
7378                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7379                Log.v(TAG, "    Class=" + p.info.name);
7380            }
7381            final int NI = p.intents.size();
7382            int j;
7383            for (j = 0; j < NI; j++) {
7384                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7385                if (DEBUG_SHOW_INFO) {
7386                    Log.v(TAG, "    IntentFilter:");
7387                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7388                }
7389                if (!intent.debugCheck()) {
7390                    Log.w(TAG, "==> For Provider " + p.info.name);
7391                }
7392                addFilter(intent);
7393            }
7394        }
7395
7396        public final void removeProvider(PackageParser.Provider p) {
7397            mProviders.remove(p.getComponentName());
7398            if (DEBUG_SHOW_INFO) {
7399                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7400                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7401                Log.v(TAG, "    Class=" + p.info.name);
7402            }
7403            final int NI = p.intents.size();
7404            int j;
7405            for (j = 0; j < NI; j++) {
7406                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7407                if (DEBUG_SHOW_INFO) {
7408                    Log.v(TAG, "    IntentFilter:");
7409                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7410                }
7411                removeFilter(intent);
7412            }
7413        }
7414
7415        @Override
7416        protected boolean allowFilterResult(
7417                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7418            ProviderInfo filterPi = filter.provider.info;
7419            for (int i = dest.size() - 1; i >= 0; i--) {
7420                ProviderInfo destPi = dest.get(i).providerInfo;
7421                if (destPi.name == filterPi.name
7422                        && destPi.packageName == filterPi.packageName) {
7423                    return false;
7424                }
7425            }
7426            return true;
7427        }
7428
7429        @Override
7430        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7431            return new PackageParser.ProviderIntentInfo[size];
7432        }
7433
7434        @Override
7435        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7436            if (!sUserManager.exists(userId))
7437                return true;
7438            PackageParser.Package p = filter.provider.owner;
7439            if (p != null) {
7440                PackageSetting ps = (PackageSetting) p.mExtras;
7441                if (ps != null) {
7442                    // System apps are never considered stopped for purposes of
7443                    // filtering, because there may be no way for the user to
7444                    // actually re-launch them.
7445                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7446                            && ps.getStopped(userId);
7447                }
7448            }
7449            return false;
7450        }
7451
7452        @Override
7453        protected boolean isPackageForFilter(String packageName,
7454                PackageParser.ProviderIntentInfo info) {
7455            return packageName.equals(info.provider.owner.packageName);
7456        }
7457
7458        @Override
7459        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7460                int match, int userId) {
7461            if (!sUserManager.exists(userId))
7462                return null;
7463            final PackageParser.ProviderIntentInfo info = filter;
7464            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7465                return null;
7466            }
7467            final PackageParser.Provider provider = info.provider;
7468            if (mSafeMode && (provider.info.applicationInfo.flags
7469                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7470                return null;
7471            }
7472            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7473            if (ps == null) {
7474                return null;
7475            }
7476            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7477                    ps.readUserState(userId), userId);
7478            if (pi == null) {
7479                return null;
7480            }
7481            final ResolveInfo res = new ResolveInfo();
7482            res.providerInfo = pi;
7483            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7484                res.filter = filter;
7485            }
7486            res.priority = info.getPriority();
7487            res.preferredOrder = provider.owner.mPreferredOrder;
7488            res.match = match;
7489            res.isDefault = info.hasDefault;
7490            res.labelRes = info.labelRes;
7491            res.nonLocalizedLabel = info.nonLocalizedLabel;
7492            res.icon = info.icon;
7493            res.system = isSystemApp(res.providerInfo.applicationInfo);
7494            return res;
7495        }
7496
7497        @Override
7498        protected void sortResults(List<ResolveInfo> results) {
7499            Collections.sort(results, mResolvePrioritySorter);
7500        }
7501
7502        @Override
7503        protected void dumpFilter(PrintWriter out, String prefix,
7504                PackageParser.ProviderIntentInfo filter) {
7505            out.print(prefix);
7506            out.print(
7507                    Integer.toHexString(System.identityHashCode(filter.provider)));
7508            out.print(' ');
7509            filter.provider.printComponentShortName(out);
7510            out.print(" filter ");
7511            out.println(Integer.toHexString(System.identityHashCode(filter)));
7512        }
7513
7514        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7515                = new HashMap<ComponentName, PackageParser.Provider>();
7516        private int mFlags;
7517    };
7518
7519    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7520            new Comparator<ResolveInfo>() {
7521        public int compare(ResolveInfo r1, ResolveInfo r2) {
7522            int v1 = r1.priority;
7523            int v2 = r2.priority;
7524            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7525            if (v1 != v2) {
7526                return (v1 > v2) ? -1 : 1;
7527            }
7528            v1 = r1.preferredOrder;
7529            v2 = r2.preferredOrder;
7530            if (v1 != v2) {
7531                return (v1 > v2) ? -1 : 1;
7532            }
7533            if (r1.isDefault != r2.isDefault) {
7534                return r1.isDefault ? -1 : 1;
7535            }
7536            v1 = r1.match;
7537            v2 = r2.match;
7538            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7539            if (v1 != v2) {
7540                return (v1 > v2) ? -1 : 1;
7541            }
7542            if (r1.system != r2.system) {
7543                return r1.system ? -1 : 1;
7544            }
7545            return 0;
7546        }
7547    };
7548
7549    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7550            new Comparator<ProviderInfo>() {
7551        public int compare(ProviderInfo p1, ProviderInfo p2) {
7552            final int v1 = p1.initOrder;
7553            final int v2 = p2.initOrder;
7554            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7555        }
7556    };
7557
7558    static final void sendPackageBroadcast(String action, String pkg,
7559            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7560            int[] userIds) {
7561        IActivityManager am = ActivityManagerNative.getDefault();
7562        if (am != null) {
7563            try {
7564                if (userIds == null) {
7565                    userIds = am.getRunningUserIds();
7566                }
7567                for (int id : userIds) {
7568                    final Intent intent = new Intent(action,
7569                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7570                    if (extras != null) {
7571                        intent.putExtras(extras);
7572                    }
7573                    if (targetPkg != null) {
7574                        intent.setPackage(targetPkg);
7575                    }
7576                    // Modify the UID when posting to other users
7577                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7578                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7579                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7580                        intent.putExtra(Intent.EXTRA_UID, uid);
7581                    }
7582                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7583                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7584                    if (DEBUG_BROADCASTS) {
7585                        RuntimeException here = new RuntimeException("here");
7586                        here.fillInStackTrace();
7587                        Slog.d(TAG, "Sending to user " + id + ": "
7588                                + intent.toShortString(false, true, false, false)
7589                                + " " + intent.getExtras(), here);
7590                    }
7591                    am.broadcastIntent(null, intent, null, finishedReceiver,
7592                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7593                            finishedReceiver != null, false, id);
7594                }
7595            } catch (RemoteException ex) {
7596            }
7597        }
7598    }
7599
7600    /**
7601     * Check if the external storage media is available. This is true if there
7602     * is a mounted external storage medium or if the external storage is
7603     * emulated.
7604     */
7605    private boolean isExternalMediaAvailable() {
7606        return mMediaMounted || Environment.isExternalStorageEmulated();
7607    }
7608
7609    @Override
7610    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7611        // writer
7612        synchronized (mPackages) {
7613            if (!isExternalMediaAvailable()) {
7614                // If the external storage is no longer mounted at this point,
7615                // the caller may not have been able to delete all of this
7616                // packages files and can not delete any more.  Bail.
7617                return null;
7618            }
7619            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7620            if (lastPackage != null) {
7621                pkgs.remove(lastPackage);
7622            }
7623            if (pkgs.size() > 0) {
7624                return pkgs.get(0);
7625            }
7626        }
7627        return null;
7628    }
7629
7630    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7631        if (false) {
7632            RuntimeException here = new RuntimeException("here");
7633            here.fillInStackTrace();
7634            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7635                    + " andCode=" + andCode, here);
7636        }
7637        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7638                userId, andCode ? 1 : 0, packageName));
7639    }
7640
7641    void startCleaningPackages() {
7642        // reader
7643        synchronized (mPackages) {
7644            if (!isExternalMediaAvailable()) {
7645                return;
7646            }
7647            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7648                return;
7649            }
7650        }
7651        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7652        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7653        IActivityManager am = ActivityManagerNative.getDefault();
7654        if (am != null) {
7655            try {
7656                am.startService(null, intent, null, UserHandle.USER_OWNER);
7657            } catch (RemoteException e) {
7658            }
7659        }
7660    }
7661
7662    private final class AppDirObserver extends FileObserver {
7663        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7664            super(path, mask);
7665            mRootDir = path;
7666            mIsRom = isrom;
7667            mIsPrivileged = isPrivileged;
7668        }
7669
7670        public void onEvent(int event, String path) {
7671            String removedPackage = null;
7672            int removedAppId = -1;
7673            int[] removedUsers = null;
7674            String addedPackage = null;
7675            int addedAppId = -1;
7676            int[] addedUsers = null;
7677
7678            // TODO post a message to the handler to obtain serial ordering
7679            synchronized (mInstallLock) {
7680                String fullPathStr = null;
7681                File fullPath = null;
7682                if (path != null) {
7683                    fullPath = new File(mRootDir, path);
7684                    fullPathStr = fullPath.getPath();
7685                }
7686
7687                if (DEBUG_APP_DIR_OBSERVER)
7688                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7689
7690                if (!isApkFile(fullPath)) {
7691                    if (DEBUG_APP_DIR_OBSERVER)
7692                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7693                    return;
7694                }
7695
7696                // Ignore packages that are being installed or
7697                // have just been installed.
7698                if (ignoreCodePath(fullPathStr)) {
7699                    return;
7700                }
7701                PackageParser.Package p = null;
7702                PackageSetting ps = null;
7703                // reader
7704                synchronized (mPackages) {
7705                    p = mAppDirs.get(fullPathStr);
7706                    if (p != null) {
7707                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7708                        if (ps != null) {
7709                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7710                        } else {
7711                            removedUsers = sUserManager.getUserIds();
7712                        }
7713                    }
7714                    addedUsers = sUserManager.getUserIds();
7715                }
7716                if ((event&REMOVE_EVENTS) != 0) {
7717                    if (ps != null) {
7718                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7719                        removePackageLI(ps, true);
7720                        removedPackage = ps.name;
7721                        removedAppId = ps.appId;
7722                    }
7723                }
7724
7725                if ((event&ADD_EVENTS) != 0) {
7726                    if (p == null) {
7727                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7728                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7729                        if (mIsRom) {
7730                            flags |= PackageParser.PARSE_IS_SYSTEM
7731                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7732                            if (mIsPrivileged) {
7733                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7734                            }
7735                        }
7736                        try {
7737                            p = scanPackageLI(fullPath, flags,
7738                                    SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7739                                    System.currentTimeMillis(), UserHandle.ALL, null);
7740                        } catch (PackageManagerException e) {
7741                            Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage());
7742                            p = null;
7743                        }
7744                        if (p != null) {
7745                            /*
7746                             * TODO this seems dangerous as the package may have
7747                             * changed since we last acquired the mPackages
7748                             * lock.
7749                             */
7750                            // writer
7751                            synchronized (mPackages) {
7752                                updatePermissionsLPw(p.packageName, p,
7753                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7754                            }
7755                            addedPackage = p.applicationInfo.packageName;
7756                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7757                        }
7758                    }
7759                }
7760
7761                // reader
7762                synchronized (mPackages) {
7763                    mSettings.writeLPr();
7764                }
7765            }
7766
7767            if (removedPackage != null) {
7768                Bundle extras = new Bundle(1);
7769                extras.putInt(Intent.EXTRA_UID, removedAppId);
7770                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7771                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7772                        extras, null, null, removedUsers);
7773            }
7774            if (addedPackage != null) {
7775                Bundle extras = new Bundle(1);
7776                extras.putInt(Intent.EXTRA_UID, addedAppId);
7777                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7778                        extras, null, null, addedUsers);
7779            }
7780        }
7781
7782        private final String mRootDir;
7783        private final boolean mIsRom;
7784        private final boolean mIsPrivileged;
7785    }
7786
7787    @Override
7788    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7789            String installerPackageName, VerificationParams verificationParams,
7790            String packageAbiOverride) {
7791        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7792                null);
7793
7794        final File originFile = new File(originPath);
7795        final int uid = Binder.getCallingUid();
7796        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7797            try {
7798                if (observer != null) {
7799                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null);
7800                }
7801            } catch (RemoteException re) {
7802            }
7803            return;
7804        }
7805
7806        UserHandle user;
7807        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7808            user = UserHandle.ALL;
7809        } else {
7810            user = new UserHandle(UserHandle.getUserId(uid));
7811        }
7812
7813        final int filteredFlags;
7814        if (uid == Process.SHELL_UID || uid == 0) {
7815            if (DEBUG_INSTALL) {
7816                Slog.v(TAG, "Install from ADB");
7817            }
7818            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7819        } else {
7820            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7821        }
7822
7823        verificationParams.setInstallerUid(uid);
7824
7825        final Message msg = mHandler.obtainMessage(INIT_COPY);
7826        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7827                installerPackageName, verificationParams, user, packageAbiOverride);
7828        mHandler.sendMessage(msg);
7829    }
7830
7831    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7832            InstallSessionParams params, String installerPackageName, int installerUid,
7833            UserHandle user) {
7834        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7835                params.referrerUri, installerUid, null);
7836
7837        final Message msg = mHandler.obtainMessage(INIT_COPY);
7838        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7839                installerPackageName, verifParams, user, params.abiOverride);
7840        mHandler.sendMessage(msg);
7841    }
7842
7843    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7844        Bundle extras = new Bundle(1);
7845        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7846
7847        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7848                packageName, extras, null, null, new int[] {userId});
7849        try {
7850            IActivityManager am = ActivityManagerNative.getDefault();
7851            final boolean isSystem =
7852                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7853            if (isSystem && am.isUserRunning(userId, false)) {
7854                // The just-installed/enabled app is bundled on the system, so presumed
7855                // to be able to run automatically without needing an explicit launch.
7856                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7857                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7858                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7859                        .setPackage(packageName);
7860                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7861                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7862            }
7863        } catch (RemoteException e) {
7864            // shouldn't happen
7865            Slog.w(TAG, "Unable to bootstrap installed package", e);
7866        }
7867    }
7868
7869    @Override
7870    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7871            int userId) {
7872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7873        PackageSetting pkgSetting;
7874        final int uid = Binder.getCallingUid();
7875        if (UserHandle.getUserId(uid) != userId) {
7876            mContext.enforceCallingOrSelfPermission(
7877                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7878                    "setApplicationBlockedSetting for user " + userId);
7879        }
7880
7881        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7882            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7883            return false;
7884        }
7885
7886        long callingId = Binder.clearCallingIdentity();
7887        try {
7888            boolean sendAdded = false;
7889            boolean sendRemoved = false;
7890            // writer
7891            synchronized (mPackages) {
7892                pkgSetting = mSettings.mPackages.get(packageName);
7893                if (pkgSetting == null) {
7894                    return false;
7895                }
7896                if (pkgSetting.getBlocked(userId) != blocked) {
7897                    pkgSetting.setBlocked(blocked, userId);
7898                    mSettings.writePackageRestrictionsLPr(userId);
7899                    if (blocked) {
7900                        sendRemoved = true;
7901                    } else {
7902                        sendAdded = true;
7903                    }
7904                }
7905            }
7906            if (sendAdded) {
7907                sendPackageAddedForUser(packageName, pkgSetting, userId);
7908                return true;
7909            }
7910            if (sendRemoved) {
7911                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7912                        "blocking pkg");
7913                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7914            }
7915        } finally {
7916            Binder.restoreCallingIdentity(callingId);
7917        }
7918        return false;
7919    }
7920
7921    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7922            int userId) {
7923        final PackageRemovedInfo info = new PackageRemovedInfo();
7924        info.removedPackage = packageName;
7925        info.removedUsers = new int[] {userId};
7926        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7927        info.sendBroadcast(false, false, false);
7928    }
7929
7930    /**
7931     * Returns true if application is not found or there was an error. Otherwise it returns
7932     * the blocked state of the package for the given user.
7933     */
7934    @Override
7935    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7938                "getApplicationBlocked for user " + userId);
7939        PackageSetting pkgSetting;
7940        long callingId = Binder.clearCallingIdentity();
7941        try {
7942            // writer
7943            synchronized (mPackages) {
7944                pkgSetting = mSettings.mPackages.get(packageName);
7945                if (pkgSetting == null) {
7946                    return true;
7947                }
7948                return pkgSetting.getBlocked(userId);
7949            }
7950        } finally {
7951            Binder.restoreCallingIdentity(callingId);
7952        }
7953    }
7954
7955    /**
7956     * @hide
7957     */
7958    @Override
7959    public int installExistingPackageAsUser(String packageName, int userId) {
7960        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7961                null);
7962        PackageSetting pkgSetting;
7963        final int uid = Binder.getCallingUid();
7964        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7965        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7966            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7967        }
7968
7969        long callingId = Binder.clearCallingIdentity();
7970        try {
7971            boolean sendAdded = false;
7972            Bundle extras = new Bundle(1);
7973
7974            // writer
7975            synchronized (mPackages) {
7976                pkgSetting = mSettings.mPackages.get(packageName);
7977                if (pkgSetting == null) {
7978                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7979                }
7980                if (!pkgSetting.getInstalled(userId)) {
7981                    pkgSetting.setInstalled(true, userId);
7982                    pkgSetting.setBlocked(false, userId);
7983                    mSettings.writePackageRestrictionsLPr(userId);
7984                    sendAdded = true;
7985                }
7986            }
7987
7988            if (sendAdded) {
7989                sendPackageAddedForUser(packageName, pkgSetting, userId);
7990            }
7991        } finally {
7992            Binder.restoreCallingIdentity(callingId);
7993        }
7994
7995        return PackageManager.INSTALL_SUCCEEDED;
7996    }
7997
7998    boolean isUserRestricted(int userId, String restrictionKey) {
7999        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8000        if (restrictions.getBoolean(restrictionKey, false)) {
8001            Log.w(TAG, "User is restricted: " + restrictionKey);
8002            return true;
8003        }
8004        return false;
8005    }
8006
8007    @Override
8008    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8009        mContext.enforceCallingOrSelfPermission(
8010                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8011                "Only package verification agents can verify applications");
8012
8013        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8014        final PackageVerificationResponse response = new PackageVerificationResponse(
8015                verificationCode, Binder.getCallingUid());
8016        msg.arg1 = id;
8017        msg.obj = response;
8018        mHandler.sendMessage(msg);
8019    }
8020
8021    @Override
8022    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8023            long millisecondsToDelay) {
8024        mContext.enforceCallingOrSelfPermission(
8025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8026                "Only package verification agents can extend verification timeouts");
8027
8028        final PackageVerificationState state = mPendingVerification.get(id);
8029        final PackageVerificationResponse response = new PackageVerificationResponse(
8030                verificationCodeAtTimeout, Binder.getCallingUid());
8031
8032        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8033            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8034        }
8035        if (millisecondsToDelay < 0) {
8036            millisecondsToDelay = 0;
8037        }
8038        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8039                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8040            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8041        }
8042
8043        if ((state != null) && !state.timeoutExtended()) {
8044            state.extendTimeout();
8045
8046            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8047            msg.arg1 = id;
8048            msg.obj = response;
8049            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8050        }
8051    }
8052
8053    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8054            int verificationCode, UserHandle user) {
8055        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8056        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8057        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8058        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8059        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8060
8061        mContext.sendBroadcastAsUser(intent, user,
8062                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8063    }
8064
8065    private ComponentName matchComponentForVerifier(String packageName,
8066            List<ResolveInfo> receivers) {
8067        ActivityInfo targetReceiver = null;
8068
8069        final int NR = receivers.size();
8070        for (int i = 0; i < NR; i++) {
8071            final ResolveInfo info = receivers.get(i);
8072            if (info.activityInfo == null) {
8073                continue;
8074            }
8075
8076            if (packageName.equals(info.activityInfo.packageName)) {
8077                targetReceiver = info.activityInfo;
8078                break;
8079            }
8080        }
8081
8082        if (targetReceiver == null) {
8083            return null;
8084        }
8085
8086        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8087    }
8088
8089    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8090            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8091        if (pkgInfo.verifiers.length == 0) {
8092            return null;
8093        }
8094
8095        final int N = pkgInfo.verifiers.length;
8096        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8097        for (int i = 0; i < N; i++) {
8098            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8099
8100            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8101                    receivers);
8102            if (comp == null) {
8103                continue;
8104            }
8105
8106            final int verifierUid = getUidForVerifier(verifierInfo);
8107            if (verifierUid == -1) {
8108                continue;
8109            }
8110
8111            if (DEBUG_VERIFY) {
8112                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8113                        + " with the correct signature");
8114            }
8115            sufficientVerifiers.add(comp);
8116            verificationState.addSufficientVerifier(verifierUid);
8117        }
8118
8119        return sufficientVerifiers;
8120    }
8121
8122    private int getUidForVerifier(VerifierInfo verifierInfo) {
8123        synchronized (mPackages) {
8124            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8125            if (pkg == null) {
8126                return -1;
8127            } else if (pkg.mSignatures.length != 1) {
8128                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8129                        + " has more than one signature; ignoring");
8130                return -1;
8131            }
8132
8133            /*
8134             * If the public key of the package's signature does not match
8135             * our expected public key, then this is a different package and
8136             * we should skip.
8137             */
8138
8139            final byte[] expectedPublicKey;
8140            try {
8141                final Signature verifierSig = pkg.mSignatures[0];
8142                final PublicKey publicKey = verifierSig.getPublicKey();
8143                expectedPublicKey = publicKey.getEncoded();
8144            } catch (CertificateException e) {
8145                return -1;
8146            }
8147
8148            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8149
8150            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8151                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8152                        + " does not have the expected public key; ignoring");
8153                return -1;
8154            }
8155
8156            return pkg.applicationInfo.uid;
8157        }
8158    }
8159
8160    @Override
8161    public void finishPackageInstall(int token) {
8162        enforceSystemOrRoot("Only the system is allowed to finish installs");
8163
8164        if (DEBUG_INSTALL) {
8165            Slog.v(TAG, "BM finishing package install for " + token);
8166        }
8167
8168        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8169        mHandler.sendMessage(msg);
8170    }
8171
8172    /**
8173     * Get the verification agent timeout.
8174     *
8175     * @return verification timeout in milliseconds
8176     */
8177    private long getVerificationTimeout() {
8178        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8179                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8180                DEFAULT_VERIFICATION_TIMEOUT);
8181    }
8182
8183    /**
8184     * Get the default verification agent response code.
8185     *
8186     * @return default verification response code
8187     */
8188    private int getDefaultVerificationResponse() {
8189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8190                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8191                DEFAULT_VERIFICATION_RESPONSE);
8192    }
8193
8194    /**
8195     * Check whether or not package verification has been enabled.
8196     *
8197     * @return true if verification should be performed
8198     */
8199    private boolean isVerificationEnabled(int userId, int flags) {
8200        if (!DEFAULT_VERIFY_ENABLE) {
8201            return false;
8202        }
8203
8204        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8205
8206        // Check if installing from ADB
8207        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8208            // Do not run verification in a test harness environment
8209            if (ActivityManager.isRunningInTestHarness()) {
8210                return false;
8211            }
8212            if (ensureVerifyAppsEnabled) {
8213                return true;
8214            }
8215            // Check if the developer does not want package verification for ADB installs
8216            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8217                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8218                return false;
8219            }
8220        }
8221
8222        if (ensureVerifyAppsEnabled) {
8223            return true;
8224        }
8225
8226        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8227                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8228    }
8229
8230    /**
8231     * Get the "allow unknown sources" setting.
8232     *
8233     * @return the current "allow unknown sources" setting
8234     */
8235    private int getUnknownSourcesSettings() {
8236        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8237                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8238                -1);
8239    }
8240
8241    @Override
8242    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8243        final int uid = Binder.getCallingUid();
8244        // writer
8245        synchronized (mPackages) {
8246            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8247            if (targetPackageSetting == null) {
8248                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8249            }
8250
8251            PackageSetting installerPackageSetting;
8252            if (installerPackageName != null) {
8253                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8254                if (installerPackageSetting == null) {
8255                    throw new IllegalArgumentException("Unknown installer package: "
8256                            + installerPackageName);
8257                }
8258            } else {
8259                installerPackageSetting = null;
8260            }
8261
8262            Signature[] callerSignature;
8263            Object obj = mSettings.getUserIdLPr(uid);
8264            if (obj != null) {
8265                if (obj instanceof SharedUserSetting) {
8266                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8267                } else if (obj instanceof PackageSetting) {
8268                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8269                } else {
8270                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8271                }
8272            } else {
8273                throw new SecurityException("Unknown calling uid " + uid);
8274            }
8275
8276            // Verify: can't set installerPackageName to a package that is
8277            // not signed with the same cert as the caller.
8278            if (installerPackageSetting != null) {
8279                if (compareSignatures(callerSignature,
8280                        installerPackageSetting.signatures.mSignatures)
8281                        != PackageManager.SIGNATURE_MATCH) {
8282                    throw new SecurityException(
8283                            "Caller does not have same cert as new installer package "
8284                            + installerPackageName);
8285                }
8286            }
8287
8288            // Verify: if target already has an installer package, it must
8289            // be signed with the same cert as the caller.
8290            if (targetPackageSetting.installerPackageName != null) {
8291                PackageSetting setting = mSettings.mPackages.get(
8292                        targetPackageSetting.installerPackageName);
8293                // If the currently set package isn't valid, then it's always
8294                // okay to change it.
8295                if (setting != null) {
8296                    if (compareSignatures(callerSignature,
8297                            setting.signatures.mSignatures)
8298                            != PackageManager.SIGNATURE_MATCH) {
8299                        throw new SecurityException(
8300                                "Caller does not have same cert as old installer package "
8301                                + targetPackageSetting.installerPackageName);
8302                    }
8303                }
8304            }
8305
8306            // Okay!
8307            targetPackageSetting.installerPackageName = installerPackageName;
8308            scheduleWriteSettingsLocked();
8309        }
8310    }
8311
8312    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8313        // Queue up an async operation since the package installation may take a little while.
8314        mHandler.post(new Runnable() {
8315            public void run() {
8316                mHandler.removeCallbacks(this);
8317                 // Result object to be returned
8318                PackageInstalledInfo res = new PackageInstalledInfo();
8319                res.returnCode = currentStatus;
8320                res.uid = -1;
8321                res.pkg = null;
8322                res.removedInfo = new PackageRemovedInfo();
8323                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8324                    args.doPreInstall(res.returnCode);
8325                    synchronized (mInstallLock) {
8326                        installPackageLI(args, true, res);
8327                    }
8328                    args.doPostInstall(res.returnCode, res.uid);
8329                }
8330
8331                // A restore should be performed at this point if (a) the install
8332                // succeeded, (b) the operation is not an update, and (c) the new
8333                // package has a backupAgent defined.
8334                final boolean update = res.removedInfo.removedPackage != null;
8335                boolean doRestore = (!update
8336                        && res.pkg != null
8337                        && res.pkg.applicationInfo.backupAgentName != null);
8338
8339                // Set up the post-install work request bookkeeping.  This will be used
8340                // and cleaned up by the post-install event handling regardless of whether
8341                // there's a restore pass performed.  Token values are >= 1.
8342                int token;
8343                if (mNextInstallToken < 0) mNextInstallToken = 1;
8344                token = mNextInstallToken++;
8345
8346                PostInstallData data = new PostInstallData(args, res);
8347                mRunningInstalls.put(token, data);
8348                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8349
8350                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8351                    // Pass responsibility to the Backup Manager.  It will perform a
8352                    // restore if appropriate, then pass responsibility back to the
8353                    // Package Manager to run the post-install observer callbacks
8354                    // and broadcasts.
8355                    IBackupManager bm = IBackupManager.Stub.asInterface(
8356                            ServiceManager.getService(Context.BACKUP_SERVICE));
8357                    if (bm != null) {
8358                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8359                                + " to BM for possible restore");
8360                        try {
8361                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8362                        } catch (RemoteException e) {
8363                            // can't happen; the backup manager is local
8364                        } catch (Exception e) {
8365                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8366                            doRestore = false;
8367                        }
8368                    } else {
8369                        Slog.e(TAG, "Backup Manager not found!");
8370                        doRestore = false;
8371                    }
8372                }
8373
8374                if (!doRestore) {
8375                    // No restore possible, or the Backup Manager was mysteriously not
8376                    // available -- just fire the post-install work request directly.
8377                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8378                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8379                    mHandler.sendMessage(msg);
8380                }
8381            }
8382        });
8383    }
8384
8385    private abstract class HandlerParams {
8386        private static final int MAX_RETRIES = 4;
8387
8388        /**
8389         * Number of times startCopy() has been attempted and had a non-fatal
8390         * error.
8391         */
8392        private int mRetries = 0;
8393
8394        /** User handle for the user requesting the information or installation. */
8395        private final UserHandle mUser;
8396
8397        HandlerParams(UserHandle user) {
8398            mUser = user;
8399        }
8400
8401        UserHandle getUser() {
8402            return mUser;
8403        }
8404
8405        final boolean startCopy() {
8406            boolean res;
8407            try {
8408                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8409
8410                if (++mRetries > MAX_RETRIES) {
8411                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8412                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8413                    handleServiceError();
8414                    return false;
8415                } else {
8416                    handleStartCopy();
8417                    res = true;
8418                }
8419            } catch (RemoteException e) {
8420                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8421                mHandler.sendEmptyMessage(MCS_RECONNECT);
8422                res = false;
8423            }
8424            handleReturnCode();
8425            return res;
8426        }
8427
8428        final void serviceError() {
8429            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8430            handleServiceError();
8431            handleReturnCode();
8432        }
8433
8434        abstract void handleStartCopy() throws RemoteException;
8435        abstract void handleServiceError();
8436        abstract void handleReturnCode();
8437    }
8438
8439    class MeasureParams extends HandlerParams {
8440        private final PackageStats mStats;
8441        private boolean mSuccess;
8442
8443        private final IPackageStatsObserver mObserver;
8444
8445        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8446            super(new UserHandle(stats.userHandle));
8447            mObserver = observer;
8448            mStats = stats;
8449        }
8450
8451        @Override
8452        public String toString() {
8453            return "MeasureParams{"
8454                + Integer.toHexString(System.identityHashCode(this))
8455                + " " + mStats.packageName + "}";
8456        }
8457
8458        @Override
8459        void handleStartCopy() throws RemoteException {
8460            synchronized (mInstallLock) {
8461                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8462            }
8463
8464            if (mSuccess) {
8465                final boolean mounted;
8466                if (Environment.isExternalStorageEmulated()) {
8467                    mounted = true;
8468                } else {
8469                    final String status = Environment.getExternalStorageState();
8470                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8471                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8472                }
8473
8474                if (mounted) {
8475                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8476
8477                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8478                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8479
8480                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8481                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8482
8483                    // Always subtract cache size, since it's a subdirectory
8484                    mStats.externalDataSize -= mStats.externalCacheSize;
8485
8486                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8487                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8488
8489                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8490                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8491                }
8492            }
8493        }
8494
8495        @Override
8496        void handleReturnCode() {
8497            if (mObserver != null) {
8498                try {
8499                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8500                } catch (RemoteException e) {
8501                    Slog.i(TAG, "Observer no longer exists.");
8502                }
8503            }
8504        }
8505
8506        @Override
8507        void handleServiceError() {
8508            Slog.e(TAG, "Could not measure application " + mStats.packageName
8509                            + " external storage");
8510        }
8511    }
8512
8513    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8514            throws RemoteException {
8515        long result = 0;
8516        for (File path : paths) {
8517            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8518        }
8519        return result;
8520    }
8521
8522    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8523        for (File path : paths) {
8524            try {
8525                mcs.clearDirectory(path.getAbsolutePath());
8526            } catch (RemoteException e) {
8527            }
8528        }
8529    }
8530
8531    class InstallParams extends HandlerParams {
8532        /**
8533         * Location where install is coming from, before it has been
8534         * copied/renamed into place. This could be a single monolithic APK
8535         * file, or a cluster directory. This location may be untrusted.
8536         */
8537        final File originFile;
8538
8539        /**
8540         * Flag indicating that {@link #originFile} has already been staged,
8541         * meaning downstream users don't need to defensively copy the contents.
8542         */
8543        boolean originStaged;
8544
8545        final IPackageInstallObserver2 observer;
8546        int flags;
8547        final String installerPackageName;
8548        final VerificationParams verificationParams;
8549        private InstallArgs mArgs;
8550        private int mRet;
8551        final String packageAbiOverride;
8552        boolean multiArch;
8553
8554        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8555                int flags, String installerPackageName, VerificationParams verificationParams,
8556                UserHandle user, String packageAbiOverride) {
8557            super(user);
8558            this.originFile = Preconditions.checkNotNull(originFile);
8559            this.originStaged = originStaged;
8560            this.observer = observer;
8561            this.flags = flags;
8562            this.installerPackageName = installerPackageName;
8563            this.verificationParams = verificationParams;
8564            this.packageAbiOverride = packageAbiOverride;
8565        }
8566
8567        @Override
8568        public String toString() {
8569            return "InstallParams{"
8570                + Integer.toHexString(System.identityHashCode(this))
8571                + " " + originFile + "}";
8572        }
8573
8574        public ManifestDigest getManifestDigest() {
8575            if (verificationParams == null) {
8576                return null;
8577            }
8578            return verificationParams.getManifestDigest();
8579        }
8580
8581        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8582            String packageName = pkgLite.packageName;
8583            int installLocation = pkgLite.installLocation;
8584            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8585            // reader
8586            synchronized (mPackages) {
8587                PackageParser.Package pkg = mPackages.get(packageName);
8588                if (pkg != null) {
8589                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8590                        // Check for downgrading.
8591                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8592                            if (pkgLite.versionCode < pkg.mVersionCode) {
8593                                Slog.w(TAG, "Can't install update of " + packageName
8594                                        + " update version " + pkgLite.versionCode
8595                                        + " is older than installed version "
8596                                        + pkg.mVersionCode);
8597                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8598                            }
8599                        }
8600                        // Check for updated system application.
8601                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8602                            if (onSd) {
8603                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8604                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8605                            }
8606                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8607                        } else {
8608                            if (onSd) {
8609                                // Install flag overrides everything.
8610                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8611                            }
8612                            // If current upgrade specifies particular preference
8613                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8614                                // Application explicitly specified internal.
8615                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8616                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8617                                // App explictly prefers external. Let policy decide
8618                            } else {
8619                                // Prefer previous location
8620                                if (isExternal(pkg)) {
8621                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8622                                }
8623                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8624                            }
8625                        }
8626                    } else {
8627                        // Invalid install. Return error code
8628                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8629                    }
8630                }
8631            }
8632            // All the special cases have been taken care of.
8633            // Return result based on recommended install location.
8634            if (onSd) {
8635                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8636            }
8637            return pkgLite.recommendedInstallLocation;
8638        }
8639
8640        private long getMemoryLowThreshold() {
8641            final DeviceStorageMonitorInternal
8642                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8643            if (dsm == null) {
8644                return 0L;
8645            }
8646            return dsm.getMemoryLowThreshold();
8647        }
8648
8649        /*
8650         * Invoke remote method to get package information and install
8651         * location values. Override install location based on default
8652         * policy if needed and then create install arguments based
8653         * on the install location.
8654         */
8655        public void handleStartCopy() throws RemoteException {
8656            int ret = PackageManager.INSTALL_SUCCEEDED;
8657            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8658            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8659            PackageInfoLite pkgLite = null;
8660
8661            if (onInt && onSd) {
8662                // Check if both bits are set.
8663                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8664                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8665            } else {
8666                final long lowThreshold = getMemoryLowThreshold();
8667                if (lowThreshold == 0L) {
8668                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8669                }
8670
8671                // Remote call to find out default install location
8672                final String originPath = originFile.getAbsolutePath();
8673                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8674                        packageAbiOverride);
8675                // Keep track of whether this package is a multiArch package until
8676                // we perform a full scan of it. We need to do this because we might
8677                // end up extracting the package shared libraries before we perform
8678                // a full scan.
8679                multiArch = pkgLite.multiArch;
8680
8681                /*
8682                 * If we have too little free space, try to free cache
8683                 * before giving up.
8684                 */
8685                if (pkgLite.recommendedInstallLocation
8686                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8687                    final long size = mContainerService.calculateInstalledSize(
8688                            originPath, isForwardLocked(), packageAbiOverride);
8689                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8690                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8691                                lowThreshold, packageAbiOverride);
8692                    }
8693                    /*
8694                     * The cache free must have deleted the file we
8695                     * downloaded to install.
8696                     *
8697                     * TODO: fix the "freeCache" call to not delete
8698                     *       the file we care about.
8699                     */
8700                    if (pkgLite.recommendedInstallLocation
8701                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8702                        pkgLite.recommendedInstallLocation
8703                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8704                    }
8705                }
8706            }
8707
8708            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8709                int loc = pkgLite.recommendedInstallLocation;
8710                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8711                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8712                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8713                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8714                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8715                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8716                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8717                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8718                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8719                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8720                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8721                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8722                } else {
8723                    // Override with defaults if needed.
8724                    loc = installLocationPolicy(pkgLite, flags);
8725                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8726                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8727                    } else if (!onSd && !onInt) {
8728                        // Override install location with flags
8729                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8730                            // Set the flag to install on external media.
8731                            flags |= PackageManager.INSTALL_EXTERNAL;
8732                            flags &= ~PackageManager.INSTALL_INTERNAL;
8733                        } else {
8734                            // Make sure the flag for installing on external
8735                            // media is unset
8736                            flags |= PackageManager.INSTALL_INTERNAL;
8737                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8738                        }
8739                    }
8740                }
8741            }
8742
8743            final InstallArgs args = createInstallArgs(this);
8744            mArgs = args;
8745
8746            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8747                 /*
8748                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8749                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8750                 */
8751                int userIdentifier = getUser().getIdentifier();
8752                if (userIdentifier == UserHandle.USER_ALL
8753                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8754                    userIdentifier = UserHandle.USER_OWNER;
8755                }
8756
8757                /*
8758                 * Determine if we have any installed package verifiers. If we
8759                 * do, then we'll defer to them to verify the packages.
8760                 */
8761                final int requiredUid = mRequiredVerifierPackage == null ? -1
8762                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8763                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8764                    // TODO: send verifier the install session instead of uri
8765                    final Intent verification = new Intent(
8766                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8767                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8768                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8769
8770                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8771                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8772                            0 /* TODO: Which userId? */);
8773
8774                    if (DEBUG_VERIFY) {
8775                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8776                                + verification.toString() + " with " + pkgLite.verifiers.length
8777                                + " optional verifiers");
8778                    }
8779
8780                    final int verificationId = mPendingVerificationToken++;
8781
8782                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8783
8784                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8785                            installerPackageName);
8786
8787                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8788
8789                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8790                            pkgLite.packageName);
8791
8792                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8793                            pkgLite.versionCode);
8794
8795                    if (verificationParams != null) {
8796                        if (verificationParams.getVerificationURI() != null) {
8797                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8798                                 verificationParams.getVerificationURI());
8799                        }
8800                        if (verificationParams.getOriginatingURI() != null) {
8801                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8802                                  verificationParams.getOriginatingURI());
8803                        }
8804                        if (verificationParams.getReferrer() != null) {
8805                            verification.putExtra(Intent.EXTRA_REFERRER,
8806                                  verificationParams.getReferrer());
8807                        }
8808                        if (verificationParams.getOriginatingUid() >= 0) {
8809                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8810                                  verificationParams.getOriginatingUid());
8811                        }
8812                        if (verificationParams.getInstallerUid() >= 0) {
8813                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8814                                  verificationParams.getInstallerUid());
8815                        }
8816                    }
8817
8818                    final PackageVerificationState verificationState = new PackageVerificationState(
8819                            requiredUid, args);
8820
8821                    mPendingVerification.append(verificationId, verificationState);
8822
8823                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8824                            receivers, verificationState);
8825
8826                    /*
8827                     * If any sufficient verifiers were listed in the package
8828                     * manifest, attempt to ask them.
8829                     */
8830                    if (sufficientVerifiers != null) {
8831                        final int N = sufficientVerifiers.size();
8832                        if (N == 0) {
8833                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8834                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8835                        } else {
8836                            for (int i = 0; i < N; i++) {
8837                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8838
8839                                final Intent sufficientIntent = new Intent(verification);
8840                                sufficientIntent.setComponent(verifierComponent);
8841
8842                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8843                            }
8844                        }
8845                    }
8846
8847                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8848                            mRequiredVerifierPackage, receivers);
8849                    if (ret == PackageManager.INSTALL_SUCCEEDED
8850                            && mRequiredVerifierPackage != null) {
8851                        /*
8852                         * Send the intent to the required verification agent,
8853                         * but only start the verification timeout after the
8854                         * target BroadcastReceivers have run.
8855                         */
8856                        verification.setComponent(requiredVerifierComponent);
8857                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8858                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8859                                new BroadcastReceiver() {
8860                                    @Override
8861                                    public void onReceive(Context context, Intent intent) {
8862                                        final Message msg = mHandler
8863                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8864                                        msg.arg1 = verificationId;
8865                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8866                                    }
8867                                }, null, 0, null, null);
8868
8869                        /*
8870                         * We don't want the copy to proceed until verification
8871                         * succeeds, so null out this field.
8872                         */
8873                        mArgs = null;
8874                    }
8875                } else {
8876                    /*
8877                     * No package verification is enabled, so immediately start
8878                     * the remote call to initiate copy using temporary file.
8879                     */
8880                    ret = args.copyApk(mContainerService, true);
8881                }
8882            }
8883
8884            mRet = ret;
8885        }
8886
8887        @Override
8888        void handleReturnCode() {
8889            // If mArgs is null, then MCS couldn't be reached. When it
8890            // reconnects, it will try again to install. At that point, this
8891            // will succeed.
8892            if (mArgs != null) {
8893                processPendingInstall(mArgs, mRet);
8894            }
8895        }
8896
8897        @Override
8898        void handleServiceError() {
8899            mArgs = createInstallArgs(this);
8900            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8901        }
8902
8903        public boolean isForwardLocked() {
8904            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8905        }
8906    }
8907
8908    /*
8909     * Utility class used in movePackage api.
8910     * srcArgs and targetArgs are not set for invalid flags and make
8911     * sure to do null checks when invoking methods on them.
8912     * We probably want to return ErrorPrams for both failed installs
8913     * and moves.
8914     */
8915    class MoveParams extends HandlerParams {
8916        final IPackageMoveObserver observer;
8917        final int flags;
8918        final String packageName;
8919        final InstallArgs srcArgs;
8920        final InstallArgs targetArgs;
8921        int uid;
8922        int mRet;
8923
8924        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8925                String packageName, String[] instructionSets, int uid, UserHandle user,
8926                boolean isMultiArch) {
8927            super(user);
8928            this.srcArgs = srcArgs;
8929            this.observer = observer;
8930            this.flags = flags;
8931            this.packageName = packageName;
8932            this.uid = uid;
8933            if (srcArgs != null) {
8934                final String codePath = srcArgs.getCodePath();
8935                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8936                        instructionSets, isMultiArch);
8937            } else {
8938                targetArgs = null;
8939            }
8940        }
8941
8942        @Override
8943        public String toString() {
8944            return "MoveParams{"
8945                + Integer.toHexString(System.identityHashCode(this))
8946                + " " + packageName + "}";
8947        }
8948
8949        public void handleStartCopy() throws RemoteException {
8950            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8951            // Check for storage space on target medium
8952            if (!targetArgs.checkFreeStorage(mContainerService)) {
8953                Log.w(TAG, "Insufficient storage to install");
8954                return;
8955            }
8956
8957            mRet = srcArgs.doPreCopy();
8958            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8959                return;
8960            }
8961
8962            mRet = targetArgs.copyApk(mContainerService, false);
8963            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8964                srcArgs.doPostCopy(uid);
8965                return;
8966            }
8967
8968            mRet = srcArgs.doPostCopy(uid);
8969            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8970                return;
8971            }
8972
8973            mRet = targetArgs.doPreInstall(mRet);
8974            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8975                return;
8976            }
8977
8978            if (DEBUG_SD_INSTALL) {
8979                StringBuilder builder = new StringBuilder();
8980                if (srcArgs != null) {
8981                    builder.append("src: ");
8982                    builder.append(srcArgs.getCodePath());
8983                }
8984                if (targetArgs != null) {
8985                    builder.append(" target : ");
8986                    builder.append(targetArgs.getCodePath());
8987                }
8988                Log.i(TAG, builder.toString());
8989            }
8990        }
8991
8992        @Override
8993        void handleReturnCode() {
8994            targetArgs.doPostInstall(mRet, uid);
8995            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8996            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8997                currentStatus = PackageManager.MOVE_SUCCEEDED;
8998            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8999                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9000            }
9001            processPendingMove(this, currentStatus);
9002        }
9003
9004        @Override
9005        void handleServiceError() {
9006            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9007        }
9008    }
9009
9010    /**
9011     * Used during creation of InstallArgs
9012     *
9013     * @param flags package installation flags
9014     * @return true if should be installed on external storage
9015     */
9016    private static boolean installOnSd(int flags) {
9017        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9018            return false;
9019        }
9020        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9021            return true;
9022        }
9023        return false;
9024    }
9025
9026    /**
9027     * Used during creation of InstallArgs
9028     *
9029     * @param flags package installation flags
9030     * @return true if should be installed as forward locked
9031     */
9032    private static boolean installForwardLocked(int flags) {
9033        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9034    }
9035
9036    private InstallArgs createInstallArgs(InstallParams params) {
9037        // TODO: extend to support incoming zero-copy locations
9038
9039        if (installOnSd(params.flags) || params.isForwardLocked()) {
9040            return new AsecInstallArgs(params);
9041        } else {
9042            return new FileInstallArgs(params);
9043        }
9044    }
9045
9046    /**
9047     * Create args that describe an existing installed package. Typically used
9048     * when cleaning up old installs, or used as a move source.
9049     */
9050    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9051            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9052            boolean isMultiArch) {
9053        final boolean isInAsec;
9054        if (installOnSd(flags)) {
9055            /* Apps on SD card are always in ASEC containers. */
9056            isInAsec = true;
9057        } else if (installForwardLocked(flags)
9058                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9059            /*
9060             * Forward-locked apps are only in ASEC containers if they're the
9061             * new style
9062             */
9063            isInAsec = true;
9064        } else {
9065            isInAsec = false;
9066        }
9067
9068        if (isInAsec) {
9069            return new AsecInstallArgs(codePath, instructionSets,
9070                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9071        } else {
9072            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9073                    instructionSets, isMultiArch);
9074        }
9075    }
9076
9077    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9078            String[] instructionSets, boolean isMultiArch) {
9079        final File codeFile = new File(codePath);
9080        if (installOnSd(flags) || installForwardLocked(flags)) {
9081            String cid = getNextCodePath(codePath, pkgName, "/"
9082                    + AsecInstallArgs.RES_FILE_NAME);
9083            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9084                    installForwardLocked(flags), isMultiArch);
9085        } else {
9086            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9087        }
9088    }
9089
9090    static abstract class InstallArgs {
9091        /** @see InstallParams#originFile */
9092        final File originFile;
9093        /** @see InstallParams#originStaged */
9094        final boolean originStaged;
9095
9096        // TODO: define inherit location
9097
9098        final IPackageInstallObserver2 observer;
9099        // Always refers to PackageManager flags only
9100        final int flags;
9101        final String installerPackageName;
9102        final ManifestDigest manifestDigest;
9103        final UserHandle user;
9104        final String abiOverride;
9105        final boolean multiArch;
9106
9107        // The list of instruction sets supported by this app. This is currently
9108        // only used during the rmdex() phase to clean up resources. We can get rid of this
9109        // if we move dex files under the common app path.
9110        /* nullable */ String[] instructionSets;
9111
9112        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9113                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9114                    UserHandle user, String[] instructionSets,
9115                    String abiOverride, boolean multiArch) {
9116            this.originFile = originFile;
9117            this.originStaged = originStaged;
9118            this.flags = flags;
9119            this.observer = observer;
9120            this.installerPackageName = installerPackageName;
9121            this.manifestDigest = manifestDigest;
9122            this.user = user;
9123            this.instructionSets = instructionSets;
9124            this.abiOverride = abiOverride;
9125            this.multiArch = multiArch;
9126        }
9127
9128        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9129        abstract int doPreInstall(int status);
9130
9131        /**
9132         * Rename package into final resting place. All paths on the given
9133         * scanned package should be updated to reflect the rename.
9134         */
9135        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9136        abstract int doPostInstall(int status, int uid);
9137
9138        /** @see PackageSettingBase#codePathString */
9139        abstract String getCodePath();
9140        /** @see PackageSettingBase#resourcePathString */
9141        abstract String getResourcePath();
9142        abstract String getLegacyNativeLibraryPath();
9143
9144        // Need installer lock especially for dex file removal.
9145        abstract void cleanUpResourcesLI();
9146        abstract boolean doPostDeleteLI(boolean delete);
9147        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9148
9149        /**
9150         * Called before the source arguments are copied. This is used mostly
9151         * for MoveParams when it needs to read the source file to put it in the
9152         * destination.
9153         */
9154        int doPreCopy() {
9155            return PackageManager.INSTALL_SUCCEEDED;
9156        }
9157
9158        /**
9159         * Called after the source arguments are copied. This is used mostly for
9160         * MoveParams when it needs to read the source file to put it in the
9161         * destination.
9162         *
9163         * @return
9164         */
9165        int doPostCopy(int uid) {
9166            return PackageManager.INSTALL_SUCCEEDED;
9167        }
9168
9169        protected boolean isFwdLocked() {
9170            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9171        }
9172
9173        UserHandle getUser() {
9174            return user;
9175        }
9176    }
9177
9178    /**
9179     * Logic to handle installation of non-ASEC applications, including copying
9180     * and renaming logic.
9181     */
9182    class FileInstallArgs extends InstallArgs {
9183        private File codeFile;
9184        private File resourceFile;
9185        private File legacyNativeLibraryPath;
9186
9187        // Example topology:
9188        // /data/app/com.example/base.apk
9189        // /data/app/com.example/split_foo.apk
9190        // /data/app/com.example/lib/arm/libfoo.so
9191        // /data/app/com.example/lib/arm64/libfoo.so
9192        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9193
9194        /** New install */
9195        FileInstallArgs(InstallParams params) {
9196            super(params.originFile, params.originStaged, params.observer, params.flags,
9197                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9198                    null /* instruction sets */, params.packageAbiOverride,
9199                    params.multiArch);
9200            if (isFwdLocked()) {
9201                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9202            }
9203        }
9204
9205        /** Existing install */
9206        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9207                String[] instructionSets, boolean isMultiArch) {
9208            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9209            this.codeFile = (codePath != null) ? new File(codePath) : null;
9210            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9211            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9212                    new File(legacyNativeLibraryPath) : null;
9213        }
9214
9215        /** New install from existing */
9216        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9217            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9218                    isMultiArch);
9219        }
9220
9221        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9222            final long lowThreshold;
9223
9224            final DeviceStorageMonitorInternal
9225                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9226            if (dsm == null) {
9227                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9228                lowThreshold = 0L;
9229            } else {
9230                if (dsm.isMemoryLow()) {
9231                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9232                    return false;
9233                }
9234
9235                lowThreshold = dsm.getMemoryLowThreshold();
9236            }
9237
9238            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9239                    lowThreshold);
9240        }
9241
9242        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9243            int ret = PackageManager.INSTALL_SUCCEEDED;
9244
9245            if (originStaged) {
9246                Slog.d(TAG, originFile + " already staged; skipping copy");
9247                codeFile = originFile;
9248                resourceFile = originFile;
9249            } else {
9250                try {
9251                    final File tempDir = mInstallerService.allocateSessionDir();
9252                    codeFile = tempDir;
9253                    resourceFile = tempDir;
9254                } catch (IOException e) {
9255                    Slog.w(TAG, "Failed to create copy file: " + e);
9256                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9257                }
9258
9259                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9260                    @Override
9261                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9262                        if (!FileUtils.isValidExtFilename(name)) {
9263                            throw new IllegalArgumentException("Invalid filename: " + name);
9264                        }
9265                        try {
9266                            final File file = new File(codeFile, name);
9267                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9268                                    O_RDWR | O_CREAT, 0644);
9269                            Os.chmod(file.getAbsolutePath(), 0644);
9270                            return new ParcelFileDescriptor(fd);
9271                        } catch (ErrnoException e) {
9272                            throw new RemoteException("Failed to open: " + e.getMessage());
9273                        }
9274                    }
9275                };
9276
9277                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9278                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9279                    Slog.e(TAG, "Failed to copy package");
9280                    return ret;
9281                }
9282            }
9283
9284            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9285            NativeLibraryHelper.Handle handle = null;
9286            try {
9287                handle = NativeLibraryHelper.Handle.create(codeFile);
9288                if (multiArch) {
9289                    // Warn if we've set an abiOverride for multi-lib packages..
9290                    // By definition, we need to copy both 32 and 64 bit libraries for
9291                    // such packages.
9292                    if (abiOverride != null) {
9293                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9294                    }
9295
9296                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9297                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9298                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9299                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9300                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9301                    }
9302
9303                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9304                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9305                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9306                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9307                    }
9308                } else {
9309                    String[] abiList = (abiOverride != null) ?
9310                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9311
9312                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9313                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9314                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9315                    }
9316
9317                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9318                            true /* use isa specific subdirs */);
9319                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9320                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9321                        return copyRet;
9322                    }
9323                }
9324            } catch (IOException e) {
9325                Slog.e(TAG, "Copying native libraries failed", e);
9326                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9327            } catch (PackageManagerException pme) {
9328                Slog.e(TAG, "Copying native libraries failed", pme);
9329                ret = pme.error;
9330            } finally {
9331                IoUtils.closeQuietly(handle);
9332            }
9333
9334            return ret;
9335        }
9336
9337        int doPreInstall(int status) {
9338            if (status != PackageManager.INSTALL_SUCCEEDED) {
9339                cleanUp();
9340            }
9341            return status;
9342        }
9343
9344        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9345            if (status != PackageManager.INSTALL_SUCCEEDED) {
9346                cleanUp();
9347                return false;
9348            } else {
9349                final File beforeCodeFile = codeFile;
9350                final File afterCodeFile = getNextCodePath(pkg.packageName);
9351
9352                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9353                try {
9354                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9355                } catch (ErrnoException e) {
9356                    Slog.d(TAG, "Failed to rename", e);
9357                    return false;
9358                }
9359
9360                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9361                    Slog.d(TAG, "Failed to restorecon");
9362                    return false;
9363                }
9364
9365                // Reflect the rename internally
9366                codeFile = afterCodeFile;
9367                resourceFile = afterCodeFile;
9368
9369                // Reflect the rename in scanned details
9370                pkg.codePath = afterCodeFile.getAbsolutePath();
9371                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9372                        pkg.baseCodePath);
9373                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9374                        pkg.splitCodePaths);
9375
9376                // Reflect the rename in app info
9377                pkg.applicationInfo.setCodePath(pkg.codePath);
9378                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9379                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9380                pkg.applicationInfo.setResourcePath(pkg.codePath);
9381                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9382                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9383
9384                return true;
9385            }
9386        }
9387
9388        int doPostInstall(int status, int uid) {
9389            if (status != PackageManager.INSTALL_SUCCEEDED) {
9390                cleanUp();
9391            }
9392            return status;
9393        }
9394
9395        @Override
9396        String getCodePath() {
9397            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9398        }
9399
9400        @Override
9401        String getResourcePath() {
9402            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9403        }
9404
9405        @Override
9406        String getLegacyNativeLibraryPath() {
9407            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9408        }
9409
9410        private boolean cleanUp() {
9411            if (codeFile == null || !codeFile.exists()) {
9412                return false;
9413            }
9414
9415            if (codeFile.isDirectory()) {
9416                FileUtils.deleteContents(codeFile);
9417            }
9418            codeFile.delete();
9419
9420            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9421                resourceFile.delete();
9422            }
9423
9424            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9425                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9426                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9427                }
9428                legacyNativeLibraryPath.delete();
9429            }
9430
9431            return true;
9432        }
9433
9434        void cleanUpResourcesLI() {
9435            // Try enumerating all code paths before deleting
9436            List<String> allCodePaths = Collections.EMPTY_LIST;
9437            if (codeFile != null && codeFile.exists()) {
9438                try {
9439                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9440                    allCodePaths = pkg.getAllCodePaths();
9441                } catch (PackageParserException e) {
9442                    // Ignored; we tried our best
9443                }
9444            }
9445
9446            cleanUp();
9447
9448            if (!allCodePaths.isEmpty()) {
9449                if (instructionSets == null) {
9450                    throw new IllegalStateException("instructionSet == null");
9451                }
9452
9453                for (String codePath : allCodePaths) {
9454                    for (String instructionSet : instructionSets) {
9455                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9456                        if (retCode < 0) {
9457                            Slog.w(TAG, "Couldn't remove dex file for package: "
9458                                    + " at location " + codePath + ", retcode=" + retCode);
9459                            // we don't consider this to be a failure of the core package deletion
9460                        }
9461                    }
9462                }
9463            }
9464        }
9465
9466        boolean doPostDeleteLI(boolean delete) {
9467            // XXX err, shouldn't we respect the delete flag?
9468            cleanUpResourcesLI();
9469            return true;
9470        }
9471    }
9472
9473    private boolean isAsecExternal(String cid) {
9474        final String asecPath = PackageHelper.getSdFilesystem(cid);
9475        return !asecPath.startsWith(mAsecInternalPath);
9476    }
9477
9478    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9479            PackageManagerException {
9480        if (copyRet < 0) {
9481            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9482                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9483                throw new PackageManagerException(copyRet, message);
9484            }
9485        }
9486    }
9487
9488    /**
9489     * Extract the MountService "container ID" from the full code path of an
9490     * .apk.
9491     */
9492    static String cidFromCodePath(String fullCodePath) {
9493        int eidx = fullCodePath.lastIndexOf("/");
9494        String subStr1 = fullCodePath.substring(0, eidx);
9495        int sidx = subStr1.lastIndexOf("/");
9496        return subStr1.substring(sidx+1, eidx);
9497    }
9498
9499    /**
9500     * Logic to handle installation of ASEC applications, including copying and
9501     * renaming logic.
9502     */
9503    class AsecInstallArgs extends InstallArgs {
9504        // TODO: teach about handling cluster directories
9505
9506        static final String RES_FILE_NAME = "pkg.apk";
9507        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9508
9509        String cid;
9510        String packagePath;
9511        String resourcePath;
9512        String legacyNativeLibraryDir;
9513
9514        /** New install */
9515        AsecInstallArgs(InstallParams params) {
9516            super(params.originFile, params.originStaged, params.observer, params.flags,
9517                    params.installerPackageName, params.getManifestDigest(),
9518                    params.getUser(), null /* instruction sets */,
9519                    params.packageAbiOverride, params.multiArch);
9520        }
9521
9522        /** Existing install */
9523        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9524                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9525            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9526                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9527                    instructionSets, null, isMultiArch);
9528            // Extract cid from fullCodePath
9529            int eidx = fullCodePath.lastIndexOf("/");
9530            String subStr1 = fullCodePath.substring(0, eidx);
9531            int sidx = subStr1.lastIndexOf("/");
9532            cid = subStr1.substring(sidx+1, eidx);
9533            setCachePath(subStr1);
9534        }
9535
9536        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9537                        boolean isMultiArch) {
9538            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9539                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9540                    instructionSets, null, isMultiArch);
9541            this.cid = cid;
9542            setCachePath(PackageHelper.getSdDir(cid));
9543        }
9544
9545        /** New install from existing */
9546        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9547                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9548            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9549                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9550                    instructionSets, null, isMultiArch);
9551            this.cid = cid;
9552        }
9553
9554        void createCopyFile() {
9555            cid = getTempContainerId();
9556        }
9557
9558        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9559            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9560                    abiOverride);
9561        }
9562
9563        private final boolean isExternal() {
9564            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9565        }
9566
9567        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9568            if (temp) {
9569                createCopyFile();
9570            } else {
9571                /*
9572                 * Pre-emptively destroy the container since it's destroyed if
9573                 * copying fails due to it existing anyway.
9574                 */
9575                PackageHelper.destroySdDir(cid);
9576            }
9577
9578            final String newCachePath = imcs.copyPackageToContainer(
9579                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9580                    isFwdLocked(), abiOverride);
9581
9582            if (newCachePath != null) {
9583                setCachePath(newCachePath);
9584                return PackageManager.INSTALL_SUCCEEDED;
9585            } else {
9586                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9587            }
9588        }
9589
9590        @Override
9591        String getCodePath() {
9592            return packagePath;
9593        }
9594
9595        @Override
9596        String getResourcePath() {
9597            return resourcePath;
9598        }
9599
9600        @Override
9601        String getLegacyNativeLibraryPath() {
9602            return legacyNativeLibraryDir;
9603        }
9604
9605        int doPreInstall(int status) {
9606            if (status != PackageManager.INSTALL_SUCCEEDED) {
9607                // Destroy container
9608                PackageHelper.destroySdDir(cid);
9609            } else {
9610                boolean mounted = PackageHelper.isContainerMounted(cid);
9611                if (!mounted) {
9612                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9613                            Process.SYSTEM_UID);
9614                    if (newCachePath != null) {
9615                        setCachePath(newCachePath);
9616                    } else {
9617                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9618                    }
9619                }
9620            }
9621            return status;
9622        }
9623
9624        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9625            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9626            String newCachePath = null;
9627            if (PackageHelper.isContainerMounted(cid)) {
9628                // Unmount the container
9629                if (!PackageHelper.unMountSdDir(cid)) {
9630                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9631                    return false;
9632                }
9633            }
9634            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9635                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9636                        " which might be stale. Will try to clean up.");
9637                // Clean up the stale container and proceed to recreate.
9638                if (!PackageHelper.destroySdDir(newCacheId)) {
9639                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9640                    return false;
9641                }
9642                // Successfully cleaned up stale container. Try to rename again.
9643                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9644                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9645                            + " inspite of cleaning it up.");
9646                    return false;
9647                }
9648            }
9649            if (!PackageHelper.isContainerMounted(newCacheId)) {
9650                Slog.w(TAG, "Mounting container " + newCacheId);
9651                newCachePath = PackageHelper.mountSdDir(newCacheId,
9652                        getEncryptKey(), Process.SYSTEM_UID);
9653            } else {
9654                newCachePath = PackageHelper.getSdDir(newCacheId);
9655            }
9656            if (newCachePath == null) {
9657                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9658                return false;
9659            }
9660            Log.i(TAG, "Succesfully renamed " + cid +
9661                    " to " + newCacheId +
9662                    " at new path: " + newCachePath);
9663            cid = newCacheId;
9664            setCachePath(newCachePath);
9665
9666            // TODO: extend to support split APKs
9667            pkg.codePath = getCodePath();
9668            pkg.baseCodePath = getCodePath();
9669            pkg.splitCodePaths = null;
9670
9671            pkg.applicationInfo.setCodePath(getCodePath());
9672            pkg.applicationInfo.setBaseCodePath(getCodePath());
9673            pkg.applicationInfo.setSplitCodePaths(null);
9674            pkg.applicationInfo.setResourcePath(getResourcePath());
9675            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9676            pkg.applicationInfo.setSplitResourcePaths(null);
9677
9678            return true;
9679        }
9680
9681        private void setCachePath(String newCachePath) {
9682            File cachePath = new File(newCachePath);
9683            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9684            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9685
9686            if (isFwdLocked()) {
9687                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9688            } else {
9689                resourcePath = packagePath;
9690            }
9691        }
9692
9693        int doPostInstall(int status, int uid) {
9694            if (status != PackageManager.INSTALL_SUCCEEDED) {
9695                cleanUp();
9696            } else {
9697                final int groupOwner;
9698                final String protectedFile;
9699                if (isFwdLocked()) {
9700                    groupOwner = UserHandle.getSharedAppGid(uid);
9701                    protectedFile = RES_FILE_NAME;
9702                } else {
9703                    groupOwner = -1;
9704                    protectedFile = null;
9705                }
9706
9707                if (uid < Process.FIRST_APPLICATION_UID
9708                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9709                    Slog.e(TAG, "Failed to finalize " + cid);
9710                    PackageHelper.destroySdDir(cid);
9711                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9712                }
9713
9714                boolean mounted = PackageHelper.isContainerMounted(cid);
9715                if (!mounted) {
9716                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9717                }
9718            }
9719            return status;
9720        }
9721
9722        private void cleanUp() {
9723            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9724
9725            // Destroy secure container
9726            PackageHelper.destroySdDir(cid);
9727        }
9728
9729        void cleanUpResourcesLI() {
9730            String sourceFile = getCodePath();
9731            // Remove dex file
9732            if (instructionSets == null) {
9733                throw new IllegalStateException("instructionSet == null");
9734            }
9735            for (String instructionSet : instructionSets) {
9736                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9737                if (retCode < 0) {
9738                    Slog.w(TAG, "Couldn't remove dex file for package: "
9739                            + " at location "
9740                            + sourceFile.toString() + ", retcode=" + retCode);
9741                    // we don't consider this to be a failure of the core package deletion
9742                }
9743            }
9744            cleanUp();
9745        }
9746
9747        boolean matchContainer(String app) {
9748            if (cid.startsWith(app)) {
9749                return true;
9750            }
9751            return false;
9752        }
9753
9754        String getPackageName() {
9755            return getAsecPackageName(cid);
9756        }
9757
9758        boolean doPostDeleteLI(boolean delete) {
9759            boolean ret = false;
9760            boolean mounted = PackageHelper.isContainerMounted(cid);
9761            if (mounted) {
9762                // Unmount first
9763                ret = PackageHelper.unMountSdDir(cid);
9764            }
9765            if (ret && delete) {
9766                cleanUpResourcesLI();
9767            }
9768            return ret;
9769        }
9770
9771        @Override
9772        int doPreCopy() {
9773            if (isFwdLocked()) {
9774                if (!PackageHelper.fixSdPermissions(cid,
9775                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9776                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9777                }
9778            }
9779
9780            return PackageManager.INSTALL_SUCCEEDED;
9781        }
9782
9783        @Override
9784        int doPostCopy(int uid) {
9785            if (isFwdLocked()) {
9786                if (uid < Process.FIRST_APPLICATION_UID
9787                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9788                                RES_FILE_NAME)) {
9789                    Slog.e(TAG, "Failed to finalize " + cid);
9790                    PackageHelper.destroySdDir(cid);
9791                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9792                }
9793            }
9794
9795            return PackageManager.INSTALL_SUCCEEDED;
9796        }
9797    }
9798
9799    static String getAsecPackageName(String packageCid) {
9800        int idx = packageCid.lastIndexOf("-");
9801        if (idx == -1) {
9802            return packageCid;
9803        }
9804        return packageCid.substring(0, idx);
9805    }
9806
9807    // Utility method used to create code paths based on package name and available index.
9808    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9809        String idxStr = "";
9810        int idx = 1;
9811        // Fall back to default value of idx=1 if prefix is not
9812        // part of oldCodePath
9813        if (oldCodePath != null) {
9814            String subStr = oldCodePath;
9815            // Drop the suffix right away
9816            if (suffix != null && subStr.endsWith(suffix)) {
9817                subStr = subStr.substring(0, subStr.length() - suffix.length());
9818            }
9819            // If oldCodePath already contains prefix find out the
9820            // ending index to either increment or decrement.
9821            int sidx = subStr.lastIndexOf(prefix);
9822            if (sidx != -1) {
9823                subStr = subStr.substring(sidx + prefix.length());
9824                if (subStr != null) {
9825                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9826                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9827                    }
9828                    try {
9829                        idx = Integer.parseInt(subStr);
9830                        if (idx <= 1) {
9831                            idx++;
9832                        } else {
9833                            idx--;
9834                        }
9835                    } catch(NumberFormatException e) {
9836                    }
9837                }
9838            }
9839        }
9840        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9841        return prefix + idxStr;
9842    }
9843
9844    private File getNextCodePath(String packageName) {
9845        int suffix = 1;
9846        File result;
9847        do {
9848            result = new File(mAppInstallDir, packageName + "-" + suffix);
9849            suffix++;
9850        } while (result.exists());
9851        return result;
9852    }
9853
9854    // Utility method used to ignore ADD/REMOVE events
9855    // by directory observer.
9856    private static boolean ignoreCodePath(String fullPathStr) {
9857        String apkName = deriveCodePathName(fullPathStr);
9858        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9859        if (idx != -1 && ((idx+1) < apkName.length())) {
9860            // Make sure the package ends with a numeral
9861            String version = apkName.substring(idx+1);
9862            try {
9863                Integer.parseInt(version);
9864                return true;
9865            } catch (NumberFormatException e) {}
9866        }
9867        return false;
9868    }
9869
9870    // Utility method that returns the relative package path with respect
9871    // to the installation directory. Like say for /data/data/com.test-1.apk
9872    // string com.test-1 is returned.
9873    static String deriveCodePathName(String codePath) {
9874        if (codePath == null) {
9875            return null;
9876        }
9877        final File codeFile = new File(codePath);
9878        final String name = codeFile.getName();
9879        if (codeFile.isDirectory()) {
9880            return name;
9881        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9882            final int lastDot = name.lastIndexOf('.');
9883            return name.substring(0, lastDot);
9884        } else {
9885            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9886            return null;
9887        }
9888    }
9889
9890    class PackageInstalledInfo {
9891        String name;
9892        int uid;
9893        // The set of users that originally had this package installed.
9894        int[] origUsers;
9895        // The set of users that now have this package installed.
9896        int[] newUsers;
9897        PackageParser.Package pkg;
9898        int returnCode;
9899        String returnMsg;
9900        PackageRemovedInfo removedInfo;
9901
9902        public void setError(int code, String msg) {
9903            returnCode = code;
9904            returnMsg = msg;
9905            Slog.w(TAG, msg);
9906        }
9907
9908        public void setError(String msg, PackageParserException e) {
9909            returnCode = e.error;
9910            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9911            Slog.w(TAG, msg, e);
9912        }
9913
9914        public void setError(String msg, PackageManagerException e) {
9915            returnCode = e.error;
9916            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9917            Slog.w(TAG, msg, e);
9918        }
9919
9920        // In some error cases we want to convey more info back to the observer
9921        String origPackage;
9922        String origPermission;
9923    }
9924
9925    /*
9926     * Install a non-existing package.
9927     */
9928    private void installNewPackageLI(PackageParser.Package pkg,
9929            int parseFlags, int scanMode, UserHandle user,
9930            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9931        // Remember this for later, in case we need to rollback this install
9932        String pkgName = pkg.packageName;
9933
9934        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9935        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9936        synchronized(mPackages) {
9937            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9938                // A package with the same name is already installed, though
9939                // it has been renamed to an older name.  The package we
9940                // are trying to install should be installed as an update to
9941                // the existing one, but that has not been requested, so bail.
9942                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9943                        + " without first uninstalling package running as "
9944                        + mSettings.mRenamedPackages.get(pkgName));
9945                return;
9946            }
9947            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9948                // Don't allow installation over an existing package with the same name.
9949                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9950                        + " without first uninstalling.");
9951                return;
9952            }
9953        }
9954
9955        try {
9956            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9957                    System.currentTimeMillis(), user, abiOverride);
9958
9959            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9960            // delete the partially installed application. the data directory will have to be
9961            // restored if it was already existing
9962            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9963                // remove package from internal structures.  Note that we want deletePackageX to
9964                // delete the package data and cache directories that it created in
9965                // scanPackageLocked, unless those directories existed before we even tried to
9966                // install.
9967                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9968                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9969                                res.removedInfo, true);
9970            }
9971
9972        } catch (PackageManagerException e) {
9973            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9974        }
9975    }
9976
9977    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9978        // Upgrade keysets are being used.  Determine if new package has a superset of the
9979        // required keys.
9980        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9981        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9982        for (int i = 0; i < upgradeKeySets.length; i++) {
9983            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9984            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9985                return true;
9986            }
9987        }
9988        return false;
9989    }
9990
9991    private void replacePackageLI(PackageParser.Package pkg,
9992            int parseFlags, int scanMode, UserHandle user,
9993            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9994        PackageParser.Package oldPackage;
9995        String pkgName = pkg.packageName;
9996        int[] allUsers;
9997        boolean[] perUserInstalled;
9998
9999        // First find the old package info and check signatures
10000        synchronized(mPackages) {
10001            oldPackage = mPackages.get(pkgName);
10002            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10003            PackageSetting ps = mSettings.mPackages.get(pkgName);
10004            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10005                // default to original signature matching
10006                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10007                    != PackageManager.SIGNATURE_MATCH) {
10008                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10009                            "New package has a different signature: " + pkgName);
10010                    return;
10011                }
10012            } else {
10013                if(!checkUpgradeKeySetLP(ps, pkg)) {
10014                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10015                            "New package not signed by keys specified by upgrade-keysets: "
10016                            + pkgName);
10017                    return;
10018                }
10019            }
10020
10021            // In case of rollback, remember per-user/profile install state
10022            allUsers = sUserManager.getUserIds();
10023            perUserInstalled = new boolean[allUsers.length];
10024            for (int i = 0; i < allUsers.length; i++) {
10025                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10026            }
10027        }
10028
10029        boolean sysPkg = (isSystemApp(oldPackage));
10030        if (sysPkg) {
10031            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10032                    user, allUsers, perUserInstalled, installerPackageName, res,
10033                    abiOverride);
10034        } else {
10035            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10036                    user, allUsers, perUserInstalled, installerPackageName, res,
10037                    abiOverride);
10038        }
10039    }
10040
10041    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10042            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10043            int[] allUsers, boolean[] perUserInstalled,
10044            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10045        String pkgName = deletedPackage.packageName;
10046        boolean deletedPkg = true;
10047        boolean updatedSettings = false;
10048
10049        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10050                + deletedPackage);
10051        long origUpdateTime;
10052        if (pkg.mExtras != null) {
10053            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10054        } else {
10055            origUpdateTime = 0;
10056        }
10057
10058        // First delete the existing package while retaining the data directory
10059        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10060                res.removedInfo, true)) {
10061            // If the existing package wasn't successfully deleted
10062            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10063            deletedPkg = false;
10064        } else {
10065            // Successfully deleted the old package. Now proceed with re-installation
10066            deleteCodeCacheDirsLI(pkgName);
10067            try {
10068                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10069                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
10070                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10071                updatedSettings = true;
10072            } catch (PackageManagerException e) {
10073                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10074            }
10075        }
10076
10077        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10078            // remove package from internal structures.  Note that we want deletePackageX to
10079            // delete the package data and cache directories that it created in
10080            // scanPackageLocked, unless those directories existed before we even tried to
10081            // install.
10082            if(updatedSettings) {
10083                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10084                deletePackageLI(
10085                        pkgName, null, true, allUsers, perUserInstalled,
10086                        PackageManager.DELETE_KEEP_DATA,
10087                                res.removedInfo, true);
10088            }
10089            // Since we failed to install the new package we need to restore the old
10090            // package that we deleted.
10091            if (deletedPkg) {
10092                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10093                File restoreFile = new File(deletedPackage.codePath);
10094                // Parse old package
10095                boolean oldOnSd = isExternal(deletedPackage);
10096                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10097                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10098                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10099                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10100                        | SCAN_UPDATE_TIME;
10101                try {
10102                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10103                            null);
10104                } catch (PackageManagerException e) {
10105                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10106                            + e.getMessage());
10107                    return;
10108                }
10109                // Restore of old package succeeded. Update permissions.
10110                // writer
10111                synchronized (mPackages) {
10112                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10113                            UPDATE_PERMISSIONS_ALL);
10114                    // can downgrade to reader
10115                    mSettings.writeLPr();
10116                }
10117                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10118            }
10119        }
10120    }
10121
10122    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10123            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10124            int[] allUsers, boolean[] perUserInstalled,
10125            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10126        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10127                + ", old=" + deletedPackage);
10128        boolean updatedSettings = false;
10129        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10130                PackageParser.PARSE_IS_SYSTEM;
10131        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10132            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10133        }
10134        String packageName = deletedPackage.packageName;
10135        if (packageName == null) {
10136            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10137                    "Attempt to delete null packageName.");
10138            return;
10139        }
10140        PackageParser.Package oldPkg;
10141        PackageSetting oldPkgSetting;
10142        // reader
10143        synchronized (mPackages) {
10144            oldPkg = mPackages.get(packageName);
10145            oldPkgSetting = mSettings.mPackages.get(packageName);
10146            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10147                    (oldPkgSetting == null)) {
10148                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10149                        "Couldn't find package:" + packageName + " information");
10150                return;
10151            }
10152        }
10153
10154        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10155
10156        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10157        res.removedInfo.removedPackage = packageName;
10158        // Remove existing system package
10159        removePackageLI(oldPkgSetting, true);
10160        // writer
10161        synchronized (mPackages) {
10162            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10163                // We didn't need to disable the .apk as a current system package,
10164                // which means we are replacing another update that is already
10165                // installed.  We need to make sure to delete the older one's .apk.
10166                res.removedInfo.args = createInstallArgsForExisting(0,
10167                        deletedPackage.applicationInfo.getCodePath(),
10168                        deletedPackage.applicationInfo.getResourcePath(),
10169                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10170                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10171                        isMultiArch(deletedPackage.applicationInfo));
10172            } else {
10173                res.removedInfo.args = null;
10174            }
10175        }
10176
10177        // Successfully disabled the old package. Now proceed with re-installation
10178        deleteCodeCacheDirsLI(packageName);
10179
10180        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10181        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10182
10183        PackageParser.Package newPackage = null;
10184        try {
10185            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10186            if (newPackage.mExtras != null) {
10187                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10188                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10189                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10190
10191                // is the update attempting to change shared user? that isn't going to work...
10192                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10193                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10194                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10195                            + " to " + newPkgSetting.sharedUser);
10196                    updatedSettings = true;
10197                }
10198            }
10199
10200            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10201                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10202                updatedSettings = true;
10203            }
10204
10205        } catch (PackageManagerException e) {
10206            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10207        }
10208
10209        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10210            // Re installation failed. Restore old information
10211            // Remove new pkg information
10212            if (newPackage != null) {
10213                removeInstalledPackageLI(newPackage, true);
10214            }
10215            // Add back the old system package
10216            try {
10217                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10218                        null);
10219            } catch (PackageManagerException e) {
10220                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10221            }
10222            // Restore the old system information in Settings
10223            synchronized(mPackages) {
10224                if (updatedSettings) {
10225                    mSettings.enableSystemPackageLPw(packageName);
10226                    mSettings.setInstallerPackageName(packageName,
10227                            oldPkgSetting.installerPackageName);
10228                }
10229                mSettings.writeLPr();
10230            }
10231        }
10232    }
10233
10234    // Utility method used to move dex files during install.
10235    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10236        // TODO: extend to move split APK dex files
10237        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10238            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10239            for (String instructionSet : instructionSets) {
10240                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10241                        instructionSet);
10242                if (retCode != 0) {
10243                /*
10244                 * Programs may be lazily run through dexopt, so the
10245                 * source may not exist. However, something seems to
10246                 * have gone wrong, so note that dexopt needs to be
10247                 * run again and remove the source file. In addition,
10248                 * remove the target to make sure there isn't a stale
10249                 * file from a previous version of the package.
10250                 */
10251                    newPackage.mDexOptPerformed.clear();
10252                    mInstaller.rmdex(oldCodePath, instructionSet);
10253                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10254                }
10255            }
10256        }
10257        return PackageManager.INSTALL_SUCCEEDED;
10258    }
10259
10260    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10261            int[] allUsers, boolean[] perUserInstalled,
10262            PackageInstalledInfo res) {
10263        String pkgName = newPackage.packageName;
10264        synchronized (mPackages) {
10265            //write settings. the installStatus will be incomplete at this stage.
10266            //note that the new package setting would have already been
10267            //added to mPackages. It hasn't been persisted yet.
10268            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10269            mSettings.writeLPr();
10270        }
10271
10272        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10273
10274        synchronized (mPackages) {
10275            updatePermissionsLPw(newPackage.packageName, newPackage,
10276                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10277                            ? UPDATE_PERMISSIONS_ALL : 0));
10278            // For system-bundled packages, we assume that installing an upgraded version
10279            // of the package implies that the user actually wants to run that new code,
10280            // so we enable the package.
10281            if (isSystemApp(newPackage)) {
10282                // NB: implicit assumption that system package upgrades apply to all users
10283                if (DEBUG_INSTALL) {
10284                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10285                }
10286                PackageSetting ps = mSettings.mPackages.get(pkgName);
10287                if (ps != null) {
10288                    if (res.origUsers != null) {
10289                        for (int userHandle : res.origUsers) {
10290                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10291                                    userHandle, installerPackageName);
10292                        }
10293                    }
10294                    // Also convey the prior install/uninstall state
10295                    if (allUsers != null && perUserInstalled != null) {
10296                        for (int i = 0; i < allUsers.length; i++) {
10297                            if (DEBUG_INSTALL) {
10298                                Slog.d(TAG, "    user " + allUsers[i]
10299                                        + " => " + perUserInstalled[i]);
10300                            }
10301                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10302                        }
10303                        // these install state changes will be persisted in the
10304                        // upcoming call to mSettings.writeLPr().
10305                    }
10306                }
10307            }
10308            res.name = pkgName;
10309            res.uid = newPackage.applicationInfo.uid;
10310            res.pkg = newPackage;
10311            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10312            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10313            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10314            //to update install status
10315            mSettings.writeLPr();
10316        }
10317    }
10318
10319    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10320        int pFlags = args.flags;
10321        String installerPackageName = args.installerPackageName;
10322        File tmpPackageFile = new File(args.getCodePath());
10323        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10324        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10325        boolean replace = false;
10326        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10327                | (newInstall ? SCAN_NEW_INSTALL : 0);
10328        // Result object to be returned
10329        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10330
10331        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10332        // Retrieve PackageSettings and parse package
10333        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10334                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10335                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10336        PackageParser pp = new PackageParser();
10337        pp.setSeparateProcesses(mSeparateProcesses);
10338        pp.setDisplayMetrics(mMetrics);
10339
10340        final PackageParser.Package pkg;
10341        try {
10342            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10343        } catch (PackageParserException e) {
10344            res.setError("Failed parse during installPackageLI", e);
10345            return;
10346        }
10347
10348        String pkgName = res.name = pkg.packageName;
10349        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10350            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10351                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10352                return;
10353            }
10354        }
10355
10356        try {
10357            pp.collectCertificates(pkg, parseFlags);
10358            pp.collectManifestDigest(pkg);
10359        } catch (PackageParserException e) {
10360            res.setError("Failed collect during installPackageLI", e);
10361            return;
10362        }
10363
10364        /* If the installer passed in a manifest digest, compare it now. */
10365        if (args.manifestDigest != null) {
10366            if (DEBUG_INSTALL) {
10367                final String parsedManifest = pkg.manifestDigest == null ? "null"
10368                        : pkg.manifestDigest.toString();
10369                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10370                        + parsedManifest);
10371            }
10372
10373            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10374                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10375                return;
10376            }
10377        } else if (DEBUG_INSTALL) {
10378            final String parsedManifest = pkg.manifestDigest == null
10379                    ? "null" : pkg.manifestDigest.toString();
10380            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10381        }
10382
10383        // Get rid of all references to package scan path via parser.
10384        pp = null;
10385        String oldCodePath = null;
10386        boolean systemApp = false;
10387        synchronized (mPackages) {
10388            // Check whether the newly-scanned package wants to define an already-defined perm
10389            int N = pkg.permissions.size();
10390            for (int i = N-1; i >= 0; i--) {
10391                PackageParser.Permission perm = pkg.permissions.get(i);
10392                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10393                if (bp != null) {
10394                    // If the defining package is signed with our cert, it's okay.  This
10395                    // also includes the "updating the same package" case, of course.
10396                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10397                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10398                        // If the owning package is the system itself, we log but allow
10399                        // install to proceed; we fail the install on all other permission
10400                        // redefinitions.
10401                        if (!bp.sourcePackage.equals("android")) {
10402                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10403                                    + pkg.packageName + " attempting to redeclare permission "
10404                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10405                            res.origPermission = perm.info.name;
10406                            res.origPackage = bp.sourcePackage;
10407                            return;
10408                        } else {
10409                            Slog.w(TAG, "Package " + pkg.packageName
10410                                    + " attempting to redeclare system permission "
10411                                    + perm.info.name + "; ignoring new declaration");
10412                            pkg.permissions.remove(i);
10413                        }
10414                    }
10415                }
10416            }
10417
10418            // Check if installing already existing package
10419            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10420                String oldName = mSettings.mRenamedPackages.get(pkgName);
10421                if (pkg.mOriginalPackages != null
10422                        && pkg.mOriginalPackages.contains(oldName)
10423                        && mPackages.containsKey(oldName)) {
10424                    // This package is derived from an original package,
10425                    // and this device has been updating from that original
10426                    // name.  We must continue using the original name, so
10427                    // rename the new package here.
10428                    pkg.setPackageName(oldName);
10429                    pkgName = pkg.packageName;
10430                    replace = true;
10431                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10432                            + oldName + " pkgName=" + pkgName);
10433                } else if (mPackages.containsKey(pkgName)) {
10434                    // This package, under its official name, already exists
10435                    // on the device; we should replace it.
10436                    replace = true;
10437                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10438                }
10439            }
10440            PackageSetting ps = mSettings.mPackages.get(pkgName);
10441            if (ps != null) {
10442                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10443                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10444                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10445                    systemApp = (ps.pkg.applicationInfo.flags &
10446                            ApplicationInfo.FLAG_SYSTEM) != 0;
10447                }
10448                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10449            }
10450        }
10451
10452        if (systemApp && onSd) {
10453            // Disable updates to system apps on sdcard
10454            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10455                    "Cannot install updates to system apps on sdcard");
10456            return;
10457        }
10458
10459        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10460            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10461            return;
10462        }
10463
10464        if (replace) {
10465            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10466                    installerPackageName, res, args.abiOverride);
10467        } else {
10468            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10469                    installerPackageName, res, args.abiOverride);
10470        }
10471        synchronized (mPackages) {
10472            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10473            if (ps != null) {
10474                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10475            }
10476        }
10477    }
10478
10479    private static boolean isForwardLocked(PackageParser.Package pkg) {
10480        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10481    }
10482
10483    private static boolean isForwardLocked(ApplicationInfo info) {
10484        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10485    }
10486
10487    private boolean isForwardLocked(PackageSetting ps) {
10488        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10489    }
10490
10491    private static boolean isMultiArch(PackageSetting ps) {
10492        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10493    }
10494
10495    private static boolean isMultiArch(ApplicationInfo info) {
10496        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10497    }
10498
10499    private static boolean isExternal(PackageParser.Package pkg) {
10500        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10501    }
10502
10503    private static boolean isExternal(PackageSetting ps) {
10504        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10505    }
10506
10507    private static boolean isExternal(ApplicationInfo info) {
10508        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10509    }
10510
10511    private static boolean isSystemApp(PackageParser.Package pkg) {
10512        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10513    }
10514
10515    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10516        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10517    }
10518
10519    private static boolean isSystemApp(ApplicationInfo info) {
10520        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10521    }
10522
10523    private static boolean isSystemApp(PackageSetting ps) {
10524        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10525    }
10526
10527    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10528        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10529    }
10530
10531    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10532        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10533    }
10534
10535    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10536        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10537    }
10538
10539    private int packageFlagsToInstallFlags(PackageSetting ps) {
10540        int installFlags = 0;
10541        if (isExternal(ps)) {
10542            installFlags |= PackageManager.INSTALL_EXTERNAL;
10543        }
10544        if (isForwardLocked(ps)) {
10545            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10546        }
10547        return installFlags;
10548    }
10549
10550    private void deleteTempPackageFiles() {
10551        final FilenameFilter filter = new FilenameFilter() {
10552            public boolean accept(File dir, String name) {
10553                return name.startsWith("vmdl") && name.endsWith(".tmp");
10554            }
10555        };
10556        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10557            file.delete();
10558        }
10559    }
10560
10561    @Override
10562    public void deletePackageAsUser(final String packageName,
10563                                    final IPackageDeleteObserver observer,
10564                                    final int userId, final int flags) {
10565        mContext.enforceCallingOrSelfPermission(
10566                android.Manifest.permission.DELETE_PACKAGES, null);
10567        final int uid = Binder.getCallingUid();
10568        if (UserHandle.getUserId(uid) != userId) {
10569            mContext.enforceCallingPermission(
10570                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10571                    "deletePackage for user " + userId);
10572        }
10573        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10574            try {
10575                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10576            } catch (RemoteException re) {
10577            }
10578            return;
10579        }
10580
10581        boolean blocked = false;
10582        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10583            int[] users = sUserManager.getUserIds();
10584            for (int i = 0; i < users.length; ++i) {
10585                if (getBlockUninstallForUser(packageName, users[i])) {
10586                    blocked = true;
10587                    break;
10588                }
10589            }
10590        } else {
10591            blocked = getBlockUninstallForUser(packageName, userId);
10592        }
10593        if (blocked) {
10594            try {
10595                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED);
10596            } catch (RemoteException re) {
10597            }
10598            return;
10599        }
10600
10601        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10602        // Queue up an async operation since the package deletion may take a little while.
10603        mHandler.post(new Runnable() {
10604            public void run() {
10605                mHandler.removeCallbacks(this);
10606                final int returnCode = deletePackageX(packageName, userId, flags);
10607                if (observer != null) {
10608                    try {
10609                        observer.packageDeleted(packageName, returnCode);
10610                    } catch (RemoteException e) {
10611                        Log.i(TAG, "Observer no longer exists.");
10612                    } //end catch
10613                } //end if
10614            } //end run
10615        });
10616    }
10617
10618    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10619        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10620                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10621        try {
10622            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10623                    || dpm.isDeviceOwner(packageName))) {
10624                return true;
10625            }
10626        } catch (RemoteException e) {
10627        }
10628        return false;
10629    }
10630
10631    /**
10632     *  This method is an internal method that could be get invoked either
10633     *  to delete an installed package or to clean up a failed installation.
10634     *  After deleting an installed package, a broadcast is sent to notify any
10635     *  listeners that the package has been installed. For cleaning up a failed
10636     *  installation, the broadcast is not necessary since the package's
10637     *  installation wouldn't have sent the initial broadcast either
10638     *  The key steps in deleting a package are
10639     *  deleting the package information in internal structures like mPackages,
10640     *  deleting the packages base directories through installd
10641     *  updating mSettings to reflect current status
10642     *  persisting settings for later use
10643     *  sending a broadcast if necessary
10644     */
10645    private int deletePackageX(String packageName, int userId, int flags) {
10646        final PackageRemovedInfo info = new PackageRemovedInfo();
10647        final boolean res;
10648
10649        if (isPackageDeviceAdmin(packageName, userId)) {
10650            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10651            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10652        }
10653
10654        boolean removedForAllUsers = false;
10655        boolean systemUpdate = false;
10656
10657        // for the uninstall-updates case and restricted profiles, remember the per-
10658        // userhandle installed state
10659        int[] allUsers;
10660        boolean[] perUserInstalled;
10661        synchronized (mPackages) {
10662            PackageSetting ps = mSettings.mPackages.get(packageName);
10663            allUsers = sUserManager.getUserIds();
10664            perUserInstalled = new boolean[allUsers.length];
10665            for (int i = 0; i < allUsers.length; i++) {
10666                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10667            }
10668        }
10669
10670        synchronized (mInstallLock) {
10671            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10672            res = deletePackageLI(packageName,
10673                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10674                            ? UserHandle.ALL : new UserHandle(userId),
10675                    true, allUsers, perUserInstalled,
10676                    flags | REMOVE_CHATTY, info, true);
10677            systemUpdate = info.isRemovedPackageSystemUpdate;
10678            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10679                removedForAllUsers = true;
10680            }
10681            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10682                    + " removedForAllUsers=" + removedForAllUsers);
10683        }
10684
10685        if (res) {
10686            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10687
10688            // If the removed package was a system update, the old system package
10689            // was re-enabled; we need to broadcast this information
10690            if (systemUpdate) {
10691                Bundle extras = new Bundle(1);
10692                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10693                        ? info.removedAppId : info.uid);
10694                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10695
10696                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10697                        extras, null, null, null);
10698                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10699                        extras, null, null, null);
10700                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10701                        null, packageName, null, null);
10702            }
10703        }
10704        // Force a gc here.
10705        Runtime.getRuntime().gc();
10706        // Delete the resources here after sending the broadcast to let
10707        // other processes clean up before deleting resources.
10708        if (info.args != null) {
10709            synchronized (mInstallLock) {
10710                info.args.doPostDeleteLI(true);
10711            }
10712        }
10713
10714        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10715    }
10716
10717    static class PackageRemovedInfo {
10718        String removedPackage;
10719        int uid = -1;
10720        int removedAppId = -1;
10721        int[] removedUsers = null;
10722        boolean isRemovedPackageSystemUpdate = false;
10723        // Clean up resources deleted packages.
10724        InstallArgs args = null;
10725
10726        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10727            Bundle extras = new Bundle(1);
10728            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10729            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10730            if (replacing) {
10731                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10732            }
10733            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10734            if (removedPackage != null) {
10735                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10736                        extras, null, null, removedUsers);
10737                if (fullRemove && !replacing) {
10738                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10739                            extras, null, null, removedUsers);
10740                }
10741            }
10742            if (removedAppId >= 0) {
10743                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10744                        removedUsers);
10745            }
10746        }
10747    }
10748
10749    /*
10750     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10751     * flag is not set, the data directory is removed as well.
10752     * make sure this flag is set for partially installed apps. If not its meaningless to
10753     * delete a partially installed application.
10754     */
10755    private void removePackageDataLI(PackageSetting ps,
10756            int[] allUserHandles, boolean[] perUserInstalled,
10757            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10758        String packageName = ps.name;
10759        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10760        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10761        // Retrieve object to delete permissions for shared user later on
10762        final PackageSetting deletedPs;
10763        // reader
10764        synchronized (mPackages) {
10765            deletedPs = mSettings.mPackages.get(packageName);
10766            if (outInfo != null) {
10767                outInfo.removedPackage = packageName;
10768                outInfo.removedUsers = deletedPs != null
10769                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10770                        : null;
10771            }
10772        }
10773        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10774            removeDataDirsLI(packageName);
10775            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10776        }
10777        // writer
10778        synchronized (mPackages) {
10779            if (deletedPs != null) {
10780                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10781                    if (outInfo != null) {
10782                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10783                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10784                    }
10785                    if (deletedPs != null) {
10786                        updatePermissionsLPw(deletedPs.name, null, 0);
10787                        if (deletedPs.sharedUser != null) {
10788                            // remove permissions associated with package
10789                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10790                        }
10791                    }
10792                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10793                }
10794                // make sure to preserve per-user disabled state if this removal was just
10795                // a downgrade of a system app to the factory package
10796                if (allUserHandles != null && perUserInstalled != null) {
10797                    if (DEBUG_REMOVE) {
10798                        Slog.d(TAG, "Propagating install state across downgrade");
10799                    }
10800                    for (int i = 0; i < allUserHandles.length; i++) {
10801                        if (DEBUG_REMOVE) {
10802                            Slog.d(TAG, "    user " + allUserHandles[i]
10803                                    + " => " + perUserInstalled[i]);
10804                        }
10805                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10806                    }
10807                }
10808            }
10809            // can downgrade to reader
10810            if (writeSettings) {
10811                // Save settings now
10812                mSettings.writeLPr();
10813            }
10814        }
10815        if (outInfo != null) {
10816            // A user ID was deleted here. Go through all users and remove it
10817            // from KeyStore.
10818            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10819        }
10820    }
10821
10822    static boolean locationIsPrivileged(File path) {
10823        try {
10824            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10825                    .getCanonicalPath();
10826            return path.getCanonicalPath().startsWith(privilegedAppDir);
10827        } catch (IOException e) {
10828            Slog.e(TAG, "Unable to access code path " + path);
10829        }
10830        return false;
10831    }
10832
10833    /*
10834     * Tries to delete system package.
10835     */
10836    private boolean deleteSystemPackageLI(PackageSetting newPs,
10837            int[] allUserHandles, boolean[] perUserInstalled,
10838            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10839        final boolean applyUserRestrictions
10840                = (allUserHandles != null) && (perUserInstalled != null);
10841        PackageSetting disabledPs = null;
10842        // Confirm if the system package has been updated
10843        // An updated system app can be deleted. This will also have to restore
10844        // the system pkg from system partition
10845        // reader
10846        synchronized (mPackages) {
10847            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10848        }
10849        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10850                + " disabledPs=" + disabledPs);
10851        if (disabledPs == null) {
10852            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10853            return false;
10854        } else if (DEBUG_REMOVE) {
10855            Slog.d(TAG, "Deleting system pkg from data partition");
10856        }
10857        if (DEBUG_REMOVE) {
10858            if (applyUserRestrictions) {
10859                Slog.d(TAG, "Remembering install states:");
10860                for (int i = 0; i < allUserHandles.length; i++) {
10861                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10862                }
10863            }
10864        }
10865        // Delete the updated package
10866        outInfo.isRemovedPackageSystemUpdate = true;
10867        if (disabledPs.versionCode < newPs.versionCode) {
10868            // Delete data for downgrades
10869            flags &= ~PackageManager.DELETE_KEEP_DATA;
10870        } else {
10871            // Preserve data by setting flag
10872            flags |= PackageManager.DELETE_KEEP_DATA;
10873        }
10874        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10875                allUserHandles, perUserInstalled, outInfo, writeSettings);
10876        if (!ret) {
10877            return false;
10878        }
10879        // writer
10880        synchronized (mPackages) {
10881            // Reinstate the old system package
10882            mSettings.enableSystemPackageLPw(newPs.name);
10883            // Remove any native libraries from the upgraded package.
10884            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10885        }
10886        // Install the system package
10887        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10888        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10889        if (locationIsPrivileged(disabledPs.codePath)) {
10890            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10891        }
10892
10893        final PackageParser.Package newPkg;
10894        try {
10895            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10896                    null, null);
10897        } catch (PackageManagerException e) {
10898            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10899            return false;
10900        }
10901
10902        // writer
10903        synchronized (mPackages) {
10904            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10905            setBundledAppAbisAndRoots(newPkg, ps);
10906            updatePermissionsLPw(newPkg.packageName, newPkg,
10907                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10908            if (applyUserRestrictions) {
10909                if (DEBUG_REMOVE) {
10910                    Slog.d(TAG, "Propagating install state across reinstall");
10911                }
10912                for (int i = 0; i < allUserHandles.length; i++) {
10913                    if (DEBUG_REMOVE) {
10914                        Slog.d(TAG, "    user " + allUserHandles[i]
10915                                + " => " + perUserInstalled[i]);
10916                    }
10917                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10918                }
10919                // Regardless of writeSettings we need to ensure that this restriction
10920                // state propagation is persisted
10921                mSettings.writeAllUsersPackageRestrictionsLPr();
10922            }
10923            // can downgrade to reader here
10924            if (writeSettings) {
10925                mSettings.writeLPr();
10926            }
10927        }
10928        return true;
10929    }
10930
10931    private boolean deleteInstalledPackageLI(PackageSetting ps,
10932            boolean deleteCodeAndResources, int flags,
10933            int[] allUserHandles, boolean[] perUserInstalled,
10934            PackageRemovedInfo outInfo, boolean writeSettings) {
10935        if (outInfo != null) {
10936            outInfo.uid = ps.appId;
10937        }
10938
10939        // Delete package data from internal structures and also remove data if flag is set
10940        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10941
10942        // Delete application code and resources
10943        if (deleteCodeAndResources && (outInfo != null)) {
10944            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10945                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10946                    getAppDexInstructionSets(ps), isMultiArch(ps));
10947        }
10948        return true;
10949    }
10950
10951    @Override
10952    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10953            int userId) {
10954        mContext.enforceCallingOrSelfPermission(
10955                android.Manifest.permission.DELETE_PACKAGES, null);
10956        synchronized (mPackages) {
10957            PackageSetting ps = mSettings.mPackages.get(packageName);
10958            if (ps == null) {
10959                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10960                return false;
10961            }
10962            if (!ps.getInstalled(userId)) {
10963                // Can't block uninstall for an app that is not installed or enabled.
10964                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10965                return false;
10966            }
10967            ps.setBlockUninstall(blockUninstall, userId);
10968            mSettings.writePackageRestrictionsLPr(userId);
10969        }
10970        return true;
10971    }
10972
10973    @Override
10974    public boolean getBlockUninstallForUser(String packageName, int userId) {
10975        synchronized (mPackages) {
10976            PackageSetting ps = mSettings.mPackages.get(packageName);
10977            if (ps == null) {
10978                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10979                return false;
10980            }
10981            return ps.getBlockUninstall(userId);
10982        }
10983    }
10984
10985    /*
10986     * This method handles package deletion in general
10987     */
10988    private boolean deletePackageLI(String packageName, UserHandle user,
10989            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10990            int flags, PackageRemovedInfo outInfo,
10991            boolean writeSettings) {
10992        if (packageName == null) {
10993            Slog.w(TAG, "Attempt to delete null packageName.");
10994            return false;
10995        }
10996        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10997        PackageSetting ps;
10998        boolean dataOnly = false;
10999        int removeUser = -1;
11000        int appId = -1;
11001        synchronized (mPackages) {
11002            ps = mSettings.mPackages.get(packageName);
11003            if (ps == null) {
11004                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11005                return false;
11006            }
11007            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11008                    && user.getIdentifier() != UserHandle.USER_ALL) {
11009                // The caller is asking that the package only be deleted for a single
11010                // user.  To do this, we just mark its uninstalled state and delete
11011                // its data.  If this is a system app, we only allow this to happen if
11012                // they have set the special DELETE_SYSTEM_APP which requests different
11013                // semantics than normal for uninstalling system apps.
11014                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11015                ps.setUserState(user.getIdentifier(),
11016                        COMPONENT_ENABLED_STATE_DEFAULT,
11017                        false, //installed
11018                        true,  //stopped
11019                        true,  //notLaunched
11020                        false, //blocked
11021                        null, null, null,
11022                        false // blockUninstall
11023                        );
11024                if (!isSystemApp(ps)) {
11025                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11026                        // Other user still have this package installed, so all
11027                        // we need to do is clear this user's data and save that
11028                        // it is uninstalled.
11029                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11030                        removeUser = user.getIdentifier();
11031                        appId = ps.appId;
11032                        mSettings.writePackageRestrictionsLPr(removeUser);
11033                    } else {
11034                        // We need to set it back to 'installed' so the uninstall
11035                        // broadcasts will be sent correctly.
11036                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11037                        ps.setInstalled(true, user.getIdentifier());
11038                    }
11039                } else {
11040                    // This is a system app, so we assume that the
11041                    // other users still have this package installed, so all
11042                    // we need to do is clear this user's data and save that
11043                    // it is uninstalled.
11044                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11045                    removeUser = user.getIdentifier();
11046                    appId = ps.appId;
11047                    mSettings.writePackageRestrictionsLPr(removeUser);
11048                }
11049            }
11050        }
11051
11052        if (removeUser >= 0) {
11053            // From above, we determined that we are deleting this only
11054            // for a single user.  Continue the work here.
11055            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11056            if (outInfo != null) {
11057                outInfo.removedPackage = packageName;
11058                outInfo.removedAppId = appId;
11059                outInfo.removedUsers = new int[] {removeUser};
11060            }
11061            mInstaller.clearUserData(packageName, removeUser);
11062            removeKeystoreDataIfNeeded(removeUser, appId);
11063            schedulePackageCleaning(packageName, removeUser, false);
11064            return true;
11065        }
11066
11067        if (dataOnly) {
11068            // Delete application data first
11069            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11070            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11071            return true;
11072        }
11073
11074        boolean ret = false;
11075        if (isSystemApp(ps)) {
11076            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11077            // When an updated system application is deleted we delete the existing resources as well and
11078            // fall back to existing code in system partition
11079            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11080                    flags, outInfo, writeSettings);
11081        } else {
11082            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11083            // Kill application pre-emptively especially for apps on sd.
11084            killApplication(packageName, ps.appId, "uninstall pkg");
11085            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11086                    allUserHandles, perUserInstalled,
11087                    outInfo, writeSettings);
11088        }
11089
11090        return ret;
11091    }
11092
11093    private final class ClearStorageConnection implements ServiceConnection {
11094        IMediaContainerService mContainerService;
11095
11096        @Override
11097        public void onServiceConnected(ComponentName name, IBinder service) {
11098            synchronized (this) {
11099                mContainerService = IMediaContainerService.Stub.asInterface(service);
11100                notifyAll();
11101            }
11102        }
11103
11104        @Override
11105        public void onServiceDisconnected(ComponentName name) {
11106        }
11107    }
11108
11109    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11110        final boolean mounted;
11111        if (Environment.isExternalStorageEmulated()) {
11112            mounted = true;
11113        } else {
11114            final String status = Environment.getExternalStorageState();
11115
11116            mounted = status.equals(Environment.MEDIA_MOUNTED)
11117                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11118        }
11119
11120        if (!mounted) {
11121            return;
11122        }
11123
11124        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11125        int[] users;
11126        if (userId == UserHandle.USER_ALL) {
11127            users = sUserManager.getUserIds();
11128        } else {
11129            users = new int[] { userId };
11130        }
11131        final ClearStorageConnection conn = new ClearStorageConnection();
11132        if (mContext.bindServiceAsUser(
11133                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11134            try {
11135                for (int curUser : users) {
11136                    long timeout = SystemClock.uptimeMillis() + 5000;
11137                    synchronized (conn) {
11138                        long now = SystemClock.uptimeMillis();
11139                        while (conn.mContainerService == null && now < timeout) {
11140                            try {
11141                                conn.wait(timeout - now);
11142                            } catch (InterruptedException e) {
11143                            }
11144                        }
11145                    }
11146                    if (conn.mContainerService == null) {
11147                        return;
11148                    }
11149
11150                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11151                    clearDirectory(conn.mContainerService,
11152                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11153                    if (allData) {
11154                        clearDirectory(conn.mContainerService,
11155                                userEnv.buildExternalStorageAppDataDirs(packageName));
11156                        clearDirectory(conn.mContainerService,
11157                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11158                    }
11159                }
11160            } finally {
11161                mContext.unbindService(conn);
11162            }
11163        }
11164    }
11165
11166    @Override
11167    public void clearApplicationUserData(final String packageName,
11168            final IPackageDataObserver observer, final int userId) {
11169        mContext.enforceCallingOrSelfPermission(
11170                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11171        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11172        // Queue up an async operation since the package deletion may take a little while.
11173        mHandler.post(new Runnable() {
11174            public void run() {
11175                mHandler.removeCallbacks(this);
11176                final boolean succeeded;
11177                synchronized (mInstallLock) {
11178                    succeeded = clearApplicationUserDataLI(packageName, userId);
11179                }
11180                clearExternalStorageDataSync(packageName, userId, true);
11181                if (succeeded) {
11182                    // invoke DeviceStorageMonitor's update method to clear any notifications
11183                    DeviceStorageMonitorInternal
11184                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11185                    if (dsm != null) {
11186                        dsm.checkMemory();
11187                    }
11188                }
11189                if(observer != null) {
11190                    try {
11191                        observer.onRemoveCompleted(packageName, succeeded);
11192                    } catch (RemoteException e) {
11193                        Log.i(TAG, "Observer no longer exists.");
11194                    }
11195                } //end if observer
11196            } //end run
11197        });
11198    }
11199
11200    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11201        if (packageName == null) {
11202            Slog.w(TAG, "Attempt to delete null packageName.");
11203            return false;
11204        }
11205        PackageParser.Package p;
11206        boolean dataOnly = false;
11207        final int appId;
11208        synchronized (mPackages) {
11209            p = mPackages.get(packageName);
11210            if (p == null) {
11211                dataOnly = true;
11212                PackageSetting ps = mSettings.mPackages.get(packageName);
11213                if ((ps == null) || (ps.pkg == null)) {
11214                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11215                    return false;
11216                }
11217                p = ps.pkg;
11218            }
11219            if (!dataOnly) {
11220                // need to check this only for fully installed applications
11221                if (p == null) {
11222                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11223                    return false;
11224                }
11225                final ApplicationInfo applicationInfo = p.applicationInfo;
11226                if (applicationInfo == null) {
11227                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11228                    return false;
11229                }
11230            }
11231            if (p != null && p.applicationInfo != null) {
11232                appId = p.applicationInfo.uid;
11233            } else {
11234                appId = -1;
11235            }
11236        }
11237        int retCode = mInstaller.clearUserData(packageName, userId);
11238        if (retCode < 0) {
11239            Slog.w(TAG, "Couldn't remove cache files for package: "
11240                    + packageName);
11241            return false;
11242        }
11243        removeKeystoreDataIfNeeded(userId, appId);
11244        return true;
11245    }
11246
11247    /**
11248     * Remove entries from the keystore daemon. Will only remove it if the
11249     * {@code appId} is valid.
11250     */
11251    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11252        if (appId < 0) {
11253            return;
11254        }
11255
11256        final KeyStore keyStore = KeyStore.getInstance();
11257        if (keyStore != null) {
11258            if (userId == UserHandle.USER_ALL) {
11259                for (final int individual : sUserManager.getUserIds()) {
11260                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11261                }
11262            } else {
11263                keyStore.clearUid(UserHandle.getUid(userId, appId));
11264            }
11265        } else {
11266            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11267        }
11268    }
11269
11270    @Override
11271    public void deleteApplicationCacheFiles(final String packageName,
11272            final IPackageDataObserver observer) {
11273        mContext.enforceCallingOrSelfPermission(
11274                android.Manifest.permission.DELETE_CACHE_FILES, null);
11275        // Queue up an async operation since the package deletion may take a little while.
11276        final int userId = UserHandle.getCallingUserId();
11277        mHandler.post(new Runnable() {
11278            public void run() {
11279                mHandler.removeCallbacks(this);
11280                final boolean succeded;
11281                synchronized (mInstallLock) {
11282                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11283                }
11284                clearExternalStorageDataSync(packageName, userId, false);
11285                if(observer != null) {
11286                    try {
11287                        observer.onRemoveCompleted(packageName, succeded);
11288                    } catch (RemoteException e) {
11289                        Log.i(TAG, "Observer no longer exists.");
11290                    }
11291                } //end if observer
11292            } //end run
11293        });
11294    }
11295
11296    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11297        if (packageName == null) {
11298            Slog.w(TAG, "Attempt to delete null packageName.");
11299            return false;
11300        }
11301        PackageParser.Package p;
11302        synchronized (mPackages) {
11303            p = mPackages.get(packageName);
11304        }
11305        if (p == null) {
11306            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11307            return false;
11308        }
11309        final ApplicationInfo applicationInfo = p.applicationInfo;
11310        if (applicationInfo == null) {
11311            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11312            return false;
11313        }
11314        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11315        if (retCode < 0) {
11316            Slog.w(TAG, "Couldn't remove cache files for package: "
11317                       + packageName + " u" + userId);
11318            return false;
11319        }
11320        return true;
11321    }
11322
11323    @Override
11324    public void getPackageSizeInfo(final String packageName, int userHandle,
11325            final IPackageStatsObserver observer) {
11326        mContext.enforceCallingOrSelfPermission(
11327                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11328        if (packageName == null) {
11329            throw new IllegalArgumentException("Attempt to get size of null packageName");
11330        }
11331
11332        PackageStats stats = new PackageStats(packageName, userHandle);
11333
11334        /*
11335         * Queue up an async operation since the package measurement may take a
11336         * little while.
11337         */
11338        Message msg = mHandler.obtainMessage(INIT_COPY);
11339        msg.obj = new MeasureParams(stats, observer);
11340        mHandler.sendMessage(msg);
11341    }
11342
11343    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11344            PackageStats pStats) {
11345        if (packageName == null) {
11346            Slog.w(TAG, "Attempt to get size of null packageName.");
11347            return false;
11348        }
11349        PackageParser.Package p;
11350        boolean dataOnly = false;
11351        String libDirRoot = null;
11352        String asecPath = null;
11353        PackageSetting ps = null;
11354        synchronized (mPackages) {
11355            p = mPackages.get(packageName);
11356            ps = mSettings.mPackages.get(packageName);
11357            if(p == null) {
11358                dataOnly = true;
11359                if((ps == null) || (ps.pkg == null)) {
11360                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11361                    return false;
11362                }
11363                p = ps.pkg;
11364            }
11365            if (ps != null) {
11366                libDirRoot = ps.legacyNativeLibraryPathString;
11367            }
11368            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11369                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11370                if (secureContainerId != null) {
11371                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11372                }
11373            }
11374        }
11375        String publicSrcDir = null;
11376        if(!dataOnly) {
11377            final ApplicationInfo applicationInfo = p.applicationInfo;
11378            if (applicationInfo == null) {
11379                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11380                return false;
11381            }
11382            if (isForwardLocked(p)) {
11383                publicSrcDir = applicationInfo.getBaseResourcePath();
11384            }
11385        }
11386        // TODO: extend to measure size of split APKs
11387        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11388        // not just the first level.
11389        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11390        // just the primary.
11391        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11392                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11393                pStats);
11394        if (res < 0) {
11395            return false;
11396        }
11397
11398        // Fix-up for forward-locked applications in ASEC containers.
11399        if (!isExternal(p)) {
11400            pStats.codeSize += pStats.externalCodeSize;
11401            pStats.externalCodeSize = 0L;
11402        }
11403
11404        return true;
11405    }
11406
11407
11408    @Override
11409    public void addPackageToPreferred(String packageName) {
11410        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11411    }
11412
11413    @Override
11414    public void removePackageFromPreferred(String packageName) {
11415        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11416    }
11417
11418    @Override
11419    public List<PackageInfo> getPreferredPackages(int flags) {
11420        return new ArrayList<PackageInfo>();
11421    }
11422
11423    private int getUidTargetSdkVersionLockedLPr(int uid) {
11424        Object obj = mSettings.getUserIdLPr(uid);
11425        if (obj instanceof SharedUserSetting) {
11426            final SharedUserSetting sus = (SharedUserSetting) obj;
11427            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11428            final Iterator<PackageSetting> it = sus.packages.iterator();
11429            while (it.hasNext()) {
11430                final PackageSetting ps = it.next();
11431                if (ps.pkg != null) {
11432                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11433                    if (v < vers) vers = v;
11434                }
11435            }
11436            return vers;
11437        } else if (obj instanceof PackageSetting) {
11438            final PackageSetting ps = (PackageSetting) obj;
11439            if (ps.pkg != null) {
11440                return ps.pkg.applicationInfo.targetSdkVersion;
11441            }
11442        }
11443        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11444    }
11445
11446    @Override
11447    public void addPreferredActivity(IntentFilter filter, int match,
11448            ComponentName[] set, ComponentName activity, int userId) {
11449        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11450    }
11451
11452    private void addPreferredActivityInternal(IntentFilter filter, int match,
11453            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11454        // writer
11455        int callingUid = Binder.getCallingUid();
11456        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11457        if (filter.countActions() == 0) {
11458            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11459            return;
11460        }
11461        synchronized (mPackages) {
11462            if (mContext.checkCallingOrSelfPermission(
11463                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11464                    != PackageManager.PERMISSION_GRANTED) {
11465                if (getUidTargetSdkVersionLockedLPr(callingUid)
11466                        < Build.VERSION_CODES.FROYO) {
11467                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11468                            + callingUid);
11469                    return;
11470                }
11471                mContext.enforceCallingOrSelfPermission(
11472                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11473            }
11474
11475            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11476            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11477            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11478                    new PreferredActivity(filter, match, set, activity, always));
11479            mSettings.writePackageRestrictionsLPr(userId);
11480        }
11481    }
11482
11483    @Override
11484    public void replacePreferredActivity(IntentFilter filter, int match,
11485            ComponentName[] set, ComponentName activity) {
11486        if (filter.countActions() != 1) {
11487            throw new IllegalArgumentException(
11488                    "replacePreferredActivity expects filter to have only 1 action.");
11489        }
11490        if (filter.countDataAuthorities() != 0
11491                || filter.countDataPaths() != 0
11492                || filter.countDataSchemes() > 1
11493                || filter.countDataTypes() != 0) {
11494            throw new IllegalArgumentException(
11495                    "replacePreferredActivity expects filter to have no data authorities, " +
11496                    "paths, or types; and at most one scheme.");
11497        }
11498        synchronized (mPackages) {
11499            if (mContext.checkCallingOrSelfPermission(
11500                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11501                    != PackageManager.PERMISSION_GRANTED) {
11502                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11503                        < Build.VERSION_CODES.FROYO) {
11504                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11505                            + Binder.getCallingUid());
11506                    return;
11507                }
11508                mContext.enforceCallingOrSelfPermission(
11509                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11510            }
11511
11512            final int callingUserId = UserHandle.getCallingUserId();
11513            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11514            if (pir != null) {
11515                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11516                if (filter.countDataSchemes() == 1) {
11517                    Uri.Builder builder = new Uri.Builder();
11518                    builder.scheme(filter.getDataScheme(0));
11519                    intent.setData(builder.build());
11520                }
11521                List<PreferredActivity> matches = pir.queryIntent(
11522                        intent, null, true, callingUserId);
11523                if (DEBUG_PREFERRED) {
11524                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11525                }
11526                for (int i = 0; i < matches.size(); i++) {
11527                    PreferredActivity pa = matches.get(i);
11528                    if (DEBUG_PREFERRED) {
11529                        Slog.i(TAG, "Removing preferred activity "
11530                                + pa.mPref.mComponent + ":");
11531                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11532                    }
11533                    pir.removeFilter(pa);
11534                }
11535            }
11536            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11537        }
11538    }
11539
11540    @Override
11541    public void clearPackagePreferredActivities(String packageName) {
11542        final int uid = Binder.getCallingUid();
11543        // writer
11544        synchronized (mPackages) {
11545            PackageParser.Package pkg = mPackages.get(packageName);
11546            if (pkg == null || pkg.applicationInfo.uid != uid) {
11547                if (mContext.checkCallingOrSelfPermission(
11548                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11549                        != PackageManager.PERMISSION_GRANTED) {
11550                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11551                            < Build.VERSION_CODES.FROYO) {
11552                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11553                                + Binder.getCallingUid());
11554                        return;
11555                    }
11556                    mContext.enforceCallingOrSelfPermission(
11557                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11558                }
11559            }
11560
11561            int user = UserHandle.getCallingUserId();
11562            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11563                mSettings.writePackageRestrictionsLPr(user);
11564                scheduleWriteSettingsLocked();
11565            }
11566        }
11567    }
11568
11569    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11570    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11571        ArrayList<PreferredActivity> removed = null;
11572        boolean changed = false;
11573        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11574            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11575            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11576            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11577                continue;
11578            }
11579            Iterator<PreferredActivity> it = pir.filterIterator();
11580            while (it.hasNext()) {
11581                PreferredActivity pa = it.next();
11582                // Mark entry for removal only if it matches the package name
11583                // and the entry is of type "always".
11584                if (packageName == null ||
11585                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11586                                && pa.mPref.mAlways)) {
11587                    if (removed == null) {
11588                        removed = new ArrayList<PreferredActivity>();
11589                    }
11590                    removed.add(pa);
11591                }
11592            }
11593            if (removed != null) {
11594                for (int j=0; j<removed.size(); j++) {
11595                    PreferredActivity pa = removed.get(j);
11596                    pir.removeFilter(pa);
11597                }
11598                changed = true;
11599            }
11600        }
11601        return changed;
11602    }
11603
11604    @Override
11605    public void resetPreferredActivities(int userId) {
11606        mContext.enforceCallingOrSelfPermission(
11607                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11608        // writer
11609        synchronized (mPackages) {
11610            int user = UserHandle.getCallingUserId();
11611            clearPackagePreferredActivitiesLPw(null, user);
11612            mSettings.readDefaultPreferredAppsLPw(this, user);
11613            mSettings.writePackageRestrictionsLPr(user);
11614            scheduleWriteSettingsLocked();
11615        }
11616    }
11617
11618    @Override
11619    public int getPreferredActivities(List<IntentFilter> outFilters,
11620            List<ComponentName> outActivities, String packageName) {
11621
11622        int num = 0;
11623        final int userId = UserHandle.getCallingUserId();
11624        // reader
11625        synchronized (mPackages) {
11626            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11627            if (pir != null) {
11628                final Iterator<PreferredActivity> it = pir.filterIterator();
11629                while (it.hasNext()) {
11630                    final PreferredActivity pa = it.next();
11631                    if (packageName == null
11632                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11633                                    && pa.mPref.mAlways)) {
11634                        if (outFilters != null) {
11635                            outFilters.add(new IntentFilter(pa));
11636                        }
11637                        if (outActivities != null) {
11638                            outActivities.add(pa.mPref.mComponent);
11639                        }
11640                    }
11641                }
11642            }
11643        }
11644
11645        return num;
11646    }
11647
11648    @Override
11649    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11650            int userId) {
11651        int callingUid = Binder.getCallingUid();
11652        if (callingUid != Process.SYSTEM_UID) {
11653            throw new SecurityException(
11654                    "addPersistentPreferredActivity can only be run by the system");
11655        }
11656        if (filter.countActions() == 0) {
11657            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11658            return;
11659        }
11660        synchronized (mPackages) {
11661            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11662                    " :");
11663            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11664            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11665                    new PersistentPreferredActivity(filter, activity));
11666            mSettings.writePackageRestrictionsLPr(userId);
11667        }
11668    }
11669
11670    @Override
11671    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11672        int callingUid = Binder.getCallingUid();
11673        if (callingUid != Process.SYSTEM_UID) {
11674            throw new SecurityException(
11675                    "clearPackagePersistentPreferredActivities can only be run by the system");
11676        }
11677        ArrayList<PersistentPreferredActivity> removed = null;
11678        boolean changed = false;
11679        synchronized (mPackages) {
11680            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11681                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11682                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11683                        .valueAt(i);
11684                if (userId != thisUserId) {
11685                    continue;
11686                }
11687                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11688                while (it.hasNext()) {
11689                    PersistentPreferredActivity ppa = it.next();
11690                    // Mark entry for removal only if it matches the package name.
11691                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11692                        if (removed == null) {
11693                            removed = new ArrayList<PersistentPreferredActivity>();
11694                        }
11695                        removed.add(ppa);
11696                    }
11697                }
11698                if (removed != null) {
11699                    for (int j=0; j<removed.size(); j++) {
11700                        PersistentPreferredActivity ppa = removed.get(j);
11701                        ppir.removeFilter(ppa);
11702                    }
11703                    changed = true;
11704                }
11705            }
11706
11707            if (changed) {
11708                mSettings.writePackageRestrictionsLPr(userId);
11709            }
11710        }
11711    }
11712
11713    @Override
11714    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11715            int targetUserId, int flags) {
11716        mContext.enforceCallingOrSelfPermission(
11717                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11718        if (intentFilter.countActions() == 0) {
11719            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11720            return;
11721        }
11722        synchronized (mPackages) {
11723            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11724                    targetUserId, flags);
11725            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11726            mSettings.writePackageRestrictionsLPr(sourceUserId);
11727        }
11728    }
11729
11730    public void addCrossProfileIntentsForPackage(String packageName,
11731            int sourceUserId, int targetUserId) {
11732        mContext.enforceCallingOrSelfPermission(
11733                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11734        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11735        mSettings.writePackageRestrictionsLPr(sourceUserId);
11736    }
11737
11738    public void removeCrossProfileIntentsForPackage(String packageName,
11739            int sourceUserId, int targetUserId) {
11740        mContext.enforceCallingOrSelfPermission(
11741                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11742        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11743        mSettings.writePackageRestrictionsLPr(sourceUserId);
11744    }
11745
11746    @Override
11747    public void clearCrossProfileIntentFilters(int sourceUserId) {
11748        mContext.enforceCallingOrSelfPermission(
11749                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11750        synchronized (mPackages) {
11751            CrossProfileIntentResolver resolver =
11752                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11753            HashSet<CrossProfileIntentFilter> set =
11754                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11755            for (CrossProfileIntentFilter filter : set) {
11756                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11757                    resolver.removeFilter(filter);
11758                }
11759            }
11760            mSettings.writePackageRestrictionsLPr(sourceUserId);
11761        }
11762    }
11763
11764    @Override
11765    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11766        Intent intent = new Intent(Intent.ACTION_MAIN);
11767        intent.addCategory(Intent.CATEGORY_HOME);
11768
11769        final int callingUserId = UserHandle.getCallingUserId();
11770        List<ResolveInfo> list = queryIntentActivities(intent, null,
11771                PackageManager.GET_META_DATA, callingUserId);
11772        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11773                true, false, false, callingUserId);
11774
11775        allHomeCandidates.clear();
11776        if (list != null) {
11777            for (ResolveInfo ri : list) {
11778                allHomeCandidates.add(ri);
11779            }
11780        }
11781        return (preferred == null || preferred.activityInfo == null)
11782                ? null
11783                : new ComponentName(preferred.activityInfo.packageName,
11784                        preferred.activityInfo.name);
11785    }
11786
11787    @Override
11788    public void setApplicationEnabledSetting(String appPackageName,
11789            int newState, int flags, int userId, String callingPackage) {
11790        if (!sUserManager.exists(userId)) return;
11791        if (callingPackage == null) {
11792            callingPackage = Integer.toString(Binder.getCallingUid());
11793        }
11794        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11795    }
11796
11797    @Override
11798    public void setComponentEnabledSetting(ComponentName componentName,
11799            int newState, int flags, int userId) {
11800        if (!sUserManager.exists(userId)) return;
11801        setEnabledSetting(componentName.getPackageName(),
11802                componentName.getClassName(), newState, flags, userId, null);
11803    }
11804
11805    private void setEnabledSetting(final String packageName, String className, int newState,
11806            final int flags, int userId, String callingPackage) {
11807        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11808              || newState == COMPONENT_ENABLED_STATE_ENABLED
11809              || newState == COMPONENT_ENABLED_STATE_DISABLED
11810              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11811              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11812            throw new IllegalArgumentException("Invalid new component state: "
11813                    + newState);
11814        }
11815        PackageSetting pkgSetting;
11816        final int uid = Binder.getCallingUid();
11817        final int permission = mContext.checkCallingOrSelfPermission(
11818                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11819        enforceCrossUserPermission(uid, userId, false, "set enabled");
11820        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11821        boolean sendNow = false;
11822        boolean isApp = (className == null);
11823        String componentName = isApp ? packageName : className;
11824        int packageUid = -1;
11825        ArrayList<String> components;
11826
11827        // writer
11828        synchronized (mPackages) {
11829            pkgSetting = mSettings.mPackages.get(packageName);
11830            if (pkgSetting == null) {
11831                if (className == null) {
11832                    throw new IllegalArgumentException(
11833                            "Unknown package: " + packageName);
11834                }
11835                throw new IllegalArgumentException(
11836                        "Unknown component: " + packageName
11837                        + "/" + className);
11838            }
11839            // Allow root and verify that userId is not being specified by a different user
11840            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11841                throw new SecurityException(
11842                        "Permission Denial: attempt to change component state from pid="
11843                        + Binder.getCallingPid()
11844                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11845            }
11846            if (className == null) {
11847                // We're dealing with an application/package level state change
11848                if (pkgSetting.getEnabled(userId) == newState) {
11849                    // Nothing to do
11850                    return;
11851                }
11852                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11853                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11854                    // Don't care about who enables an app.
11855                    callingPackage = null;
11856                }
11857                pkgSetting.setEnabled(newState, userId, callingPackage);
11858                // pkgSetting.pkg.mSetEnabled = newState;
11859            } else {
11860                // We're dealing with a component level state change
11861                // First, verify that this is a valid class name.
11862                PackageParser.Package pkg = pkgSetting.pkg;
11863                if (pkg == null || !pkg.hasComponentClassName(className)) {
11864                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11865                        throw new IllegalArgumentException("Component class " + className
11866                                + " does not exist in " + packageName);
11867                    } else {
11868                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11869                                + className + " does not exist in " + packageName);
11870                    }
11871                }
11872                switch (newState) {
11873                case COMPONENT_ENABLED_STATE_ENABLED:
11874                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11875                        return;
11876                    }
11877                    break;
11878                case COMPONENT_ENABLED_STATE_DISABLED:
11879                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11880                        return;
11881                    }
11882                    break;
11883                case COMPONENT_ENABLED_STATE_DEFAULT:
11884                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11885                        return;
11886                    }
11887                    break;
11888                default:
11889                    Slog.e(TAG, "Invalid new component state: " + newState);
11890                    return;
11891                }
11892            }
11893            mSettings.writePackageRestrictionsLPr(userId);
11894            components = mPendingBroadcasts.get(userId, packageName);
11895            final boolean newPackage = components == null;
11896            if (newPackage) {
11897                components = new ArrayList<String>();
11898            }
11899            if (!components.contains(componentName)) {
11900                components.add(componentName);
11901            }
11902            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11903                sendNow = true;
11904                // Purge entry from pending broadcast list if another one exists already
11905                // since we are sending one right away.
11906                mPendingBroadcasts.remove(userId, packageName);
11907            } else {
11908                if (newPackage) {
11909                    mPendingBroadcasts.put(userId, packageName, components);
11910                }
11911                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11912                    // Schedule a message
11913                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11914                }
11915            }
11916        }
11917
11918        long callingId = Binder.clearCallingIdentity();
11919        try {
11920            if (sendNow) {
11921                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11922                sendPackageChangedBroadcast(packageName,
11923                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11924            }
11925        } finally {
11926            Binder.restoreCallingIdentity(callingId);
11927        }
11928    }
11929
11930    private void sendPackageChangedBroadcast(String packageName,
11931            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11932        if (DEBUG_INSTALL)
11933            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11934                    + componentNames);
11935        Bundle extras = new Bundle(4);
11936        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11937        String nameList[] = new String[componentNames.size()];
11938        componentNames.toArray(nameList);
11939        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11940        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11941        extras.putInt(Intent.EXTRA_UID, packageUid);
11942        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11943                new int[] {UserHandle.getUserId(packageUid)});
11944    }
11945
11946    @Override
11947    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11948        if (!sUserManager.exists(userId)) return;
11949        final int uid = Binder.getCallingUid();
11950        final int permission = mContext.checkCallingOrSelfPermission(
11951                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11952        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11953        enforceCrossUserPermission(uid, userId, true, "stop package");
11954        // writer
11955        synchronized (mPackages) {
11956            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11957                    uid, userId)) {
11958                scheduleWritePackageRestrictionsLocked(userId);
11959            }
11960        }
11961    }
11962
11963    @Override
11964    public String getInstallerPackageName(String packageName) {
11965        // reader
11966        synchronized (mPackages) {
11967            return mSettings.getInstallerPackageNameLPr(packageName);
11968        }
11969    }
11970
11971    @Override
11972    public int getApplicationEnabledSetting(String packageName, int userId) {
11973        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11974        int uid = Binder.getCallingUid();
11975        enforceCrossUserPermission(uid, userId, false, "get enabled");
11976        // reader
11977        synchronized (mPackages) {
11978            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11979        }
11980    }
11981
11982    @Override
11983    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11984        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11985        int uid = Binder.getCallingUid();
11986        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11987        // reader
11988        synchronized (mPackages) {
11989            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11990        }
11991    }
11992
11993    @Override
11994    public void enterSafeMode() {
11995        enforceSystemOrRoot("Only the system can request entering safe mode");
11996
11997        if (!mSystemReady) {
11998            mSafeMode = true;
11999        }
12000    }
12001
12002    @Override
12003    public void systemReady() {
12004        mSystemReady = true;
12005
12006        // Read the compatibilty setting when the system is ready.
12007        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12008                mContext.getContentResolver(),
12009                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12010        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12011        if (DEBUG_SETTINGS) {
12012            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12013        }
12014
12015        synchronized (mPackages) {
12016            // Verify that all of the preferred activity components actually
12017            // exist.  It is possible for applications to be updated and at
12018            // that point remove a previously declared activity component that
12019            // had been set as a preferred activity.  We try to clean this up
12020            // the next time we encounter that preferred activity, but it is
12021            // possible for the user flow to never be able to return to that
12022            // situation so here we do a sanity check to make sure we haven't
12023            // left any junk around.
12024            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12025            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12026                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12027                removed.clear();
12028                for (PreferredActivity pa : pir.filterSet()) {
12029                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12030                        removed.add(pa);
12031                    }
12032                }
12033                if (removed.size() > 0) {
12034                    for (int r=0; r<removed.size(); r++) {
12035                        PreferredActivity pa = removed.get(r);
12036                        Slog.w(TAG, "Removing dangling preferred activity: "
12037                                + pa.mPref.mComponent);
12038                        pir.removeFilter(pa);
12039                    }
12040                    mSettings.writePackageRestrictionsLPr(
12041                            mSettings.mPreferredActivities.keyAt(i));
12042                }
12043            }
12044        }
12045        sUserManager.systemReady();
12046    }
12047
12048    @Override
12049    public boolean isSafeMode() {
12050        return mSafeMode;
12051    }
12052
12053    @Override
12054    public boolean hasSystemUidErrors() {
12055        return mHasSystemUidErrors;
12056    }
12057
12058    static String arrayToString(int[] array) {
12059        StringBuffer buf = new StringBuffer(128);
12060        buf.append('[');
12061        if (array != null) {
12062            for (int i=0; i<array.length; i++) {
12063                if (i > 0) buf.append(", ");
12064                buf.append(array[i]);
12065            }
12066        }
12067        buf.append(']');
12068        return buf.toString();
12069    }
12070
12071    static class DumpState {
12072        public static final int DUMP_LIBS = 1 << 0;
12073        public static final int DUMP_FEATURES = 1 << 1;
12074        public static final int DUMP_RESOLVERS = 1 << 2;
12075        public static final int DUMP_PERMISSIONS = 1 << 3;
12076        public static final int DUMP_PACKAGES = 1 << 4;
12077        public static final int DUMP_SHARED_USERS = 1 << 5;
12078        public static final int DUMP_MESSAGES = 1 << 6;
12079        public static final int DUMP_PROVIDERS = 1 << 7;
12080        public static final int DUMP_VERIFIERS = 1 << 8;
12081        public static final int DUMP_PREFERRED = 1 << 9;
12082        public static final int DUMP_PREFERRED_XML = 1 << 10;
12083        public static final int DUMP_KEYSETS = 1 << 11;
12084        public static final int DUMP_VERSION = 1 << 12;
12085        public static final int DUMP_INSTALLS = 1 << 13;
12086
12087        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12088
12089        private int mTypes;
12090
12091        private int mOptions;
12092
12093        private boolean mTitlePrinted;
12094
12095        private SharedUserSetting mSharedUser;
12096
12097        public boolean isDumping(int type) {
12098            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12099                return true;
12100            }
12101
12102            return (mTypes & type) != 0;
12103        }
12104
12105        public void setDump(int type) {
12106            mTypes |= type;
12107        }
12108
12109        public boolean isOptionEnabled(int option) {
12110            return (mOptions & option) != 0;
12111        }
12112
12113        public void setOptionEnabled(int option) {
12114            mOptions |= option;
12115        }
12116
12117        public boolean onTitlePrinted() {
12118            final boolean printed = mTitlePrinted;
12119            mTitlePrinted = true;
12120            return printed;
12121        }
12122
12123        public boolean getTitlePrinted() {
12124            return mTitlePrinted;
12125        }
12126
12127        public void setTitlePrinted(boolean enabled) {
12128            mTitlePrinted = enabled;
12129        }
12130
12131        public SharedUserSetting getSharedUser() {
12132            return mSharedUser;
12133        }
12134
12135        public void setSharedUser(SharedUserSetting user) {
12136            mSharedUser = user;
12137        }
12138    }
12139
12140    @Override
12141    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12142        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12143                != PackageManager.PERMISSION_GRANTED) {
12144            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12145                    + Binder.getCallingPid()
12146                    + ", uid=" + Binder.getCallingUid()
12147                    + " without permission "
12148                    + android.Manifest.permission.DUMP);
12149            return;
12150        }
12151
12152        DumpState dumpState = new DumpState();
12153        boolean fullPreferred = false;
12154        boolean checkin = false;
12155
12156        String packageName = null;
12157
12158        int opti = 0;
12159        while (opti < args.length) {
12160            String opt = args[opti];
12161            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12162                break;
12163            }
12164            opti++;
12165            if ("-a".equals(opt)) {
12166                // Right now we only know how to print all.
12167            } else if ("-h".equals(opt)) {
12168                pw.println("Package manager dump options:");
12169                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12170                pw.println("    --checkin: dump for a checkin");
12171                pw.println("    -f: print details of intent filters");
12172                pw.println("    -h: print this help");
12173                pw.println("  cmd may be one of:");
12174                pw.println("    l[ibraries]: list known shared libraries");
12175                pw.println("    f[ibraries]: list device features");
12176                pw.println("    k[eysets]: print known keysets");
12177                pw.println("    r[esolvers]: dump intent resolvers");
12178                pw.println("    perm[issions]: dump permissions");
12179                pw.println("    pref[erred]: print preferred package settings");
12180                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12181                pw.println("    prov[iders]: dump content providers");
12182                pw.println("    p[ackages]: dump installed packages");
12183                pw.println("    s[hared-users]: dump shared user IDs");
12184                pw.println("    m[essages]: print collected runtime messages");
12185                pw.println("    v[erifiers]: print package verifier info");
12186                pw.println("    version: print database version info");
12187                pw.println("    write: write current settings now");
12188                pw.println("    <package.name>: info about given package");
12189                pw.println("    installs: details about install sessions");
12190                return;
12191            } else if ("--checkin".equals(opt)) {
12192                checkin = true;
12193            } else if ("-f".equals(opt)) {
12194                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12195            } else {
12196                pw.println("Unknown argument: " + opt + "; use -h for help");
12197            }
12198        }
12199
12200        // Is the caller requesting to dump a particular piece of data?
12201        if (opti < args.length) {
12202            String cmd = args[opti];
12203            opti++;
12204            // Is this a package name?
12205            if ("android".equals(cmd) || cmd.contains(".")) {
12206                packageName = cmd;
12207                // When dumping a single package, we always dump all of its
12208                // filter information since the amount of data will be reasonable.
12209                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12210            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_LIBS);
12212            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12213                dumpState.setDump(DumpState.DUMP_FEATURES);
12214            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12215                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12216            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12217                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12218            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12219                dumpState.setDump(DumpState.DUMP_PREFERRED);
12220            } else if ("preferred-xml".equals(cmd)) {
12221                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12222                if (opti < args.length && "--full".equals(args[opti])) {
12223                    fullPreferred = true;
12224                    opti++;
12225                }
12226            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12227                dumpState.setDump(DumpState.DUMP_PACKAGES);
12228            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12229                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12230            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12231                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12232            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12233                dumpState.setDump(DumpState.DUMP_MESSAGES);
12234            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12235                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12236            } else if ("version".equals(cmd)) {
12237                dumpState.setDump(DumpState.DUMP_VERSION);
12238            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12239                dumpState.setDump(DumpState.DUMP_KEYSETS);
12240            } else if ("write".equals(cmd)) {
12241                synchronized (mPackages) {
12242                    mSettings.writeLPr();
12243                    pw.println("Settings written.");
12244                    return;
12245                }
12246            } else if ("installs".equals(cmd)) {
12247                dumpState.setDump(DumpState.DUMP_INSTALLS);
12248            }
12249        }
12250
12251        if (checkin) {
12252            pw.println("vers,1");
12253        }
12254
12255        // reader
12256        synchronized (mPackages) {
12257            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12258                if (!checkin) {
12259                    if (dumpState.onTitlePrinted())
12260                        pw.println();
12261                    pw.println("Database versions:");
12262                    pw.print("  SDK Version:");
12263                    pw.print(" internal=");
12264                    pw.print(mSettings.mInternalSdkPlatform);
12265                    pw.print(" external=");
12266                    pw.println(mSettings.mExternalSdkPlatform);
12267                    pw.print("  DB Version:");
12268                    pw.print(" internal=");
12269                    pw.print(mSettings.mInternalDatabaseVersion);
12270                    pw.print(" external=");
12271                    pw.println(mSettings.mExternalDatabaseVersion);
12272                }
12273            }
12274
12275            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12276                if (!checkin) {
12277                    if (dumpState.onTitlePrinted())
12278                        pw.println();
12279                    pw.println("Verifiers:");
12280                    pw.print("  Required: ");
12281                    pw.print(mRequiredVerifierPackage);
12282                    pw.print(" (uid=");
12283                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12284                    pw.println(")");
12285                } else if (mRequiredVerifierPackage != null) {
12286                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12287                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12288                }
12289            }
12290
12291            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12292                boolean printedHeader = false;
12293                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12294                while (it.hasNext()) {
12295                    String name = it.next();
12296                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12297                    if (!checkin) {
12298                        if (!printedHeader) {
12299                            if (dumpState.onTitlePrinted())
12300                                pw.println();
12301                            pw.println("Libraries:");
12302                            printedHeader = true;
12303                        }
12304                        pw.print("  ");
12305                    } else {
12306                        pw.print("lib,");
12307                    }
12308                    pw.print(name);
12309                    if (!checkin) {
12310                        pw.print(" -> ");
12311                    }
12312                    if (ent.path != null) {
12313                        if (!checkin) {
12314                            pw.print("(jar) ");
12315                            pw.print(ent.path);
12316                        } else {
12317                            pw.print(",jar,");
12318                            pw.print(ent.path);
12319                        }
12320                    } else {
12321                        if (!checkin) {
12322                            pw.print("(apk) ");
12323                            pw.print(ent.apk);
12324                        } else {
12325                            pw.print(",apk,");
12326                            pw.print(ent.apk);
12327                        }
12328                    }
12329                    pw.println();
12330                }
12331            }
12332
12333            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12334                if (dumpState.onTitlePrinted())
12335                    pw.println();
12336                if (!checkin) {
12337                    pw.println("Features:");
12338                }
12339                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12340                while (it.hasNext()) {
12341                    String name = it.next();
12342                    if (!checkin) {
12343                        pw.print("  ");
12344                    } else {
12345                        pw.print("feat,");
12346                    }
12347                    pw.println(name);
12348                }
12349            }
12350
12351            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12352                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12353                        : "Activity Resolver Table:", "  ", packageName,
12354                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12355                    dumpState.setTitlePrinted(true);
12356                }
12357                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12358                        : "Receiver Resolver Table:", "  ", packageName,
12359                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12360                    dumpState.setTitlePrinted(true);
12361                }
12362                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12363                        : "Service Resolver Table:", "  ", packageName,
12364                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12365                    dumpState.setTitlePrinted(true);
12366                }
12367                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12368                        : "Provider Resolver Table:", "  ", packageName,
12369                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12370                    dumpState.setTitlePrinted(true);
12371                }
12372            }
12373
12374            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12375                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12376                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12377                    int user = mSettings.mPreferredActivities.keyAt(i);
12378                    if (pir.dump(pw,
12379                            dumpState.getTitlePrinted()
12380                                ? "\nPreferred Activities User " + user + ":"
12381                                : "Preferred Activities User " + user + ":", "  ",
12382                            packageName, true)) {
12383                        dumpState.setTitlePrinted(true);
12384                    }
12385                }
12386            }
12387
12388            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12389                pw.flush();
12390                FileOutputStream fout = new FileOutputStream(fd);
12391                BufferedOutputStream str = new BufferedOutputStream(fout);
12392                XmlSerializer serializer = new FastXmlSerializer();
12393                try {
12394                    serializer.setOutput(str, "utf-8");
12395                    serializer.startDocument(null, true);
12396                    serializer.setFeature(
12397                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12398                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12399                    serializer.endDocument();
12400                    serializer.flush();
12401                } catch (IllegalArgumentException e) {
12402                    pw.println("Failed writing: " + e);
12403                } catch (IllegalStateException e) {
12404                    pw.println("Failed writing: " + e);
12405                } catch (IOException e) {
12406                    pw.println("Failed writing: " + e);
12407                }
12408            }
12409
12410            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12411                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12412            }
12413
12414            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12415                boolean printedSomething = false;
12416                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12417                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12418                        continue;
12419                    }
12420                    if (!printedSomething) {
12421                        if (dumpState.onTitlePrinted())
12422                            pw.println();
12423                        pw.println("Registered ContentProviders:");
12424                        printedSomething = true;
12425                    }
12426                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12427                    pw.print("    "); pw.println(p.toString());
12428                }
12429                printedSomething = false;
12430                for (Map.Entry<String, PackageParser.Provider> entry :
12431                        mProvidersByAuthority.entrySet()) {
12432                    PackageParser.Provider p = entry.getValue();
12433                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12434                        continue;
12435                    }
12436                    if (!printedSomething) {
12437                        if (dumpState.onTitlePrinted())
12438                            pw.println();
12439                        pw.println("ContentProvider Authorities:");
12440                        printedSomething = true;
12441                    }
12442                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12443                    pw.print("    "); pw.println(p.toString());
12444                    if (p.info != null && p.info.applicationInfo != null) {
12445                        final String appInfo = p.info.applicationInfo.toString();
12446                        pw.print("      applicationInfo="); pw.println(appInfo);
12447                    }
12448                }
12449            }
12450
12451            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12452                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12453            }
12454
12455            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12456                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12457            }
12458
12459            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12460                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12461            }
12462
12463            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12464                if (dumpState.onTitlePrinted()) pw.println();
12465                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12466            }
12467
12468            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12469                if (dumpState.onTitlePrinted()) pw.println();
12470                mSettings.dumpReadMessagesLPr(pw, dumpState);
12471
12472                pw.println();
12473                pw.println("Package warning messages:");
12474                final File fname = getSettingsProblemFile();
12475                FileInputStream in = null;
12476                try {
12477                    in = new FileInputStream(fname);
12478                    final int avail = in.available();
12479                    final byte[] data = new byte[avail];
12480                    in.read(data);
12481                    pw.print(new String(data));
12482                } catch (FileNotFoundException e) {
12483                } catch (IOException e) {
12484                } finally {
12485                    if (in != null) {
12486                        try {
12487                            in.close();
12488                        } catch (IOException e) {
12489                        }
12490                    }
12491                }
12492            }
12493        }
12494    }
12495
12496    // ------- apps on sdcard specific code -------
12497    static final boolean DEBUG_SD_INSTALL = false;
12498
12499    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12500
12501    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12502
12503    private boolean mMediaMounted = false;
12504
12505    private String getEncryptKey() {
12506        try {
12507            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12508                    SD_ENCRYPTION_KEYSTORE_NAME);
12509            if (sdEncKey == null) {
12510                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12511                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12512                if (sdEncKey == null) {
12513                    Slog.e(TAG, "Failed to create encryption keys");
12514                    return null;
12515                }
12516            }
12517            return sdEncKey;
12518        } catch (NoSuchAlgorithmException nsae) {
12519            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12520            return null;
12521        } catch (IOException ioe) {
12522            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12523            return null;
12524        }
12525
12526    }
12527
12528    /* package */static String getTempContainerId() {
12529        int tmpIdx = 1;
12530        String list[] = PackageHelper.getSecureContainerList();
12531        if (list != null) {
12532            for (final String name : list) {
12533                // Ignore null and non-temporary container entries
12534                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12535                    continue;
12536                }
12537
12538                String subStr = name.substring(mTempContainerPrefix.length());
12539                try {
12540                    int cid = Integer.parseInt(subStr);
12541                    if (cid >= tmpIdx) {
12542                        tmpIdx = cid + 1;
12543                    }
12544                } catch (NumberFormatException e) {
12545                }
12546            }
12547        }
12548        return mTempContainerPrefix + tmpIdx;
12549    }
12550
12551    /*
12552     * Update media status on PackageManager.
12553     */
12554    @Override
12555    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12556        int callingUid = Binder.getCallingUid();
12557        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12558            throw new SecurityException("Media status can only be updated by the system");
12559        }
12560        // reader; this apparently protects mMediaMounted, but should probably
12561        // be a different lock in that case.
12562        synchronized (mPackages) {
12563            Log.i(TAG, "Updating external media status from "
12564                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12565                    + (mediaStatus ? "mounted" : "unmounted"));
12566            if (DEBUG_SD_INSTALL)
12567                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12568                        + ", mMediaMounted=" + mMediaMounted);
12569            if (mediaStatus == mMediaMounted) {
12570                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12571                        : 0, -1);
12572                mHandler.sendMessage(msg);
12573                return;
12574            }
12575            mMediaMounted = mediaStatus;
12576        }
12577        // Queue up an async operation since the package installation may take a
12578        // little while.
12579        mHandler.post(new Runnable() {
12580            public void run() {
12581                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12582            }
12583        });
12584    }
12585
12586    /**
12587     * Called by MountService when the initial ASECs to scan are available.
12588     * Should block until all the ASEC containers are finished being scanned.
12589     */
12590    public void scanAvailableAsecs() {
12591        updateExternalMediaStatusInner(true, false, false);
12592        if (mShouldRestoreconData) {
12593            SELinuxMMAC.setRestoreconDone();
12594            mShouldRestoreconData = false;
12595        }
12596    }
12597
12598    /*
12599     * Collect information of applications on external media, map them against
12600     * existing containers and update information based on current mount status.
12601     * Please note that we always have to report status if reportStatus has been
12602     * set to true especially when unloading packages.
12603     */
12604    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12605            boolean externalStorage) {
12606        // Collection of uids
12607        int uidArr[] = null;
12608        // Collection of stale containers
12609        HashSet<String> removeCids = new HashSet<String>();
12610        // Collection of packages on external media with valid containers.
12611        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12612        // Get list of secure containers.
12613        final String list[] = PackageHelper.getSecureContainerList();
12614        if (list == null || list.length == 0) {
12615            Log.i(TAG, "No secure containers on sdcard");
12616        } else {
12617            // Process list of secure containers and categorize them
12618            // as active or stale based on their package internal state.
12619            int uidList[] = new int[list.length];
12620            int num = 0;
12621            // reader
12622            synchronized (mPackages) {
12623                for (String cid : list) {
12624                    if (DEBUG_SD_INSTALL)
12625                        Log.i(TAG, "Processing container " + cid);
12626                    String pkgName = getAsecPackageName(cid);
12627                    if (pkgName == null) {
12628                        if (DEBUG_SD_INSTALL)
12629                            Log.i(TAG, "Container : " + cid + " stale");
12630                        removeCids.add(cid);
12631                        continue;
12632                    }
12633                    if (DEBUG_SD_INSTALL)
12634                        Log.i(TAG, "Looking for pkg : " + pkgName);
12635
12636                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12637                    if (ps == null) {
12638                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12639                        removeCids.add(cid);
12640                        continue;
12641                    }
12642
12643                    /*
12644                     * Skip packages that are not external if we're unmounting
12645                     * external storage.
12646                     */
12647                    if (externalStorage && !isMounted && !isExternal(ps)) {
12648                        continue;
12649                    }
12650
12651                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12652                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12653                    // The package status is changed only if the code path
12654                    // matches between settings and the container id.
12655                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12656                        if (DEBUG_SD_INSTALL) {
12657                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12658                                    + " at code path: " + ps.codePathString);
12659                        }
12660
12661                        // We do have a valid package installed on sdcard
12662                        processCids.put(args, ps.codePathString);
12663                        final int uid = ps.appId;
12664                        if (uid != -1) {
12665                            uidList[num++] = uid;
12666                        }
12667                    } else {
12668                        Log.i(TAG, "Deleting stale container for " + cid);
12669                        removeCids.add(cid);
12670                    }
12671                }
12672            }
12673
12674            if (num > 0) {
12675                // Sort uid list
12676                Arrays.sort(uidList, 0, num);
12677                // Throw away duplicates
12678                uidArr = new int[num];
12679                uidArr[0] = uidList[0];
12680                int di = 0;
12681                for (int i = 1; i < num; i++) {
12682                    if (uidList[i - 1] != uidList[i]) {
12683                        uidArr[di++] = uidList[i];
12684                    }
12685                }
12686            }
12687        }
12688        // Process packages with valid entries.
12689        if (isMounted) {
12690            if (DEBUG_SD_INSTALL)
12691                Log.i(TAG, "Loading packages");
12692            loadMediaPackages(processCids, uidArr, removeCids);
12693            startCleaningPackages();
12694        } else {
12695            if (DEBUG_SD_INSTALL)
12696                Log.i(TAG, "Unloading packages");
12697            unloadMediaPackages(processCids, uidArr, reportStatus);
12698        }
12699    }
12700
12701   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12702           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12703        int size = pkgList.size();
12704        if (size > 0) {
12705            // Send broadcasts here
12706            Bundle extras = new Bundle();
12707            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12708                    .toArray(new String[size]));
12709            if (uidArr != null) {
12710                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12711            }
12712            if (replacing) {
12713                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12714            }
12715            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12716                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12717            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12718        }
12719    }
12720
12721   /*
12722     * Look at potentially valid container ids from processCids If package
12723     * information doesn't match the one on record or package scanning fails,
12724     * the cid is added to list of removeCids. We currently don't delete stale
12725     * containers.
12726     */
12727   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12728            HashSet<String> removeCids) {
12729        ArrayList<String> pkgList = new ArrayList<String>();
12730        Set<AsecInstallArgs> keys = processCids.keySet();
12731        boolean doGc = false;
12732        for (AsecInstallArgs args : keys) {
12733            String codePath = processCids.get(args);
12734            if (DEBUG_SD_INSTALL)
12735                Log.i(TAG, "Loading container : " + args.cid);
12736            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12737            try {
12738                // Make sure there are no container errors first.
12739                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12740                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12741                            + " when installing from sdcard");
12742                    continue;
12743                }
12744                // Check code path here.
12745                if (codePath == null || !codePath.equals(args.getCodePath())) {
12746                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12747                            + " does not match one in settings " + codePath);
12748                    continue;
12749                }
12750                // Parse package
12751                int parseFlags = mDefParseFlags;
12752                if (args.isExternal()) {
12753                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12754                }
12755                if (args.isFwdLocked()) {
12756                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12757                }
12758
12759                doGc = true;
12760                synchronized (mInstallLock) {
12761                    PackageParser.Package pkg = null;
12762                    try {
12763                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12764                    } catch (PackageManagerException e) {
12765                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12766                    }
12767                    // Scan the package
12768                    if (pkg != null) {
12769                        /*
12770                         * TODO why is the lock being held? doPostInstall is
12771                         * called in other places without the lock. This needs
12772                         * to be straightened out.
12773                         */
12774                        // writer
12775                        synchronized (mPackages) {
12776                            retCode = PackageManager.INSTALL_SUCCEEDED;
12777                            pkgList.add(pkg.packageName);
12778                            // Post process args
12779                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12780                                    pkg.applicationInfo.uid);
12781                        }
12782                    } else {
12783                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12784                    }
12785                }
12786
12787            } finally {
12788                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12789                    // Don't destroy container here. Wait till gc clears things
12790                    // up.
12791                    removeCids.add(args.cid);
12792                }
12793            }
12794        }
12795        // writer
12796        synchronized (mPackages) {
12797            // If the platform SDK has changed since the last time we booted,
12798            // we need to re-grant app permission to catch any new ones that
12799            // appear. This is really a hack, and means that apps can in some
12800            // cases get permissions that the user didn't initially explicitly
12801            // allow... it would be nice to have some better way to handle
12802            // this situation.
12803            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12804            if (regrantPermissions)
12805                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12806                        + mSdkVersion + "; regranting permissions for external storage");
12807            mSettings.mExternalSdkPlatform = mSdkVersion;
12808
12809            // Make sure group IDs have been assigned, and any permission
12810            // changes in other apps are accounted for
12811            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12812                    | (regrantPermissions
12813                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12814                            : 0));
12815
12816            mSettings.updateExternalDatabaseVersion();
12817
12818            // can downgrade to reader
12819            // Persist settings
12820            mSettings.writeLPr();
12821        }
12822        // Send a broadcast to let everyone know we are done processing
12823        if (pkgList.size() > 0) {
12824            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12825        }
12826        // Force gc to avoid any stale parser references that we might have.
12827        if (doGc) {
12828            Runtime.getRuntime().gc();
12829        }
12830        // List stale containers and destroy stale temporary containers.
12831        if (removeCids != null) {
12832            for (String cid : removeCids) {
12833                if (cid.startsWith(mTempContainerPrefix)) {
12834                    Log.i(TAG, "Destroying stale temporary container " + cid);
12835                    PackageHelper.destroySdDir(cid);
12836                } else {
12837                    Log.w(TAG, "Container " + cid + " is stale");
12838               }
12839           }
12840        }
12841    }
12842
12843   /*
12844     * Utility method to unload a list of specified containers
12845     */
12846    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12847        // Just unmount all valid containers.
12848        for (AsecInstallArgs arg : cidArgs) {
12849            synchronized (mInstallLock) {
12850                arg.doPostDeleteLI(false);
12851           }
12852       }
12853   }
12854
12855    /*
12856     * Unload packages mounted on external media. This involves deleting package
12857     * data from internal structures, sending broadcasts about diabled packages,
12858     * gc'ing to free up references, unmounting all secure containers
12859     * corresponding to packages on external media, and posting a
12860     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12861     * that we always have to post this message if status has been requested no
12862     * matter what.
12863     */
12864    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12865            final boolean reportStatus) {
12866        if (DEBUG_SD_INSTALL)
12867            Log.i(TAG, "unloading media packages");
12868        ArrayList<String> pkgList = new ArrayList<String>();
12869        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12870        final Set<AsecInstallArgs> keys = processCids.keySet();
12871        for (AsecInstallArgs args : keys) {
12872            String pkgName = args.getPackageName();
12873            if (DEBUG_SD_INSTALL)
12874                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12875            // Delete package internally
12876            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12877            synchronized (mInstallLock) {
12878                boolean res = deletePackageLI(pkgName, null, false, null, null,
12879                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12880                if (res) {
12881                    pkgList.add(pkgName);
12882                } else {
12883                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12884                    failedList.add(args);
12885                }
12886            }
12887        }
12888
12889        // reader
12890        synchronized (mPackages) {
12891            // We didn't update the settings after removing each package;
12892            // write them now for all packages.
12893            mSettings.writeLPr();
12894        }
12895
12896        // We have to absolutely send UPDATED_MEDIA_STATUS only
12897        // after confirming that all the receivers processed the ordered
12898        // broadcast when packages get disabled, force a gc to clean things up.
12899        // and unload all the containers.
12900        if (pkgList.size() > 0) {
12901            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12902                    new IIntentReceiver.Stub() {
12903                public void performReceive(Intent intent, int resultCode, String data,
12904                        Bundle extras, boolean ordered, boolean sticky,
12905                        int sendingUser) throws RemoteException {
12906                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12907                            reportStatus ? 1 : 0, 1, keys);
12908                    mHandler.sendMessage(msg);
12909                }
12910            });
12911        } else {
12912            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12913                    keys);
12914            mHandler.sendMessage(msg);
12915        }
12916    }
12917
12918    /** Binder call */
12919    @Override
12920    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12921            final int flags) {
12922        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12923        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12924        int returnCode = PackageManager.MOVE_SUCCEEDED;
12925        int currFlags = 0;
12926        int newFlags = 0;
12927        // reader
12928        synchronized (mPackages) {
12929            PackageParser.Package pkg = mPackages.get(packageName);
12930            if (pkg == null) {
12931                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12932            } else {
12933                // Disable moving fwd locked apps and system packages
12934                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12935                    Slog.w(TAG, "Cannot move system application");
12936                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12937                } else if (pkg.mOperationPending) {
12938                    Slog.w(TAG, "Attempt to move package which has pending operations");
12939                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12940                } else {
12941                    // Find install location first
12942                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12943                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12944                        Slog.w(TAG, "Ambigous flags specified for move location.");
12945                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12946                    } else {
12947                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12948                                : PackageManager.INSTALL_INTERNAL;
12949                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12950                                : PackageManager.INSTALL_INTERNAL;
12951
12952                        if (newFlags == currFlags) {
12953                            Slog.w(TAG, "No move required. Trying to move to same location");
12954                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12955                        } else {
12956                            if (isForwardLocked(pkg)) {
12957                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12958                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12959                            }
12960                        }
12961                    }
12962                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12963                        pkg.mOperationPending = true;
12964                    }
12965                }
12966            }
12967
12968            /*
12969             * TODO this next block probably shouldn't be inside the lock. We
12970             * can't guarantee these won't change after this is fired off
12971             * anyway.
12972             */
12973            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12974                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
12975                        returnCode);
12976            } else {
12977                Message msg = mHandler.obtainMessage(INIT_COPY);
12978                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
12979                final boolean multiArch = isMultiArch(pkg.applicationInfo);
12980                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12981                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12982                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
12983                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12984                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
12985                msg.obj = mp;
12986                mHandler.sendMessage(msg);
12987            }
12988        }
12989    }
12990
12991    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12992        // Queue up an async operation since the package deletion may take a
12993        // little while.
12994        mHandler.post(new Runnable() {
12995            public void run() {
12996                // TODO fix this; this does nothing.
12997                mHandler.removeCallbacks(this);
12998                int returnCode = currentStatus;
12999                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13000                    int uidArr[] = null;
13001                    ArrayList<String> pkgList = null;
13002                    synchronized (mPackages) {
13003                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13004                        if (pkg == null) {
13005                            Slog.w(TAG, " Package " + mp.packageName
13006                                    + " doesn't exist. Aborting move");
13007                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13008                        } else if (!mp.srcArgs.getCodePath().equals(
13009                                pkg.applicationInfo.getCodePath())) {
13010                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13011                                    + mp.srcArgs.getCodePath() + " to "
13012                                    + pkg.applicationInfo.getCodePath()
13013                                    + " Aborting move and returning error");
13014                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13015                        } else {
13016                            uidArr = new int[] {
13017                                pkg.applicationInfo.uid
13018                            };
13019                            pkgList = new ArrayList<String>();
13020                            pkgList.add(mp.packageName);
13021                        }
13022                    }
13023                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13024                        // Send resources unavailable broadcast
13025                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13026                        // Update package code and resource paths
13027                        synchronized (mInstallLock) {
13028                            synchronized (mPackages) {
13029                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13030                                // Recheck for package again.
13031                                if (pkg == null) {
13032                                    Slog.w(TAG, " Package " + mp.packageName
13033                                            + " doesn't exist. Aborting move");
13034                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13035                                } else if (!mp.srcArgs.getCodePath().equals(
13036                                        pkg.applicationInfo.getCodePath())) {
13037                                    Slog.w(TAG, "Package " + mp.packageName
13038                                            + " code path changed from " + mp.srcArgs.getCodePath()
13039                                            + " to " + pkg.applicationInfo.getCodePath()
13040                                            + " Aborting move and returning error");
13041                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13042                                } else {
13043                                    final String oldCodePath = pkg.codePath;
13044                                    final String newCodePath = mp.targetArgs.getCodePath();
13045                                    final String newResPath = mp.targetArgs.getResourcePath();
13046                                    // TODO: This assumes the new style of installation.
13047                                    // should we look at legacyNativeLibraryPath ?
13048                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13049                                    final File newNativeDir = new File(newNativeRoot);
13050
13051                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13052                                        // TODO(multiArch): Fix this so that it looks at the existing
13053                                        // recorded CPU abis from the package. There's no need for a separate
13054                                        // round of ABI scanning here.
13055                                        NativeLibraryHelper.Handle handle = null;
13056                                        try {
13057                                            handle = NativeLibraryHelper.Handle.create(
13058                                                    new File(newCodePath));
13059                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13060                                                    handle, Build.SUPPORTED_ABIS);
13061                                            if (abi >= 0) {
13062                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13063                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13064                                            }
13065                                        } catch (IOException ioe) {
13066                                            Slog.w(TAG, "Unable to extract native libs for package :"
13067                                                    + mp.packageName, ioe);
13068                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13069                                        } finally {
13070                                            IoUtils.closeQuietly(handle);
13071                                        }
13072                                    }
13073
13074                                    final int[] users = sUserManager.getUserIds();
13075                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13076                                        for (int user : users) {
13077                                            // TODO(multiArch): Fix this so that it links to the
13078                                            // correct directory. We're currently pointing to root. but we
13079                                            // must point to the arch specific subdirectory (if applicable).
13080                                            //
13081                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13082                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13083                                                    newNativeRoot, user) < 0) {
13084                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13085                                            }
13086                                        }
13087                                    }
13088
13089                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13090                                        pkg.codePath = newCodePath;
13091                                        pkg.baseCodePath = newCodePath;
13092                                        // Move dex files around
13093                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13094                                            // Moving of dex files failed. Set
13095                                            // error code and abort move.
13096                                            pkg.codePath = oldCodePath;
13097                                            pkg.baseCodePath = oldCodePath;
13098                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13099                                        }
13100                                    }
13101
13102                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13103                                        pkg.applicationInfo.setCodePath(newCodePath);
13104                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13105                                        pkg.applicationInfo.setSplitCodePaths(null);
13106                                        pkg.applicationInfo.setResourcePath(newResPath);
13107                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13108                                        pkg.applicationInfo.setSplitResourcePaths(null);
13109
13110                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13111                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13112                                        ps.codePathString = ps.codePath.getPath();
13113                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13114                                        ps.resourcePathString = ps.resourcePath.getPath();
13115
13116                                        // Note that we don't have to recalculate the primary and secondary
13117                                        // CPU ABIs because they must already have been calculated during the
13118                                        // initial install of the app.
13119                                        ps.legacyNativeLibraryPathString = null;
13120
13121                                        // Set the application info flag
13122                                        // correctly.
13123                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13124                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13125                                        } else {
13126                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13127                                        }
13128                                        ps.setFlags(pkg.applicationInfo.flags);
13129                                        mAppDirs.remove(oldCodePath);
13130                                        mAppDirs.put(newCodePath, pkg);
13131                                        // Persist settings
13132                                        mSettings.writeLPr();
13133                                    }
13134                                }
13135                            }
13136                        }
13137                        // Send resources available broadcast
13138                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13139                    }
13140                }
13141                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13142                    // Clean up failed installation
13143                    if (mp.targetArgs != null) {
13144                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13145                                -1);
13146                    }
13147                } else {
13148                    // Force a gc to clear things up.
13149                    Runtime.getRuntime().gc();
13150                    // Delete older code
13151                    synchronized (mInstallLock) {
13152                        mp.srcArgs.doPostDeleteLI(true);
13153                    }
13154                }
13155
13156                // Allow more operations on this file if we didn't fail because
13157                // an operation was already pending for this package.
13158                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13159                    synchronized (mPackages) {
13160                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13161                        if (pkg != null) {
13162                            pkg.mOperationPending = false;
13163                       }
13164                   }
13165                }
13166
13167                IPackageMoveObserver observer = mp.observer;
13168                if (observer != null) {
13169                    try {
13170                        observer.packageMoved(mp.packageName, returnCode);
13171                    } catch (RemoteException e) {
13172                        Log.i(TAG, "Observer no longer exists.");
13173                    }
13174                }
13175            }
13176        });
13177    }
13178
13179    @Override
13180    public boolean setInstallLocation(int loc) {
13181        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13182                null);
13183        if (getInstallLocation() == loc) {
13184            return true;
13185        }
13186        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13187                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13188            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13189                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13190            return true;
13191        }
13192        return false;
13193   }
13194
13195    @Override
13196    public int getInstallLocation() {
13197        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13198                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13199                PackageHelper.APP_INSTALL_AUTO);
13200    }
13201
13202    /** Called by UserManagerService */
13203    void cleanUpUserLILPw(int userHandle) {
13204        mDirtyUsers.remove(userHandle);
13205        mSettings.removeUserLPw(userHandle);
13206        mPendingBroadcasts.remove(userHandle);
13207        if (mInstaller != null) {
13208            // Technically, we shouldn't be doing this with the package lock
13209            // held.  However, this is very rare, and there is already so much
13210            // other disk I/O going on, that we'll let it slide for now.
13211            mInstaller.removeUserDataDirs(userHandle);
13212        }
13213        mUserNeedsBadging.delete(userHandle);
13214    }
13215
13216    /** Called by UserManagerService */
13217    void createNewUserLILPw(int userHandle, File path) {
13218        if (mInstaller != null) {
13219            mInstaller.createUserConfig(userHandle);
13220            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13221        }
13222    }
13223
13224    @Override
13225    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13226        mContext.enforceCallingOrSelfPermission(
13227                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13228                "Only package verification agents can read the verifier device identity");
13229
13230        synchronized (mPackages) {
13231            return mSettings.getVerifierDeviceIdentityLPw();
13232        }
13233    }
13234
13235    @Override
13236    public void setPermissionEnforced(String permission, boolean enforced) {
13237        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13238        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13239            synchronized (mPackages) {
13240                if (mSettings.mReadExternalStorageEnforced == null
13241                        || mSettings.mReadExternalStorageEnforced != enforced) {
13242                    mSettings.mReadExternalStorageEnforced = enforced;
13243                    mSettings.writeLPr();
13244                }
13245            }
13246            // kill any non-foreground processes so we restart them and
13247            // grant/revoke the GID.
13248            final IActivityManager am = ActivityManagerNative.getDefault();
13249            if (am != null) {
13250                final long token = Binder.clearCallingIdentity();
13251                try {
13252                    am.killProcessesBelowForeground("setPermissionEnforcement");
13253                } catch (RemoteException e) {
13254                } finally {
13255                    Binder.restoreCallingIdentity(token);
13256                }
13257            }
13258        } else {
13259            throw new IllegalArgumentException("No selective enforcement for " + permission);
13260        }
13261    }
13262
13263    @Override
13264    @Deprecated
13265    public boolean isPermissionEnforced(String permission) {
13266        return true;
13267    }
13268
13269    @Override
13270    public boolean isStorageLow() {
13271        final long token = Binder.clearCallingIdentity();
13272        try {
13273            final DeviceStorageMonitorInternal
13274                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13275            if (dsm != null) {
13276                return dsm.isMemoryLow();
13277            } else {
13278                return false;
13279            }
13280        } finally {
13281            Binder.restoreCallingIdentity(token);
13282        }
13283    }
13284
13285    @Override
13286    public IPackageInstaller getPackageInstaller() {
13287        return mInstallerService;
13288    }
13289
13290    private boolean userNeedsBadging(int userId) {
13291        int index = mUserNeedsBadging.indexOfKey(userId);
13292        if (index < 0) {
13293            final UserInfo userInfo;
13294            final long token = Binder.clearCallingIdentity();
13295            try {
13296                userInfo = sUserManager.getUserInfo(userId);
13297            } finally {
13298                Binder.restoreCallingIdentity(token);
13299            }
13300            final boolean b;
13301            if (userInfo != null && userInfo.isManagedProfile()) {
13302                b = true;
13303            } else {
13304                b = false;
13305            }
13306            mUserNeedsBadging.put(userId, b);
13307            return b;
13308        }
13309        return mUserNeedsBadging.valueAt(index);
13310    }
13311
13312    @Override
13313    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13314        if (packageName == null || alias == null) {
13315            return null;
13316        }
13317        synchronized(mPackages) {
13318            final PackageParser.Package pkg = mPackages.get(packageName);
13319            if (pkg == null) {
13320                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13321                throw new IllegalArgumentException("Unknown package: " + packageName);
13322            }
13323            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13324                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13325                throw new SecurityException("May not access KeySets defined by"
13326                        + " aliases in other applications.");
13327            }
13328            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13329            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13330        }
13331    }
13332
13333    @Override
13334    public KeySetHandle getSigningKeySet(String packageName) {
13335        if (packageName == null) {
13336            return null;
13337        }
13338        synchronized(mPackages) {
13339            final PackageParser.Package pkg = mPackages.get(packageName);
13340            if (pkg == null) {
13341                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13342                throw new IllegalArgumentException("Unknown package: " + packageName);
13343            }
13344            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13345                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13346                throw new SecurityException("May not access signing KeySet of other apps.");
13347            }
13348            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13349            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13350        }
13351    }
13352
13353    @Override
13354    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13355        if (packageName == null || ks == null) {
13356            return false;
13357        }
13358        synchronized(mPackages) {
13359            final PackageParser.Package pkg = mPackages.get(packageName);
13360            if (pkg == null) {
13361                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13362                throw new IllegalArgumentException("Unknown package: " + packageName);
13363            }
13364            if (ks instanceof KeySetHandle) {
13365                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13366                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13367            }
13368            return false;
13369        }
13370    }
13371
13372    @Override
13373    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13374        if (packageName == null || ks == null) {
13375            return false;
13376        }
13377        synchronized(mPackages) {
13378            final PackageParser.Package pkg = mPackages.get(packageName);
13379            if (pkg == null) {
13380                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13381                throw new IllegalArgumentException("Unknown package: " + packageName);
13382            }
13383            if (ks instanceof KeySetHandle) {
13384                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13385                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13386            }
13387            return false;
13388        }
13389    }
13390}
13391