PackageManagerService.java revision 4282924ed33102605d6c295f164ffb3249ced7b4
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_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
56import static com.android.internal.util.ArrayUtils.appendInt;
57import static com.android.internal.util.ArrayUtils.removeInt;
58import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
60import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
61import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
62
63import android.util.ArrayMap;
64
65import com.android.internal.R;
66import com.android.internal.app.IMediaContainerService;
67import com.android.internal.app.ResolverActivity;
68import com.android.internal.content.NativeLibraryHelper;
69import com.android.internal.content.PackageHelper;
70import com.android.internal.os.IParcelFileDescriptorFactory;
71import com.android.internal.util.ArrayUtils;
72import com.android.internal.util.FastPrintWriter;
73import com.android.internal.util.FastXmlSerializer;
74import com.android.internal.util.IndentingPrintWriter;
75import com.android.server.EventLogTags;
76import com.android.server.IntentResolver;
77import com.android.server.LocalServices;
78import com.android.server.ServiceThread;
79import com.android.server.SystemConfig;
80import com.android.server.Watchdog;
81import com.android.server.pm.Settings.DatabaseVersion;
82import com.android.server.storage.DeviceStorageMonitorInternal;
83
84import org.xmlpull.v1.XmlSerializer;
85
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IPackageDataObserver;
107import android.content.pm.IPackageDeleteObserver;
108import android.content.pm.IPackageDeleteObserver2;
109import android.content.pm.IPackageInstallObserver2;
110import android.content.pm.IPackageInstaller;
111import android.content.pm.IPackageManager;
112import android.content.pm.IPackageMoveObserver;
113import android.content.pm.IPackageStatsObserver;
114import android.content.pm.InstrumentationInfo;
115import android.content.pm.KeySet;
116import android.content.pm.ManifestDigest;
117import android.content.pm.PackageCleanItem;
118import android.content.pm.PackageInfo;
119import android.content.pm.PackageInfoLite;
120import android.content.pm.PackageInstaller;
121import android.content.pm.PackageManager;
122import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
123import android.content.pm.PackageParser.ActivityIntentInfo;
124import android.content.pm.PackageParser.PackageLite;
125import android.content.pm.PackageParser.PackageParserException;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageStats;
128import android.content.pm.PackageUserState;
129import android.content.pm.ParceledListSlice;
130import android.content.pm.PermissionGroupInfo;
131import android.content.pm.PermissionInfo;
132import android.content.pm.ProviderInfo;
133import android.content.pm.ResolveInfo;
134import android.content.pm.ServiceInfo;
135import android.content.pm.Signature;
136import android.content.pm.UserInfo;
137import android.content.pm.VerificationParams;
138import android.content.pm.VerifierDeviceIdentity;
139import android.content.pm.VerifierInfo;
140import android.content.res.Resources;
141import android.hardware.display.DisplayManager;
142import android.net.Uri;
143import android.os.Binder;
144import android.os.Build;
145import android.os.Bundle;
146import android.os.Environment;
147import android.os.Environment.UserEnvironment;
148import android.os.storage.IMountService;
149import android.os.storage.StorageManager;
150import android.os.Debug;
151import android.os.FileUtils;
152import android.os.Handler;
153import android.os.IBinder;
154import android.os.Looper;
155import android.os.Message;
156import android.os.Parcel;
157import android.os.ParcelFileDescriptor;
158import android.os.Process;
159import android.os.RemoteException;
160import android.os.SELinux;
161import android.os.ServiceManager;
162import android.os.SystemClock;
163import android.os.SystemProperties;
164import android.os.UserHandle;
165import android.os.UserManager;
166import android.security.KeyStore;
167import android.security.SystemKeyStore;
168import android.system.ErrnoException;
169import android.system.Os;
170import android.system.StructStat;
171import android.text.TextUtils;
172import android.text.format.DateUtils;
173import android.util.ArraySet;
174import android.util.AtomicFile;
175import android.util.DisplayMetrics;
176import android.util.EventLog;
177import android.util.ExceptionUtils;
178import android.util.Log;
179import android.util.LogPrinter;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.view.Display;
185
186import java.io.BufferedInputStream;
187import java.io.BufferedOutputStream;
188import java.io.BufferedReader;
189import java.io.File;
190import java.io.FileDescriptor;
191import java.io.FileNotFoundException;
192import java.io.FileOutputStream;
193import java.io.FileReader;
194import java.io.FilenameFilter;
195import java.io.IOException;
196import java.io.InputStream;
197import java.io.PrintWriter;
198import java.nio.charset.StandardCharsets;
199import java.security.NoSuchAlgorithmException;
200import java.security.PublicKey;
201import java.security.cert.CertificateEncodingException;
202import java.security.cert.CertificateException;
203import java.text.SimpleDateFormat;
204import java.util.ArrayList;
205import java.util.Arrays;
206import java.util.Collection;
207import java.util.Collections;
208import java.util.Comparator;
209import java.util.Date;
210import java.util.Iterator;
211import java.util.List;
212import java.util.Map;
213import java.util.Objects;
214import java.util.Set;
215import java.util.concurrent.atomic.AtomicBoolean;
216import java.util.concurrent.atomic.AtomicLong;
217
218import dalvik.system.DexFile;
219import dalvik.system.VMRuntime;
220
221import libcore.io.IoUtils;
222import libcore.util.EmptyArray;
223
224/**
225 * Keep track of all those .apks everywhere.
226 *
227 * This is very central to the platform's security; please run the unit
228 * tests whenever making modifications here:
229 *
230mmm frameworks/base/tests/AndroidTests
231adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
232adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
233 *
234 * {@hide}
235 */
236public class PackageManagerService extends IPackageManager.Stub {
237    static final String TAG = "PackageManager";
238    static final boolean DEBUG_SETTINGS = false;
239    static final boolean DEBUG_PREFERRED = false;
240    static final boolean DEBUG_UPGRADE = false;
241    private static final boolean DEBUG_INSTALL = false;
242    private static final boolean DEBUG_REMOVE = false;
243    private static final boolean DEBUG_BROADCASTS = false;
244    private static final boolean DEBUG_SHOW_INFO = false;
245    private static final boolean DEBUG_PACKAGE_INFO = false;
246    private static final boolean DEBUG_INTENT_MATCHING = false;
247    private static final boolean DEBUG_PACKAGE_SCANNING = false;
248    private static final boolean DEBUG_VERIFY = false;
249    private static final boolean DEBUG_DEXOPT = false;
250    private static final boolean DEBUG_ABI_SELECTION = false;
251
252    private static final int RADIO_UID = Process.PHONE_UID;
253    private static final int LOG_UID = Process.LOG_UID;
254    private static final int NFC_UID = Process.NFC_UID;
255    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
256    private static final int SHELL_UID = Process.SHELL_UID;
257
258    // Cap the size of permission trees that 3rd party apps can define
259    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
260
261    // Suffix used during package installation when copying/moving
262    // package apks to install directory.
263    private static final String INSTALL_PACKAGE_SUFFIX = "-";
264
265    static final int SCAN_NO_DEX = 1<<1;
266    static final int SCAN_FORCE_DEX = 1<<2;
267    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
268    static final int SCAN_NEW_INSTALL = 1<<4;
269    static final int SCAN_NO_PATHS = 1<<5;
270    static final int SCAN_UPDATE_TIME = 1<<6;
271    static final int SCAN_DEFER_DEX = 1<<7;
272    static final int SCAN_BOOTING = 1<<8;
273    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
274    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
275    static final int SCAN_REPLACING = 1<<11;
276
277    static final int REMOVE_CHATTY = 1<<16;
278
279    /**
280     * Timeout (in milliseconds) after which the watchdog should declare that
281     * our handler thread is wedged.  The usual default for such things is one
282     * minute but we sometimes do very lengthy I/O operations on this thread,
283     * such as installing multi-gigabyte applications, so ours needs to be longer.
284     */
285    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
286
287    /**
288     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
289     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
290     * settings entry if available, otherwise we use the hardcoded default.  If it's been
291     * more than this long since the last fstrim, we force one during the boot sequence.
292     *
293     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
294     * one gets run at the next available charging+idle time.  This final mandatory
295     * no-fstrim check kicks in only of the other scheduling criteria is never met.
296     */
297    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
298
299    /**
300     * Whether verification is enabled by default.
301     */
302    private static final boolean DEFAULT_VERIFY_ENABLE = true;
303
304    /**
305     * The default maximum time to wait for the verification agent to return in
306     * milliseconds.
307     */
308    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
309
310    /**
311     * The default response for package verification timeout.
312     *
313     * This can be either PackageManager.VERIFICATION_ALLOW or
314     * PackageManager.VERIFICATION_REJECT.
315     */
316    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
317
318    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
319
320    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
321            DEFAULT_CONTAINER_PACKAGE,
322            "com.android.defcontainer.DefaultContainerService");
323
324    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
325
326    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
327
328    final ServiceThread mHandlerThread;
329
330    final PackageHandler mHandler;
331
332    /**
333     * Messages for {@link #mHandler} that need to wait for system ready before
334     * being dispatched.
335     */
336    private ArrayList<Message> mPostSystemReadyMessages;
337
338    final int mSdkVersion = Build.VERSION.SDK_INT;
339
340    final Context mContext;
341    final boolean mFactoryTest;
342    final boolean mOnlyCore;
343    final boolean mLazyDexOpt;
344    final long mDexOptLRUThresholdInMills;
345    final DisplayMetrics mMetrics;
346    final int mDefParseFlags;
347    final String[] mSeparateProcesses;
348    final boolean mIsUpgrade;
349
350    // This is where all application persistent data goes.
351    final File mAppDataDir;
352
353    // This is where all application persistent data goes for secondary users.
354    final File mUserAppDataDir;
355
356    /** The location for ASEC container files on internal storage. */
357    final String mAsecInternalPath;
358
359    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
360    // LOCK HELD.  Can be called with mInstallLock held.
361    final Installer mInstaller;
362
363    /** Directory where installed third-party apps stored */
364    final File mAppInstallDir;
365
366    /**
367     * Directory to which applications installed internally have their
368     * 32 bit native libraries copied.
369     */
370    private File mAppLib32InstallDir;
371
372    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
373    // apps.
374    final File mDrmAppPrivateInstallDir;
375
376    // ----------------------------------------------------------------
377
378    // Lock for state used when installing and doing other long running
379    // operations.  Methods that must be called with this lock held have
380    // the suffix "LI".
381    final Object mInstallLock = new Object();
382
383    // ----------------------------------------------------------------
384
385    // Keys are String (package name), values are Package.  This also serves
386    // as the lock for the global state.  Methods that must be called with
387    // this lock held have the prefix "LP".
388    final ArrayMap<String, PackageParser.Package> mPackages =
389            new ArrayMap<String, PackageParser.Package>();
390
391    // Tracks available target package names -> overlay package paths.
392    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
393        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
394
395    final Settings mSettings;
396    boolean mRestoredSettings;
397
398    // System configuration read by SystemConfig.
399    final int[] mGlobalGids;
400    final SparseArray<ArraySet<String>> mSystemPermissions;
401    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
402
403    // If mac_permissions.xml was found for seinfo labeling.
404    boolean mFoundPolicyFile;
405
406    // If a recursive restorecon of /data/data/<pkg> is needed.
407    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
408
409    public static final class SharedLibraryEntry {
410        public final String path;
411        public final String apk;
412
413        SharedLibraryEntry(String _path, String _apk) {
414            path = _path;
415            apk = _apk;
416        }
417    }
418
419    // Currently known shared libraries.
420    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
421            new ArrayMap<String, SharedLibraryEntry>();
422
423    // All available activities, for your resolving pleasure.
424    final ActivityIntentResolver mActivities =
425            new ActivityIntentResolver();
426
427    // All available receivers, for your resolving pleasure.
428    final ActivityIntentResolver mReceivers =
429            new ActivityIntentResolver();
430
431    // All available services, for your resolving pleasure.
432    final ServiceIntentResolver mServices = new ServiceIntentResolver();
433
434    // All available providers, for your resolving pleasure.
435    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
436
437    // Mapping from provider base names (first directory in content URI codePath)
438    // to the provider information.
439    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
440            new ArrayMap<String, PackageParser.Provider>();
441
442    // Mapping from instrumentation class names to info about them.
443    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
444            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
445
446    // Mapping from permission names to info about them.
447    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
448            new ArrayMap<String, PackageParser.PermissionGroup>();
449
450    // Packages whose data we have transfered into another package, thus
451    // should no longer exist.
452    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
453
454    // Broadcast actions that are only available to the system.
455    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
456
457    /** List of packages waiting for verification. */
458    final SparseArray<PackageVerificationState> mPendingVerification
459            = new SparseArray<PackageVerificationState>();
460
461    /** Set of packages associated with each app op permission. */
462    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
463
464    final PackageInstallerService mInstallerService;
465
466    private final PackageDexOptimizer mPackageDexOptimizer;
467    // Cache of users who need badging.
468    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    volatile boolean mSystemReady;
474    volatile boolean mSafeMode;
475    volatile boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new ArrayMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsHistoricalPackageUsageAvailable = true;
625
626        boolean isHistoricalPackageUsageAvailable() {
627            return mIsHistoricalPackageUsageAvailable;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsHistoricalPackageUsageAvailable = false;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                Bundle extras = extrasForInstallResult(res);
1081                                args.observer.onPackageInstalled(res.name, res.returnCode,
1082                                        res.returnMsg, extras);
1083                            } catch (RemoteException e) {
1084                                Slog.i(TAG, "Observer no longer exists.");
1085                            }
1086                        }
1087                    } else {
1088                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1089                    }
1090                } break;
1091                case UPDATED_MEDIA_STATUS: {
1092                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1093                    boolean reportStatus = msg.arg1 == 1;
1094                    boolean doGc = msg.arg2 == 1;
1095                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1096                    if (doGc) {
1097                        // Force a gc to clear up stale containers.
1098                        Runtime.getRuntime().gc();
1099                    }
1100                    if (msg.obj != null) {
1101                        @SuppressWarnings("unchecked")
1102                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1103                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1104                        // Unload containers
1105                        unloadAllContainers(args);
1106                    }
1107                    if (reportStatus) {
1108                        try {
1109                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1110                            PackageHelper.getMountService().finishMediaUpdate();
1111                        } catch (RemoteException e) {
1112                            Log.e(TAG, "MountService not running?");
1113                        }
1114                    }
1115                } break;
1116                case WRITE_SETTINGS: {
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1118                    synchronized (mPackages) {
1119                        removeMessages(WRITE_SETTINGS);
1120                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1121                        mSettings.writeLPr();
1122                        mDirtyUsers.clear();
1123                    }
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125                } break;
1126                case WRITE_PACKAGE_RESTRICTIONS: {
1127                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1128                    synchronized (mPackages) {
1129                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1130                        for (int userId : mDirtyUsers) {
1131                            mSettings.writePackageRestrictionsLPr(userId);
1132                        }
1133                        mDirtyUsers.clear();
1134                    }
1135                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136                } break;
1137                case CHECK_PENDING_VERIFICATION: {
1138                    final int verificationId = msg.arg1;
1139                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1140
1141                    if ((state != null) && !state.timeoutExtended()) {
1142                        final InstallArgs args = state.getInstallArgs();
1143                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1144
1145                        Slog.i(TAG, "Verification timed out for " + originUri);
1146                        mPendingVerification.remove(verificationId);
1147
1148                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1149
1150                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1151                            Slog.i(TAG, "Continuing with installation of " + originUri);
1152                            state.setVerifierResponse(Binder.getCallingUid(),
1153                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1154                            broadcastPackageVerified(verificationId, originUri,
1155                                    PackageManager.VERIFICATION_ALLOW,
1156                                    state.getInstallArgs().getUser());
1157                            try {
1158                                ret = args.copyApk(mContainerService, true);
1159                            } catch (RemoteException e) {
1160                                Slog.e(TAG, "Could not contact the ContainerService");
1161                            }
1162                        } else {
1163                            broadcastPackageVerified(verificationId, originUri,
1164                                    PackageManager.VERIFICATION_REJECT,
1165                                    state.getInstallArgs().getUser());
1166                        }
1167
1168                        processPendingInstall(args, ret);
1169                        mHandler.sendEmptyMessage(MCS_UNBIND);
1170                    }
1171                    break;
1172                }
1173                case PACKAGE_VERIFIED: {
1174                    final int verificationId = msg.arg1;
1175
1176                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1177                    if (state == null) {
1178                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1179                        break;
1180                    }
1181
1182                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1183
1184                    state.setVerifierResponse(response.callerUid, response.code);
1185
1186                    if (state.isVerificationComplete()) {
1187                        mPendingVerification.remove(verificationId);
1188
1189                        final InstallArgs args = state.getInstallArgs();
1190                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1191
1192                        int ret;
1193                        if (state.isInstallAllowed()) {
1194                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1195                            broadcastPackageVerified(verificationId, originUri,
1196                                    response.code, state.getInstallArgs().getUser());
1197                            try {
1198                                ret = args.copyApk(mContainerService, true);
1199                            } catch (RemoteException e) {
1200                                Slog.e(TAG, "Could not contact the ContainerService");
1201                            }
1202                        } else {
1203                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1204                        }
1205
1206                        processPendingInstall(args, ret);
1207
1208                        mHandler.sendEmptyMessage(MCS_UNBIND);
1209                    }
1210
1211                    break;
1212                }
1213            }
1214        }
1215    }
1216
1217    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1218        Bundle extras = null;
1219        switch (res.returnCode) {
1220            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1221                extras = new Bundle();
1222                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1223                        res.origPermission);
1224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1225                        res.origPackage);
1226                break;
1227            }
1228        }
1229        return extras;
1230    }
1231
1232    void scheduleWriteSettingsLocked() {
1233        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1234            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1235        }
1236    }
1237
1238    void scheduleWritePackageRestrictionsLocked(int userId) {
1239        if (!sUserManager.exists(userId)) return;
1240        mDirtyUsers.add(userId);
1241        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1242            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1243        }
1244    }
1245
1246    public static final PackageManagerService main(Context context, Installer installer,
1247            boolean factoryTest, boolean onlyCore) {
1248        PackageManagerService m = new PackageManagerService(context, installer,
1249                factoryTest, onlyCore);
1250        ServiceManager.addService("package", m);
1251        return m;
1252    }
1253
1254    static String[] splitString(String str, char sep) {
1255        int count = 1;
1256        int i = 0;
1257        while ((i=str.indexOf(sep, i)) >= 0) {
1258            count++;
1259            i++;
1260        }
1261
1262        String[] res = new String[count];
1263        i=0;
1264        count = 0;
1265        int lastI=0;
1266        while ((i=str.indexOf(sep, i)) >= 0) {
1267            res[count] = str.substring(lastI, i);
1268            count++;
1269            i++;
1270            lastI = i;
1271        }
1272        res[count] = str.substring(lastI, str.length());
1273        return res;
1274    }
1275
1276    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1277        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1278                Context.DISPLAY_SERVICE);
1279        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1280    }
1281
1282    public PackageManagerService(Context context, Installer installer,
1283            boolean factoryTest, boolean onlyCore) {
1284        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1285                SystemClock.uptimeMillis());
1286
1287        if (mSdkVersion <= 0) {
1288            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1289        }
1290
1291        mContext = context;
1292        mFactoryTest = factoryTest;
1293        mOnlyCore = onlyCore;
1294        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1295        mMetrics = new DisplayMetrics();
1296        mSettings = new Settings(context);
1297        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1298                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1299        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1300                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1302                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1304                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1306                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1308                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1309
1310        // TODO: add a property to control this?
1311        long dexOptLRUThresholdInMinutes;
1312        if (mLazyDexOpt) {
1313            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1314        } else {
1315            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1316        }
1317        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1318
1319        String separateProcesses = SystemProperties.get("debug.separate_processes");
1320        if (separateProcesses != null && separateProcesses.length() > 0) {
1321            if ("*".equals(separateProcesses)) {
1322                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1323                mSeparateProcesses = null;
1324                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1325            } else {
1326                mDefParseFlags = 0;
1327                mSeparateProcesses = separateProcesses.split(",");
1328                Slog.w(TAG, "Running with debug.separate_processes: "
1329                        + separateProcesses);
1330            }
1331        } else {
1332            mDefParseFlags = 0;
1333            mSeparateProcesses = null;
1334        }
1335
1336        mInstaller = installer;
1337        mPackageDexOptimizer = new PackageDexOptimizer(this);
1338
1339        getDefaultDisplayMetrics(context, mMetrics);
1340
1341        SystemConfig systemConfig = SystemConfig.getInstance();
1342        mGlobalGids = systemConfig.getGlobalGids();
1343        mSystemPermissions = systemConfig.getSystemPermissions();
1344        mAvailableFeatures = systemConfig.getAvailableFeatures();
1345
1346        synchronized (mInstallLock) {
1347        // writer
1348        synchronized (mPackages) {
1349            mHandlerThread = new ServiceThread(TAG,
1350                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1351            mHandlerThread.start();
1352            mHandler = new PackageHandler(mHandlerThread.getLooper());
1353            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1354
1355            File dataDir = Environment.getDataDirectory();
1356            mAppDataDir = new File(dataDir, "data");
1357            mAppInstallDir = new File(dataDir, "app");
1358            mAppLib32InstallDir = new File(dataDir, "app-lib");
1359            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1360            mUserAppDataDir = new File(dataDir, "user");
1361            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1362
1363            sUserManager = new UserManagerService(context, this,
1364                    mInstallLock, mPackages);
1365
1366            // Propagate permission configuration in to package manager.
1367            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1368                    = systemConfig.getPermissions();
1369            for (int i=0; i<permConfig.size(); i++) {
1370                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1371                BasePermission bp = mSettings.mPermissions.get(perm.name);
1372                if (bp == null) {
1373                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1374                    mSettings.mPermissions.put(perm.name, bp);
1375                }
1376                if (perm.gids != null) {
1377                    bp.gids = appendInts(bp.gids, perm.gids);
1378                }
1379            }
1380
1381            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1382            for (int i=0; i<libConfig.size(); i++) {
1383                mSharedLibraries.put(libConfig.keyAt(i),
1384                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1385            }
1386
1387            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1388
1389            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1390                    mSdkVersion, mOnlyCore);
1391
1392            String customResolverActivity = Resources.getSystem().getString(
1393                    R.string.config_customResolverActivity);
1394            if (TextUtils.isEmpty(customResolverActivity)) {
1395                customResolverActivity = null;
1396            } else {
1397                mCustomResolverComponentName = ComponentName.unflattenFromString(
1398                        customResolverActivity);
1399            }
1400
1401            long startTime = SystemClock.uptimeMillis();
1402
1403            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1404                    startTime);
1405
1406            // Set flag to monitor and not change apk file paths when
1407            // scanning install directories.
1408            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1409
1410            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1411
1412            /**
1413             * Add everything in the in the boot class path to the
1414             * list of process files because dexopt will have been run
1415             * if necessary during zygote startup.
1416             */
1417            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1418            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1419
1420            if (bootClassPath != null) {
1421                String[] bootClassPathElements = splitString(bootClassPath, ':');
1422                for (String element : bootClassPathElements) {
1423                    alreadyDexOpted.add(element);
1424                }
1425            } else {
1426                Slog.w(TAG, "No BOOTCLASSPATH found!");
1427            }
1428
1429            if (systemServerClassPath != null) {
1430                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1431                for (String element : systemServerClassPathElements) {
1432                    alreadyDexOpted.add(element);
1433                }
1434            } else {
1435                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1436            }
1437
1438            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1439            final String[] dexCodeInstructionSets =
1440                    getDexCodeInstructionSets(
1441                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1442
1443            /**
1444             * Ensure all external libraries have had dexopt run on them.
1445             */
1446            if (mSharedLibraries.size() > 0) {
1447                // NOTE: For now, we're compiling these system "shared libraries"
1448                // (and framework jars) into all available architectures. It's possible
1449                // to compile them only when we come across an app that uses them (there's
1450                // already logic for that in scanPackageLI) but that adds some complexity.
1451                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1452                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1453                        final String lib = libEntry.path;
1454                        if (lib == null) {
1455                            continue;
1456                        }
1457
1458                        try {
1459                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1460                                                                                 dexCodeInstructionSet,
1461                                                                                 false);
1462                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1463                                alreadyDexOpted.add(lib);
1464
1465                                // The list of "shared libraries" we have at this point is
1466                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1467                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1468                                } else {
1469                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1470                                }
1471                            }
1472                        } catch (FileNotFoundException e) {
1473                            Slog.w(TAG, "Library not found: " + lib);
1474                        } catch (IOException e) {
1475                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1476                                    + e.getMessage());
1477                        }
1478                    }
1479                }
1480            }
1481
1482            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1483
1484            // Gross hack for now: we know this file doesn't contain any
1485            // code, so don't dexopt it to avoid the resulting log spew.
1486            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1487
1488            // Gross hack for now: we know this file is only part of
1489            // the boot class path for art, so don't dexopt it to
1490            // avoid the resulting log spew.
1491            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1492
1493            /**
1494             * And there are a number of commands implemented in Java, which
1495             * we currently need to do the dexopt on so that they can be
1496             * run from a non-root shell.
1497             */
1498            String[] frameworkFiles = frameworkDir.list();
1499            if (frameworkFiles != null) {
1500                // TODO: We could compile these only for the most preferred ABI. We should
1501                // first double check that the dex files for these commands are not referenced
1502                // by other system apps.
1503                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1504                    for (int i=0; i<frameworkFiles.length; i++) {
1505                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1506                        String path = libPath.getPath();
1507                        // Skip the file if we already did it.
1508                        if (alreadyDexOpted.contains(path)) {
1509                            continue;
1510                        }
1511                        // Skip the file if it is not a type we want to dexopt.
1512                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1513                            continue;
1514                        }
1515                        try {
1516                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1517                                                                                 dexCodeInstructionSet,
1518                                                                                 false);
1519                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1520                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1521                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1522                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                            }
1524                        } catch (FileNotFoundException e) {
1525                            Slog.w(TAG, "Jar not found: " + path);
1526                        } catch (IOException e) {
1527                            Slog.w(TAG, "Exception reading jar: " + path, e);
1528                        }
1529                    }
1530                }
1531            }
1532
1533            // Collect vendor overlay packages.
1534            // (Do this before scanning any apps.)
1535            // For security and version matching reason, only consider
1536            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1537            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1538            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1540
1541            // Find base frameworks (resource packages without code).
1542            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR
1544                    | PackageParser.PARSE_IS_PRIVILEGED,
1545                    scanFlags | SCAN_NO_DEX, 0);
1546
1547            // Collected privileged system packages.
1548            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1549            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1550                    | PackageParser.PARSE_IS_SYSTEM_DIR
1551                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1552
1553            // Collect ordinary system packages.
1554            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1555            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1556                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1557
1558            // Collect all vendor packages.
1559            File vendorAppDir = new File("/vendor/app");
1560            try {
1561                vendorAppDir = vendorAppDir.getCanonicalFile();
1562            } catch (IOException e) {
1563                // failed to look up canonical path, continue with original one
1564            }
1565            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1566                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1567
1568            // Collect all OEM packages.
1569            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1570            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1571                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1572
1573            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1574            mInstaller.moveFiles();
1575
1576            // Prune any system packages that no longer exist.
1577            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1578            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1579            if (!mOnlyCore) {
1580                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1581                while (psit.hasNext()) {
1582                    PackageSetting ps = psit.next();
1583
1584                    /*
1585                     * If this is not a system app, it can't be a
1586                     * disable system app.
1587                     */
1588                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1589                        continue;
1590                    }
1591
1592                    /*
1593                     * If the package is scanned, it's not erased.
1594                     */
1595                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1596                    if (scannedPkg != null) {
1597                        /*
1598                         * If the system app is both scanned and in the
1599                         * disabled packages list, then it must have been
1600                         * added via OTA. Remove it from the currently
1601                         * scanned package so the previously user-installed
1602                         * application can be scanned.
1603                         */
1604                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1605                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1606                                    + ps.name + "; removing system app.  Last known codePath="
1607                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1608                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1609                                    + scannedPkg.mVersionCode);
1610                            removePackageLI(ps, true);
1611                            expectingBetter.put(ps.name, ps.codePath);
1612                        }
1613
1614                        continue;
1615                    }
1616
1617                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1618                        psit.remove();
1619                        logCriticalInfo(Log.WARN, "System package " + ps.name
1620                                + " no longer exists; wiping its data");
1621                        removeDataDirsLI(ps.name);
1622                    } else {
1623                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1624                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1625                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1626                        }
1627                    }
1628                }
1629            }
1630
1631            //look for any incomplete package installations
1632            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1633            //clean up list
1634            for(int i = 0; i < deletePkgsList.size(); i++) {
1635                //clean up here
1636                cleanupInstallFailedPackage(deletePkgsList.get(i));
1637            }
1638            //delete tmp files
1639            deleteTempPackageFiles();
1640
1641            // Remove any shared userIDs that have no associated packages
1642            mSettings.pruneSharedUsersLPw();
1643
1644            if (!mOnlyCore) {
1645                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1646                        SystemClock.uptimeMillis());
1647                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1648
1649                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1650                        scanFlags, 0);
1651
1652                /**
1653                 * Remove disable package settings for any updated system
1654                 * apps that were removed via an OTA. If they're not a
1655                 * previously-updated app, remove them completely.
1656                 * Otherwise, just revoke their system-level permissions.
1657                 */
1658                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1659                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1660                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1661
1662                    String msg;
1663                    if (deletedPkg == null) {
1664                        msg = "Updated system package " + deletedAppName
1665                                + " no longer exists; wiping its data";
1666                        removeDataDirsLI(deletedAppName);
1667                    } else {
1668                        msg = "Updated system app + " + deletedAppName
1669                                + " no longer present; removing system privileges for "
1670                                + deletedAppName;
1671
1672                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1673
1674                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1675                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1676                    }
1677                    logCriticalInfo(Log.WARN, msg);
1678                }
1679
1680                /**
1681                 * Make sure all system apps that we expected to appear on
1682                 * the userdata partition actually showed up. If they never
1683                 * appeared, crawl back and revive the system version.
1684                 */
1685                for (int i = 0; i < expectingBetter.size(); i++) {
1686                    final String packageName = expectingBetter.keyAt(i);
1687                    if (!mPackages.containsKey(packageName)) {
1688                        final File scanFile = expectingBetter.valueAt(i);
1689
1690                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1691                                + " but never showed up; reverting to system");
1692
1693                        final int reparseFlags;
1694                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1695                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1696                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1697                                    | PackageParser.PARSE_IS_PRIVILEGED;
1698                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1699                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1700                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1701                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1702                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1703                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1704                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1705                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1706                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1707                        } else {
1708                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1709                            continue;
1710                        }
1711
1712                        mSettings.enableSystemPackageLPw(packageName);
1713
1714                        try {
1715                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1716                        } catch (PackageManagerException e) {
1717                            Slog.e(TAG, "Failed to parse original system package: "
1718                                    + e.getMessage());
1719                        }
1720                    }
1721                }
1722            }
1723
1724            // Now that we know all of the shared libraries, update all clients to have
1725            // the correct library paths.
1726            updateAllSharedLibrariesLPw();
1727
1728            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1729                // NOTE: We ignore potential failures here during a system scan (like
1730                // the rest of the commands above) because there's precious little we
1731                // can do about it. A settings error is reported, though.
1732                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1733                        false /* force dexopt */, false /* defer dexopt */);
1734            }
1735
1736            // Now that we know all the packages we are keeping,
1737            // read and update their last usage times.
1738            mPackageUsage.readLP();
1739
1740            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1741                    SystemClock.uptimeMillis());
1742            Slog.i(TAG, "Time to scan packages: "
1743                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1744                    + " seconds");
1745
1746            // If the platform SDK has changed since the last time we booted,
1747            // we need to re-grant app permission to catch any new ones that
1748            // appear.  This is really a hack, and means that apps can in some
1749            // cases get permissions that the user didn't initially explicitly
1750            // allow...  it would be nice to have some better way to handle
1751            // this situation.
1752            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1753                    != mSdkVersion;
1754            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1755                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1756                    + "; regranting permissions for internal storage");
1757            mSettings.mInternalSdkPlatform = mSdkVersion;
1758
1759            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1760                    | (regrantPermissions
1761                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1762                            : 0));
1763
1764            // If this is the first boot, and it is a normal boot, then
1765            // we need to initialize the default preferred apps.
1766            if (!mRestoredSettings && !onlyCore) {
1767                mSettings.readDefaultPreferredAppsLPw(this, 0);
1768            }
1769
1770            // If this is first boot after an OTA, and a normal boot, then
1771            // we need to clear code cache directories.
1772            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1773            if (mIsUpgrade && !onlyCore) {
1774                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1775                for (String pkgName : mSettings.mPackages.keySet()) {
1776                    deleteCodeCacheDirsLI(pkgName);
1777                }
1778                mSettings.mFingerprint = Build.FINGERPRINT;
1779            }
1780
1781            // All the changes are done during package scanning.
1782            mSettings.updateInternalDatabaseVersion();
1783
1784            // can downgrade to reader
1785            mSettings.writeLPr();
1786
1787            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1788                    SystemClock.uptimeMillis());
1789
1790
1791            mRequiredVerifierPackage = getRequiredVerifierLPr();
1792        } // synchronized (mPackages)
1793        } // synchronized (mInstallLock)
1794
1795        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1796
1797        // Now after opening every single application zip, make sure they
1798        // are all flushed.  Not really needed, but keeps things nice and
1799        // tidy.
1800        Runtime.getRuntime().gc();
1801    }
1802
1803    @Override
1804    public boolean isFirstBoot() {
1805        return !mRestoredSettings;
1806    }
1807
1808    @Override
1809    public boolean isOnlyCoreApps() {
1810        return mOnlyCore;
1811    }
1812
1813    @Override
1814    public boolean isUpgrade() {
1815        return mIsUpgrade;
1816    }
1817
1818    private String getRequiredVerifierLPr() {
1819        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1820        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1821                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1822
1823        String requiredVerifier = null;
1824
1825        final int N = receivers.size();
1826        for (int i = 0; i < N; i++) {
1827            final ResolveInfo info = receivers.get(i);
1828
1829            if (info.activityInfo == null) {
1830                continue;
1831            }
1832
1833            final String packageName = info.activityInfo.packageName;
1834
1835            final PackageSetting ps = mSettings.mPackages.get(packageName);
1836            if (ps == null) {
1837                continue;
1838            }
1839
1840            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1841            if (!gp.grantedPermissions
1842                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1843                continue;
1844            }
1845
1846            if (requiredVerifier != null) {
1847                throw new RuntimeException("There can be only one required verifier");
1848            }
1849
1850            requiredVerifier = packageName;
1851        }
1852
1853        return requiredVerifier;
1854    }
1855
1856    @Override
1857    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1858            throws RemoteException {
1859        try {
1860            return super.onTransact(code, data, reply, flags);
1861        } catch (RuntimeException e) {
1862            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1863                Slog.wtf(TAG, "Package Manager Crash", e);
1864            }
1865            throw e;
1866        }
1867    }
1868
1869    void cleanupInstallFailedPackage(PackageSetting ps) {
1870        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1871
1872        removeDataDirsLI(ps.name);
1873        if (ps.codePath != null) {
1874            if (ps.codePath.isDirectory()) {
1875                FileUtils.deleteContents(ps.codePath);
1876            }
1877            ps.codePath.delete();
1878        }
1879        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1880            if (ps.resourcePath.isDirectory()) {
1881                FileUtils.deleteContents(ps.resourcePath);
1882            }
1883            ps.resourcePath.delete();
1884        }
1885        mSettings.removePackageLPw(ps.name);
1886    }
1887
1888    static int[] appendInts(int[] cur, int[] add) {
1889        if (add == null) return cur;
1890        if (cur == null) return add;
1891        final int N = add.length;
1892        for (int i=0; i<N; i++) {
1893            cur = appendInt(cur, add[i]);
1894        }
1895        return cur;
1896    }
1897
1898    static int[] removeInts(int[] cur, int[] rem) {
1899        if (rem == null) return cur;
1900        if (cur == null) return cur;
1901        final int N = rem.length;
1902        for (int i=0; i<N; i++) {
1903            cur = removeInt(cur, rem[i]);
1904        }
1905        return cur;
1906    }
1907
1908    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1909        if (!sUserManager.exists(userId)) return null;
1910        final PackageSetting ps = (PackageSetting) p.mExtras;
1911        if (ps == null) {
1912            return null;
1913        }
1914        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1915        final PackageUserState state = ps.readUserState(userId);
1916        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1917                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1918                state, userId);
1919    }
1920
1921    @Override
1922    public boolean isPackageAvailable(String packageName, int userId) {
1923        if (!sUserManager.exists(userId)) return false;
1924        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1925        synchronized (mPackages) {
1926            PackageParser.Package p = mPackages.get(packageName);
1927            if (p != null) {
1928                final PackageSetting ps = (PackageSetting) p.mExtras;
1929                if (ps != null) {
1930                    final PackageUserState state = ps.readUserState(userId);
1931                    if (state != null) {
1932                        return PackageParser.isAvailable(state);
1933                    }
1934                }
1935            }
1936        }
1937        return false;
1938    }
1939
1940    @Override
1941    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1942        if (!sUserManager.exists(userId)) return null;
1943        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1944        // reader
1945        synchronized (mPackages) {
1946            PackageParser.Package p = mPackages.get(packageName);
1947            if (DEBUG_PACKAGE_INFO)
1948                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1949            if (p != null) {
1950                return generatePackageInfo(p, flags, userId);
1951            }
1952            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1953                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1954            }
1955        }
1956        return null;
1957    }
1958
1959    @Override
1960    public String[] currentToCanonicalPackageNames(String[] names) {
1961        String[] out = new String[names.length];
1962        // reader
1963        synchronized (mPackages) {
1964            for (int i=names.length-1; i>=0; i--) {
1965                PackageSetting ps = mSettings.mPackages.get(names[i]);
1966                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1967            }
1968        }
1969        return out;
1970    }
1971
1972    @Override
1973    public String[] canonicalToCurrentPackageNames(String[] names) {
1974        String[] out = new String[names.length];
1975        // reader
1976        synchronized (mPackages) {
1977            for (int i=names.length-1; i>=0; i--) {
1978                String cur = mSettings.mRenamedPackages.get(names[i]);
1979                out[i] = cur != null ? cur : names[i];
1980            }
1981        }
1982        return out;
1983    }
1984
1985    @Override
1986    public int getPackageUid(String packageName, int userId) {
1987        if (!sUserManager.exists(userId)) return -1;
1988        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1989        // reader
1990        synchronized (mPackages) {
1991            PackageParser.Package p = mPackages.get(packageName);
1992            if(p != null) {
1993                return UserHandle.getUid(userId, p.applicationInfo.uid);
1994            }
1995            PackageSetting ps = mSettings.mPackages.get(packageName);
1996            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1997                return -1;
1998            }
1999            p = ps.pkg;
2000            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2001        }
2002    }
2003
2004    @Override
2005    public int[] getPackageGids(String packageName) {
2006        // reader
2007        synchronized (mPackages) {
2008            PackageParser.Package p = mPackages.get(packageName);
2009            if (DEBUG_PACKAGE_INFO)
2010                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2011            if (p != null) {
2012                final PackageSetting ps = (PackageSetting)p.mExtras;
2013                return ps.getGids();
2014            }
2015        }
2016        // stupid thing to indicate an error.
2017        return new int[0];
2018    }
2019
2020    static final PermissionInfo generatePermissionInfo(
2021            BasePermission bp, int flags) {
2022        if (bp.perm != null) {
2023            return PackageParser.generatePermissionInfo(bp.perm, flags);
2024        }
2025        PermissionInfo pi = new PermissionInfo();
2026        pi.name = bp.name;
2027        pi.packageName = bp.sourcePackage;
2028        pi.nonLocalizedLabel = bp.name;
2029        pi.protectionLevel = bp.protectionLevel;
2030        return pi;
2031    }
2032
2033    @Override
2034    public PermissionInfo getPermissionInfo(String name, int flags) {
2035        // reader
2036        synchronized (mPackages) {
2037            final BasePermission p = mSettings.mPermissions.get(name);
2038            if (p != null) {
2039                return generatePermissionInfo(p, flags);
2040            }
2041            return null;
2042        }
2043    }
2044
2045    @Override
2046    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2047        // reader
2048        synchronized (mPackages) {
2049            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2050            for (BasePermission p : mSettings.mPermissions.values()) {
2051                if (group == null) {
2052                    if (p.perm == null || p.perm.info.group == null) {
2053                        out.add(generatePermissionInfo(p, flags));
2054                    }
2055                } else {
2056                    if (p.perm != null && group.equals(p.perm.info.group)) {
2057                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2058                    }
2059                }
2060            }
2061
2062            if (out.size() > 0) {
2063                return out;
2064            }
2065            return mPermissionGroups.containsKey(group) ? out : null;
2066        }
2067    }
2068
2069    @Override
2070    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2071        // reader
2072        synchronized (mPackages) {
2073            return PackageParser.generatePermissionGroupInfo(
2074                    mPermissionGroups.get(name), flags);
2075        }
2076    }
2077
2078    @Override
2079    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2080        // reader
2081        synchronized (mPackages) {
2082            final int N = mPermissionGroups.size();
2083            ArrayList<PermissionGroupInfo> out
2084                    = new ArrayList<PermissionGroupInfo>(N);
2085            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2086                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2087            }
2088            return out;
2089        }
2090    }
2091
2092    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2093            int userId) {
2094        if (!sUserManager.exists(userId)) return null;
2095        PackageSetting ps = mSettings.mPackages.get(packageName);
2096        if (ps != null) {
2097            if (ps.pkg == null) {
2098                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2099                        flags, userId);
2100                if (pInfo != null) {
2101                    return pInfo.applicationInfo;
2102                }
2103                return null;
2104            }
2105            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2106                    ps.readUserState(userId), userId);
2107        }
2108        return null;
2109    }
2110
2111    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2112            int userId) {
2113        if (!sUserManager.exists(userId)) return null;
2114        PackageSetting ps = mSettings.mPackages.get(packageName);
2115        if (ps != null) {
2116            PackageParser.Package pkg = ps.pkg;
2117            if (pkg == null) {
2118                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2119                    return null;
2120                }
2121                // Only data remains, so we aren't worried about code paths
2122                pkg = new PackageParser.Package(packageName);
2123                pkg.applicationInfo.packageName = packageName;
2124                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2125                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2126                pkg.applicationInfo.dataDir =
2127                        getDataPathForPackage(packageName, 0).getPath();
2128                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2129                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2130            }
2131            return generatePackageInfo(pkg, flags, userId);
2132        }
2133        return null;
2134    }
2135
2136    @Override
2137    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2138        if (!sUserManager.exists(userId)) return null;
2139        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2140        // writer
2141        synchronized (mPackages) {
2142            PackageParser.Package p = mPackages.get(packageName);
2143            if (DEBUG_PACKAGE_INFO) Log.v(
2144                    TAG, "getApplicationInfo " + packageName
2145                    + ": " + p);
2146            if (p != null) {
2147                PackageSetting ps = mSettings.mPackages.get(packageName);
2148                if (ps == null) return null;
2149                // Note: isEnabledLP() does not apply here - always return info
2150                return PackageParser.generateApplicationInfo(
2151                        p, flags, ps.readUserState(userId), userId);
2152            }
2153            if ("android".equals(packageName)||"system".equals(packageName)) {
2154                return mAndroidApplication;
2155            }
2156            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2157                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2158            }
2159        }
2160        return null;
2161    }
2162
2163
2164    @Override
2165    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2166        mContext.enforceCallingOrSelfPermission(
2167                android.Manifest.permission.CLEAR_APP_CACHE, null);
2168        // Queue up an async operation since clearing cache may take a little while.
2169        mHandler.post(new Runnable() {
2170            public void run() {
2171                mHandler.removeCallbacks(this);
2172                int retCode = -1;
2173                synchronized (mInstallLock) {
2174                    retCode = mInstaller.freeCache(freeStorageSize);
2175                    if (retCode < 0) {
2176                        Slog.w(TAG, "Couldn't clear application caches");
2177                    }
2178                }
2179                if (observer != null) {
2180                    try {
2181                        observer.onRemoveCompleted(null, (retCode >= 0));
2182                    } catch (RemoteException e) {
2183                        Slog.w(TAG, "RemoveException when invoking call back");
2184                    }
2185                }
2186            }
2187        });
2188    }
2189
2190    @Override
2191    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2192        mContext.enforceCallingOrSelfPermission(
2193                android.Manifest.permission.CLEAR_APP_CACHE, null);
2194        // Queue up an async operation since clearing cache may take a little while.
2195        mHandler.post(new Runnable() {
2196            public void run() {
2197                mHandler.removeCallbacks(this);
2198                int retCode = -1;
2199                synchronized (mInstallLock) {
2200                    retCode = mInstaller.freeCache(freeStorageSize);
2201                    if (retCode < 0) {
2202                        Slog.w(TAG, "Couldn't clear application caches");
2203                    }
2204                }
2205                if(pi != null) {
2206                    try {
2207                        // Callback via pending intent
2208                        int code = (retCode >= 0) ? 1 : 0;
2209                        pi.sendIntent(null, code, null,
2210                                null, null);
2211                    } catch (SendIntentException e1) {
2212                        Slog.i(TAG, "Failed to send pending intent");
2213                    }
2214                }
2215            }
2216        });
2217    }
2218
2219    void freeStorage(long freeStorageSize) throws IOException {
2220        synchronized (mInstallLock) {
2221            if (mInstaller.freeCache(freeStorageSize) < 0) {
2222                throw new IOException("Failed to free enough space");
2223            }
2224        }
2225    }
2226
2227    @Override
2228    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2229        if (!sUserManager.exists(userId)) return null;
2230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2231        synchronized (mPackages) {
2232            PackageParser.Activity a = mActivities.mActivities.get(component);
2233
2234            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2235            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2236                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2237                if (ps == null) return null;
2238                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2239                        userId);
2240            }
2241            if (mResolveComponentName.equals(component)) {
2242                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2243                        new PackageUserState(), userId);
2244            }
2245        }
2246        return null;
2247    }
2248
2249    @Override
2250    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2251            String resolvedType) {
2252        synchronized (mPackages) {
2253            PackageParser.Activity a = mActivities.mActivities.get(component);
2254            if (a == null) {
2255                return false;
2256            }
2257            for (int i=0; i<a.intents.size(); i++) {
2258                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2259                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2260                    return true;
2261                }
2262            }
2263            return false;
2264        }
2265    }
2266
2267    @Override
2268    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2269        if (!sUserManager.exists(userId)) return null;
2270        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2271        synchronized (mPackages) {
2272            PackageParser.Activity a = mReceivers.mActivities.get(component);
2273            if (DEBUG_PACKAGE_INFO) Log.v(
2274                TAG, "getReceiverInfo " + component + ": " + a);
2275            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2276                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2277                if (ps == null) return null;
2278                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2279                        userId);
2280            }
2281        }
2282        return null;
2283    }
2284
2285    @Override
2286    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2287        if (!sUserManager.exists(userId)) return null;
2288        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2289        synchronized (mPackages) {
2290            PackageParser.Service s = mServices.mServices.get(component);
2291            if (DEBUG_PACKAGE_INFO) Log.v(
2292                TAG, "getServiceInfo " + component + ": " + s);
2293            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2294                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2295                if (ps == null) return null;
2296                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2297                        userId);
2298            }
2299        }
2300        return null;
2301    }
2302
2303    @Override
2304    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2305        if (!sUserManager.exists(userId)) return null;
2306        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2307        synchronized (mPackages) {
2308            PackageParser.Provider p = mProviders.mProviders.get(component);
2309            if (DEBUG_PACKAGE_INFO) Log.v(
2310                TAG, "getProviderInfo " + component + ": " + p);
2311            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2312                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2313                if (ps == null) return null;
2314                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2315                        userId);
2316            }
2317        }
2318        return null;
2319    }
2320
2321    @Override
2322    public String[] getSystemSharedLibraryNames() {
2323        Set<String> libSet;
2324        synchronized (mPackages) {
2325            libSet = mSharedLibraries.keySet();
2326            int size = libSet.size();
2327            if (size > 0) {
2328                String[] libs = new String[size];
2329                libSet.toArray(libs);
2330                return libs;
2331            }
2332        }
2333        return null;
2334    }
2335
2336    /**
2337     * @hide
2338     */
2339    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2340        synchronized (mPackages) {
2341            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2342            if (lib != null && lib.apk != null) {
2343                return mPackages.get(lib.apk);
2344            }
2345        }
2346        return null;
2347    }
2348
2349    @Override
2350    public FeatureInfo[] getSystemAvailableFeatures() {
2351        Collection<FeatureInfo> featSet;
2352        synchronized (mPackages) {
2353            featSet = mAvailableFeatures.values();
2354            int size = featSet.size();
2355            if (size > 0) {
2356                FeatureInfo[] features = new FeatureInfo[size+1];
2357                featSet.toArray(features);
2358                FeatureInfo fi = new FeatureInfo();
2359                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2360                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2361                features[size] = fi;
2362                return features;
2363            }
2364        }
2365        return null;
2366    }
2367
2368    @Override
2369    public boolean hasSystemFeature(String name) {
2370        synchronized (mPackages) {
2371            return mAvailableFeatures.containsKey(name);
2372        }
2373    }
2374
2375    private void checkValidCaller(int uid, int userId) {
2376        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2377            return;
2378
2379        throw new SecurityException("Caller uid=" + uid
2380                + " is not privileged to communicate with user=" + userId);
2381    }
2382
2383    @Override
2384    public int checkPermission(String permName, String pkgName) {
2385        synchronized (mPackages) {
2386            PackageParser.Package p = mPackages.get(pkgName);
2387            if (p != null && p.mExtras != null) {
2388                PackageSetting ps = (PackageSetting)p.mExtras;
2389                if (ps.sharedUser != null) {
2390                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2391                        return PackageManager.PERMISSION_GRANTED;
2392                    }
2393                } else if (ps.grantedPermissions.contains(permName)) {
2394                    return PackageManager.PERMISSION_GRANTED;
2395                }
2396            }
2397        }
2398        return PackageManager.PERMISSION_DENIED;
2399    }
2400
2401    @Override
2402    public int checkUidPermission(String permName, int uid) {
2403        synchronized (mPackages) {
2404            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2405            if (obj != null) {
2406                GrantedPermissions gp = (GrantedPermissions)obj;
2407                if (gp.grantedPermissions.contains(permName)) {
2408                    return PackageManager.PERMISSION_GRANTED;
2409                }
2410            } else {
2411                ArraySet<String> perms = mSystemPermissions.get(uid);
2412                if (perms != null && perms.contains(permName)) {
2413                    return PackageManager.PERMISSION_GRANTED;
2414                }
2415            }
2416        }
2417        return PackageManager.PERMISSION_DENIED;
2418    }
2419
2420    /**
2421     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2422     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2423     * @param checkShell TODO(yamasani):
2424     * @param message the message to log on security exception
2425     */
2426    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2427            boolean checkShell, String message) {
2428        if (userId < 0) {
2429            throw new IllegalArgumentException("Invalid userId " + userId);
2430        }
2431        if (checkShell) {
2432            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2433        }
2434        if (userId == UserHandle.getUserId(callingUid)) return;
2435        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2436            if (requireFullPermission) {
2437                mContext.enforceCallingOrSelfPermission(
2438                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2439            } else {
2440                try {
2441                    mContext.enforceCallingOrSelfPermission(
2442                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2443                } catch (SecurityException se) {
2444                    mContext.enforceCallingOrSelfPermission(
2445                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2446                }
2447            }
2448        }
2449    }
2450
2451    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2452        if (callingUid == Process.SHELL_UID) {
2453            if (userHandle >= 0
2454                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2455                throw new SecurityException("Shell does not have permission to access user "
2456                        + userHandle);
2457            } else if (userHandle < 0) {
2458                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2459                        + Debug.getCallers(3));
2460            }
2461        }
2462    }
2463
2464    private BasePermission findPermissionTreeLP(String permName) {
2465        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2466            if (permName.startsWith(bp.name) &&
2467                    permName.length() > bp.name.length() &&
2468                    permName.charAt(bp.name.length()) == '.') {
2469                return bp;
2470            }
2471        }
2472        return null;
2473    }
2474
2475    private BasePermission checkPermissionTreeLP(String permName) {
2476        if (permName != null) {
2477            BasePermission bp = findPermissionTreeLP(permName);
2478            if (bp != null) {
2479                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2480                    return bp;
2481                }
2482                throw new SecurityException("Calling uid "
2483                        + Binder.getCallingUid()
2484                        + " is not allowed to add to permission tree "
2485                        + bp.name + " owned by uid " + bp.uid);
2486            }
2487        }
2488        throw new SecurityException("No permission tree found for " + permName);
2489    }
2490
2491    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2492        if (s1 == null) {
2493            return s2 == null;
2494        }
2495        if (s2 == null) {
2496            return false;
2497        }
2498        if (s1.getClass() != s2.getClass()) {
2499            return false;
2500        }
2501        return s1.equals(s2);
2502    }
2503
2504    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2505        if (pi1.icon != pi2.icon) return false;
2506        if (pi1.logo != pi2.logo) return false;
2507        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2508        if (!compareStrings(pi1.name, pi2.name)) return false;
2509        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2510        // We'll take care of setting this one.
2511        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2512        // These are not currently stored in settings.
2513        //if (!compareStrings(pi1.group, pi2.group)) return false;
2514        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2515        //if (pi1.labelRes != pi2.labelRes) return false;
2516        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2517        return true;
2518    }
2519
2520    int permissionInfoFootprint(PermissionInfo info) {
2521        int size = info.name.length();
2522        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2523        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2524        return size;
2525    }
2526
2527    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2528        int size = 0;
2529        for (BasePermission perm : mSettings.mPermissions.values()) {
2530            if (perm.uid == tree.uid) {
2531                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2532            }
2533        }
2534        return size;
2535    }
2536
2537    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2538        // We calculate the max size of permissions defined by this uid and throw
2539        // if that plus the size of 'info' would exceed our stated maximum.
2540        if (tree.uid != Process.SYSTEM_UID) {
2541            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2542            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2543                throw new SecurityException("Permission tree size cap exceeded");
2544            }
2545        }
2546    }
2547
2548    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2549        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2550            throw new SecurityException("Label must be specified in permission");
2551        }
2552        BasePermission tree = checkPermissionTreeLP(info.name);
2553        BasePermission bp = mSettings.mPermissions.get(info.name);
2554        boolean added = bp == null;
2555        boolean changed = true;
2556        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2557        if (added) {
2558            enforcePermissionCapLocked(info, tree);
2559            bp = new BasePermission(info.name, tree.sourcePackage,
2560                    BasePermission.TYPE_DYNAMIC);
2561        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2562            throw new SecurityException(
2563                    "Not allowed to modify non-dynamic permission "
2564                    + info.name);
2565        } else {
2566            if (bp.protectionLevel == fixedLevel
2567                    && bp.perm.owner.equals(tree.perm.owner)
2568                    && bp.uid == tree.uid
2569                    && comparePermissionInfos(bp.perm.info, info)) {
2570                changed = false;
2571            }
2572        }
2573        bp.protectionLevel = fixedLevel;
2574        info = new PermissionInfo(info);
2575        info.protectionLevel = fixedLevel;
2576        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2577        bp.perm.info.packageName = tree.perm.info.packageName;
2578        bp.uid = tree.uid;
2579        if (added) {
2580            mSettings.mPermissions.put(info.name, bp);
2581        }
2582        if (changed) {
2583            if (!async) {
2584                mSettings.writeLPr();
2585            } else {
2586                scheduleWriteSettingsLocked();
2587            }
2588        }
2589        return added;
2590    }
2591
2592    @Override
2593    public boolean addPermission(PermissionInfo info) {
2594        synchronized (mPackages) {
2595            return addPermissionLocked(info, false);
2596        }
2597    }
2598
2599    @Override
2600    public boolean addPermissionAsync(PermissionInfo info) {
2601        synchronized (mPackages) {
2602            return addPermissionLocked(info, true);
2603        }
2604    }
2605
2606    @Override
2607    public void removePermission(String name) {
2608        synchronized (mPackages) {
2609            checkPermissionTreeLP(name);
2610            BasePermission bp = mSettings.mPermissions.get(name);
2611            if (bp != null) {
2612                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2613                    throw new SecurityException(
2614                            "Not allowed to modify non-dynamic permission "
2615                            + name);
2616                }
2617                mSettings.mPermissions.remove(name);
2618                mSettings.writeLPr();
2619            }
2620        }
2621    }
2622
2623    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2624        int index = pkg.requestedPermissions.indexOf(bp.name);
2625        if (index == -1) {
2626            throw new SecurityException("Package " + pkg.packageName
2627                    + " has not requested permission " + bp.name);
2628        }
2629        boolean isNormal =
2630                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2631                        == PermissionInfo.PROTECTION_NORMAL);
2632        boolean isDangerous =
2633                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2634                        == PermissionInfo.PROTECTION_DANGEROUS);
2635        boolean isDevelopment =
2636                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2637
2638        if (!isNormal && !isDangerous && !isDevelopment) {
2639            throw new SecurityException("Permission " + bp.name
2640                    + " is not a changeable permission type");
2641        }
2642
2643        if (isNormal || isDangerous) {
2644            if (pkg.requestedPermissionsRequired.get(index)) {
2645                throw new SecurityException("Can't change " + bp.name
2646                        + ". It is required by the application");
2647            }
2648        }
2649    }
2650
2651    @Override
2652    public void grantPermission(String packageName, String permissionName) {
2653        mContext.enforceCallingOrSelfPermission(
2654                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2655        synchronized (mPackages) {
2656            final PackageParser.Package pkg = mPackages.get(packageName);
2657            if (pkg == null) {
2658                throw new IllegalArgumentException("Unknown package: " + packageName);
2659            }
2660            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2661            if (bp == null) {
2662                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2663            }
2664
2665            checkGrantRevokePermissions(pkg, bp);
2666
2667            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2668            if (ps == null) {
2669                return;
2670            }
2671            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2672            if (gp.grantedPermissions.add(permissionName)) {
2673                if (ps.haveGids) {
2674                    gp.gids = appendInts(gp.gids, bp.gids);
2675                }
2676                mSettings.writeLPr();
2677            }
2678        }
2679    }
2680
2681    @Override
2682    public void revokePermission(String packageName, String permissionName) {
2683        int changedAppId = -1;
2684
2685        synchronized (mPackages) {
2686            final PackageParser.Package pkg = mPackages.get(packageName);
2687            if (pkg == null) {
2688                throw new IllegalArgumentException("Unknown package: " + packageName);
2689            }
2690            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2691                mContext.enforceCallingOrSelfPermission(
2692                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2693            }
2694            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2695            if (bp == null) {
2696                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2697            }
2698
2699            checkGrantRevokePermissions(pkg, bp);
2700
2701            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2702            if (ps == null) {
2703                return;
2704            }
2705            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2706            if (gp.grantedPermissions.remove(permissionName)) {
2707                gp.grantedPermissions.remove(permissionName);
2708                if (ps.haveGids) {
2709                    gp.gids = removeInts(gp.gids, bp.gids);
2710                }
2711                mSettings.writeLPr();
2712                changedAppId = ps.appId;
2713            }
2714        }
2715
2716        if (changedAppId >= 0) {
2717            // We changed the perm on someone, kill its processes.
2718            IActivityManager am = ActivityManagerNative.getDefault();
2719            if (am != null) {
2720                final int callingUserId = UserHandle.getCallingUserId();
2721                final long ident = Binder.clearCallingIdentity();
2722                try {
2723                    //XXX we should only revoke for the calling user's app permissions,
2724                    // but for now we impact all users.
2725                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2726                    //        "revoke " + permissionName);
2727                    int[] users = sUserManager.getUserIds();
2728                    for (int user : users) {
2729                        am.killUid(UserHandle.getUid(user, changedAppId),
2730                                "revoke " + permissionName);
2731                    }
2732                } catch (RemoteException e) {
2733                } finally {
2734                    Binder.restoreCallingIdentity(ident);
2735                }
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public boolean isProtectedBroadcast(String actionName) {
2742        synchronized (mPackages) {
2743            return mProtectedBroadcasts.contains(actionName);
2744        }
2745    }
2746
2747    @Override
2748    public int checkSignatures(String pkg1, String pkg2) {
2749        synchronized (mPackages) {
2750            final PackageParser.Package p1 = mPackages.get(pkg1);
2751            final PackageParser.Package p2 = mPackages.get(pkg2);
2752            if (p1 == null || p1.mExtras == null
2753                    || p2 == null || p2.mExtras == null) {
2754                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2755            }
2756            return compareSignatures(p1.mSignatures, p2.mSignatures);
2757        }
2758    }
2759
2760    @Override
2761    public int checkUidSignatures(int uid1, int uid2) {
2762        // Map to base uids.
2763        uid1 = UserHandle.getAppId(uid1);
2764        uid2 = UserHandle.getAppId(uid2);
2765        // reader
2766        synchronized (mPackages) {
2767            Signature[] s1;
2768            Signature[] s2;
2769            Object obj = mSettings.getUserIdLPr(uid1);
2770            if (obj != null) {
2771                if (obj instanceof SharedUserSetting) {
2772                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2773                } else if (obj instanceof PackageSetting) {
2774                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2775                } else {
2776                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2777                }
2778            } else {
2779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2780            }
2781            obj = mSettings.getUserIdLPr(uid2);
2782            if (obj != null) {
2783                if (obj instanceof SharedUserSetting) {
2784                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2785                } else if (obj instanceof PackageSetting) {
2786                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2787                } else {
2788                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2789                }
2790            } else {
2791                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2792            }
2793            return compareSignatures(s1, s2);
2794        }
2795    }
2796
2797    /**
2798     * Compares two sets of signatures. Returns:
2799     * <br />
2800     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2801     * <br />
2802     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2803     * <br />
2804     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2805     * <br />
2806     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2807     * <br />
2808     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2809     */
2810    static int compareSignatures(Signature[] s1, Signature[] s2) {
2811        if (s1 == null) {
2812            return s2 == null
2813                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2814                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2815        }
2816
2817        if (s2 == null) {
2818            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2819        }
2820
2821        if (s1.length != s2.length) {
2822            return PackageManager.SIGNATURE_NO_MATCH;
2823        }
2824
2825        // Since both signature sets are of size 1, we can compare without HashSets.
2826        if (s1.length == 1) {
2827            return s1[0].equals(s2[0]) ?
2828                    PackageManager.SIGNATURE_MATCH :
2829                    PackageManager.SIGNATURE_NO_MATCH;
2830        }
2831
2832        ArraySet<Signature> set1 = new ArraySet<Signature>();
2833        for (Signature sig : s1) {
2834            set1.add(sig);
2835        }
2836        ArraySet<Signature> set2 = new ArraySet<Signature>();
2837        for (Signature sig : s2) {
2838            set2.add(sig);
2839        }
2840        // Make sure s2 contains all signatures in s1.
2841        if (set1.equals(set2)) {
2842            return PackageManager.SIGNATURE_MATCH;
2843        }
2844        return PackageManager.SIGNATURE_NO_MATCH;
2845    }
2846
2847    /**
2848     * If the database version for this type of package (internal storage or
2849     * external storage) is less than the version where package signatures
2850     * were updated, return true.
2851     */
2852    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2853        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2854                DatabaseVersion.SIGNATURE_END_ENTITY))
2855                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2856                        DatabaseVersion.SIGNATURE_END_ENTITY));
2857    }
2858
2859    /**
2860     * Used for backward compatibility to make sure any packages with
2861     * certificate chains get upgraded to the new style. {@code existingSigs}
2862     * will be in the old format (since they were stored on disk from before the
2863     * system upgrade) and {@code scannedSigs} will be in the newer format.
2864     */
2865    private int compareSignaturesCompat(PackageSignatures existingSigs,
2866            PackageParser.Package scannedPkg) {
2867        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2868            return PackageManager.SIGNATURE_NO_MATCH;
2869        }
2870
2871        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2872        for (Signature sig : existingSigs.mSignatures) {
2873            existingSet.add(sig);
2874        }
2875        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2876        for (Signature sig : scannedPkg.mSignatures) {
2877            try {
2878                Signature[] chainSignatures = sig.getChainSignatures();
2879                for (Signature chainSig : chainSignatures) {
2880                    scannedCompatSet.add(chainSig);
2881                }
2882            } catch (CertificateEncodingException e) {
2883                scannedCompatSet.add(sig);
2884            }
2885        }
2886        /*
2887         * Make sure the expanded scanned set contains all signatures in the
2888         * existing one.
2889         */
2890        if (scannedCompatSet.equals(existingSet)) {
2891            // Migrate the old signatures to the new scheme.
2892            existingSigs.assignSignatures(scannedPkg.mSignatures);
2893            // The new KeySets will be re-added later in the scanning process.
2894            synchronized (mPackages) {
2895                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2896            }
2897            return PackageManager.SIGNATURE_MATCH;
2898        }
2899        return PackageManager.SIGNATURE_NO_MATCH;
2900    }
2901
2902    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2903        if (isExternal(scannedPkg)) {
2904            return mSettings.isExternalDatabaseVersionOlderThan(
2905                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2906        } else {
2907            return mSettings.isInternalDatabaseVersionOlderThan(
2908                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2909        }
2910    }
2911
2912    private int compareSignaturesRecover(PackageSignatures existingSigs,
2913            PackageParser.Package scannedPkg) {
2914        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2915            return PackageManager.SIGNATURE_NO_MATCH;
2916        }
2917
2918        String msg = null;
2919        try {
2920            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2921                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2922                        + scannedPkg.packageName);
2923                return PackageManager.SIGNATURE_MATCH;
2924            }
2925        } catch (CertificateException e) {
2926            msg = e.getMessage();
2927        }
2928
2929        logCriticalInfo(Log.INFO,
2930                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2931        return PackageManager.SIGNATURE_NO_MATCH;
2932    }
2933
2934    @Override
2935    public String[] getPackagesForUid(int uid) {
2936        uid = UserHandle.getAppId(uid);
2937        // reader
2938        synchronized (mPackages) {
2939            Object obj = mSettings.getUserIdLPr(uid);
2940            if (obj instanceof SharedUserSetting) {
2941                final SharedUserSetting sus = (SharedUserSetting) obj;
2942                final int N = sus.packages.size();
2943                final String[] res = new String[N];
2944                final Iterator<PackageSetting> it = sus.packages.iterator();
2945                int i = 0;
2946                while (it.hasNext()) {
2947                    res[i++] = it.next().name;
2948                }
2949                return res;
2950            } else if (obj instanceof PackageSetting) {
2951                final PackageSetting ps = (PackageSetting) obj;
2952                return new String[] { ps.name };
2953            }
2954        }
2955        return null;
2956    }
2957
2958    @Override
2959    public String getNameForUid(int uid) {
2960        // reader
2961        synchronized (mPackages) {
2962            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2963            if (obj instanceof SharedUserSetting) {
2964                final SharedUserSetting sus = (SharedUserSetting) obj;
2965                return sus.name + ":" + sus.userId;
2966            } else if (obj instanceof PackageSetting) {
2967                final PackageSetting ps = (PackageSetting) obj;
2968                return ps.name;
2969            }
2970        }
2971        return null;
2972    }
2973
2974    @Override
2975    public int getUidForSharedUser(String sharedUserName) {
2976        if(sharedUserName == null) {
2977            return -1;
2978        }
2979        // reader
2980        synchronized (mPackages) {
2981            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
2982            if (suid == null) {
2983                return -1;
2984            }
2985            return suid.userId;
2986        }
2987    }
2988
2989    @Override
2990    public int getFlagsForUid(int uid) {
2991        synchronized (mPackages) {
2992            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2993            if (obj instanceof SharedUserSetting) {
2994                final SharedUserSetting sus = (SharedUserSetting) obj;
2995                return sus.pkgFlags;
2996            } else if (obj instanceof PackageSetting) {
2997                final PackageSetting ps = (PackageSetting) obj;
2998                return ps.pkgFlags;
2999            }
3000        }
3001        return 0;
3002    }
3003
3004    @Override
3005    public int getPrivateFlagsForUid(int uid) {
3006        synchronized (mPackages) {
3007            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3008            if (obj instanceof SharedUserSetting) {
3009                final SharedUserSetting sus = (SharedUserSetting) obj;
3010                return sus.pkgPrivateFlags;
3011            } else if (obj instanceof PackageSetting) {
3012                final PackageSetting ps = (PackageSetting) obj;
3013                return ps.pkgPrivateFlags;
3014            }
3015        }
3016        return 0;
3017    }
3018
3019    @Override
3020    public boolean isUidPrivileged(int uid) {
3021        uid = UserHandle.getAppId(uid);
3022        // reader
3023        synchronized (mPackages) {
3024            Object obj = mSettings.getUserIdLPr(uid);
3025            if (obj instanceof SharedUserSetting) {
3026                final SharedUserSetting sus = (SharedUserSetting) obj;
3027                final Iterator<PackageSetting> it = sus.packages.iterator();
3028                while (it.hasNext()) {
3029                    if (it.next().isPrivileged()) {
3030                        return true;
3031                    }
3032                }
3033            } else if (obj instanceof PackageSetting) {
3034                final PackageSetting ps = (PackageSetting) obj;
3035                return ps.isPrivileged();
3036            }
3037        }
3038        return false;
3039    }
3040
3041    @Override
3042    public String[] getAppOpPermissionPackages(String permissionName) {
3043        synchronized (mPackages) {
3044            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3045            if (pkgs == null) {
3046                return null;
3047            }
3048            return pkgs.toArray(new String[pkgs.size()]);
3049        }
3050    }
3051
3052    @Override
3053    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3054            int flags, int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3057        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3058        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3059    }
3060
3061    @Override
3062    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3063            IntentFilter filter, int match, ComponentName activity) {
3064        final int userId = UserHandle.getCallingUserId();
3065        if (DEBUG_PREFERRED) {
3066            Log.v(TAG, "setLastChosenActivity intent=" + intent
3067                + " resolvedType=" + resolvedType
3068                + " flags=" + flags
3069                + " filter=" + filter
3070                + " match=" + match
3071                + " activity=" + activity);
3072            filter.dump(new PrintStreamPrinter(System.out), "    ");
3073        }
3074        intent.setComponent(null);
3075        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3076        // Find any earlier preferred or last chosen entries and nuke them
3077        findPreferredActivity(intent, resolvedType,
3078                flags, query, 0, false, true, false, userId);
3079        // Add the new activity as the last chosen for this filter
3080        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3081                "Setting last chosen");
3082    }
3083
3084    @Override
3085    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3086        final int userId = UserHandle.getCallingUserId();
3087        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3088        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3089        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3090                false, false, false, userId);
3091    }
3092
3093    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3094            int flags, List<ResolveInfo> query, int userId) {
3095        if (query != null) {
3096            final int N = query.size();
3097            if (N == 1) {
3098                return query.get(0);
3099            } else if (N > 1) {
3100                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3101                // If there is more than one activity with the same priority,
3102                // then let the user decide between them.
3103                ResolveInfo r0 = query.get(0);
3104                ResolveInfo r1 = query.get(1);
3105                if (DEBUG_INTENT_MATCHING || debug) {
3106                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3107                            + r1.activityInfo.name + "=" + r1.priority);
3108                }
3109                // If the first activity has a higher priority, or a different
3110                // default, then it is always desireable to pick it.
3111                if (r0.priority != r1.priority
3112                        || r0.preferredOrder != r1.preferredOrder
3113                        || r0.isDefault != r1.isDefault) {
3114                    return query.get(0);
3115                }
3116                // If we have saved a preference for a preferred activity for
3117                // this Intent, use that.
3118                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3119                        flags, query, r0.priority, true, false, debug, userId);
3120                if (ri != null) {
3121                    return ri;
3122                }
3123                if (userId != 0) {
3124                    ri = new ResolveInfo(mResolveInfo);
3125                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3126                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3127                            ri.activityInfo.applicationInfo);
3128                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3129                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3130                    return ri;
3131                }
3132                return mResolveInfo;
3133            }
3134        }
3135        return null;
3136    }
3137
3138    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3139            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3140        final int N = query.size();
3141        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3142                .get(userId);
3143        // Get the list of persistent preferred activities that handle the intent
3144        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3145        List<PersistentPreferredActivity> pprefs = ppir != null
3146                ? ppir.queryIntent(intent, resolvedType,
3147                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3148                : null;
3149        if (pprefs != null && pprefs.size() > 0) {
3150            final int M = pprefs.size();
3151            for (int i=0; i<M; i++) {
3152                final PersistentPreferredActivity ppa = pprefs.get(i);
3153                if (DEBUG_PREFERRED || debug) {
3154                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3155                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3156                            + "\n  component=" + ppa.mComponent);
3157                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3158                }
3159                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3160                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3161                if (DEBUG_PREFERRED || debug) {
3162                    Slog.v(TAG, "Found persistent preferred activity:");
3163                    if (ai != null) {
3164                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3165                    } else {
3166                        Slog.v(TAG, "  null");
3167                    }
3168                }
3169                if (ai == null) {
3170                    // This previously registered persistent preferred activity
3171                    // component is no longer known. Ignore it and do NOT remove it.
3172                    continue;
3173                }
3174                for (int j=0; j<N; j++) {
3175                    final ResolveInfo ri = query.get(j);
3176                    if (!ri.activityInfo.applicationInfo.packageName
3177                            .equals(ai.applicationInfo.packageName)) {
3178                        continue;
3179                    }
3180                    if (!ri.activityInfo.name.equals(ai.name)) {
3181                        continue;
3182                    }
3183                    //  Found a persistent preference that can handle the intent.
3184                    if (DEBUG_PREFERRED || debug) {
3185                        Slog.v(TAG, "Returning persistent preferred activity: " +
3186                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3187                    }
3188                    return ri;
3189                }
3190            }
3191        }
3192        return null;
3193    }
3194
3195    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3196            List<ResolveInfo> query, int priority, boolean always,
3197            boolean removeMatches, boolean debug, int userId) {
3198        if (!sUserManager.exists(userId)) return null;
3199        // writer
3200        synchronized (mPackages) {
3201            if (intent.getSelector() != null) {
3202                intent = intent.getSelector();
3203            }
3204            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3205
3206            // Try to find a matching persistent preferred activity.
3207            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3208                    debug, userId);
3209
3210            // If a persistent preferred activity matched, use it.
3211            if (pri != null) {
3212                return pri;
3213            }
3214
3215            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3216            // Get the list of preferred activities that handle the intent
3217            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3218            List<PreferredActivity> prefs = pir != null
3219                    ? pir.queryIntent(intent, resolvedType,
3220                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3221                    : null;
3222            if (prefs != null && prefs.size() > 0) {
3223                boolean changed = false;
3224                try {
3225                    // First figure out how good the original match set is.
3226                    // We will only allow preferred activities that came
3227                    // from the same match quality.
3228                    int match = 0;
3229
3230                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3231
3232                    final int N = query.size();
3233                    for (int j=0; j<N; j++) {
3234                        final ResolveInfo ri = query.get(j);
3235                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3236                                + ": 0x" + Integer.toHexString(match));
3237                        if (ri.match > match) {
3238                            match = ri.match;
3239                        }
3240                    }
3241
3242                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3243                            + Integer.toHexString(match));
3244
3245                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3246                    final int M = prefs.size();
3247                    for (int i=0; i<M; i++) {
3248                        final PreferredActivity pa = prefs.get(i);
3249                        if (DEBUG_PREFERRED || debug) {
3250                            Slog.v(TAG, "Checking PreferredActivity ds="
3251                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3252                                    + "\n  component=" + pa.mPref.mComponent);
3253                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3254                        }
3255                        if (pa.mPref.mMatch != match) {
3256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3257                                    + Integer.toHexString(pa.mPref.mMatch));
3258                            continue;
3259                        }
3260                        // If it's not an "always" type preferred activity and that's what we're
3261                        // looking for, skip it.
3262                        if (always && !pa.mPref.mAlways) {
3263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3264                            continue;
3265                        }
3266                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3267                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3268                        if (DEBUG_PREFERRED || debug) {
3269                            Slog.v(TAG, "Found preferred activity:");
3270                            if (ai != null) {
3271                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3272                            } else {
3273                                Slog.v(TAG, "  null");
3274                            }
3275                        }
3276                        if (ai == null) {
3277                            // This previously registered preferred activity
3278                            // component is no longer known.  Most likely an update
3279                            // to the app was installed and in the new version this
3280                            // component no longer exists.  Clean it up by removing
3281                            // it from the preferred activities list, and skip it.
3282                            Slog.w(TAG, "Removing dangling preferred activity: "
3283                                    + pa.mPref.mComponent);
3284                            pir.removeFilter(pa);
3285                            changed = true;
3286                            continue;
3287                        }
3288                        for (int j=0; j<N; j++) {
3289                            final ResolveInfo ri = query.get(j);
3290                            if (!ri.activityInfo.applicationInfo.packageName
3291                                    .equals(ai.applicationInfo.packageName)) {
3292                                continue;
3293                            }
3294                            if (!ri.activityInfo.name.equals(ai.name)) {
3295                                continue;
3296                            }
3297
3298                            if (removeMatches) {
3299                                pir.removeFilter(pa);
3300                                changed = true;
3301                                if (DEBUG_PREFERRED) {
3302                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3303                                }
3304                                break;
3305                            }
3306
3307                            // Okay we found a previously set preferred or last chosen app.
3308                            // If the result set is different from when this
3309                            // was created, we need to clear it and re-ask the
3310                            // user their preference, if we're looking for an "always" type entry.
3311                            if (always && !pa.mPref.sameSet(query)) {
3312                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3313                                        + intent + " type " + resolvedType);
3314                                if (DEBUG_PREFERRED) {
3315                                    Slog.v(TAG, "Removing preferred activity since set changed "
3316                                            + pa.mPref.mComponent);
3317                                }
3318                                pir.removeFilter(pa);
3319                                // Re-add the filter as a "last chosen" entry (!always)
3320                                PreferredActivity lastChosen = new PreferredActivity(
3321                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3322                                pir.addFilter(lastChosen);
3323                                changed = true;
3324                                return null;
3325                            }
3326
3327                            // Yay! Either the set matched or we're looking for the last chosen
3328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3329                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3330                            return ri;
3331                        }
3332                    }
3333                } finally {
3334                    if (changed) {
3335                        if (DEBUG_PREFERRED) {
3336                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3337                        }
3338                        scheduleWritePackageRestrictionsLocked(userId);
3339                    }
3340                }
3341            }
3342        }
3343        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3344        return null;
3345    }
3346
3347    /*
3348     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3349     */
3350    @Override
3351    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3352            int targetUserId) {
3353        mContext.enforceCallingOrSelfPermission(
3354                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3355        List<CrossProfileIntentFilter> matches =
3356                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3357        if (matches != null) {
3358            int size = matches.size();
3359            for (int i = 0; i < size; i++) {
3360                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3361            }
3362        }
3363        return false;
3364    }
3365
3366    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3367            String resolvedType, int userId) {
3368        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3369        if (resolver != null) {
3370            return resolver.queryIntent(intent, resolvedType, false, userId);
3371        }
3372        return null;
3373    }
3374
3375    @Override
3376    public List<ResolveInfo> queryIntentActivities(Intent intent,
3377            String resolvedType, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return Collections.emptyList();
3379        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3380        ComponentName comp = intent.getComponent();
3381        if (comp == null) {
3382            if (intent.getSelector() != null) {
3383                intent = intent.getSelector();
3384                comp = intent.getComponent();
3385            }
3386        }
3387
3388        if (comp != null) {
3389            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3390            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3391            if (ai != null) {
3392                final ResolveInfo ri = new ResolveInfo();
3393                ri.activityInfo = ai;
3394                list.add(ri);
3395            }
3396            return list;
3397        }
3398
3399        // reader
3400        synchronized (mPackages) {
3401            final String pkgName = intent.getPackage();
3402            if (pkgName == null) {
3403                List<CrossProfileIntentFilter> matchingFilters =
3404                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3405                // Check for results that need to skip the current profile.
3406                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3407                        resolvedType, flags, userId);
3408                if (resolveInfo != null) {
3409                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3410                    result.add(resolveInfo);
3411                    return filterIfNotPrimaryUser(result, userId);
3412                }
3413                // Check for cross profile results.
3414                resolveInfo = queryCrossProfileIntents(
3415                        matchingFilters, intent, resolvedType, flags, userId);
3416
3417                // Check for results in the current profile.
3418                List<ResolveInfo> result = mActivities.queryIntent(
3419                        intent, resolvedType, flags, userId);
3420                if (resolveInfo != null) {
3421                    result.add(resolveInfo);
3422                    Collections.sort(result, mResolvePrioritySorter);
3423                }
3424                return filterIfNotPrimaryUser(result, userId);
3425            }
3426            final PackageParser.Package pkg = mPackages.get(pkgName);
3427            if (pkg != null) {
3428                return filterIfNotPrimaryUser(
3429                        mActivities.queryIntentForPackage(
3430                                intent, resolvedType, flags, pkg.activities, userId),
3431                        userId);
3432            }
3433            return new ArrayList<ResolveInfo>();
3434        }
3435    }
3436
3437    /**
3438     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3439     *
3440     * @return filtered list
3441     */
3442    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3443        if (userId == UserHandle.USER_OWNER) {
3444            return resolveInfos;
3445        }
3446        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3447            ResolveInfo info = resolveInfos.get(i);
3448            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3449                resolveInfos.remove(i);
3450            }
3451        }
3452        return resolveInfos;
3453    }
3454
3455
3456    private ResolveInfo querySkipCurrentProfileIntents(
3457            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3458            int flags, int sourceUserId) {
3459        if (matchingFilters != null) {
3460            int size = matchingFilters.size();
3461            for (int i = 0; i < size; i ++) {
3462                CrossProfileIntentFilter filter = matchingFilters.get(i);
3463                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3464                    // Checking if there are activities in the target user that can handle the
3465                    // intent.
3466                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3467                            flags, sourceUserId);
3468                    if (resolveInfo != null) {
3469                        return resolveInfo;
3470                    }
3471                }
3472            }
3473        }
3474        return null;
3475    }
3476
3477    // Return matching ResolveInfo if any for skip current profile intent filters.
3478    private ResolveInfo queryCrossProfileIntents(
3479            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3480            int flags, int sourceUserId) {
3481        if (matchingFilters != null) {
3482            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3483            // match the same intent. For performance reasons, it is better not to
3484            // run queryIntent twice for the same userId
3485            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3486            int size = matchingFilters.size();
3487            for (int i = 0; i < size; i++) {
3488                CrossProfileIntentFilter filter = matchingFilters.get(i);
3489                int targetUserId = filter.getTargetUserId();
3490                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3491                        && !alreadyTriedUserIds.get(targetUserId)) {
3492                    // Checking if there are activities in the target user that can handle the
3493                    // intent.
3494                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3495                            flags, sourceUserId);
3496                    if (resolveInfo != null) return resolveInfo;
3497                    alreadyTriedUserIds.put(targetUserId, true);
3498                }
3499            }
3500        }
3501        return null;
3502    }
3503
3504    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3505            String resolvedType, int flags, int sourceUserId) {
3506        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3507                resolvedType, flags, filter.getTargetUserId());
3508        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3509            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3510        }
3511        return null;
3512    }
3513
3514    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3515            int sourceUserId, int targetUserId) {
3516        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3517        String className;
3518        if (targetUserId == UserHandle.USER_OWNER) {
3519            className = FORWARD_INTENT_TO_USER_OWNER;
3520        } else {
3521            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3522        }
3523        ComponentName forwardingActivityComponentName = new ComponentName(
3524                mAndroidApplication.packageName, className);
3525        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3526                sourceUserId);
3527        if (targetUserId == UserHandle.USER_OWNER) {
3528            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3529            forwardingResolveInfo.noResourceId = true;
3530        }
3531        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3532        forwardingResolveInfo.priority = 0;
3533        forwardingResolveInfo.preferredOrder = 0;
3534        forwardingResolveInfo.match = 0;
3535        forwardingResolveInfo.isDefault = true;
3536        forwardingResolveInfo.filter = filter;
3537        forwardingResolveInfo.targetUserId = targetUserId;
3538        return forwardingResolveInfo;
3539    }
3540
3541    @Override
3542    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3543            Intent[] specifics, String[] specificTypes, Intent intent,
3544            String resolvedType, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return Collections.emptyList();
3546        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3547                false, "query intent activity options");
3548        final String resultsAction = intent.getAction();
3549
3550        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3551                | PackageManager.GET_RESOLVED_FILTER, userId);
3552
3553        if (DEBUG_INTENT_MATCHING) {
3554            Log.v(TAG, "Query " + intent + ": " + results);
3555        }
3556
3557        int specificsPos = 0;
3558        int N;
3559
3560        // todo: note that the algorithm used here is O(N^2).  This
3561        // isn't a problem in our current environment, but if we start running
3562        // into situations where we have more than 5 or 10 matches then this
3563        // should probably be changed to something smarter...
3564
3565        // First we go through and resolve each of the specific items
3566        // that were supplied, taking care of removing any corresponding
3567        // duplicate items in the generic resolve list.
3568        if (specifics != null) {
3569            for (int i=0; i<specifics.length; i++) {
3570                final Intent sintent = specifics[i];
3571                if (sintent == null) {
3572                    continue;
3573                }
3574
3575                if (DEBUG_INTENT_MATCHING) {
3576                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3577                }
3578
3579                String action = sintent.getAction();
3580                if (resultsAction != null && resultsAction.equals(action)) {
3581                    // If this action was explicitly requested, then don't
3582                    // remove things that have it.
3583                    action = null;
3584                }
3585
3586                ResolveInfo ri = null;
3587                ActivityInfo ai = null;
3588
3589                ComponentName comp = sintent.getComponent();
3590                if (comp == null) {
3591                    ri = resolveIntent(
3592                        sintent,
3593                        specificTypes != null ? specificTypes[i] : null,
3594                            flags, userId);
3595                    if (ri == null) {
3596                        continue;
3597                    }
3598                    if (ri == mResolveInfo) {
3599                        // ACK!  Must do something better with this.
3600                    }
3601                    ai = ri.activityInfo;
3602                    comp = new ComponentName(ai.applicationInfo.packageName,
3603                            ai.name);
3604                } else {
3605                    ai = getActivityInfo(comp, flags, userId);
3606                    if (ai == null) {
3607                        continue;
3608                    }
3609                }
3610
3611                // Look for any generic query activities that are duplicates
3612                // of this specific one, and remove them from the results.
3613                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3614                N = results.size();
3615                int j;
3616                for (j=specificsPos; j<N; j++) {
3617                    ResolveInfo sri = results.get(j);
3618                    if ((sri.activityInfo.name.equals(comp.getClassName())
3619                            && sri.activityInfo.applicationInfo.packageName.equals(
3620                                    comp.getPackageName()))
3621                        || (action != null && sri.filter.matchAction(action))) {
3622                        results.remove(j);
3623                        if (DEBUG_INTENT_MATCHING) Log.v(
3624                            TAG, "Removing duplicate item from " + j
3625                            + " due to specific " + specificsPos);
3626                        if (ri == null) {
3627                            ri = sri;
3628                        }
3629                        j--;
3630                        N--;
3631                    }
3632                }
3633
3634                // Add this specific item to its proper place.
3635                if (ri == null) {
3636                    ri = new ResolveInfo();
3637                    ri.activityInfo = ai;
3638                }
3639                results.add(specificsPos, ri);
3640                ri.specificIndex = i;
3641                specificsPos++;
3642            }
3643        }
3644
3645        // Now we go through the remaining generic results and remove any
3646        // duplicate actions that are found here.
3647        N = results.size();
3648        for (int i=specificsPos; i<N-1; i++) {
3649            final ResolveInfo rii = results.get(i);
3650            if (rii.filter == null) {
3651                continue;
3652            }
3653
3654            // Iterate over all of the actions of this result's intent
3655            // filter...  typically this should be just one.
3656            final Iterator<String> it = rii.filter.actionsIterator();
3657            if (it == null) {
3658                continue;
3659            }
3660            while (it.hasNext()) {
3661                final String action = it.next();
3662                if (resultsAction != null && resultsAction.equals(action)) {
3663                    // If this action was explicitly requested, then don't
3664                    // remove things that have it.
3665                    continue;
3666                }
3667                for (int j=i+1; j<N; j++) {
3668                    final ResolveInfo rij = results.get(j);
3669                    if (rij.filter != null && rij.filter.hasAction(action)) {
3670                        results.remove(j);
3671                        if (DEBUG_INTENT_MATCHING) Log.v(
3672                            TAG, "Removing duplicate item from " + j
3673                            + " due to action " + action + " at " + i);
3674                        j--;
3675                        N--;
3676                    }
3677                }
3678            }
3679
3680            // If the caller didn't request filter information, drop it now
3681            // so we don't have to marshall/unmarshall it.
3682            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3683                rii.filter = null;
3684            }
3685        }
3686
3687        // Filter out the caller activity if so requested.
3688        if (caller != null) {
3689            N = results.size();
3690            for (int i=0; i<N; i++) {
3691                ActivityInfo ainfo = results.get(i).activityInfo;
3692                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3693                        && caller.getClassName().equals(ainfo.name)) {
3694                    results.remove(i);
3695                    break;
3696                }
3697            }
3698        }
3699
3700        // If the caller didn't request filter information,
3701        // drop them now so we don't have to
3702        // marshall/unmarshall it.
3703        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3704            N = results.size();
3705            for (int i=0; i<N; i++) {
3706                results.get(i).filter = null;
3707            }
3708        }
3709
3710        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3711        return results;
3712    }
3713
3714    @Override
3715    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3716            int userId) {
3717        if (!sUserManager.exists(userId)) return Collections.emptyList();
3718        ComponentName comp = intent.getComponent();
3719        if (comp == null) {
3720            if (intent.getSelector() != null) {
3721                intent = intent.getSelector();
3722                comp = intent.getComponent();
3723            }
3724        }
3725        if (comp != null) {
3726            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3727            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3728            if (ai != null) {
3729                ResolveInfo ri = new ResolveInfo();
3730                ri.activityInfo = ai;
3731                list.add(ri);
3732            }
3733            return list;
3734        }
3735
3736        // reader
3737        synchronized (mPackages) {
3738            String pkgName = intent.getPackage();
3739            if (pkgName == null) {
3740                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3741            }
3742            final PackageParser.Package pkg = mPackages.get(pkgName);
3743            if (pkg != null) {
3744                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3745                        userId);
3746            }
3747            return null;
3748        }
3749    }
3750
3751    @Override
3752    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3753        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3754        if (!sUserManager.exists(userId)) return null;
3755        if (query != null) {
3756            if (query.size() >= 1) {
3757                // If there is more than one service with the same priority,
3758                // just arbitrarily pick the first one.
3759                return query.get(0);
3760            }
3761        }
3762        return null;
3763    }
3764
3765    @Override
3766    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3767            int userId) {
3768        if (!sUserManager.exists(userId)) return Collections.emptyList();
3769        ComponentName comp = intent.getComponent();
3770        if (comp == null) {
3771            if (intent.getSelector() != null) {
3772                intent = intent.getSelector();
3773                comp = intent.getComponent();
3774            }
3775        }
3776        if (comp != null) {
3777            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3778            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3779            if (si != null) {
3780                final ResolveInfo ri = new ResolveInfo();
3781                ri.serviceInfo = si;
3782                list.add(ri);
3783            }
3784            return list;
3785        }
3786
3787        // reader
3788        synchronized (mPackages) {
3789            String pkgName = intent.getPackage();
3790            if (pkgName == null) {
3791                return mServices.queryIntent(intent, resolvedType, flags, userId);
3792            }
3793            final PackageParser.Package pkg = mPackages.get(pkgName);
3794            if (pkg != null) {
3795                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3796                        userId);
3797            }
3798            return null;
3799        }
3800    }
3801
3802    @Override
3803    public List<ResolveInfo> queryIntentContentProviders(
3804            Intent intent, String resolvedType, int flags, int userId) {
3805        if (!sUserManager.exists(userId)) return Collections.emptyList();
3806        ComponentName comp = intent.getComponent();
3807        if (comp == null) {
3808            if (intent.getSelector() != null) {
3809                intent = intent.getSelector();
3810                comp = intent.getComponent();
3811            }
3812        }
3813        if (comp != null) {
3814            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3815            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3816            if (pi != null) {
3817                final ResolveInfo ri = new ResolveInfo();
3818                ri.providerInfo = pi;
3819                list.add(ri);
3820            }
3821            return list;
3822        }
3823
3824        // reader
3825        synchronized (mPackages) {
3826            String pkgName = intent.getPackage();
3827            if (pkgName == null) {
3828                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3829            }
3830            final PackageParser.Package pkg = mPackages.get(pkgName);
3831            if (pkg != null) {
3832                return mProviders.queryIntentForPackage(
3833                        intent, resolvedType, flags, pkg.providers, userId);
3834            }
3835            return null;
3836        }
3837    }
3838
3839    @Override
3840    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3841        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3842
3843        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3844
3845        // writer
3846        synchronized (mPackages) {
3847            ArrayList<PackageInfo> list;
3848            if (listUninstalled) {
3849                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3850                for (PackageSetting ps : mSettings.mPackages.values()) {
3851                    PackageInfo pi;
3852                    if (ps.pkg != null) {
3853                        pi = generatePackageInfo(ps.pkg, flags, userId);
3854                    } else {
3855                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3856                    }
3857                    if (pi != null) {
3858                        list.add(pi);
3859                    }
3860                }
3861            } else {
3862                list = new ArrayList<PackageInfo>(mPackages.size());
3863                for (PackageParser.Package p : mPackages.values()) {
3864                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3865                    if (pi != null) {
3866                        list.add(pi);
3867                    }
3868                }
3869            }
3870
3871            return new ParceledListSlice<PackageInfo>(list);
3872        }
3873    }
3874
3875    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3876            String[] permissions, boolean[] tmp, int flags, int userId) {
3877        int numMatch = 0;
3878        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3879        for (int i=0; i<permissions.length; i++) {
3880            if (gp.grantedPermissions.contains(permissions[i])) {
3881                tmp[i] = true;
3882                numMatch++;
3883            } else {
3884                tmp[i] = false;
3885            }
3886        }
3887        if (numMatch == 0) {
3888            return;
3889        }
3890        PackageInfo pi;
3891        if (ps.pkg != null) {
3892            pi = generatePackageInfo(ps.pkg, flags, userId);
3893        } else {
3894            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3895        }
3896        // The above might return null in cases of uninstalled apps or install-state
3897        // skew across users/profiles.
3898        if (pi != null) {
3899            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3900                if (numMatch == permissions.length) {
3901                    pi.requestedPermissions = permissions;
3902                } else {
3903                    pi.requestedPermissions = new String[numMatch];
3904                    numMatch = 0;
3905                    for (int i=0; i<permissions.length; i++) {
3906                        if (tmp[i]) {
3907                            pi.requestedPermissions[numMatch] = permissions[i];
3908                            numMatch++;
3909                        }
3910                    }
3911                }
3912            }
3913            list.add(pi);
3914        }
3915    }
3916
3917    @Override
3918    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3919            String[] permissions, int flags, int userId) {
3920        if (!sUserManager.exists(userId)) return null;
3921        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3922
3923        // writer
3924        synchronized (mPackages) {
3925            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3926            boolean[] tmpBools = new boolean[permissions.length];
3927            if (listUninstalled) {
3928                for (PackageSetting ps : mSettings.mPackages.values()) {
3929                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3930                }
3931            } else {
3932                for (PackageParser.Package pkg : mPackages.values()) {
3933                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3934                    if (ps != null) {
3935                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3936                                userId);
3937                    }
3938                }
3939            }
3940
3941            return new ParceledListSlice<PackageInfo>(list);
3942        }
3943    }
3944
3945    @Override
3946    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3947        if (!sUserManager.exists(userId)) return null;
3948        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3949
3950        // writer
3951        synchronized (mPackages) {
3952            ArrayList<ApplicationInfo> list;
3953            if (listUninstalled) {
3954                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3955                for (PackageSetting ps : mSettings.mPackages.values()) {
3956                    ApplicationInfo ai;
3957                    if (ps.pkg != null) {
3958                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3959                                ps.readUserState(userId), userId);
3960                    } else {
3961                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3962                    }
3963                    if (ai != null) {
3964                        list.add(ai);
3965                    }
3966                }
3967            } else {
3968                list = new ArrayList<ApplicationInfo>(mPackages.size());
3969                for (PackageParser.Package p : mPackages.values()) {
3970                    if (p.mExtras != null) {
3971                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3972                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3973                        if (ai != null) {
3974                            list.add(ai);
3975                        }
3976                    }
3977                }
3978            }
3979
3980            return new ParceledListSlice<ApplicationInfo>(list);
3981        }
3982    }
3983
3984    public List<ApplicationInfo> getPersistentApplications(int flags) {
3985        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3986
3987        // reader
3988        synchronized (mPackages) {
3989            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3990            final int userId = UserHandle.getCallingUserId();
3991            while (i.hasNext()) {
3992                final PackageParser.Package p = i.next();
3993                if (p.applicationInfo != null
3994                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3995                        && (!mSafeMode || isSystemApp(p))) {
3996                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3997                    if (ps != null) {
3998                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3999                                ps.readUserState(userId), userId);
4000                        if (ai != null) {
4001                            finalList.add(ai);
4002                        }
4003                    }
4004                }
4005            }
4006        }
4007
4008        return finalList;
4009    }
4010
4011    @Override
4012    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4013        if (!sUserManager.exists(userId)) return null;
4014        // reader
4015        synchronized (mPackages) {
4016            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4017            PackageSetting ps = provider != null
4018                    ? mSettings.mPackages.get(provider.owner.packageName)
4019                    : null;
4020            return ps != null
4021                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4022                    && (!mSafeMode || (provider.info.applicationInfo.flags
4023                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4024                    ? PackageParser.generateProviderInfo(provider, flags,
4025                            ps.readUserState(userId), userId)
4026                    : null;
4027        }
4028    }
4029
4030    /**
4031     * @deprecated
4032     */
4033    @Deprecated
4034    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4035        // reader
4036        synchronized (mPackages) {
4037            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4038                    .entrySet().iterator();
4039            final int userId = UserHandle.getCallingUserId();
4040            while (i.hasNext()) {
4041                Map.Entry<String, PackageParser.Provider> entry = i.next();
4042                PackageParser.Provider p = entry.getValue();
4043                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4044
4045                if (ps != null && p.syncable
4046                        && (!mSafeMode || (p.info.applicationInfo.flags
4047                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4048                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4049                            ps.readUserState(userId), userId);
4050                    if (info != null) {
4051                        outNames.add(entry.getKey());
4052                        outInfo.add(info);
4053                    }
4054                }
4055            }
4056        }
4057    }
4058
4059    @Override
4060    public List<ProviderInfo> queryContentProviders(String processName,
4061            int uid, int flags) {
4062        ArrayList<ProviderInfo> finalList = null;
4063        // reader
4064        synchronized (mPackages) {
4065            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4066            final int userId = processName != null ?
4067                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4068            while (i.hasNext()) {
4069                final PackageParser.Provider p = i.next();
4070                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4071                if (ps != null && p.info.authority != null
4072                        && (processName == null
4073                                || (p.info.processName.equals(processName)
4074                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4075                        && mSettings.isEnabledLPr(p.info, flags, userId)
4076                        && (!mSafeMode
4077                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4078                    if (finalList == null) {
4079                        finalList = new ArrayList<ProviderInfo>(3);
4080                    }
4081                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4082                            ps.readUserState(userId), userId);
4083                    if (info != null) {
4084                        finalList.add(info);
4085                    }
4086                }
4087            }
4088        }
4089
4090        if (finalList != null) {
4091            Collections.sort(finalList, mProviderInitOrderSorter);
4092        }
4093
4094        return finalList;
4095    }
4096
4097    @Override
4098    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4099            int flags) {
4100        // reader
4101        synchronized (mPackages) {
4102            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4103            return PackageParser.generateInstrumentationInfo(i, flags);
4104        }
4105    }
4106
4107    @Override
4108    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4109            int flags) {
4110        ArrayList<InstrumentationInfo> finalList =
4111            new ArrayList<InstrumentationInfo>();
4112
4113        // reader
4114        synchronized (mPackages) {
4115            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4116            while (i.hasNext()) {
4117                final PackageParser.Instrumentation p = i.next();
4118                if (targetPackage == null
4119                        || targetPackage.equals(p.info.targetPackage)) {
4120                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4121                            flags);
4122                    if (ii != null) {
4123                        finalList.add(ii);
4124                    }
4125                }
4126            }
4127        }
4128
4129        return finalList;
4130    }
4131
4132    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4133        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4134        if (overlays == null) {
4135            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4136            return;
4137        }
4138        for (PackageParser.Package opkg : overlays.values()) {
4139            // Not much to do if idmap fails: we already logged the error
4140            // and we certainly don't want to abort installation of pkg simply
4141            // because an overlay didn't fit properly. For these reasons,
4142            // ignore the return value of createIdmapForPackagePairLI.
4143            createIdmapForPackagePairLI(pkg, opkg);
4144        }
4145    }
4146
4147    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4148            PackageParser.Package opkg) {
4149        if (!opkg.mTrustedOverlay) {
4150            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4151                    opkg.baseCodePath + ": overlay not trusted");
4152            return false;
4153        }
4154        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4155        if (overlaySet == null) {
4156            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4157                    opkg.baseCodePath + " but target package has no known overlays");
4158            return false;
4159        }
4160        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4161        // TODO: generate idmap for split APKs
4162        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4163            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4164                    + opkg.baseCodePath);
4165            return false;
4166        }
4167        PackageParser.Package[] overlayArray =
4168            overlaySet.values().toArray(new PackageParser.Package[0]);
4169        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4170            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4171                return p1.mOverlayPriority - p2.mOverlayPriority;
4172            }
4173        };
4174        Arrays.sort(overlayArray, cmp);
4175
4176        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4177        int i = 0;
4178        for (PackageParser.Package p : overlayArray) {
4179            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4180        }
4181        return true;
4182    }
4183
4184    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4185        final File[] files = dir.listFiles();
4186        if (ArrayUtils.isEmpty(files)) {
4187            Log.d(TAG, "No files in app dir " + dir);
4188            return;
4189        }
4190
4191        if (DEBUG_PACKAGE_SCANNING) {
4192            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4193                    + " flags=0x" + Integer.toHexString(parseFlags));
4194        }
4195
4196        for (File file : files) {
4197            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4198                    && !PackageInstallerService.isStageName(file.getName());
4199            if (!isPackage) {
4200                // Ignore entries which are not packages
4201                continue;
4202            }
4203            try {
4204                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4205                        scanFlags, currentTime, null);
4206            } catch (PackageManagerException e) {
4207                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4208
4209                // Delete invalid userdata apps
4210                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4211                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4212                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4213                    if (file.isDirectory()) {
4214                        FileUtils.deleteContents(file);
4215                    }
4216                    file.delete();
4217                }
4218            }
4219        }
4220    }
4221
4222    private static File getSettingsProblemFile() {
4223        File dataDir = Environment.getDataDirectory();
4224        File systemDir = new File(dataDir, "system");
4225        File fname = new File(systemDir, "uiderrors.txt");
4226        return fname;
4227    }
4228
4229    static void reportSettingsProblem(int priority, String msg) {
4230        logCriticalInfo(priority, msg);
4231    }
4232
4233    static void logCriticalInfo(int priority, String msg) {
4234        Slog.println(priority, TAG, msg);
4235        EventLogTags.writePmCriticalInfo(msg);
4236        try {
4237            File fname = getSettingsProblemFile();
4238            FileOutputStream out = new FileOutputStream(fname, true);
4239            PrintWriter pw = new FastPrintWriter(out);
4240            SimpleDateFormat formatter = new SimpleDateFormat();
4241            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4242            pw.println(dateString + ": " + msg);
4243            pw.close();
4244            FileUtils.setPermissions(
4245                    fname.toString(),
4246                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4247                    -1, -1);
4248        } catch (java.io.IOException e) {
4249        }
4250    }
4251
4252    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4253            PackageParser.Package pkg, File srcFile, int parseFlags)
4254            throws PackageManagerException {
4255        if (ps != null
4256                && ps.codePath.equals(srcFile)
4257                && ps.timeStamp == srcFile.lastModified()
4258                && !isCompatSignatureUpdateNeeded(pkg)
4259                && !isRecoverSignatureUpdateNeeded(pkg)) {
4260            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4261            if (ps.signatures.mSignatures != null
4262                    && ps.signatures.mSignatures.length != 0
4263                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4264                // Optimization: reuse the existing cached certificates
4265                // if the package appears to be unchanged.
4266                pkg.mSignatures = ps.signatures.mSignatures;
4267                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4268                synchronized (mPackages) {
4269                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4270                }
4271                return;
4272            }
4273
4274            Slog.w(TAG, "PackageSetting for " + ps.name
4275                    + " is missing signatures.  Collecting certs again to recover them.");
4276        } else {
4277            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4278        }
4279
4280        try {
4281            pp.collectCertificates(pkg, parseFlags);
4282            pp.collectManifestDigest(pkg);
4283        } catch (PackageParserException e) {
4284            throw PackageManagerException.from(e);
4285        }
4286    }
4287
4288    /*
4289     *  Scan a package and return the newly parsed package.
4290     *  Returns null in case of errors and the error code is stored in mLastScanError
4291     */
4292    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4293            long currentTime, UserHandle user) throws PackageManagerException {
4294        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4295        parseFlags |= mDefParseFlags;
4296        PackageParser pp = new PackageParser();
4297        pp.setSeparateProcesses(mSeparateProcesses);
4298        pp.setOnlyCoreApps(mOnlyCore);
4299        pp.setDisplayMetrics(mMetrics);
4300
4301        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4302            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4303        }
4304
4305        final PackageParser.Package pkg;
4306        try {
4307            pkg = pp.parsePackage(scanFile, parseFlags);
4308        } catch (PackageParserException e) {
4309            throw PackageManagerException.from(e);
4310        }
4311
4312        PackageSetting ps = null;
4313        PackageSetting updatedPkg;
4314        // reader
4315        synchronized (mPackages) {
4316            // Look to see if we already know about this package.
4317            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4318            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4319                // This package has been renamed to its original name.  Let's
4320                // use that.
4321                ps = mSettings.peekPackageLPr(oldName);
4322            }
4323            // If there was no original package, see one for the real package name.
4324            if (ps == null) {
4325                ps = mSettings.peekPackageLPr(pkg.packageName);
4326            }
4327            // Check to see if this package could be hiding/updating a system
4328            // package.  Must look for it either under the original or real
4329            // package name depending on our state.
4330            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4331            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4332        }
4333        boolean updatedPkgBetter = false;
4334        // First check if this is a system package that may involve an update
4335        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4336            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4337            // it needs to drop FLAG_PRIVILEGED.
4338            if (locationIsPrivileged(scanFile)) {
4339                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4340            } else {
4341                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4342            }
4343
4344            if (ps != null && !ps.codePath.equals(scanFile)) {
4345                // The path has changed from what was last scanned...  check the
4346                // version of the new path against what we have stored to determine
4347                // what to do.
4348                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4349                if (pkg.mVersionCode <= ps.versionCode) {
4350                    // The system package has been updated and the code path does not match
4351                    // Ignore entry. Skip it.
4352                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4353                            + " ignored: updated version " + ps.versionCode
4354                            + " better than this " + pkg.mVersionCode);
4355                    if (!updatedPkg.codePath.equals(scanFile)) {
4356                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4357                                + ps.name + " changing from " + updatedPkg.codePathString
4358                                + " to " + scanFile);
4359                        updatedPkg.codePath = scanFile;
4360                        updatedPkg.codePathString = scanFile.toString();
4361                        updatedPkg.resourcePath = scanFile;
4362                        updatedPkg.resourcePathString = scanFile.toString();
4363                    }
4364                    updatedPkg.pkg = pkg;
4365                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4366                } else {
4367                    // The current app on the system partition is better than
4368                    // what we have updated to on the data partition; switch
4369                    // back to the system partition version.
4370                    // At this point, its safely assumed that package installation for
4371                    // apps in system partition will go through. If not there won't be a working
4372                    // version of the app
4373                    // writer
4374                    synchronized (mPackages) {
4375                        // Just remove the loaded entries from package lists.
4376                        mPackages.remove(ps.name);
4377                    }
4378
4379                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4380                            + " reverting from " + ps.codePathString
4381                            + ": new version " + pkg.mVersionCode
4382                            + " better than installed " + ps.versionCode);
4383
4384                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4385                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4386                            getAppDexInstructionSets(ps));
4387                    synchronized (mInstallLock) {
4388                        args.cleanUpResourcesLI();
4389                    }
4390                    synchronized (mPackages) {
4391                        mSettings.enableSystemPackageLPw(ps.name);
4392                    }
4393                    updatedPkgBetter = true;
4394                }
4395            }
4396        }
4397
4398        if (updatedPkg != null) {
4399            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4400            // initially
4401            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4402
4403            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4404            // flag set initially
4405            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4406                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4407            }
4408        }
4409
4410        // Verify certificates against what was last scanned
4411        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4412
4413        /*
4414         * A new system app appeared, but we already had a non-system one of the
4415         * same name installed earlier.
4416         */
4417        boolean shouldHideSystemApp = false;
4418        if (updatedPkg == null && ps != null
4419                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4420            /*
4421             * Check to make sure the signatures match first. If they don't,
4422             * wipe the installed application and its data.
4423             */
4424            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4425                    != PackageManager.SIGNATURE_MATCH) {
4426                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4427                        + " signatures don't match existing userdata copy; removing");
4428                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4429                ps = null;
4430            } else {
4431                /*
4432                 * If the newly-added system app is an older version than the
4433                 * already installed version, hide it. It will be scanned later
4434                 * and re-added like an update.
4435                 */
4436                if (pkg.mVersionCode <= ps.versionCode) {
4437                    shouldHideSystemApp = true;
4438                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4439                            + " but new version " + pkg.mVersionCode + " better than installed "
4440                            + ps.versionCode + "; hiding system");
4441                } else {
4442                    /*
4443                     * The newly found system app is a newer version that the
4444                     * one previously installed. Simply remove the
4445                     * already-installed application and replace it with our own
4446                     * while keeping the application data.
4447                     */
4448                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4449                            + " reverting from " + ps.codePathString + ": new version "
4450                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4451                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4452                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4453                            getAppDexInstructionSets(ps));
4454                    synchronized (mInstallLock) {
4455                        args.cleanUpResourcesLI();
4456                    }
4457                }
4458            }
4459        }
4460
4461        // The apk is forward locked (not public) if its code and resources
4462        // are kept in different files. (except for app in either system or
4463        // vendor path).
4464        // TODO grab this value from PackageSettings
4465        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4466            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4467                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4468            }
4469        }
4470
4471        // TODO: extend to support forward-locked splits
4472        String resourcePath = null;
4473        String baseResourcePath = null;
4474        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4475            if (ps != null && ps.resourcePathString != null) {
4476                resourcePath = ps.resourcePathString;
4477                baseResourcePath = ps.resourcePathString;
4478            } else {
4479                // Should not happen at all. Just log an error.
4480                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4481            }
4482        } else {
4483            resourcePath = pkg.codePath;
4484            baseResourcePath = pkg.baseCodePath;
4485        }
4486
4487        // Set application objects path explicitly.
4488        pkg.applicationInfo.setCodePath(pkg.codePath);
4489        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4490        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4491        pkg.applicationInfo.setResourcePath(resourcePath);
4492        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4493        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4494
4495        // Note that we invoke the following method only if we are about to unpack an application
4496        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4497                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4498
4499        /*
4500         * If the system app should be overridden by a previously installed
4501         * data, hide the system app now and let the /data/app scan pick it up
4502         * again.
4503         */
4504        if (shouldHideSystemApp) {
4505            synchronized (mPackages) {
4506                /*
4507                 * We have to grant systems permissions before we hide, because
4508                 * grantPermissions will assume the package update is trying to
4509                 * expand its permissions.
4510                 */
4511                grantPermissionsLPw(pkg, true, pkg.packageName);
4512                mSettings.disableSystemPackageLPw(pkg.packageName);
4513            }
4514        }
4515
4516        return scannedPkg;
4517    }
4518
4519    private static String fixProcessName(String defProcessName,
4520            String processName, int uid) {
4521        if (processName == null) {
4522            return defProcessName;
4523        }
4524        return processName;
4525    }
4526
4527    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4528            throws PackageManagerException {
4529        if (pkgSetting.signatures.mSignatures != null) {
4530            // Already existing package. Make sure signatures match
4531            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4532                    == PackageManager.SIGNATURE_MATCH;
4533            if (!match) {
4534                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4535                        == PackageManager.SIGNATURE_MATCH;
4536            }
4537            if (!match) {
4538                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4539                        == PackageManager.SIGNATURE_MATCH;
4540            }
4541            if (!match) {
4542                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4543                        + pkg.packageName + " signatures do not match the "
4544                        + "previously installed version; ignoring!");
4545            }
4546        }
4547
4548        // Check for shared user signatures
4549        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4550            // Already existing package. Make sure signatures match
4551            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4552                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4553            if (!match) {
4554                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4555                        == PackageManager.SIGNATURE_MATCH;
4556            }
4557            if (!match) {
4558                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4559                        == PackageManager.SIGNATURE_MATCH;
4560            }
4561            if (!match) {
4562                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4563                        "Package " + pkg.packageName
4564                        + " has no signatures that match those in shared user "
4565                        + pkgSetting.sharedUser.name + "; ignoring!");
4566            }
4567        }
4568    }
4569
4570    /**
4571     * Enforces that only the system UID or root's UID can call a method exposed
4572     * via Binder.
4573     *
4574     * @param message used as message if SecurityException is thrown
4575     * @throws SecurityException if the caller is not system or root
4576     */
4577    private static final void enforceSystemOrRoot(String message) {
4578        final int uid = Binder.getCallingUid();
4579        if (uid != Process.SYSTEM_UID && uid != 0) {
4580            throw new SecurityException(message);
4581        }
4582    }
4583
4584    @Override
4585    public void performBootDexOpt() {
4586        enforceSystemOrRoot("Only the system can request dexopt be performed");
4587
4588        // Before everything else, see whether we need to fstrim.
4589        try {
4590            IMountService ms = PackageHelper.getMountService();
4591            if (ms != null) {
4592                final boolean isUpgrade = isUpgrade();
4593                boolean doTrim = isUpgrade;
4594                if (doTrim) {
4595                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4596                } else {
4597                    final long interval = android.provider.Settings.Global.getLong(
4598                            mContext.getContentResolver(),
4599                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4600                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4601                    if (interval > 0) {
4602                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4603                        if (timeSinceLast > interval) {
4604                            doTrim = true;
4605                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4606                                    + "; running immediately");
4607                        }
4608                    }
4609                }
4610                if (doTrim) {
4611                    if (!isFirstBoot()) {
4612                        try {
4613                            ActivityManagerNative.getDefault().showBootMessage(
4614                                    mContext.getResources().getString(
4615                                            R.string.android_upgrading_fstrim), true);
4616                        } catch (RemoteException e) {
4617                        }
4618                    }
4619                    ms.runMaintenance();
4620                }
4621            } else {
4622                Slog.e(TAG, "Mount service unavailable!");
4623            }
4624        } catch (RemoteException e) {
4625            // Can't happen; MountService is local
4626        }
4627
4628        final ArraySet<PackageParser.Package> pkgs;
4629        synchronized (mPackages) {
4630            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
4631        }
4632
4633        if (pkgs != null) {
4634            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4635            // in case the device runs out of space.
4636            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4637            // Give priority to core apps.
4638            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4639                PackageParser.Package pkg = it.next();
4640                if (pkg.coreApp) {
4641                    if (DEBUG_DEXOPT) {
4642                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4643                    }
4644                    sortedPkgs.add(pkg);
4645                    it.remove();
4646                }
4647            }
4648            // Give priority to system apps that listen for pre boot complete.
4649            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4650            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4651            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4652                PackageParser.Package pkg = it.next();
4653                if (pkgNames.contains(pkg.packageName)) {
4654                    if (DEBUG_DEXOPT) {
4655                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4656                    }
4657                    sortedPkgs.add(pkg);
4658                    it.remove();
4659                }
4660            }
4661            // Give priority to system apps.
4662            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4663                PackageParser.Package pkg = it.next();
4664                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4665                    if (DEBUG_DEXOPT) {
4666                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4667                    }
4668                    sortedPkgs.add(pkg);
4669                    it.remove();
4670                }
4671            }
4672            // Give priority to updated system apps.
4673            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4674                PackageParser.Package pkg = it.next();
4675                if (isUpdatedSystemApp(pkg)) {
4676                    if (DEBUG_DEXOPT) {
4677                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4678                    }
4679                    sortedPkgs.add(pkg);
4680                    it.remove();
4681                }
4682            }
4683            // Give priority to apps that listen for boot complete.
4684            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4685            pkgNames = getPackageNamesForIntent(intent);
4686            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4687                PackageParser.Package pkg = it.next();
4688                if (pkgNames.contains(pkg.packageName)) {
4689                    if (DEBUG_DEXOPT) {
4690                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4691                    }
4692                    sortedPkgs.add(pkg);
4693                    it.remove();
4694                }
4695            }
4696            // Filter out packages that aren't recently used.
4697            filterRecentlyUsedApps(pkgs);
4698            // Add all remaining apps.
4699            for (PackageParser.Package pkg : pkgs) {
4700                if (DEBUG_DEXOPT) {
4701                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4702                }
4703                sortedPkgs.add(pkg);
4704            }
4705
4706            // If we want to be lazy, filter everything that wasn't recently used.
4707            if (mLazyDexOpt) {
4708                filterRecentlyUsedApps(sortedPkgs);
4709            }
4710
4711            int i = 0;
4712            int total = sortedPkgs.size();
4713            File dataDir = Environment.getDataDirectory();
4714            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4715            if (lowThreshold == 0) {
4716                throw new IllegalStateException("Invalid low memory threshold");
4717            }
4718            for (PackageParser.Package pkg : sortedPkgs) {
4719                long usableSpace = dataDir.getUsableSpace();
4720                if (usableSpace < lowThreshold) {
4721                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4722                    break;
4723                }
4724                performBootDexOpt(pkg, ++i, total);
4725            }
4726        }
4727    }
4728
4729    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4730        // Filter out packages that aren't recently used.
4731        //
4732        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4733        // should do a full dexopt.
4734        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4735            int total = pkgs.size();
4736            int skipped = 0;
4737            long now = System.currentTimeMillis();
4738            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4739                PackageParser.Package pkg = i.next();
4740                long then = pkg.mLastPackageUsageTimeInMills;
4741                if (then + mDexOptLRUThresholdInMills < now) {
4742                    if (DEBUG_DEXOPT) {
4743                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4744                              ((then == 0) ? "never" : new Date(then)));
4745                    }
4746                    i.remove();
4747                    skipped++;
4748                }
4749            }
4750            if (DEBUG_DEXOPT) {
4751                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4752            }
4753        }
4754    }
4755
4756    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4757        List<ResolveInfo> ris = null;
4758        try {
4759            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4760                    intent, null, 0, UserHandle.USER_OWNER);
4761        } catch (RemoteException e) {
4762        }
4763        ArraySet<String> pkgNames = new ArraySet<String>();
4764        if (ris != null) {
4765            for (ResolveInfo ri : ris) {
4766                pkgNames.add(ri.activityInfo.packageName);
4767            }
4768        }
4769        return pkgNames;
4770    }
4771
4772    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4773        if (DEBUG_DEXOPT) {
4774            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4775        }
4776        if (!isFirstBoot()) {
4777            try {
4778                ActivityManagerNative.getDefault().showBootMessage(
4779                        mContext.getResources().getString(R.string.android_upgrading_apk,
4780                                curr, total), true);
4781            } catch (RemoteException e) {
4782            }
4783        }
4784        PackageParser.Package p = pkg;
4785        synchronized (mInstallLock) {
4786            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4787                    false /* force dex */, false /* defer */, true /* include dependencies */);
4788        }
4789    }
4790
4791    @Override
4792    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4793        return performDexOpt(packageName, instructionSet, false);
4794    }
4795
4796    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4797        if (info.primaryCpuAbi == null) {
4798            return getPreferredInstructionSet();
4799        }
4800
4801        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4802    }
4803
4804    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4805        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4806        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4807        if (!dexopt && !updateUsage) {
4808            // We aren't going to dexopt or update usage, so bail early.
4809            return false;
4810        }
4811        PackageParser.Package p;
4812        final String targetInstructionSet;
4813        synchronized (mPackages) {
4814            p = mPackages.get(packageName);
4815            if (p == null) {
4816                return false;
4817            }
4818            if (updateUsage) {
4819                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4820            }
4821            mPackageUsage.write(false);
4822            if (!dexopt) {
4823                // We aren't going to dexopt, so bail early.
4824                return false;
4825            }
4826
4827            targetInstructionSet = instructionSet != null ? instructionSet :
4828                    getPrimaryInstructionSet(p.applicationInfo);
4829            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4830                return false;
4831            }
4832        }
4833
4834        synchronized (mInstallLock) {
4835            final String[] instructionSets = new String[] { targetInstructionSet };
4836            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4837                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4838            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4839        }
4840    }
4841
4842    public ArraySet<String> getPackagesThatNeedDexOpt() {
4843        ArraySet<String> pkgs = null;
4844        synchronized (mPackages) {
4845            for (PackageParser.Package p : mPackages.values()) {
4846                if (DEBUG_DEXOPT) {
4847                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4848                }
4849                if (!p.mDexOptPerformed.isEmpty()) {
4850                    continue;
4851                }
4852                if (pkgs == null) {
4853                    pkgs = new ArraySet<String>();
4854                }
4855                pkgs.add(p.packageName);
4856            }
4857        }
4858        return pkgs;
4859    }
4860
4861    public void shutdown() {
4862        mPackageUsage.write(true);
4863    }
4864
4865    @Override
4866    public void forceDexOpt(String packageName) {
4867        enforceSystemOrRoot("forceDexOpt");
4868
4869        PackageParser.Package pkg;
4870        synchronized (mPackages) {
4871            pkg = mPackages.get(packageName);
4872            if (pkg == null) {
4873                throw new IllegalArgumentException("Missing package: " + packageName);
4874            }
4875        }
4876
4877        synchronized (mInstallLock) {
4878            final String[] instructionSets = new String[] {
4879                    getPrimaryInstructionSet(pkg.applicationInfo) };
4880            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4881                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4882            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4883                throw new IllegalStateException("Failed to dexopt: " + res);
4884            }
4885        }
4886    }
4887
4888    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4889        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4890            Slog.w(TAG, "Unable to update from " + oldPkg.name
4891                    + " to " + newPkg.packageName
4892                    + ": old package not in system partition");
4893            return false;
4894        } else if (mPackages.get(oldPkg.name) != null) {
4895            Slog.w(TAG, "Unable to update from " + oldPkg.name
4896                    + " to " + newPkg.packageName
4897                    + ": old package still exists");
4898            return false;
4899        }
4900        return true;
4901    }
4902
4903    private File getDataPathForPackage(String packageName, int userId) {
4904        /*
4905         * Until we fully support multiple users, return the directory we
4906         * previously would have. The PackageManagerTests will need to be
4907         * revised when this is changed back..
4908         */
4909        if (userId == 0) {
4910            return new File(mAppDataDir, packageName);
4911        } else {
4912            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4913                + File.separator + packageName);
4914        }
4915    }
4916
4917    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4918        int[] users = sUserManager.getUserIds();
4919        int res = mInstaller.install(packageName, uid, uid, seinfo);
4920        if (res < 0) {
4921            return res;
4922        }
4923        for (int user : users) {
4924            if (user != 0) {
4925                res = mInstaller.createUserData(packageName,
4926                        UserHandle.getUid(user, uid), user, seinfo);
4927                if (res < 0) {
4928                    return res;
4929                }
4930            }
4931        }
4932        return res;
4933    }
4934
4935    private int removeDataDirsLI(String packageName) {
4936        int[] users = sUserManager.getUserIds();
4937        int res = 0;
4938        for (int user : users) {
4939            int resInner = mInstaller.remove(packageName, user);
4940            if (resInner < 0) {
4941                res = resInner;
4942            }
4943        }
4944
4945        return res;
4946    }
4947
4948    private int deleteCodeCacheDirsLI(String packageName) {
4949        int[] users = sUserManager.getUserIds();
4950        int res = 0;
4951        for (int user : users) {
4952            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4953            if (resInner < 0) {
4954                res = resInner;
4955            }
4956        }
4957        return res;
4958    }
4959
4960    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4961            PackageParser.Package changingLib) {
4962        if (file.path != null) {
4963            usesLibraryFiles.add(file.path);
4964            return;
4965        }
4966        PackageParser.Package p = mPackages.get(file.apk);
4967        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4968            // If we are doing this while in the middle of updating a library apk,
4969            // then we need to make sure to use that new apk for determining the
4970            // dependencies here.  (We haven't yet finished committing the new apk
4971            // to the package manager state.)
4972            if (p == null || p.packageName.equals(changingLib.packageName)) {
4973                p = changingLib;
4974            }
4975        }
4976        if (p != null) {
4977            usesLibraryFiles.addAll(p.getAllCodePaths());
4978        }
4979    }
4980
4981    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4982            PackageParser.Package changingLib) throws PackageManagerException {
4983        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4984            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4985            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4986            for (int i=0; i<N; i++) {
4987                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4988                if (file == null) {
4989                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4990                            "Package " + pkg.packageName + " requires unavailable shared library "
4991                            + pkg.usesLibraries.get(i) + "; failing!");
4992                }
4993                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4994            }
4995            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4996            for (int i=0; i<N; i++) {
4997                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4998                if (file == null) {
4999                    Slog.w(TAG, "Package " + pkg.packageName
5000                            + " desires unavailable shared library "
5001                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5002                } else {
5003                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5004                }
5005            }
5006            N = usesLibraryFiles.size();
5007            if (N > 0) {
5008                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5009            } else {
5010                pkg.usesLibraryFiles = null;
5011            }
5012        }
5013    }
5014
5015    private static boolean hasString(List<String> list, List<String> which) {
5016        if (list == null) {
5017            return false;
5018        }
5019        for (int i=list.size()-1; i>=0; i--) {
5020            for (int j=which.size()-1; j>=0; j--) {
5021                if (which.get(j).equals(list.get(i))) {
5022                    return true;
5023                }
5024            }
5025        }
5026        return false;
5027    }
5028
5029    private void updateAllSharedLibrariesLPw() {
5030        for (PackageParser.Package pkg : mPackages.values()) {
5031            try {
5032                updateSharedLibrariesLPw(pkg, null);
5033            } catch (PackageManagerException e) {
5034                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5035            }
5036        }
5037    }
5038
5039    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5040            PackageParser.Package changingPkg) {
5041        ArrayList<PackageParser.Package> res = null;
5042        for (PackageParser.Package pkg : mPackages.values()) {
5043            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5044                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5045                if (res == null) {
5046                    res = new ArrayList<PackageParser.Package>();
5047                }
5048                res.add(pkg);
5049                try {
5050                    updateSharedLibrariesLPw(pkg, changingPkg);
5051                } catch (PackageManagerException e) {
5052                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5053                }
5054            }
5055        }
5056        return res;
5057    }
5058
5059    /**
5060     * Derive the value of the {@code cpuAbiOverride} based on the provided
5061     * value and an optional stored value from the package settings.
5062     */
5063    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5064        String cpuAbiOverride = null;
5065
5066        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5067            cpuAbiOverride = null;
5068        } else if (abiOverride != null) {
5069            cpuAbiOverride = abiOverride;
5070        } else if (settings != null) {
5071            cpuAbiOverride = settings.cpuAbiOverrideString;
5072        }
5073
5074        return cpuAbiOverride;
5075    }
5076
5077    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5078            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5079        boolean success = false;
5080        try {
5081            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5082                    currentTime, user);
5083            success = true;
5084            return res;
5085        } finally {
5086            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5087                removeDataDirsLI(pkg.packageName);
5088            }
5089        }
5090    }
5091
5092    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5093            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5094        final File scanFile = new File(pkg.codePath);
5095        if (pkg.applicationInfo.getCodePath() == null ||
5096                pkg.applicationInfo.getResourcePath() == null) {
5097            // Bail out. The resource and code paths haven't been set.
5098            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5099                    "Code and resource paths haven't been set correctly");
5100        }
5101
5102        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5103            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5104        } else {
5105            // Only allow system apps to be flagged as core apps.
5106            pkg.coreApp = false;
5107        }
5108
5109        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5110            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5111        }
5112
5113        if (mCustomResolverComponentName != null &&
5114                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5115            setUpCustomResolverActivity(pkg);
5116        }
5117
5118        if (pkg.packageName.equals("android")) {
5119            synchronized (mPackages) {
5120                if (mAndroidApplication != null) {
5121                    Slog.w(TAG, "*************************************************");
5122                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5123                    Slog.w(TAG, " file=" + scanFile);
5124                    Slog.w(TAG, "*************************************************");
5125                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5126                            "Core android package being redefined.  Skipping.");
5127                }
5128
5129                // Set up information for our fall-back user intent resolution activity.
5130                mPlatformPackage = pkg;
5131                pkg.mVersionCode = mSdkVersion;
5132                mAndroidApplication = pkg.applicationInfo;
5133
5134                if (!mResolverReplaced) {
5135                    mResolveActivity.applicationInfo = mAndroidApplication;
5136                    mResolveActivity.name = ResolverActivity.class.getName();
5137                    mResolveActivity.packageName = mAndroidApplication.packageName;
5138                    mResolveActivity.processName = "system:ui";
5139                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5140                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5141                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5142                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5143                    mResolveActivity.exported = true;
5144                    mResolveActivity.enabled = true;
5145                    mResolveInfo.activityInfo = mResolveActivity;
5146                    mResolveInfo.priority = 0;
5147                    mResolveInfo.preferredOrder = 0;
5148                    mResolveInfo.match = 0;
5149                    mResolveComponentName = new ComponentName(
5150                            mAndroidApplication.packageName, mResolveActivity.name);
5151                }
5152            }
5153        }
5154
5155        if (DEBUG_PACKAGE_SCANNING) {
5156            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5157                Log.d(TAG, "Scanning package " + pkg.packageName);
5158        }
5159
5160        if (mPackages.containsKey(pkg.packageName)
5161                || mSharedLibraries.containsKey(pkg.packageName)) {
5162            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5163                    "Application package " + pkg.packageName
5164                    + " already installed.  Skipping duplicate.");
5165        }
5166
5167        // Initialize package source and resource directories
5168        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5169        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5170
5171        SharedUserSetting suid = null;
5172        PackageSetting pkgSetting = null;
5173
5174        if (!isSystemApp(pkg)) {
5175            // Only system apps can use these features.
5176            pkg.mOriginalPackages = null;
5177            pkg.mRealPackage = null;
5178            pkg.mAdoptPermissions = null;
5179        }
5180
5181        // writer
5182        synchronized (mPackages) {
5183            if (pkg.mSharedUserId != null) {
5184                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5185                if (suid == null) {
5186                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5187                            "Creating application package " + pkg.packageName
5188                            + " for shared user failed");
5189                }
5190                if (DEBUG_PACKAGE_SCANNING) {
5191                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5192                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5193                                + "): packages=" + suid.packages);
5194                }
5195            }
5196
5197            // Check if we are renaming from an original package name.
5198            PackageSetting origPackage = null;
5199            String realName = null;
5200            if (pkg.mOriginalPackages != null) {
5201                // This package may need to be renamed to a previously
5202                // installed name.  Let's check on that...
5203                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5204                if (pkg.mOriginalPackages.contains(renamed)) {
5205                    // This package had originally been installed as the
5206                    // original name, and we have already taken care of
5207                    // transitioning to the new one.  Just update the new
5208                    // one to continue using the old name.
5209                    realName = pkg.mRealPackage;
5210                    if (!pkg.packageName.equals(renamed)) {
5211                        // Callers into this function may have already taken
5212                        // care of renaming the package; only do it here if
5213                        // it is not already done.
5214                        pkg.setPackageName(renamed);
5215                    }
5216
5217                } else {
5218                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5219                        if ((origPackage = mSettings.peekPackageLPr(
5220                                pkg.mOriginalPackages.get(i))) != null) {
5221                            // We do have the package already installed under its
5222                            // original name...  should we use it?
5223                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5224                                // New package is not compatible with original.
5225                                origPackage = null;
5226                                continue;
5227                            } else if (origPackage.sharedUser != null) {
5228                                // Make sure uid is compatible between packages.
5229                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5230                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5231                                            + " to " + pkg.packageName + ": old uid "
5232                                            + origPackage.sharedUser.name
5233                                            + " differs from " + pkg.mSharedUserId);
5234                                    origPackage = null;
5235                                    continue;
5236                                }
5237                            } else {
5238                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5239                                        + pkg.packageName + " to old name " + origPackage.name);
5240                            }
5241                            break;
5242                        }
5243                    }
5244                }
5245            }
5246
5247            if (mTransferedPackages.contains(pkg.packageName)) {
5248                Slog.w(TAG, "Package " + pkg.packageName
5249                        + " was transferred to another, but its .apk remains");
5250            }
5251
5252            // Just create the setting, don't add it yet. For already existing packages
5253            // the PkgSetting exists already and doesn't have to be created.
5254            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5255                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5256                    pkg.applicationInfo.primaryCpuAbi,
5257                    pkg.applicationInfo.secondaryCpuAbi,
5258                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5259                    user, false);
5260            if (pkgSetting == null) {
5261                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5262                        "Creating application package " + pkg.packageName + " failed");
5263            }
5264
5265            if (pkgSetting.origPackage != null) {
5266                // If we are first transitioning from an original package,
5267                // fix up the new package's name now.  We need to do this after
5268                // looking up the package under its new name, so getPackageLP
5269                // can take care of fiddling things correctly.
5270                pkg.setPackageName(origPackage.name);
5271
5272                // File a report about this.
5273                String msg = "New package " + pkgSetting.realName
5274                        + " renamed to replace old package " + pkgSetting.name;
5275                reportSettingsProblem(Log.WARN, msg);
5276
5277                // Make a note of it.
5278                mTransferedPackages.add(origPackage.name);
5279
5280                // No longer need to retain this.
5281                pkgSetting.origPackage = null;
5282            }
5283
5284            if (realName != null) {
5285                // Make a note of it.
5286                mTransferedPackages.add(pkg.packageName);
5287            }
5288
5289            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5290                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5291            }
5292
5293            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5294                // Check all shared libraries and map to their actual file path.
5295                // We only do this here for apps not on a system dir, because those
5296                // are the only ones that can fail an install due to this.  We
5297                // will take care of the system apps by updating all of their
5298                // library paths after the scan is done.
5299                updateSharedLibrariesLPw(pkg, null);
5300            }
5301
5302            if (mFoundPolicyFile) {
5303                SELinuxMMAC.assignSeinfoValue(pkg);
5304            }
5305
5306            pkg.applicationInfo.uid = pkgSetting.appId;
5307            pkg.mExtras = pkgSetting;
5308            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5309                try {
5310                    verifySignaturesLP(pkgSetting, pkg);
5311                    // We just determined the app is signed correctly, so bring
5312                    // over the latest parsed certs.
5313                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5314                } catch (PackageManagerException e) {
5315                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5316                        throw e;
5317                    }
5318                    // The signature has changed, but this package is in the system
5319                    // image...  let's recover!
5320                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5321                    // However...  if this package is part of a shared user, but it
5322                    // doesn't match the signature of the shared user, let's fail.
5323                    // What this means is that you can't change the signatures
5324                    // associated with an overall shared user, which doesn't seem all
5325                    // that unreasonable.
5326                    if (pkgSetting.sharedUser != null) {
5327                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5328                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5329                            throw new PackageManagerException(
5330                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5331                                            "Signature mismatch for shared user : "
5332                                            + pkgSetting.sharedUser);
5333                        }
5334                    }
5335                    // File a report about this.
5336                    String msg = "System package " + pkg.packageName
5337                        + " signature changed; retaining data.";
5338                    reportSettingsProblem(Log.WARN, msg);
5339                }
5340            } else {
5341                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5342                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5343                            + pkg.packageName + " upgrade keys do not match the "
5344                            + "previously installed version");
5345                } else {
5346                    // We just determined the app is signed correctly, so bring
5347                    // over the latest parsed certs.
5348                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5349                }
5350            }
5351            // Verify that this new package doesn't have any content providers
5352            // that conflict with existing packages.  Only do this if the
5353            // package isn't already installed, since we don't want to break
5354            // things that are installed.
5355            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5356                final int N = pkg.providers.size();
5357                int i;
5358                for (i=0; i<N; i++) {
5359                    PackageParser.Provider p = pkg.providers.get(i);
5360                    if (p.info.authority != null) {
5361                        String names[] = p.info.authority.split(";");
5362                        for (int j = 0; j < names.length; j++) {
5363                            if (mProvidersByAuthority.containsKey(names[j])) {
5364                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5365                                final String otherPackageName =
5366                                        ((other != null && other.getComponentName() != null) ?
5367                                                other.getComponentName().getPackageName() : "?");
5368                                throw new PackageManagerException(
5369                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5370                                                "Can't install because provider name " + names[j]
5371                                                + " (in package " + pkg.applicationInfo.packageName
5372                                                + ") is already used by " + otherPackageName);
5373                            }
5374                        }
5375                    }
5376                }
5377            }
5378
5379            if (pkg.mAdoptPermissions != null) {
5380                // This package wants to adopt ownership of permissions from
5381                // another package.
5382                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5383                    final String origName = pkg.mAdoptPermissions.get(i);
5384                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5385                    if (orig != null) {
5386                        if (verifyPackageUpdateLPr(orig, pkg)) {
5387                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5388                                    + pkg.packageName);
5389                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5390                        }
5391                    }
5392                }
5393            }
5394        }
5395
5396        final String pkgName = pkg.packageName;
5397
5398        final long scanFileTime = scanFile.lastModified();
5399        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5400        pkg.applicationInfo.processName = fixProcessName(
5401                pkg.applicationInfo.packageName,
5402                pkg.applicationInfo.processName,
5403                pkg.applicationInfo.uid);
5404
5405        File dataPath;
5406        if (mPlatformPackage == pkg) {
5407            // The system package is special.
5408            dataPath = new File(Environment.getDataDirectory(), "system");
5409
5410            pkg.applicationInfo.dataDir = dataPath.getPath();
5411
5412        } else {
5413            // This is a normal package, need to make its data directory.
5414            dataPath = getDataPathForPackage(pkg.packageName, 0);
5415
5416            boolean uidError = false;
5417            if (dataPath.exists()) {
5418                int currentUid = 0;
5419                try {
5420                    StructStat stat = Os.stat(dataPath.getPath());
5421                    currentUid = stat.st_uid;
5422                } catch (ErrnoException e) {
5423                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5424                }
5425
5426                // If we have mismatched owners for the data path, we have a problem.
5427                if (currentUid != pkg.applicationInfo.uid) {
5428                    boolean recovered = false;
5429                    if (currentUid == 0) {
5430                        // The directory somehow became owned by root.  Wow.
5431                        // This is probably because the system was stopped while
5432                        // installd was in the middle of messing with its libs
5433                        // directory.  Ask installd to fix that.
5434                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5435                                pkg.applicationInfo.uid);
5436                        if (ret >= 0) {
5437                            recovered = true;
5438                            String msg = "Package " + pkg.packageName
5439                                    + " unexpectedly changed to uid 0; recovered to " +
5440                                    + pkg.applicationInfo.uid;
5441                            reportSettingsProblem(Log.WARN, msg);
5442                        }
5443                    }
5444                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5445                            || (scanFlags&SCAN_BOOTING) != 0)) {
5446                        // If this is a system app, we can at least delete its
5447                        // current data so the application will still work.
5448                        int ret = removeDataDirsLI(pkgName);
5449                        if (ret >= 0) {
5450                            // TODO: Kill the processes first
5451                            // Old data gone!
5452                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5453                                    ? "System package " : "Third party package ";
5454                            String msg = prefix + pkg.packageName
5455                                    + " has changed from uid: "
5456                                    + currentUid + " to "
5457                                    + pkg.applicationInfo.uid + "; old data erased";
5458                            reportSettingsProblem(Log.WARN, msg);
5459                            recovered = true;
5460
5461                            // And now re-install the app.
5462                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5463                                                   pkg.applicationInfo.seinfo);
5464                            if (ret == -1) {
5465                                // Ack should not happen!
5466                                msg = prefix + pkg.packageName
5467                                        + " could not have data directory re-created after delete.";
5468                                reportSettingsProblem(Log.WARN, msg);
5469                                throw new PackageManagerException(
5470                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5471                            }
5472                        }
5473                        if (!recovered) {
5474                            mHasSystemUidErrors = true;
5475                        }
5476                    } else if (!recovered) {
5477                        // If we allow this install to proceed, we will be broken.
5478                        // Abort, abort!
5479                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5480                                "scanPackageLI");
5481                    }
5482                    if (!recovered) {
5483                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5484                            + pkg.applicationInfo.uid + "/fs_"
5485                            + currentUid;
5486                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5487                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5488                        String msg = "Package " + pkg.packageName
5489                                + " has mismatched uid: "
5490                                + currentUid + " on disk, "
5491                                + pkg.applicationInfo.uid + " in settings";
5492                        // writer
5493                        synchronized (mPackages) {
5494                            mSettings.mReadMessages.append(msg);
5495                            mSettings.mReadMessages.append('\n');
5496                            uidError = true;
5497                            if (!pkgSetting.uidError) {
5498                                reportSettingsProblem(Log.ERROR, msg);
5499                            }
5500                        }
5501                    }
5502                }
5503                pkg.applicationInfo.dataDir = dataPath.getPath();
5504                if (mShouldRestoreconData) {
5505                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5506                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5507                                pkg.applicationInfo.uid);
5508                }
5509            } else {
5510                if (DEBUG_PACKAGE_SCANNING) {
5511                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5512                        Log.v(TAG, "Want this data dir: " + dataPath);
5513                }
5514                //invoke installer to do the actual installation
5515                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5516                                           pkg.applicationInfo.seinfo);
5517                if (ret < 0) {
5518                    // Error from installer
5519                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5520                            "Unable to create data dirs [errorCode=" + ret + "]");
5521                }
5522
5523                if (dataPath.exists()) {
5524                    pkg.applicationInfo.dataDir = dataPath.getPath();
5525                } else {
5526                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5527                    pkg.applicationInfo.dataDir = null;
5528                }
5529            }
5530
5531            pkgSetting.uidError = uidError;
5532        }
5533
5534        final String path = scanFile.getPath();
5535        final String codePath = pkg.applicationInfo.getCodePath();
5536        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5537        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5538            setBundledAppAbisAndRoots(pkg, pkgSetting);
5539
5540            // If we haven't found any native libraries for the app, check if it has
5541            // renderscript code. We'll need to force the app to 32 bit if it has
5542            // renderscript bitcode.
5543            if (pkg.applicationInfo.primaryCpuAbi == null
5544                    && pkg.applicationInfo.secondaryCpuAbi == null
5545                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5546                NativeLibraryHelper.Handle handle = null;
5547                try {
5548                    handle = NativeLibraryHelper.Handle.create(scanFile);
5549                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5550                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5551                    }
5552                } catch (IOException ioe) {
5553                    Slog.w(TAG, "Error scanning system app : " + ioe);
5554                } finally {
5555                    IoUtils.closeQuietly(handle);
5556                }
5557            }
5558
5559            setNativeLibraryPaths(pkg);
5560        } else {
5561            // TODO: We can probably be smarter about this stuff. For installed apps,
5562            // we can calculate this information at install time once and for all. For
5563            // system apps, we can probably assume that this information doesn't change
5564            // after the first boot scan. As things stand, we do lots of unnecessary work.
5565
5566            // Give ourselves some initial paths; we'll come back for another
5567            // pass once we've determined ABI below.
5568            setNativeLibraryPaths(pkg);
5569
5570            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5571            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5572            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5573
5574            NativeLibraryHelper.Handle handle = null;
5575            try {
5576                handle = NativeLibraryHelper.Handle.create(scanFile);
5577                // TODO(multiArch): This can be null for apps that didn't go through the
5578                // usual installation process. We can calculate it again, like we
5579                // do during install time.
5580                //
5581                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5582                // unnecessary.
5583                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5584
5585                // Null out the abis so that they can be recalculated.
5586                pkg.applicationInfo.primaryCpuAbi = null;
5587                pkg.applicationInfo.secondaryCpuAbi = null;
5588                if (isMultiArch(pkg.applicationInfo)) {
5589                    // Warn if we've set an abiOverride for multi-lib packages..
5590                    // By definition, we need to copy both 32 and 64 bit libraries for
5591                    // such packages.
5592                    if (pkg.cpuAbiOverride != null
5593                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5594                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5595                    }
5596
5597                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5598                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5599                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5600                        if (isAsec) {
5601                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5602                        } else {
5603                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5604                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5605                                    useIsaSpecificSubdirs);
5606                        }
5607                    }
5608
5609                    maybeThrowExceptionForMultiArchCopy(
5610                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5611
5612                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5613                        if (isAsec) {
5614                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5615                        } else {
5616                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5617                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5618                                    useIsaSpecificSubdirs);
5619                        }
5620                    }
5621
5622                    maybeThrowExceptionForMultiArchCopy(
5623                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5624
5625                    if (abi64 >= 0) {
5626                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5627                    }
5628
5629                    if (abi32 >= 0) {
5630                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5631                        if (abi64 >= 0) {
5632                            pkg.applicationInfo.secondaryCpuAbi = abi;
5633                        } else {
5634                            pkg.applicationInfo.primaryCpuAbi = abi;
5635                        }
5636                    }
5637                } else {
5638                    String[] abiList = (cpuAbiOverride != null) ?
5639                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5640
5641                    // Enable gross and lame hacks for apps that are built with old
5642                    // SDK tools. We must scan their APKs for renderscript bitcode and
5643                    // not launch them if it's present. Don't bother checking on devices
5644                    // that don't have 64 bit support.
5645                    boolean needsRenderScriptOverride = false;
5646                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5647                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5648                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5649                        needsRenderScriptOverride = true;
5650                    }
5651
5652                    final int copyRet;
5653                    if (isAsec) {
5654                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5655                    } else {
5656                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5657                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5658                    }
5659
5660                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5661                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5662                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5663                    }
5664
5665                    if (copyRet >= 0) {
5666                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5667                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5668                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5669                    } else if (needsRenderScriptOverride) {
5670                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5671                    }
5672                }
5673            } catch (IOException ioe) {
5674                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5675            } finally {
5676                IoUtils.closeQuietly(handle);
5677            }
5678
5679            // Now that we've calculated the ABIs and determined if it's an internal app,
5680            // we will go ahead and populate the nativeLibraryPath.
5681            setNativeLibraryPaths(pkg);
5682
5683            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5684            final int[] userIds = sUserManager.getUserIds();
5685            synchronized (mInstallLock) {
5686                // Create a native library symlink only if we have native libraries
5687                // and if the native libraries are 32 bit libraries. We do not provide
5688                // this symlink for 64 bit libraries.
5689                if (pkg.applicationInfo.primaryCpuAbi != null &&
5690                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5691                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5692                    for (int userId : userIds) {
5693                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5694                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5695                                    "Failed linking native library dir (user=" + userId + ")");
5696                        }
5697                    }
5698                }
5699            }
5700        }
5701
5702        // This is a special case for the "system" package, where the ABI is
5703        // dictated by the zygote configuration (and init.rc). We should keep track
5704        // of this ABI so that we can deal with "normal" applications that run under
5705        // the same UID correctly.
5706        if (mPlatformPackage == pkg) {
5707            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5708                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5709        }
5710
5711        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5712        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5713        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5714        // Copy the derived override back to the parsed package, so that we can
5715        // update the package settings accordingly.
5716        pkg.cpuAbiOverride = cpuAbiOverride;
5717
5718        if (DEBUG_ABI_SELECTION) {
5719            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5720                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5721                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5722        }
5723
5724        // Push the derived path down into PackageSettings so we know what to
5725        // clean up at uninstall time.
5726        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5727
5728        if (DEBUG_ABI_SELECTION) {
5729            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5730                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5731                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5732        }
5733
5734        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5735            // We don't do this here during boot because we can do it all
5736            // at once after scanning all existing packages.
5737            //
5738            // We also do this *before* we perform dexopt on this package, so that
5739            // we can avoid redundant dexopts, and also to make sure we've got the
5740            // code and package path correct.
5741            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5742                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5743        }
5744
5745        if ((scanFlags & SCAN_NO_DEX) == 0) {
5746            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5747                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5748            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5749                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5750            }
5751        }
5752
5753        if (mFactoryTest && pkg.requestedPermissions.contains(
5754                android.Manifest.permission.FACTORY_TEST)) {
5755            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5756        }
5757
5758        ArrayList<PackageParser.Package> clientLibPkgs = null;
5759
5760        // writer
5761        synchronized (mPackages) {
5762            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5763                // Only system apps can add new shared libraries.
5764                if (pkg.libraryNames != null) {
5765                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5766                        String name = pkg.libraryNames.get(i);
5767                        boolean allowed = false;
5768                        if (isUpdatedSystemApp(pkg)) {
5769                            // New library entries can only be added through the
5770                            // system image.  This is important to get rid of a lot
5771                            // of nasty edge cases: for example if we allowed a non-
5772                            // system update of the app to add a library, then uninstalling
5773                            // the update would make the library go away, and assumptions
5774                            // we made such as through app install filtering would now
5775                            // have allowed apps on the device which aren't compatible
5776                            // with it.  Better to just have the restriction here, be
5777                            // conservative, and create many fewer cases that can negatively
5778                            // impact the user experience.
5779                            final PackageSetting sysPs = mSettings
5780                                    .getDisabledSystemPkgLPr(pkg.packageName);
5781                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5782                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5783                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5784                                        allowed = true;
5785                                        allowed = true;
5786                                        break;
5787                                    }
5788                                }
5789                            }
5790                        } else {
5791                            allowed = true;
5792                        }
5793                        if (allowed) {
5794                            if (!mSharedLibraries.containsKey(name)) {
5795                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5796                            } else if (!name.equals(pkg.packageName)) {
5797                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5798                                        + name + " already exists; skipping");
5799                            }
5800                        } else {
5801                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5802                                    + name + " that is not declared on system image; skipping");
5803                        }
5804                    }
5805                    if ((scanFlags&SCAN_BOOTING) == 0) {
5806                        // If we are not booting, we need to update any applications
5807                        // that are clients of our shared library.  If we are booting,
5808                        // this will all be done once the scan is complete.
5809                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5810                    }
5811                }
5812            }
5813        }
5814
5815        // We also need to dexopt any apps that are dependent on this library.  Note that
5816        // if these fail, we should abort the install since installing the library will
5817        // result in some apps being broken.
5818        if (clientLibPkgs != null) {
5819            if ((scanFlags & SCAN_NO_DEX) == 0) {
5820                for (int i = 0; i < clientLibPkgs.size(); i++) {
5821                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5822                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5823                            null /* instruction sets */, forceDex,
5824                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5825                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5826                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5827                                "scanPackageLI failed to dexopt clientLibPkgs");
5828                    }
5829                }
5830            }
5831        }
5832
5833        // Request the ActivityManager to kill the process(only for existing packages)
5834        // so that we do not end up in a confused state while the user is still using the older
5835        // version of the application while the new one gets installed.
5836        if ((scanFlags & SCAN_REPLACING) != 0) {
5837            killApplication(pkg.applicationInfo.packageName,
5838                        pkg.applicationInfo.uid, "update pkg");
5839        }
5840
5841        // Also need to kill any apps that are dependent on the library.
5842        if (clientLibPkgs != null) {
5843            for (int i=0; i<clientLibPkgs.size(); i++) {
5844                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5845                killApplication(clientPkg.applicationInfo.packageName,
5846                        clientPkg.applicationInfo.uid, "update lib");
5847            }
5848        }
5849
5850        // writer
5851        synchronized (mPackages) {
5852            // We don't expect installation to fail beyond this point
5853
5854            // Add the new setting to mSettings
5855            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5856            // Add the new setting to mPackages
5857            mPackages.put(pkg.applicationInfo.packageName, pkg);
5858            // Make sure we don't accidentally delete its data.
5859            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5860            while (iter.hasNext()) {
5861                PackageCleanItem item = iter.next();
5862                if (pkgName.equals(item.packageName)) {
5863                    iter.remove();
5864                }
5865            }
5866
5867            // Take care of first install / last update times.
5868            if (currentTime != 0) {
5869                if (pkgSetting.firstInstallTime == 0) {
5870                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5871                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5872                    pkgSetting.lastUpdateTime = currentTime;
5873                }
5874            } else if (pkgSetting.firstInstallTime == 0) {
5875                // We need *something*.  Take time time stamp of the file.
5876                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5877            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5878                if (scanFileTime != pkgSetting.timeStamp) {
5879                    // A package on the system image has changed; consider this
5880                    // to be an update.
5881                    pkgSetting.lastUpdateTime = scanFileTime;
5882                }
5883            }
5884
5885            // Add the package's KeySets to the global KeySetManagerService
5886            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5887            try {
5888                // Old KeySetData no longer valid.
5889                ksms.removeAppKeySetDataLPw(pkg.packageName);
5890                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5891                if (pkg.mKeySetMapping != null) {
5892                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5893                            pkg.mKeySetMapping.entrySet()) {
5894                        if (entry.getValue() != null) {
5895                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5896                                                          entry.getValue(), entry.getKey());
5897                        }
5898                    }
5899                    if (pkg.mUpgradeKeySets != null) {
5900                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5901                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5902                        }
5903                    }
5904                }
5905            } catch (NullPointerException e) {
5906                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5907            } catch (IllegalArgumentException e) {
5908                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5909            }
5910
5911            int N = pkg.providers.size();
5912            StringBuilder r = null;
5913            int i;
5914            for (i=0; i<N; i++) {
5915                PackageParser.Provider p = pkg.providers.get(i);
5916                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5917                        p.info.processName, pkg.applicationInfo.uid);
5918                mProviders.addProvider(p);
5919                p.syncable = p.info.isSyncable;
5920                if (p.info.authority != null) {
5921                    String names[] = p.info.authority.split(";");
5922                    p.info.authority = null;
5923                    for (int j = 0; j < names.length; j++) {
5924                        if (j == 1 && p.syncable) {
5925                            // We only want the first authority for a provider to possibly be
5926                            // syncable, so if we already added this provider using a different
5927                            // authority clear the syncable flag. We copy the provider before
5928                            // changing it because the mProviders object contains a reference
5929                            // to a provider that we don't want to change.
5930                            // Only do this for the second authority since the resulting provider
5931                            // object can be the same for all future authorities for this provider.
5932                            p = new PackageParser.Provider(p);
5933                            p.syncable = false;
5934                        }
5935                        if (!mProvidersByAuthority.containsKey(names[j])) {
5936                            mProvidersByAuthority.put(names[j], p);
5937                            if (p.info.authority == null) {
5938                                p.info.authority = names[j];
5939                            } else {
5940                                p.info.authority = p.info.authority + ";" + names[j];
5941                            }
5942                            if (DEBUG_PACKAGE_SCANNING) {
5943                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5944                                    Log.d(TAG, "Registered content provider: " + names[j]
5945                                            + ", className = " + p.info.name + ", isSyncable = "
5946                                            + p.info.isSyncable);
5947                            }
5948                        } else {
5949                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5950                            Slog.w(TAG, "Skipping provider name " + names[j] +
5951                                    " (in package " + pkg.applicationInfo.packageName +
5952                                    "): name already used by "
5953                                    + ((other != null && other.getComponentName() != null)
5954                                            ? other.getComponentName().getPackageName() : "?"));
5955                        }
5956                    }
5957                }
5958                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5959                    if (r == null) {
5960                        r = new StringBuilder(256);
5961                    } else {
5962                        r.append(' ');
5963                    }
5964                    r.append(p.info.name);
5965                }
5966            }
5967            if (r != null) {
5968                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5969            }
5970
5971            N = pkg.services.size();
5972            r = null;
5973            for (i=0; i<N; i++) {
5974                PackageParser.Service s = pkg.services.get(i);
5975                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5976                        s.info.processName, pkg.applicationInfo.uid);
5977                mServices.addService(s);
5978                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5979                    if (r == null) {
5980                        r = new StringBuilder(256);
5981                    } else {
5982                        r.append(' ');
5983                    }
5984                    r.append(s.info.name);
5985                }
5986            }
5987            if (r != null) {
5988                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5989            }
5990
5991            N = pkg.receivers.size();
5992            r = null;
5993            for (i=0; i<N; i++) {
5994                PackageParser.Activity a = pkg.receivers.get(i);
5995                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5996                        a.info.processName, pkg.applicationInfo.uid);
5997                mReceivers.addActivity(a, "receiver");
5998                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5999                    if (r == null) {
6000                        r = new StringBuilder(256);
6001                    } else {
6002                        r.append(' ');
6003                    }
6004                    r.append(a.info.name);
6005                }
6006            }
6007            if (r != null) {
6008                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6009            }
6010
6011            N = pkg.activities.size();
6012            r = null;
6013            for (i=0; i<N; i++) {
6014                PackageParser.Activity a = pkg.activities.get(i);
6015                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6016                        a.info.processName, pkg.applicationInfo.uid);
6017                mActivities.addActivity(a, "activity");
6018                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6019                    if (r == null) {
6020                        r = new StringBuilder(256);
6021                    } else {
6022                        r.append(' ');
6023                    }
6024                    r.append(a.info.name);
6025                }
6026            }
6027            if (r != null) {
6028                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6029            }
6030
6031            N = pkg.permissionGroups.size();
6032            r = null;
6033            for (i=0; i<N; i++) {
6034                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6035                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6036                if (cur == null) {
6037                    mPermissionGroups.put(pg.info.name, pg);
6038                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6039                        if (r == null) {
6040                            r = new StringBuilder(256);
6041                        } else {
6042                            r.append(' ');
6043                        }
6044                        r.append(pg.info.name);
6045                    }
6046                } else {
6047                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6048                            + pg.info.packageName + " ignored: original from "
6049                            + cur.info.packageName);
6050                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6051                        if (r == null) {
6052                            r = new StringBuilder(256);
6053                        } else {
6054                            r.append(' ');
6055                        }
6056                        r.append("DUP:");
6057                        r.append(pg.info.name);
6058                    }
6059                }
6060            }
6061            if (r != null) {
6062                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6063            }
6064
6065            N = pkg.permissions.size();
6066            r = null;
6067            for (i=0; i<N; i++) {
6068                PackageParser.Permission p = pkg.permissions.get(i);
6069                ArrayMap<String, BasePermission> permissionMap =
6070                        p.tree ? mSettings.mPermissionTrees
6071                        : mSettings.mPermissions;
6072                p.group = mPermissionGroups.get(p.info.group);
6073                if (p.info.group == null || p.group != null) {
6074                    BasePermission bp = permissionMap.get(p.info.name);
6075
6076                    // Allow system apps to redefine non-system permissions
6077                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6078                        final boolean currentOwnerIsSystem = (bp.perm != null
6079                                && isSystemApp(bp.perm.owner));
6080                        if (isSystemApp(p.owner)) {
6081                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6082                                // It's a built-in permission and no owner, take ownership now
6083                                bp.packageSetting = pkgSetting;
6084                                bp.perm = p;
6085                                bp.uid = pkg.applicationInfo.uid;
6086                                bp.sourcePackage = p.info.packageName;
6087                            } else if (!currentOwnerIsSystem) {
6088                                String msg = "New decl " + p.owner + " of permission  "
6089                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6090                                reportSettingsProblem(Log.WARN, msg);
6091                                bp = null;
6092                            }
6093                        }
6094                    }
6095
6096                    if (bp == null) {
6097                        bp = new BasePermission(p.info.name, p.info.packageName,
6098                                BasePermission.TYPE_NORMAL);
6099                        permissionMap.put(p.info.name, bp);
6100                    }
6101
6102                    if (bp.perm == null) {
6103                        if (bp.sourcePackage == null
6104                                || bp.sourcePackage.equals(p.info.packageName)) {
6105                            BasePermission tree = findPermissionTreeLP(p.info.name);
6106                            if (tree == null
6107                                    || tree.sourcePackage.equals(p.info.packageName)) {
6108                                bp.packageSetting = pkgSetting;
6109                                bp.perm = p;
6110                                bp.uid = pkg.applicationInfo.uid;
6111                                bp.sourcePackage = p.info.packageName;
6112                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6113                                    if (r == null) {
6114                                        r = new StringBuilder(256);
6115                                    } else {
6116                                        r.append(' ');
6117                                    }
6118                                    r.append(p.info.name);
6119                                }
6120                            } else {
6121                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6122                                        + p.info.packageName + " ignored: base tree "
6123                                        + tree.name + " is from package "
6124                                        + tree.sourcePackage);
6125                            }
6126                        } else {
6127                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6128                                    + p.info.packageName + " ignored: original from "
6129                                    + bp.sourcePackage);
6130                        }
6131                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6132                        if (r == null) {
6133                            r = new StringBuilder(256);
6134                        } else {
6135                            r.append(' ');
6136                        }
6137                        r.append("DUP:");
6138                        r.append(p.info.name);
6139                    }
6140                    if (bp.perm == p) {
6141                        bp.protectionLevel = p.info.protectionLevel;
6142                    }
6143                } else {
6144                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6145                            + p.info.packageName + " ignored: no group "
6146                            + p.group);
6147                }
6148            }
6149            if (r != null) {
6150                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6151            }
6152
6153            N = pkg.instrumentation.size();
6154            r = null;
6155            for (i=0; i<N; i++) {
6156                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6157                a.info.packageName = pkg.applicationInfo.packageName;
6158                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6159                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6160                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6161                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6162                a.info.dataDir = pkg.applicationInfo.dataDir;
6163
6164                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6165                // need other information about the application, like the ABI and what not ?
6166                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6167                mInstrumentation.put(a.getComponentName(), a);
6168                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6169                    if (r == null) {
6170                        r = new StringBuilder(256);
6171                    } else {
6172                        r.append(' ');
6173                    }
6174                    r.append(a.info.name);
6175                }
6176            }
6177            if (r != null) {
6178                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6179            }
6180
6181            if (pkg.protectedBroadcasts != null) {
6182                N = pkg.protectedBroadcasts.size();
6183                for (i=0; i<N; i++) {
6184                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6185                }
6186            }
6187
6188            pkgSetting.setTimeStamp(scanFileTime);
6189
6190            // Create idmap files for pairs of (packages, overlay packages).
6191            // Note: "android", ie framework-res.apk, is handled by native layers.
6192            if (pkg.mOverlayTarget != null) {
6193                // This is an overlay package.
6194                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6195                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6196                        mOverlays.put(pkg.mOverlayTarget,
6197                                new ArrayMap<String, PackageParser.Package>());
6198                    }
6199                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6200                    map.put(pkg.packageName, pkg);
6201                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6202                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6203                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6204                                "scanPackageLI failed to createIdmap");
6205                    }
6206                }
6207            } else if (mOverlays.containsKey(pkg.packageName) &&
6208                    !pkg.packageName.equals("android")) {
6209                // This is a regular package, with one or more known overlay packages.
6210                createIdmapsForPackageLI(pkg);
6211            }
6212        }
6213
6214        return pkg;
6215    }
6216
6217    /**
6218     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6219     * i.e, so that all packages can be run inside a single process if required.
6220     *
6221     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6222     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6223     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6224     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6225     * updating a package that belongs to a shared user.
6226     *
6227     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6228     * adds unnecessary complexity.
6229     */
6230    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6231            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6232        String requiredInstructionSet = null;
6233        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6234            requiredInstructionSet = VMRuntime.getInstructionSet(
6235                     scannedPackage.applicationInfo.primaryCpuAbi);
6236        }
6237
6238        PackageSetting requirer = null;
6239        for (PackageSetting ps : packagesForUser) {
6240            // If packagesForUser contains scannedPackage, we skip it. This will happen
6241            // when scannedPackage is an update of an existing package. Without this check,
6242            // we will never be able to change the ABI of any package belonging to a shared
6243            // user, even if it's compatible with other packages.
6244            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6245                if (ps.primaryCpuAbiString == null) {
6246                    continue;
6247                }
6248
6249                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6250                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6251                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6252                    // this but there's not much we can do.
6253                    String errorMessage = "Instruction set mismatch, "
6254                            + ((requirer == null) ? "[caller]" : requirer)
6255                            + " requires " + requiredInstructionSet + " whereas " + ps
6256                            + " requires " + instructionSet;
6257                    Slog.w(TAG, errorMessage);
6258                }
6259
6260                if (requiredInstructionSet == null) {
6261                    requiredInstructionSet = instructionSet;
6262                    requirer = ps;
6263                }
6264            }
6265        }
6266
6267        if (requiredInstructionSet != null) {
6268            String adjustedAbi;
6269            if (requirer != null) {
6270                // requirer != null implies that either scannedPackage was null or that scannedPackage
6271                // did not require an ABI, in which case we have to adjust scannedPackage to match
6272                // the ABI of the set (which is the same as requirer's ABI)
6273                adjustedAbi = requirer.primaryCpuAbiString;
6274                if (scannedPackage != null) {
6275                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6276                }
6277            } else {
6278                // requirer == null implies that we're updating all ABIs in the set to
6279                // match scannedPackage.
6280                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6281            }
6282
6283            for (PackageSetting ps : packagesForUser) {
6284                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6285                    if (ps.primaryCpuAbiString != null) {
6286                        continue;
6287                    }
6288
6289                    ps.primaryCpuAbiString = adjustedAbi;
6290                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6291                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6292                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6293
6294                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6295                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6296                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6297                            ps.primaryCpuAbiString = null;
6298                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6299                            return;
6300                        } else {
6301                            mInstaller.rmdex(ps.codePathString,
6302                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6303                        }
6304                    }
6305                }
6306            }
6307        }
6308    }
6309
6310    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6311        synchronized (mPackages) {
6312            mResolverReplaced = true;
6313            // Set up information for custom user intent resolution activity.
6314            mResolveActivity.applicationInfo = pkg.applicationInfo;
6315            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6316            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6317            mResolveActivity.processName = pkg.applicationInfo.packageName;
6318            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6319            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6320                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6321            mResolveActivity.theme = 0;
6322            mResolveActivity.exported = true;
6323            mResolveActivity.enabled = true;
6324            mResolveInfo.activityInfo = mResolveActivity;
6325            mResolveInfo.priority = 0;
6326            mResolveInfo.preferredOrder = 0;
6327            mResolveInfo.match = 0;
6328            mResolveComponentName = mCustomResolverComponentName;
6329            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6330                    mResolveComponentName);
6331        }
6332    }
6333
6334    private static String calculateBundledApkRoot(final String codePathString) {
6335        final File codePath = new File(codePathString);
6336        final File codeRoot;
6337        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6338            codeRoot = Environment.getRootDirectory();
6339        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6340            codeRoot = Environment.getOemDirectory();
6341        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6342            codeRoot = Environment.getVendorDirectory();
6343        } else {
6344            // Unrecognized code path; take its top real segment as the apk root:
6345            // e.g. /something/app/blah.apk => /something
6346            try {
6347                File f = codePath.getCanonicalFile();
6348                File parent = f.getParentFile();    // non-null because codePath is a file
6349                File tmp;
6350                while ((tmp = parent.getParentFile()) != null) {
6351                    f = parent;
6352                    parent = tmp;
6353                }
6354                codeRoot = f;
6355                Slog.w(TAG, "Unrecognized code path "
6356                        + codePath + " - using " + codeRoot);
6357            } catch (IOException e) {
6358                // Can't canonicalize the code path -- shenanigans?
6359                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6360                return Environment.getRootDirectory().getPath();
6361            }
6362        }
6363        return codeRoot.getPath();
6364    }
6365
6366    /**
6367     * Derive and set the location of native libraries for the given package,
6368     * which varies depending on where and how the package was installed.
6369     */
6370    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6371        final ApplicationInfo info = pkg.applicationInfo;
6372        final String codePath = pkg.codePath;
6373        final File codeFile = new File(codePath);
6374        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6375        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6376
6377        info.nativeLibraryRootDir = null;
6378        info.nativeLibraryRootRequiresIsa = false;
6379        info.nativeLibraryDir = null;
6380        info.secondaryNativeLibraryDir = null;
6381
6382        if (isApkFile(codeFile)) {
6383            // Monolithic install
6384            if (bundledApp) {
6385                // If "/system/lib64/apkname" exists, assume that is the per-package
6386                // native library directory to use; otherwise use "/system/lib/apkname".
6387                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6388                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6389                        getPrimaryInstructionSet(info));
6390
6391                // This is a bundled system app so choose the path based on the ABI.
6392                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6393                // is just the default path.
6394                final String apkName = deriveCodePathName(codePath);
6395                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6396                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6397                        apkName).getAbsolutePath();
6398
6399                if (info.secondaryCpuAbi != null) {
6400                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6401                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6402                            secondaryLibDir, apkName).getAbsolutePath();
6403                }
6404            } else if (asecApp) {
6405                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6406                        .getAbsolutePath();
6407            } else {
6408                final String apkName = deriveCodePathName(codePath);
6409                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6410                        .getAbsolutePath();
6411            }
6412
6413            info.nativeLibraryRootRequiresIsa = false;
6414            info.nativeLibraryDir = info.nativeLibraryRootDir;
6415        } else {
6416            // Cluster install
6417            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6418            info.nativeLibraryRootRequiresIsa = true;
6419
6420            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6421                    getPrimaryInstructionSet(info)).getAbsolutePath();
6422
6423            if (info.secondaryCpuAbi != null) {
6424                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6425                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6426            }
6427        }
6428    }
6429
6430    /**
6431     * Calculate the abis and roots for a bundled app. These can uniquely
6432     * be determined from the contents of the system partition, i.e whether
6433     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6434     * of this information, and instead assume that the system was built
6435     * sensibly.
6436     */
6437    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6438                                           PackageSetting pkgSetting) {
6439        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6440
6441        // If "/system/lib64/apkname" exists, assume that is the per-package
6442        // native library directory to use; otherwise use "/system/lib/apkname".
6443        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6444        setBundledAppAbi(pkg, apkRoot, apkName);
6445        // pkgSetting might be null during rescan following uninstall of updates
6446        // to a bundled app, so accommodate that possibility.  The settings in
6447        // that case will be established later from the parsed package.
6448        //
6449        // If the settings aren't null, sync them up with what we've just derived.
6450        // note that apkRoot isn't stored in the package settings.
6451        if (pkgSetting != null) {
6452            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6453            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6454        }
6455    }
6456
6457    /**
6458     * Deduces the ABI of a bundled app and sets the relevant fields on the
6459     * parsed pkg object.
6460     *
6461     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6462     *        under which system libraries are installed.
6463     * @param apkName the name of the installed package.
6464     */
6465    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6466        final File codeFile = new File(pkg.codePath);
6467
6468        final boolean has64BitLibs;
6469        final boolean has32BitLibs;
6470        if (isApkFile(codeFile)) {
6471            // Monolithic install
6472            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6473            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6474        } else {
6475            // Cluster install
6476            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6477            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6478                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6479                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6480                has64BitLibs = (new File(rootDir, isa)).exists();
6481            } else {
6482                has64BitLibs = false;
6483            }
6484            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6485                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6486                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6487                has32BitLibs = (new File(rootDir, isa)).exists();
6488            } else {
6489                has32BitLibs = false;
6490            }
6491        }
6492
6493        if (has64BitLibs && !has32BitLibs) {
6494            // The package has 64 bit libs, but not 32 bit libs. Its primary
6495            // ABI should be 64 bit. We can safely assume here that the bundled
6496            // native libraries correspond to the most preferred ABI in the list.
6497
6498            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6499            pkg.applicationInfo.secondaryCpuAbi = null;
6500        } else if (has32BitLibs && !has64BitLibs) {
6501            // The package has 32 bit libs but not 64 bit libs. Its primary
6502            // ABI should be 32 bit.
6503
6504            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6505            pkg.applicationInfo.secondaryCpuAbi = null;
6506        } else if (has32BitLibs && has64BitLibs) {
6507            // The application has both 64 and 32 bit bundled libraries. We check
6508            // here that the app declares multiArch support, and warn if it doesn't.
6509            //
6510            // We will be lenient here and record both ABIs. The primary will be the
6511            // ABI that's higher on the list, i.e, a device that's configured to prefer
6512            // 64 bit apps will see a 64 bit primary ABI,
6513
6514            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6515                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6516            }
6517
6518            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6519                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6520                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6521            } else {
6522                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6523                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6524            }
6525        } else {
6526            pkg.applicationInfo.primaryCpuAbi = null;
6527            pkg.applicationInfo.secondaryCpuAbi = null;
6528        }
6529    }
6530
6531    private void killApplication(String pkgName, int appId, String reason) {
6532        // Request the ActivityManager to kill the process(only for existing packages)
6533        // so that we do not end up in a confused state while the user is still using the older
6534        // version of the application while the new one gets installed.
6535        IActivityManager am = ActivityManagerNative.getDefault();
6536        if (am != null) {
6537            try {
6538                am.killApplicationWithAppId(pkgName, appId, reason);
6539            } catch (RemoteException e) {
6540            }
6541        }
6542    }
6543
6544    void removePackageLI(PackageSetting ps, boolean chatty) {
6545        if (DEBUG_INSTALL) {
6546            if (chatty)
6547                Log.d(TAG, "Removing package " + ps.name);
6548        }
6549
6550        // writer
6551        synchronized (mPackages) {
6552            mPackages.remove(ps.name);
6553            final PackageParser.Package pkg = ps.pkg;
6554            if (pkg != null) {
6555                cleanPackageDataStructuresLILPw(pkg, chatty);
6556            }
6557        }
6558    }
6559
6560    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6561        if (DEBUG_INSTALL) {
6562            if (chatty)
6563                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6564        }
6565
6566        // writer
6567        synchronized (mPackages) {
6568            mPackages.remove(pkg.applicationInfo.packageName);
6569            cleanPackageDataStructuresLILPw(pkg, chatty);
6570        }
6571    }
6572
6573    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6574        int N = pkg.providers.size();
6575        StringBuilder r = null;
6576        int i;
6577        for (i=0; i<N; i++) {
6578            PackageParser.Provider p = pkg.providers.get(i);
6579            mProviders.removeProvider(p);
6580            if (p.info.authority == null) {
6581
6582                /* There was another ContentProvider with this authority when
6583                 * this app was installed so this authority is null,
6584                 * Ignore it as we don't have to unregister the provider.
6585                 */
6586                continue;
6587            }
6588            String names[] = p.info.authority.split(";");
6589            for (int j = 0; j < names.length; j++) {
6590                if (mProvidersByAuthority.get(names[j]) == p) {
6591                    mProvidersByAuthority.remove(names[j]);
6592                    if (DEBUG_REMOVE) {
6593                        if (chatty)
6594                            Log.d(TAG, "Unregistered content provider: " + names[j]
6595                                    + ", className = " + p.info.name + ", isSyncable = "
6596                                    + p.info.isSyncable);
6597                    }
6598                }
6599            }
6600            if (DEBUG_REMOVE && chatty) {
6601                if (r == null) {
6602                    r = new StringBuilder(256);
6603                } else {
6604                    r.append(' ');
6605                }
6606                r.append(p.info.name);
6607            }
6608        }
6609        if (r != null) {
6610            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6611        }
6612
6613        N = pkg.services.size();
6614        r = null;
6615        for (i=0; i<N; i++) {
6616            PackageParser.Service s = pkg.services.get(i);
6617            mServices.removeService(s);
6618            if (chatty) {
6619                if (r == null) {
6620                    r = new StringBuilder(256);
6621                } else {
6622                    r.append(' ');
6623                }
6624                r.append(s.info.name);
6625            }
6626        }
6627        if (r != null) {
6628            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6629        }
6630
6631        N = pkg.receivers.size();
6632        r = null;
6633        for (i=0; i<N; i++) {
6634            PackageParser.Activity a = pkg.receivers.get(i);
6635            mReceivers.removeActivity(a, "receiver");
6636            if (DEBUG_REMOVE && chatty) {
6637                if (r == null) {
6638                    r = new StringBuilder(256);
6639                } else {
6640                    r.append(' ');
6641                }
6642                r.append(a.info.name);
6643            }
6644        }
6645        if (r != null) {
6646            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6647        }
6648
6649        N = pkg.activities.size();
6650        r = null;
6651        for (i=0; i<N; i++) {
6652            PackageParser.Activity a = pkg.activities.get(i);
6653            mActivities.removeActivity(a, "activity");
6654            if (DEBUG_REMOVE && chatty) {
6655                if (r == null) {
6656                    r = new StringBuilder(256);
6657                } else {
6658                    r.append(' ');
6659                }
6660                r.append(a.info.name);
6661            }
6662        }
6663        if (r != null) {
6664            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6665        }
6666
6667        N = pkg.permissions.size();
6668        r = null;
6669        for (i=0; i<N; i++) {
6670            PackageParser.Permission p = pkg.permissions.get(i);
6671            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6672            if (bp == null) {
6673                bp = mSettings.mPermissionTrees.get(p.info.name);
6674            }
6675            if (bp != null && bp.perm == p) {
6676                bp.perm = null;
6677                if (DEBUG_REMOVE && chatty) {
6678                    if (r == null) {
6679                        r = new StringBuilder(256);
6680                    } else {
6681                        r.append(' ');
6682                    }
6683                    r.append(p.info.name);
6684                }
6685            }
6686            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6687                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6688                if (appOpPerms != null) {
6689                    appOpPerms.remove(pkg.packageName);
6690                }
6691            }
6692        }
6693        if (r != null) {
6694            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6695        }
6696
6697        N = pkg.requestedPermissions.size();
6698        r = null;
6699        for (i=0; i<N; i++) {
6700            String perm = pkg.requestedPermissions.get(i);
6701            BasePermission bp = mSettings.mPermissions.get(perm);
6702            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6703                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6704                if (appOpPerms != null) {
6705                    appOpPerms.remove(pkg.packageName);
6706                    if (appOpPerms.isEmpty()) {
6707                        mAppOpPermissionPackages.remove(perm);
6708                    }
6709                }
6710            }
6711        }
6712        if (r != null) {
6713            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6714        }
6715
6716        N = pkg.instrumentation.size();
6717        r = null;
6718        for (i=0; i<N; i++) {
6719            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6720            mInstrumentation.remove(a.getComponentName());
6721            if (DEBUG_REMOVE && chatty) {
6722                if (r == null) {
6723                    r = new StringBuilder(256);
6724                } else {
6725                    r.append(' ');
6726                }
6727                r.append(a.info.name);
6728            }
6729        }
6730        if (r != null) {
6731            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6732        }
6733
6734        r = null;
6735        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6736            // Only system apps can hold shared libraries.
6737            if (pkg.libraryNames != null) {
6738                for (i=0; i<pkg.libraryNames.size(); i++) {
6739                    String name = pkg.libraryNames.get(i);
6740                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6741                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6742                        mSharedLibraries.remove(name);
6743                        if (DEBUG_REMOVE && chatty) {
6744                            if (r == null) {
6745                                r = new StringBuilder(256);
6746                            } else {
6747                                r.append(' ');
6748                            }
6749                            r.append(name);
6750                        }
6751                    }
6752                }
6753            }
6754        }
6755        if (r != null) {
6756            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6757        }
6758    }
6759
6760    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6761        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6762            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6763                return true;
6764            }
6765        }
6766        return false;
6767    }
6768
6769    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6770    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6771    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6772
6773    private void updatePermissionsLPw(String changingPkg,
6774            PackageParser.Package pkgInfo, int flags) {
6775        // Make sure there are no dangling permission trees.
6776        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6777        while (it.hasNext()) {
6778            final BasePermission bp = it.next();
6779            if (bp.packageSetting == null) {
6780                // We may not yet have parsed the package, so just see if
6781                // we still know about its settings.
6782                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6783            }
6784            if (bp.packageSetting == null) {
6785                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6786                        + " from package " + bp.sourcePackage);
6787                it.remove();
6788            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6789                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6790                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6791                            + " from package " + bp.sourcePackage);
6792                    flags |= UPDATE_PERMISSIONS_ALL;
6793                    it.remove();
6794                }
6795            }
6796        }
6797
6798        // Make sure all dynamic permissions have been assigned to a package,
6799        // and make sure there are no dangling permissions.
6800        it = mSettings.mPermissions.values().iterator();
6801        while (it.hasNext()) {
6802            final BasePermission bp = it.next();
6803            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6804                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6805                        + bp.name + " pkg=" + bp.sourcePackage
6806                        + " info=" + bp.pendingInfo);
6807                if (bp.packageSetting == null && bp.pendingInfo != null) {
6808                    final BasePermission tree = findPermissionTreeLP(bp.name);
6809                    if (tree != null && tree.perm != null) {
6810                        bp.packageSetting = tree.packageSetting;
6811                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6812                                new PermissionInfo(bp.pendingInfo));
6813                        bp.perm.info.packageName = tree.perm.info.packageName;
6814                        bp.perm.info.name = bp.name;
6815                        bp.uid = tree.uid;
6816                    }
6817                }
6818            }
6819            if (bp.packageSetting == null) {
6820                // We may not yet have parsed the package, so just see if
6821                // we still know about its settings.
6822                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6823            }
6824            if (bp.packageSetting == null) {
6825                Slog.w(TAG, "Removing dangling permission: " + bp.name
6826                        + " from package " + bp.sourcePackage);
6827                it.remove();
6828            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6829                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6830                    Slog.i(TAG, "Removing old permission: " + bp.name
6831                            + " from package " + bp.sourcePackage);
6832                    flags |= UPDATE_PERMISSIONS_ALL;
6833                    it.remove();
6834                }
6835            }
6836        }
6837
6838        // Now update the permissions for all packages, in particular
6839        // replace the granted permissions of the system packages.
6840        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6841            for (PackageParser.Package pkg : mPackages.values()) {
6842                if (pkg != pkgInfo) {
6843                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6844                            changingPkg);
6845                }
6846            }
6847        }
6848
6849        if (pkgInfo != null) {
6850            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6851        }
6852    }
6853
6854    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6855            String packageOfInterest) {
6856        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6857        if (ps == null) {
6858            return;
6859        }
6860        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6861        ArraySet<String> origPermissions = gp.grantedPermissions;
6862        boolean changedPermission = false;
6863
6864        if (replace) {
6865            ps.permissionsFixed = false;
6866            if (gp == ps) {
6867                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6868                gp.grantedPermissions.clear();
6869                gp.gids = mGlobalGids;
6870            }
6871        }
6872
6873        if (gp.gids == null) {
6874            gp.gids = mGlobalGids;
6875        }
6876
6877        final int N = pkg.requestedPermissions.size();
6878        for (int i=0; i<N; i++) {
6879            final String name = pkg.requestedPermissions.get(i);
6880            final boolean required = pkg.requestedPermissionsRequired.get(i);
6881            final BasePermission bp = mSettings.mPermissions.get(name);
6882            if (DEBUG_INSTALL) {
6883                if (gp != ps) {
6884                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6885                }
6886            }
6887
6888            if (bp == null || bp.packageSetting == null) {
6889                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6890                    Slog.w(TAG, "Unknown permission " + name
6891                            + " in package " + pkg.packageName);
6892                }
6893                continue;
6894            }
6895
6896            final String perm = bp.name;
6897            boolean allowed;
6898            boolean allowedSig = false;
6899            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6900                // Keep track of app op permissions.
6901                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6902                if (pkgs == null) {
6903                    pkgs = new ArraySet<>();
6904                    mAppOpPermissionPackages.put(bp.name, pkgs);
6905                }
6906                pkgs.add(pkg.packageName);
6907            }
6908            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6909            if (level == PermissionInfo.PROTECTION_NORMAL
6910                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6911                // We grant a normal or dangerous permission if any of the following
6912                // are true:
6913                // 1) The permission is required
6914                // 2) The permission is optional, but was granted in the past
6915                // 3) The permission is optional, but was requested by an
6916                //    app in /system (not /data)
6917                //
6918                // Otherwise, reject the permission.
6919                allowed = (required || origPermissions.contains(perm)
6920                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6921            } else if (bp.packageSetting == null) {
6922                // This permission is invalid; skip it.
6923                allowed = false;
6924            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6925                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6926                if (allowed) {
6927                    allowedSig = true;
6928                }
6929            } else {
6930                allowed = false;
6931            }
6932            if (DEBUG_INSTALL) {
6933                if (gp != ps) {
6934                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6935                }
6936            }
6937            if (allowed) {
6938                if (!isSystemApp(ps) && ps.permissionsFixed) {
6939                    // If this is an existing, non-system package, then
6940                    // we can't add any new permissions to it.
6941                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6942                        // Except...  if this is a permission that was added
6943                        // to the platform (note: need to only do this when
6944                        // updating the platform).
6945                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6946                    }
6947                }
6948                if (allowed) {
6949                    if (!gp.grantedPermissions.contains(perm)) {
6950                        changedPermission = true;
6951                        gp.grantedPermissions.add(perm);
6952                        gp.gids = appendInts(gp.gids, bp.gids);
6953                    } else if (!ps.haveGids) {
6954                        gp.gids = appendInts(gp.gids, bp.gids);
6955                    }
6956                } else {
6957                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6958                        Slog.w(TAG, "Not granting permission " + perm
6959                                + " to package " + pkg.packageName
6960                                + " because it was previously installed without");
6961                    }
6962                }
6963            } else {
6964                if (gp.grantedPermissions.remove(perm)) {
6965                    changedPermission = true;
6966                    gp.gids = removeInts(gp.gids, bp.gids);
6967                    Slog.i(TAG, "Un-granting permission " + perm
6968                            + " from package " + pkg.packageName
6969                            + " (protectionLevel=" + bp.protectionLevel
6970                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6971                            + ")");
6972                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6973                    // Don't print warning for app op permissions, since it is fine for them
6974                    // not to be granted, there is a UI for the user to decide.
6975                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6976                        Slog.w(TAG, "Not granting permission " + perm
6977                                + " to package " + pkg.packageName
6978                                + " (protectionLevel=" + bp.protectionLevel
6979                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6980                                + ")");
6981                    }
6982                }
6983            }
6984        }
6985
6986        if ((changedPermission || replace) && !ps.permissionsFixed &&
6987                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6988            // This is the first that we have heard about this package, so the
6989            // permissions we have now selected are fixed until explicitly
6990            // changed.
6991            ps.permissionsFixed = true;
6992        }
6993        ps.haveGids = true;
6994    }
6995
6996    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6997        boolean allowed = false;
6998        final int NP = PackageParser.NEW_PERMISSIONS.length;
6999        for (int ip=0; ip<NP; ip++) {
7000            final PackageParser.NewPermissionInfo npi
7001                    = PackageParser.NEW_PERMISSIONS[ip];
7002            if (npi.name.equals(perm)
7003                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7004                allowed = true;
7005                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7006                        + pkg.packageName);
7007                break;
7008            }
7009        }
7010        return allowed;
7011    }
7012
7013    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7014                                          BasePermission bp, ArraySet<String> origPermissions) {
7015        boolean allowed;
7016        allowed = (compareSignatures(
7017                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7018                        == PackageManager.SIGNATURE_MATCH)
7019                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7020                        == PackageManager.SIGNATURE_MATCH);
7021        if (!allowed && (bp.protectionLevel
7022                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7023            if (isSystemApp(pkg)) {
7024                // For updated system applications, a system permission
7025                // is granted only if it had been defined by the original application.
7026                if (isUpdatedSystemApp(pkg)) {
7027                    final PackageSetting sysPs = mSettings
7028                            .getDisabledSystemPkgLPr(pkg.packageName);
7029                    final GrantedPermissions origGp = sysPs.sharedUser != null
7030                            ? sysPs.sharedUser : sysPs;
7031
7032                    if (origGp.grantedPermissions.contains(perm)) {
7033                        // If the original was granted this permission, we take
7034                        // that grant decision as read and propagate it to the
7035                        // update.
7036                        if (sysPs.isPrivileged()) {
7037                            allowed = true;
7038                        }
7039                    } else {
7040                        // The system apk may have been updated with an older
7041                        // version of the one on the data partition, but which
7042                        // granted a new system permission that it didn't have
7043                        // before.  In this case we do want to allow the app to
7044                        // now get the new permission if the ancestral apk is
7045                        // privileged to get it.
7046                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7047                            for (int j=0;
7048                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7049                                if (perm.equals(
7050                                        sysPs.pkg.requestedPermissions.get(j))) {
7051                                    allowed = true;
7052                                    break;
7053                                }
7054                            }
7055                        }
7056                    }
7057                } else {
7058                    allowed = isPrivilegedApp(pkg);
7059                }
7060            }
7061        }
7062        if (!allowed && (bp.protectionLevel
7063                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7064            // For development permissions, a development permission
7065            // is granted only if it was already granted.
7066            allowed = origPermissions.contains(perm);
7067        }
7068        return allowed;
7069    }
7070
7071    final class ActivityIntentResolver
7072            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7073        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7074                boolean defaultOnly, int userId) {
7075            if (!sUserManager.exists(userId)) return null;
7076            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7077            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7078        }
7079
7080        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7081                int userId) {
7082            if (!sUserManager.exists(userId)) return null;
7083            mFlags = flags;
7084            return super.queryIntent(intent, resolvedType,
7085                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7086        }
7087
7088        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7089                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7090            if (!sUserManager.exists(userId)) return null;
7091            if (packageActivities == null) {
7092                return null;
7093            }
7094            mFlags = flags;
7095            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7096            final int N = packageActivities.size();
7097            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7098                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7099
7100            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7101            for (int i = 0; i < N; ++i) {
7102                intentFilters = packageActivities.get(i).intents;
7103                if (intentFilters != null && intentFilters.size() > 0) {
7104                    PackageParser.ActivityIntentInfo[] array =
7105                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7106                    intentFilters.toArray(array);
7107                    listCut.add(array);
7108                }
7109            }
7110            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7111        }
7112
7113        public final void addActivity(PackageParser.Activity a, String type) {
7114            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7115            mActivities.put(a.getComponentName(), a);
7116            if (DEBUG_SHOW_INFO)
7117                Log.v(
7118                TAG, "  " + type + " " +
7119                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7120            if (DEBUG_SHOW_INFO)
7121                Log.v(TAG, "    Class=" + a.info.name);
7122            final int NI = a.intents.size();
7123            for (int j=0; j<NI; j++) {
7124                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7125                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7126                    intent.setPriority(0);
7127                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7128                            + a.className + " with priority > 0, forcing to 0");
7129                }
7130                if (DEBUG_SHOW_INFO) {
7131                    Log.v(TAG, "    IntentFilter:");
7132                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7133                }
7134                if (!intent.debugCheck()) {
7135                    Log.w(TAG, "==> For Activity " + a.info.name);
7136                }
7137                addFilter(intent);
7138            }
7139        }
7140
7141        public final void removeActivity(PackageParser.Activity a, String type) {
7142            mActivities.remove(a.getComponentName());
7143            if (DEBUG_SHOW_INFO) {
7144                Log.v(TAG, "  " + type + " "
7145                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7146                                : a.info.name) + ":");
7147                Log.v(TAG, "    Class=" + a.info.name);
7148            }
7149            final int NI = a.intents.size();
7150            for (int j=0; j<NI; j++) {
7151                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7152                if (DEBUG_SHOW_INFO) {
7153                    Log.v(TAG, "    IntentFilter:");
7154                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7155                }
7156                removeFilter(intent);
7157            }
7158        }
7159
7160        @Override
7161        protected boolean allowFilterResult(
7162                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7163            ActivityInfo filterAi = filter.activity.info;
7164            for (int i=dest.size()-1; i>=0; i--) {
7165                ActivityInfo destAi = dest.get(i).activityInfo;
7166                if (destAi.name == filterAi.name
7167                        && destAi.packageName == filterAi.packageName) {
7168                    return false;
7169                }
7170            }
7171            return true;
7172        }
7173
7174        @Override
7175        protected ActivityIntentInfo[] newArray(int size) {
7176            return new ActivityIntentInfo[size];
7177        }
7178
7179        @Override
7180        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7181            if (!sUserManager.exists(userId)) return true;
7182            PackageParser.Package p = filter.activity.owner;
7183            if (p != null) {
7184                PackageSetting ps = (PackageSetting)p.mExtras;
7185                if (ps != null) {
7186                    // System apps are never considered stopped for purposes of
7187                    // filtering, because there may be no way for the user to
7188                    // actually re-launch them.
7189                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7190                            && ps.getStopped(userId);
7191                }
7192            }
7193            return false;
7194        }
7195
7196        @Override
7197        protected boolean isPackageForFilter(String packageName,
7198                PackageParser.ActivityIntentInfo info) {
7199            return packageName.equals(info.activity.owner.packageName);
7200        }
7201
7202        @Override
7203        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7204                int match, int userId) {
7205            if (!sUserManager.exists(userId)) return null;
7206            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7207                return null;
7208            }
7209            final PackageParser.Activity activity = info.activity;
7210            if (mSafeMode && (activity.info.applicationInfo.flags
7211                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7212                return null;
7213            }
7214            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7215            if (ps == null) {
7216                return null;
7217            }
7218            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7219                    ps.readUserState(userId), userId);
7220            if (ai == null) {
7221                return null;
7222            }
7223            final ResolveInfo res = new ResolveInfo();
7224            res.activityInfo = ai;
7225            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7226                res.filter = info;
7227            }
7228            res.priority = info.getPriority();
7229            res.preferredOrder = activity.owner.mPreferredOrder;
7230            //System.out.println("Result: " + res.activityInfo.className +
7231            //                   " = " + res.priority);
7232            res.match = match;
7233            res.isDefault = info.hasDefault;
7234            res.labelRes = info.labelRes;
7235            res.nonLocalizedLabel = info.nonLocalizedLabel;
7236            if (userNeedsBadging(userId)) {
7237                res.noResourceId = true;
7238            } else {
7239                res.icon = info.icon;
7240            }
7241            res.system = isSystemApp(res.activityInfo.applicationInfo);
7242            return res;
7243        }
7244
7245        @Override
7246        protected void sortResults(List<ResolveInfo> results) {
7247            Collections.sort(results, mResolvePrioritySorter);
7248        }
7249
7250        @Override
7251        protected void dumpFilter(PrintWriter out, String prefix,
7252                PackageParser.ActivityIntentInfo filter) {
7253            out.print(prefix); out.print(
7254                    Integer.toHexString(System.identityHashCode(filter.activity)));
7255                    out.print(' ');
7256                    filter.activity.printComponentShortName(out);
7257                    out.print(" filter ");
7258                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7259        }
7260
7261        @Override
7262        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7263            return filter.activity;
7264        }
7265
7266        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7267            PackageParser.Activity activity = (PackageParser.Activity)label;
7268            out.print(prefix); out.print(
7269                    Integer.toHexString(System.identityHashCode(activity)));
7270                    out.print(' ');
7271                    activity.printComponentShortName(out);
7272            if (count > 1) {
7273                out.print(" ("); out.print(count); out.print(" filters)");
7274            }
7275            out.println();
7276        }
7277
7278//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7279//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7280//            final List<ResolveInfo> retList = Lists.newArrayList();
7281//            while (i.hasNext()) {
7282//                final ResolveInfo resolveInfo = i.next();
7283//                if (isEnabledLP(resolveInfo.activityInfo)) {
7284//                    retList.add(resolveInfo);
7285//                }
7286//            }
7287//            return retList;
7288//        }
7289
7290        // Keys are String (activity class name), values are Activity.
7291        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7292                = new ArrayMap<ComponentName, PackageParser.Activity>();
7293        private int mFlags;
7294    }
7295
7296    private final class ServiceIntentResolver
7297            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7298        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7299                boolean defaultOnly, int userId) {
7300            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7301            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7302        }
7303
7304        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7305                int userId) {
7306            if (!sUserManager.exists(userId)) return null;
7307            mFlags = flags;
7308            return super.queryIntent(intent, resolvedType,
7309                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7310        }
7311
7312        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7313                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7314            if (!sUserManager.exists(userId)) return null;
7315            if (packageServices == null) {
7316                return null;
7317            }
7318            mFlags = flags;
7319            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7320            final int N = packageServices.size();
7321            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7322                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7323
7324            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7325            for (int i = 0; i < N; ++i) {
7326                intentFilters = packageServices.get(i).intents;
7327                if (intentFilters != null && intentFilters.size() > 0) {
7328                    PackageParser.ServiceIntentInfo[] array =
7329                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7330                    intentFilters.toArray(array);
7331                    listCut.add(array);
7332                }
7333            }
7334            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7335        }
7336
7337        public final void addService(PackageParser.Service s) {
7338            mServices.put(s.getComponentName(), s);
7339            if (DEBUG_SHOW_INFO) {
7340                Log.v(TAG, "  "
7341                        + (s.info.nonLocalizedLabel != null
7342                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7343                Log.v(TAG, "    Class=" + s.info.name);
7344            }
7345            final int NI = s.intents.size();
7346            int j;
7347            for (j=0; j<NI; j++) {
7348                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7349                if (DEBUG_SHOW_INFO) {
7350                    Log.v(TAG, "    IntentFilter:");
7351                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7352                }
7353                if (!intent.debugCheck()) {
7354                    Log.w(TAG, "==> For Service " + s.info.name);
7355                }
7356                addFilter(intent);
7357            }
7358        }
7359
7360        public final void removeService(PackageParser.Service s) {
7361            mServices.remove(s.getComponentName());
7362            if (DEBUG_SHOW_INFO) {
7363                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7364                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7365                Log.v(TAG, "    Class=" + s.info.name);
7366            }
7367            final int NI = s.intents.size();
7368            int j;
7369            for (j=0; j<NI; j++) {
7370                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7371                if (DEBUG_SHOW_INFO) {
7372                    Log.v(TAG, "    IntentFilter:");
7373                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7374                }
7375                removeFilter(intent);
7376            }
7377        }
7378
7379        @Override
7380        protected boolean allowFilterResult(
7381                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7382            ServiceInfo filterSi = filter.service.info;
7383            for (int i=dest.size()-1; i>=0; i--) {
7384                ServiceInfo destAi = dest.get(i).serviceInfo;
7385                if (destAi.name == filterSi.name
7386                        && destAi.packageName == filterSi.packageName) {
7387                    return false;
7388                }
7389            }
7390            return true;
7391        }
7392
7393        @Override
7394        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7395            return new PackageParser.ServiceIntentInfo[size];
7396        }
7397
7398        @Override
7399        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7400            if (!sUserManager.exists(userId)) return true;
7401            PackageParser.Package p = filter.service.owner;
7402            if (p != null) {
7403                PackageSetting ps = (PackageSetting)p.mExtras;
7404                if (ps != null) {
7405                    // System apps are never considered stopped for purposes of
7406                    // filtering, because there may be no way for the user to
7407                    // actually re-launch them.
7408                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7409                            && ps.getStopped(userId);
7410                }
7411            }
7412            return false;
7413        }
7414
7415        @Override
7416        protected boolean isPackageForFilter(String packageName,
7417                PackageParser.ServiceIntentInfo info) {
7418            return packageName.equals(info.service.owner.packageName);
7419        }
7420
7421        @Override
7422        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7423                int match, int userId) {
7424            if (!sUserManager.exists(userId)) return null;
7425            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7426            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7427                return null;
7428            }
7429            final PackageParser.Service service = info.service;
7430            if (mSafeMode && (service.info.applicationInfo.flags
7431                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7432                return null;
7433            }
7434            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7435            if (ps == null) {
7436                return null;
7437            }
7438            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7439                    ps.readUserState(userId), userId);
7440            if (si == null) {
7441                return null;
7442            }
7443            final ResolveInfo res = new ResolveInfo();
7444            res.serviceInfo = si;
7445            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7446                res.filter = filter;
7447            }
7448            res.priority = info.getPriority();
7449            res.preferredOrder = service.owner.mPreferredOrder;
7450            //System.out.println("Result: " + res.activityInfo.className +
7451            //                   " = " + res.priority);
7452            res.match = match;
7453            res.isDefault = info.hasDefault;
7454            res.labelRes = info.labelRes;
7455            res.nonLocalizedLabel = info.nonLocalizedLabel;
7456            res.icon = info.icon;
7457            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7458            return res;
7459        }
7460
7461        @Override
7462        protected void sortResults(List<ResolveInfo> results) {
7463            Collections.sort(results, mResolvePrioritySorter);
7464        }
7465
7466        @Override
7467        protected void dumpFilter(PrintWriter out, String prefix,
7468                PackageParser.ServiceIntentInfo filter) {
7469            out.print(prefix); out.print(
7470                    Integer.toHexString(System.identityHashCode(filter.service)));
7471                    out.print(' ');
7472                    filter.service.printComponentShortName(out);
7473                    out.print(" filter ");
7474                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7475        }
7476
7477        @Override
7478        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7479            return filter.service;
7480        }
7481
7482        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7483            PackageParser.Service service = (PackageParser.Service)label;
7484            out.print(prefix); out.print(
7485                    Integer.toHexString(System.identityHashCode(service)));
7486                    out.print(' ');
7487                    service.printComponentShortName(out);
7488            if (count > 1) {
7489                out.print(" ("); out.print(count); out.print(" filters)");
7490            }
7491            out.println();
7492        }
7493
7494//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7495//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7496//            final List<ResolveInfo> retList = Lists.newArrayList();
7497//            while (i.hasNext()) {
7498//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7499//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7500//                    retList.add(resolveInfo);
7501//                }
7502//            }
7503//            return retList;
7504//        }
7505
7506        // Keys are String (activity class name), values are Activity.
7507        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7508                = new ArrayMap<ComponentName, PackageParser.Service>();
7509        private int mFlags;
7510    };
7511
7512    private final class ProviderIntentResolver
7513            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7515                boolean defaultOnly, int userId) {
7516            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7517            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7518        }
7519
7520        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7521                int userId) {
7522            if (!sUserManager.exists(userId))
7523                return null;
7524            mFlags = flags;
7525            return super.queryIntent(intent, resolvedType,
7526                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7527        }
7528
7529        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7530                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7531            if (!sUserManager.exists(userId))
7532                return null;
7533            if (packageProviders == null) {
7534                return null;
7535            }
7536            mFlags = flags;
7537            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7538            final int N = packageProviders.size();
7539            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7540                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7541
7542            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7543            for (int i = 0; i < N; ++i) {
7544                intentFilters = packageProviders.get(i).intents;
7545                if (intentFilters != null && intentFilters.size() > 0) {
7546                    PackageParser.ProviderIntentInfo[] array =
7547                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7548                    intentFilters.toArray(array);
7549                    listCut.add(array);
7550                }
7551            }
7552            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7553        }
7554
7555        public final void addProvider(PackageParser.Provider p) {
7556            if (mProviders.containsKey(p.getComponentName())) {
7557                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7558                return;
7559            }
7560
7561            mProviders.put(p.getComponentName(), p);
7562            if (DEBUG_SHOW_INFO) {
7563                Log.v(TAG, "  "
7564                        + (p.info.nonLocalizedLabel != null
7565                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7566                Log.v(TAG, "    Class=" + p.info.name);
7567            }
7568            final int NI = p.intents.size();
7569            int j;
7570            for (j = 0; j < NI; j++) {
7571                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7572                if (DEBUG_SHOW_INFO) {
7573                    Log.v(TAG, "    IntentFilter:");
7574                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7575                }
7576                if (!intent.debugCheck()) {
7577                    Log.w(TAG, "==> For Provider " + p.info.name);
7578                }
7579                addFilter(intent);
7580            }
7581        }
7582
7583        public final void removeProvider(PackageParser.Provider p) {
7584            mProviders.remove(p.getComponentName());
7585            if (DEBUG_SHOW_INFO) {
7586                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7587                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7588                Log.v(TAG, "    Class=" + p.info.name);
7589            }
7590            final int NI = p.intents.size();
7591            int j;
7592            for (j = 0; j < NI; j++) {
7593                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7594                if (DEBUG_SHOW_INFO) {
7595                    Log.v(TAG, "    IntentFilter:");
7596                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7597                }
7598                removeFilter(intent);
7599            }
7600        }
7601
7602        @Override
7603        protected boolean allowFilterResult(
7604                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7605            ProviderInfo filterPi = filter.provider.info;
7606            for (int i = dest.size() - 1; i >= 0; i--) {
7607                ProviderInfo destPi = dest.get(i).providerInfo;
7608                if (destPi.name == filterPi.name
7609                        && destPi.packageName == filterPi.packageName) {
7610                    return false;
7611                }
7612            }
7613            return true;
7614        }
7615
7616        @Override
7617        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7618            return new PackageParser.ProviderIntentInfo[size];
7619        }
7620
7621        @Override
7622        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7623            if (!sUserManager.exists(userId))
7624                return true;
7625            PackageParser.Package p = filter.provider.owner;
7626            if (p != null) {
7627                PackageSetting ps = (PackageSetting) p.mExtras;
7628                if (ps != null) {
7629                    // System apps are never considered stopped for purposes of
7630                    // filtering, because there may be no way for the user to
7631                    // actually re-launch them.
7632                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7633                            && ps.getStopped(userId);
7634                }
7635            }
7636            return false;
7637        }
7638
7639        @Override
7640        protected boolean isPackageForFilter(String packageName,
7641                PackageParser.ProviderIntentInfo info) {
7642            return packageName.equals(info.provider.owner.packageName);
7643        }
7644
7645        @Override
7646        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7647                int match, int userId) {
7648            if (!sUserManager.exists(userId))
7649                return null;
7650            final PackageParser.ProviderIntentInfo info = filter;
7651            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7652                return null;
7653            }
7654            final PackageParser.Provider provider = info.provider;
7655            if (mSafeMode && (provider.info.applicationInfo.flags
7656                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7657                return null;
7658            }
7659            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7660            if (ps == null) {
7661                return null;
7662            }
7663            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7664                    ps.readUserState(userId), userId);
7665            if (pi == null) {
7666                return null;
7667            }
7668            final ResolveInfo res = new ResolveInfo();
7669            res.providerInfo = pi;
7670            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7671                res.filter = filter;
7672            }
7673            res.priority = info.getPriority();
7674            res.preferredOrder = provider.owner.mPreferredOrder;
7675            res.match = match;
7676            res.isDefault = info.hasDefault;
7677            res.labelRes = info.labelRes;
7678            res.nonLocalizedLabel = info.nonLocalizedLabel;
7679            res.icon = info.icon;
7680            res.system = isSystemApp(res.providerInfo.applicationInfo);
7681            return res;
7682        }
7683
7684        @Override
7685        protected void sortResults(List<ResolveInfo> results) {
7686            Collections.sort(results, mResolvePrioritySorter);
7687        }
7688
7689        @Override
7690        protected void dumpFilter(PrintWriter out, String prefix,
7691                PackageParser.ProviderIntentInfo filter) {
7692            out.print(prefix);
7693            out.print(
7694                    Integer.toHexString(System.identityHashCode(filter.provider)));
7695            out.print(' ');
7696            filter.provider.printComponentShortName(out);
7697            out.print(" filter ");
7698            out.println(Integer.toHexString(System.identityHashCode(filter)));
7699        }
7700
7701        @Override
7702        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7703            return filter.provider;
7704        }
7705
7706        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7707            PackageParser.Provider provider = (PackageParser.Provider)label;
7708            out.print(prefix); out.print(
7709                    Integer.toHexString(System.identityHashCode(provider)));
7710                    out.print(' ');
7711                    provider.printComponentShortName(out);
7712            if (count > 1) {
7713                out.print(" ("); out.print(count); out.print(" filters)");
7714            }
7715            out.println();
7716        }
7717
7718        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7719                = new ArrayMap<ComponentName, PackageParser.Provider>();
7720        private int mFlags;
7721    };
7722
7723    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7724            new Comparator<ResolveInfo>() {
7725        public int compare(ResolveInfo r1, ResolveInfo r2) {
7726            int v1 = r1.priority;
7727            int v2 = r2.priority;
7728            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7729            if (v1 != v2) {
7730                return (v1 > v2) ? -1 : 1;
7731            }
7732            v1 = r1.preferredOrder;
7733            v2 = r2.preferredOrder;
7734            if (v1 != v2) {
7735                return (v1 > v2) ? -1 : 1;
7736            }
7737            if (r1.isDefault != r2.isDefault) {
7738                return r1.isDefault ? -1 : 1;
7739            }
7740            v1 = r1.match;
7741            v2 = r2.match;
7742            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7743            if (v1 != v2) {
7744                return (v1 > v2) ? -1 : 1;
7745            }
7746            if (r1.system != r2.system) {
7747                return r1.system ? -1 : 1;
7748            }
7749            return 0;
7750        }
7751    };
7752
7753    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7754            new Comparator<ProviderInfo>() {
7755        public int compare(ProviderInfo p1, ProviderInfo p2) {
7756            final int v1 = p1.initOrder;
7757            final int v2 = p2.initOrder;
7758            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7759        }
7760    };
7761
7762    static final void sendPackageBroadcast(String action, String pkg,
7763            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7764            int[] userIds) {
7765        IActivityManager am = ActivityManagerNative.getDefault();
7766        if (am != null) {
7767            try {
7768                if (userIds == null) {
7769                    userIds = am.getRunningUserIds();
7770                }
7771                for (int id : userIds) {
7772                    final Intent intent = new Intent(action,
7773                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7774                    if (extras != null) {
7775                        intent.putExtras(extras);
7776                    }
7777                    if (targetPkg != null) {
7778                        intent.setPackage(targetPkg);
7779                    }
7780                    // Modify the UID when posting to other users
7781                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7782                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7783                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7784                        intent.putExtra(Intent.EXTRA_UID, uid);
7785                    }
7786                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7787                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7788                    if (DEBUG_BROADCASTS) {
7789                        RuntimeException here = new RuntimeException("here");
7790                        here.fillInStackTrace();
7791                        Slog.d(TAG, "Sending to user " + id + ": "
7792                                + intent.toShortString(false, true, false, false)
7793                                + " " + intent.getExtras(), here);
7794                    }
7795                    am.broadcastIntent(null, intent, null, finishedReceiver,
7796                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7797                            finishedReceiver != null, false, id);
7798                }
7799            } catch (RemoteException ex) {
7800            }
7801        }
7802    }
7803
7804    /**
7805     * Check if the external storage media is available. This is true if there
7806     * is a mounted external storage medium or if the external storage is
7807     * emulated.
7808     */
7809    private boolean isExternalMediaAvailable() {
7810        return mMediaMounted || Environment.isExternalStorageEmulated();
7811    }
7812
7813    @Override
7814    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7815        // writer
7816        synchronized (mPackages) {
7817            if (!isExternalMediaAvailable()) {
7818                // If the external storage is no longer mounted at this point,
7819                // the caller may not have been able to delete all of this
7820                // packages files and can not delete any more.  Bail.
7821                return null;
7822            }
7823            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7824            if (lastPackage != null) {
7825                pkgs.remove(lastPackage);
7826            }
7827            if (pkgs.size() > 0) {
7828                return pkgs.get(0);
7829            }
7830        }
7831        return null;
7832    }
7833
7834    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7835        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7836                userId, andCode ? 1 : 0, packageName);
7837        if (mSystemReady) {
7838            msg.sendToTarget();
7839        } else {
7840            if (mPostSystemReadyMessages == null) {
7841                mPostSystemReadyMessages = new ArrayList<>();
7842            }
7843            mPostSystemReadyMessages.add(msg);
7844        }
7845    }
7846
7847    void startCleaningPackages() {
7848        // reader
7849        synchronized (mPackages) {
7850            if (!isExternalMediaAvailable()) {
7851                return;
7852            }
7853            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7854                return;
7855            }
7856        }
7857        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7858        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7859        IActivityManager am = ActivityManagerNative.getDefault();
7860        if (am != null) {
7861            try {
7862                am.startService(null, intent, null, UserHandle.USER_OWNER);
7863            } catch (RemoteException e) {
7864            }
7865        }
7866    }
7867
7868    @Override
7869    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7870            int installFlags, String installerPackageName, VerificationParams verificationParams,
7871            String packageAbiOverride) {
7872        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7873                packageAbiOverride, UserHandle.getCallingUserId());
7874    }
7875
7876    @Override
7877    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7878            int installFlags, String installerPackageName, VerificationParams verificationParams,
7879            String packageAbiOverride, int userId) {
7880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7881
7882        final int callingUid = Binder.getCallingUid();
7883        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7884
7885        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7886            try {
7887                if (observer != null) {
7888                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7889                }
7890            } catch (RemoteException re) {
7891            }
7892            return;
7893        }
7894
7895        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7896            installFlags |= PackageManager.INSTALL_FROM_ADB;
7897
7898        } else {
7899            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7900            // about installerPackageName.
7901
7902            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7903            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7904        }
7905
7906        UserHandle user;
7907        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7908            user = UserHandle.ALL;
7909        } else {
7910            user = new UserHandle(userId);
7911        }
7912
7913        verificationParams.setInstallerUid(callingUid);
7914
7915        final File originFile = new File(originPath);
7916        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7917
7918        final Message msg = mHandler.obtainMessage(INIT_COPY);
7919        msg.obj = new InstallParams(origin, observer, installFlags,
7920                installerPackageName, verificationParams, user, packageAbiOverride);
7921        mHandler.sendMessage(msg);
7922    }
7923
7924    void installStage(String packageName, File stagedDir, String stagedCid,
7925            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7926            String installerPackageName, int installerUid, UserHandle user) {
7927        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7928                params.referrerUri, installerUid, null);
7929
7930        final OriginInfo origin;
7931        if (stagedDir != null) {
7932            origin = OriginInfo.fromStagedFile(stagedDir);
7933        } else {
7934            origin = OriginInfo.fromStagedContainer(stagedCid);
7935        }
7936
7937        final Message msg = mHandler.obtainMessage(INIT_COPY);
7938        msg.obj = new InstallParams(origin, observer, params.installFlags,
7939                installerPackageName, verifParams, user, params.abiOverride);
7940        mHandler.sendMessage(msg);
7941    }
7942
7943    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7944        Bundle extras = new Bundle(1);
7945        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7946
7947        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7948                packageName, extras, null, null, new int[] {userId});
7949        try {
7950            IActivityManager am = ActivityManagerNative.getDefault();
7951            final boolean isSystem =
7952                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7953            if (isSystem && am.isUserRunning(userId, false)) {
7954                // The just-installed/enabled app is bundled on the system, so presumed
7955                // to be able to run automatically without needing an explicit launch.
7956                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7957                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7958                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7959                        .setPackage(packageName);
7960                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7961                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7962            }
7963        } catch (RemoteException e) {
7964            // shouldn't happen
7965            Slog.w(TAG, "Unable to bootstrap installed package", e);
7966        }
7967    }
7968
7969    @Override
7970    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7971            int userId) {
7972        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7973        PackageSetting pkgSetting;
7974        final int uid = Binder.getCallingUid();
7975        enforceCrossUserPermission(uid, userId, true, true,
7976                "setApplicationHiddenSetting for user " + userId);
7977
7978        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7979            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7980            return false;
7981        }
7982
7983        long callingId = Binder.clearCallingIdentity();
7984        try {
7985            boolean sendAdded = false;
7986            boolean sendRemoved = false;
7987            // writer
7988            synchronized (mPackages) {
7989                pkgSetting = mSettings.mPackages.get(packageName);
7990                if (pkgSetting == null) {
7991                    return false;
7992                }
7993                if (pkgSetting.getHidden(userId) != hidden) {
7994                    pkgSetting.setHidden(hidden, userId);
7995                    mSettings.writePackageRestrictionsLPr(userId);
7996                    if (hidden) {
7997                        sendRemoved = true;
7998                    } else {
7999                        sendAdded = true;
8000                    }
8001                }
8002            }
8003            if (sendAdded) {
8004                sendPackageAddedForUser(packageName, pkgSetting, userId);
8005                return true;
8006            }
8007            if (sendRemoved) {
8008                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8009                        "hiding pkg");
8010                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8011            }
8012        } finally {
8013            Binder.restoreCallingIdentity(callingId);
8014        }
8015        return false;
8016    }
8017
8018    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8019            int userId) {
8020        final PackageRemovedInfo info = new PackageRemovedInfo();
8021        info.removedPackage = packageName;
8022        info.removedUsers = new int[] {userId};
8023        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8024        info.sendBroadcast(false, false, false);
8025    }
8026
8027    /**
8028     * Returns true if application is not found or there was an error. Otherwise it returns
8029     * the hidden state of the package for the given user.
8030     */
8031    @Override
8032    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8033        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8034        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8035                false, "getApplicationHidden for user " + userId);
8036        PackageSetting pkgSetting;
8037        long callingId = Binder.clearCallingIdentity();
8038        try {
8039            // writer
8040            synchronized (mPackages) {
8041                pkgSetting = mSettings.mPackages.get(packageName);
8042                if (pkgSetting == null) {
8043                    return true;
8044                }
8045                return pkgSetting.getHidden(userId);
8046            }
8047        } finally {
8048            Binder.restoreCallingIdentity(callingId);
8049        }
8050    }
8051
8052    /**
8053     * @hide
8054     */
8055    @Override
8056    public int installExistingPackageAsUser(String packageName, int userId) {
8057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8058                null);
8059        PackageSetting pkgSetting;
8060        final int uid = Binder.getCallingUid();
8061        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8062                + userId);
8063        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8064            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8065        }
8066
8067        long callingId = Binder.clearCallingIdentity();
8068        try {
8069            boolean sendAdded = false;
8070            Bundle extras = new Bundle(1);
8071
8072            // writer
8073            synchronized (mPackages) {
8074                pkgSetting = mSettings.mPackages.get(packageName);
8075                if (pkgSetting == null) {
8076                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8077                }
8078                if (!pkgSetting.getInstalled(userId)) {
8079                    pkgSetting.setInstalled(true, userId);
8080                    pkgSetting.setHidden(false, userId);
8081                    mSettings.writePackageRestrictionsLPr(userId);
8082                    sendAdded = true;
8083                }
8084            }
8085
8086            if (sendAdded) {
8087                sendPackageAddedForUser(packageName, pkgSetting, userId);
8088            }
8089        } finally {
8090            Binder.restoreCallingIdentity(callingId);
8091        }
8092
8093        return PackageManager.INSTALL_SUCCEEDED;
8094    }
8095
8096    boolean isUserRestricted(int userId, String restrictionKey) {
8097        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8098        if (restrictions.getBoolean(restrictionKey, false)) {
8099            Log.w(TAG, "User is restricted: " + restrictionKey);
8100            return true;
8101        }
8102        return false;
8103    }
8104
8105    @Override
8106    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8107        mContext.enforceCallingOrSelfPermission(
8108                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8109                "Only package verification agents can verify applications");
8110
8111        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8112        final PackageVerificationResponse response = new PackageVerificationResponse(
8113                verificationCode, Binder.getCallingUid());
8114        msg.arg1 = id;
8115        msg.obj = response;
8116        mHandler.sendMessage(msg);
8117    }
8118
8119    @Override
8120    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8121            long millisecondsToDelay) {
8122        mContext.enforceCallingOrSelfPermission(
8123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8124                "Only package verification agents can extend verification timeouts");
8125
8126        final PackageVerificationState state = mPendingVerification.get(id);
8127        final PackageVerificationResponse response = new PackageVerificationResponse(
8128                verificationCodeAtTimeout, Binder.getCallingUid());
8129
8130        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8131            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8132        }
8133        if (millisecondsToDelay < 0) {
8134            millisecondsToDelay = 0;
8135        }
8136        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8137                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8138            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8139        }
8140
8141        if ((state != null) && !state.timeoutExtended()) {
8142            state.extendTimeout();
8143
8144            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8145            msg.arg1 = id;
8146            msg.obj = response;
8147            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8148        }
8149    }
8150
8151    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8152            int verificationCode, UserHandle user) {
8153        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8154        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8155        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8156        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8157        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8158
8159        mContext.sendBroadcastAsUser(intent, user,
8160                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8161    }
8162
8163    private ComponentName matchComponentForVerifier(String packageName,
8164            List<ResolveInfo> receivers) {
8165        ActivityInfo targetReceiver = null;
8166
8167        final int NR = receivers.size();
8168        for (int i = 0; i < NR; i++) {
8169            final ResolveInfo info = receivers.get(i);
8170            if (info.activityInfo == null) {
8171                continue;
8172            }
8173
8174            if (packageName.equals(info.activityInfo.packageName)) {
8175                targetReceiver = info.activityInfo;
8176                break;
8177            }
8178        }
8179
8180        if (targetReceiver == null) {
8181            return null;
8182        }
8183
8184        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8185    }
8186
8187    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8188            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8189        if (pkgInfo.verifiers.length == 0) {
8190            return null;
8191        }
8192
8193        final int N = pkgInfo.verifiers.length;
8194        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8195        for (int i = 0; i < N; i++) {
8196            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8197
8198            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8199                    receivers);
8200            if (comp == null) {
8201                continue;
8202            }
8203
8204            final int verifierUid = getUidForVerifier(verifierInfo);
8205            if (verifierUid == -1) {
8206                continue;
8207            }
8208
8209            if (DEBUG_VERIFY) {
8210                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8211                        + " with the correct signature");
8212            }
8213            sufficientVerifiers.add(comp);
8214            verificationState.addSufficientVerifier(verifierUid);
8215        }
8216
8217        return sufficientVerifiers;
8218    }
8219
8220    private int getUidForVerifier(VerifierInfo verifierInfo) {
8221        synchronized (mPackages) {
8222            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8223            if (pkg == null) {
8224                return -1;
8225            } else if (pkg.mSignatures.length != 1) {
8226                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8227                        + " has more than one signature; ignoring");
8228                return -1;
8229            }
8230
8231            /*
8232             * If the public key of the package's signature does not match
8233             * our expected public key, then this is a different package and
8234             * we should skip.
8235             */
8236
8237            final byte[] expectedPublicKey;
8238            try {
8239                final Signature verifierSig = pkg.mSignatures[0];
8240                final PublicKey publicKey = verifierSig.getPublicKey();
8241                expectedPublicKey = publicKey.getEncoded();
8242            } catch (CertificateException e) {
8243                return -1;
8244            }
8245
8246            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8247
8248            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8249                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8250                        + " does not have the expected public key; ignoring");
8251                return -1;
8252            }
8253
8254            return pkg.applicationInfo.uid;
8255        }
8256    }
8257
8258    @Override
8259    public void finishPackageInstall(int token) {
8260        enforceSystemOrRoot("Only the system is allowed to finish installs");
8261
8262        if (DEBUG_INSTALL) {
8263            Slog.v(TAG, "BM finishing package install for " + token);
8264        }
8265
8266        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8267        mHandler.sendMessage(msg);
8268    }
8269
8270    /**
8271     * Get the verification agent timeout.
8272     *
8273     * @return verification timeout in milliseconds
8274     */
8275    private long getVerificationTimeout() {
8276        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8277                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8278                DEFAULT_VERIFICATION_TIMEOUT);
8279    }
8280
8281    /**
8282     * Get the default verification agent response code.
8283     *
8284     * @return default verification response code
8285     */
8286    private int getDefaultVerificationResponse() {
8287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8288                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8289                DEFAULT_VERIFICATION_RESPONSE);
8290    }
8291
8292    /**
8293     * Check whether or not package verification has been enabled.
8294     *
8295     * @return true if verification should be performed
8296     */
8297    private boolean isVerificationEnabled(int userId, int installFlags) {
8298        if (!DEFAULT_VERIFY_ENABLE) {
8299            return false;
8300        }
8301
8302        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8303
8304        // Check if installing from ADB
8305        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8306            // Do not run verification in a test harness environment
8307            if (ActivityManager.isRunningInTestHarness()) {
8308                return false;
8309            }
8310            if (ensureVerifyAppsEnabled) {
8311                return true;
8312            }
8313            // Check if the developer does not want package verification for ADB installs
8314            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8315                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8316                return false;
8317            }
8318        }
8319
8320        if (ensureVerifyAppsEnabled) {
8321            return true;
8322        }
8323
8324        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8325                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8326    }
8327
8328    /**
8329     * Get the "allow unknown sources" setting.
8330     *
8331     * @return the current "allow unknown sources" setting
8332     */
8333    private int getUnknownSourcesSettings() {
8334        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8335                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8336                -1);
8337    }
8338
8339    @Override
8340    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8341        final int uid = Binder.getCallingUid();
8342        // writer
8343        synchronized (mPackages) {
8344            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8345            if (targetPackageSetting == null) {
8346                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8347            }
8348
8349            PackageSetting installerPackageSetting;
8350            if (installerPackageName != null) {
8351                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8352                if (installerPackageSetting == null) {
8353                    throw new IllegalArgumentException("Unknown installer package: "
8354                            + installerPackageName);
8355                }
8356            } else {
8357                installerPackageSetting = null;
8358            }
8359
8360            Signature[] callerSignature;
8361            Object obj = mSettings.getUserIdLPr(uid);
8362            if (obj != null) {
8363                if (obj instanceof SharedUserSetting) {
8364                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8365                } else if (obj instanceof PackageSetting) {
8366                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8367                } else {
8368                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8369                }
8370            } else {
8371                throw new SecurityException("Unknown calling uid " + uid);
8372            }
8373
8374            // Verify: can't set installerPackageName to a package that is
8375            // not signed with the same cert as the caller.
8376            if (installerPackageSetting != null) {
8377                if (compareSignatures(callerSignature,
8378                        installerPackageSetting.signatures.mSignatures)
8379                        != PackageManager.SIGNATURE_MATCH) {
8380                    throw new SecurityException(
8381                            "Caller does not have same cert as new installer package "
8382                            + installerPackageName);
8383                }
8384            }
8385
8386            // Verify: if target already has an installer package, it must
8387            // be signed with the same cert as the caller.
8388            if (targetPackageSetting.installerPackageName != null) {
8389                PackageSetting setting = mSettings.mPackages.get(
8390                        targetPackageSetting.installerPackageName);
8391                // If the currently set package isn't valid, then it's always
8392                // okay to change it.
8393                if (setting != null) {
8394                    if (compareSignatures(callerSignature,
8395                            setting.signatures.mSignatures)
8396                            != PackageManager.SIGNATURE_MATCH) {
8397                        throw new SecurityException(
8398                                "Caller does not have same cert as old installer package "
8399                                + targetPackageSetting.installerPackageName);
8400                    }
8401                }
8402            }
8403
8404            // Okay!
8405            targetPackageSetting.installerPackageName = installerPackageName;
8406            scheduleWriteSettingsLocked();
8407        }
8408    }
8409
8410    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8411        // Queue up an async operation since the package installation may take a little while.
8412        mHandler.post(new Runnable() {
8413            public void run() {
8414                mHandler.removeCallbacks(this);
8415                 // Result object to be returned
8416                PackageInstalledInfo res = new PackageInstalledInfo();
8417                res.returnCode = currentStatus;
8418                res.uid = -1;
8419                res.pkg = null;
8420                res.removedInfo = new PackageRemovedInfo();
8421                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8422                    args.doPreInstall(res.returnCode);
8423                    synchronized (mInstallLock) {
8424                        installPackageLI(args, res);
8425                    }
8426                    args.doPostInstall(res.returnCode, res.uid);
8427                }
8428
8429                // A restore should be performed at this point if (a) the install
8430                // succeeded, (b) the operation is not an update, and (c) the new
8431                // package has not opted out of backup participation.
8432                final boolean update = res.removedInfo.removedPackage != null;
8433                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8434                boolean doRestore = !update
8435                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8436
8437                // Set up the post-install work request bookkeeping.  This will be used
8438                // and cleaned up by the post-install event handling regardless of whether
8439                // there's a restore pass performed.  Token values are >= 1.
8440                int token;
8441                if (mNextInstallToken < 0) mNextInstallToken = 1;
8442                token = mNextInstallToken++;
8443
8444                PostInstallData data = new PostInstallData(args, res);
8445                mRunningInstalls.put(token, data);
8446                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8447
8448                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8449                    // Pass responsibility to the Backup Manager.  It will perform a
8450                    // restore if appropriate, then pass responsibility back to the
8451                    // Package Manager to run the post-install observer callbacks
8452                    // and broadcasts.
8453                    IBackupManager bm = IBackupManager.Stub.asInterface(
8454                            ServiceManager.getService(Context.BACKUP_SERVICE));
8455                    if (bm != null) {
8456                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8457                                + " to BM for possible restore");
8458                        try {
8459                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8460                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8461                            } else {
8462                                doRestore = false;
8463                            }
8464                        } catch (RemoteException e) {
8465                            // can't happen; the backup manager is local
8466                        } catch (Exception e) {
8467                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8468                            doRestore = false;
8469                        }
8470                    } else {
8471                        Slog.e(TAG, "Backup Manager not found!");
8472                        doRestore = false;
8473                    }
8474                }
8475
8476                if (!doRestore) {
8477                    // No restore possible, or the Backup Manager was mysteriously not
8478                    // available -- just fire the post-install work request directly.
8479                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8480                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8481                    mHandler.sendMessage(msg);
8482                }
8483            }
8484        });
8485    }
8486
8487    private abstract class HandlerParams {
8488        private static final int MAX_RETRIES = 4;
8489
8490        /**
8491         * Number of times startCopy() has been attempted and had a non-fatal
8492         * error.
8493         */
8494        private int mRetries = 0;
8495
8496        /** User handle for the user requesting the information or installation. */
8497        private final UserHandle mUser;
8498
8499        HandlerParams(UserHandle user) {
8500            mUser = user;
8501        }
8502
8503        UserHandle getUser() {
8504            return mUser;
8505        }
8506
8507        final boolean startCopy() {
8508            boolean res;
8509            try {
8510                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8511
8512                if (++mRetries > MAX_RETRIES) {
8513                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8514                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8515                    handleServiceError();
8516                    return false;
8517                } else {
8518                    handleStartCopy();
8519                    res = true;
8520                }
8521            } catch (RemoteException e) {
8522                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8523                mHandler.sendEmptyMessage(MCS_RECONNECT);
8524                res = false;
8525            }
8526            handleReturnCode();
8527            return res;
8528        }
8529
8530        final void serviceError() {
8531            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8532            handleServiceError();
8533            handleReturnCode();
8534        }
8535
8536        abstract void handleStartCopy() throws RemoteException;
8537        abstract void handleServiceError();
8538        abstract void handleReturnCode();
8539    }
8540
8541    class MeasureParams extends HandlerParams {
8542        private final PackageStats mStats;
8543        private boolean mSuccess;
8544
8545        private final IPackageStatsObserver mObserver;
8546
8547        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8548            super(new UserHandle(stats.userHandle));
8549            mObserver = observer;
8550            mStats = stats;
8551        }
8552
8553        @Override
8554        public String toString() {
8555            return "MeasureParams{"
8556                + Integer.toHexString(System.identityHashCode(this))
8557                + " " + mStats.packageName + "}";
8558        }
8559
8560        @Override
8561        void handleStartCopy() throws RemoteException {
8562            synchronized (mInstallLock) {
8563                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8564            }
8565
8566            if (mSuccess) {
8567                final boolean mounted;
8568                if (Environment.isExternalStorageEmulated()) {
8569                    mounted = true;
8570                } else {
8571                    final String status = Environment.getExternalStorageState();
8572                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8573                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8574                }
8575
8576                if (mounted) {
8577                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8578
8579                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8580                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8581
8582                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8583                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8584
8585                    // Always subtract cache size, since it's a subdirectory
8586                    mStats.externalDataSize -= mStats.externalCacheSize;
8587
8588                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8589                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8590
8591                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8592                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8593                }
8594            }
8595        }
8596
8597        @Override
8598        void handleReturnCode() {
8599            if (mObserver != null) {
8600                try {
8601                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8602                } catch (RemoteException e) {
8603                    Slog.i(TAG, "Observer no longer exists.");
8604                }
8605            }
8606        }
8607
8608        @Override
8609        void handleServiceError() {
8610            Slog.e(TAG, "Could not measure application " + mStats.packageName
8611                            + " external storage");
8612        }
8613    }
8614
8615    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8616            throws RemoteException {
8617        long result = 0;
8618        for (File path : paths) {
8619            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8620        }
8621        return result;
8622    }
8623
8624    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8625        for (File path : paths) {
8626            try {
8627                mcs.clearDirectory(path.getAbsolutePath());
8628            } catch (RemoteException e) {
8629            }
8630        }
8631    }
8632
8633    static class OriginInfo {
8634        /**
8635         * Location where install is coming from, before it has been
8636         * copied/renamed into place. This could be a single monolithic APK
8637         * file, or a cluster directory. This location may be untrusted.
8638         */
8639        final File file;
8640        final String cid;
8641
8642        /**
8643         * Flag indicating that {@link #file} or {@link #cid} has already been
8644         * staged, meaning downstream users don't need to defensively copy the
8645         * contents.
8646         */
8647        final boolean staged;
8648
8649        /**
8650         * Flag indicating that {@link #file} or {@link #cid} is an already
8651         * installed app that is being moved.
8652         */
8653        final boolean existing;
8654
8655        final String resolvedPath;
8656        final File resolvedFile;
8657
8658        static OriginInfo fromNothing() {
8659            return new OriginInfo(null, null, false, false);
8660        }
8661
8662        static OriginInfo fromUntrustedFile(File file) {
8663            return new OriginInfo(file, null, false, false);
8664        }
8665
8666        static OriginInfo fromExistingFile(File file) {
8667            return new OriginInfo(file, null, false, true);
8668        }
8669
8670        static OriginInfo fromStagedFile(File file) {
8671            return new OriginInfo(file, null, true, false);
8672        }
8673
8674        static OriginInfo fromStagedContainer(String cid) {
8675            return new OriginInfo(null, cid, true, false);
8676        }
8677
8678        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8679            this.file = file;
8680            this.cid = cid;
8681            this.staged = staged;
8682            this.existing = existing;
8683
8684            if (cid != null) {
8685                resolvedPath = PackageHelper.getSdDir(cid);
8686                resolvedFile = new File(resolvedPath);
8687            } else if (file != null) {
8688                resolvedPath = file.getAbsolutePath();
8689                resolvedFile = file;
8690            } else {
8691                resolvedPath = null;
8692                resolvedFile = null;
8693            }
8694        }
8695    }
8696
8697    class InstallParams extends HandlerParams {
8698        final OriginInfo origin;
8699        final IPackageInstallObserver2 observer;
8700        int installFlags;
8701        final String installerPackageName;
8702        final VerificationParams verificationParams;
8703        private InstallArgs mArgs;
8704        private int mRet;
8705        final String packageAbiOverride;
8706
8707        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8708                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8709                String packageAbiOverride) {
8710            super(user);
8711            this.origin = origin;
8712            this.observer = observer;
8713            this.installFlags = installFlags;
8714            this.installerPackageName = installerPackageName;
8715            this.verificationParams = verificationParams;
8716            this.packageAbiOverride = packageAbiOverride;
8717        }
8718
8719        @Override
8720        public String toString() {
8721            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8722                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8723        }
8724
8725        public ManifestDigest getManifestDigest() {
8726            if (verificationParams == null) {
8727                return null;
8728            }
8729            return verificationParams.getManifestDigest();
8730        }
8731
8732        private int installLocationPolicy(PackageInfoLite pkgLite) {
8733            String packageName = pkgLite.packageName;
8734            int installLocation = pkgLite.installLocation;
8735            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8736            // reader
8737            synchronized (mPackages) {
8738                PackageParser.Package pkg = mPackages.get(packageName);
8739                if (pkg != null) {
8740                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8741                        // Check for downgrading.
8742                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8743                            try {
8744                                checkDowngrade(pkg, pkgLite);
8745                            } catch (PackageManagerException e) {
8746                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8747                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8748                            }
8749                        }
8750                        // Check for updated system application.
8751                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8752                            if (onSd) {
8753                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8754                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8755                            }
8756                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8757                        } else {
8758                            if (onSd) {
8759                                // Install flag overrides everything.
8760                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8761                            }
8762                            // If current upgrade specifies particular preference
8763                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8764                                // Application explicitly specified internal.
8765                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8766                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8767                                // App explictly prefers external. Let policy decide
8768                            } else {
8769                                // Prefer previous location
8770                                if (isExternal(pkg)) {
8771                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8772                                }
8773                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8774                            }
8775                        }
8776                    } else {
8777                        // Invalid install. Return error code
8778                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8779                    }
8780                }
8781            }
8782            // All the special cases have been taken care of.
8783            // Return result based on recommended install location.
8784            if (onSd) {
8785                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8786            }
8787            return pkgLite.recommendedInstallLocation;
8788        }
8789
8790        /*
8791         * Invoke remote method to get package information and install
8792         * location values. Override install location based on default
8793         * policy if needed and then create install arguments based
8794         * on the install location.
8795         */
8796        public void handleStartCopy() throws RemoteException {
8797            int ret = PackageManager.INSTALL_SUCCEEDED;
8798
8799            // If we're already staged, we've firmly committed to an install location
8800            if (origin.staged) {
8801                if (origin.file != null) {
8802                    installFlags |= PackageManager.INSTALL_INTERNAL;
8803                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8804                } else if (origin.cid != null) {
8805                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8806                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8807                } else {
8808                    throw new IllegalStateException("Invalid stage location");
8809                }
8810            }
8811
8812            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8813            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8814
8815            PackageInfoLite pkgLite = null;
8816
8817            if (onInt && onSd) {
8818                // Check if both bits are set.
8819                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8820                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8821            } else {
8822                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8823                        packageAbiOverride);
8824
8825                /*
8826                 * If we have too little free space, try to free cache
8827                 * before giving up.
8828                 */
8829                if (!origin.staged && pkgLite.recommendedInstallLocation
8830                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8831                    // TODO: focus freeing disk space on the target device
8832                    final StorageManager storage = StorageManager.from(mContext);
8833                    final long lowThreshold = storage.getStorageLowBytes(
8834                            Environment.getDataDirectory());
8835
8836                    final long sizeBytes = mContainerService.calculateInstalledSize(
8837                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8838
8839                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8840                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8841                                installFlags, packageAbiOverride);
8842                    }
8843
8844                    /*
8845                     * The cache free must have deleted the file we
8846                     * downloaded to install.
8847                     *
8848                     * TODO: fix the "freeCache" call to not delete
8849                     *       the file we care about.
8850                     */
8851                    if (pkgLite.recommendedInstallLocation
8852                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8853                        pkgLite.recommendedInstallLocation
8854                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8855                    }
8856                }
8857            }
8858
8859            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8860                int loc = pkgLite.recommendedInstallLocation;
8861                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8862                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8863                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8864                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8865                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8866                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8867                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8868                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8869                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8870                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8871                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8872                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8873                } else {
8874                    // Override with defaults if needed.
8875                    loc = installLocationPolicy(pkgLite);
8876                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8877                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8878                    } else if (!onSd && !onInt) {
8879                        // Override install location with flags
8880                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8881                            // Set the flag to install on external media.
8882                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8883                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8884                        } else {
8885                            // Make sure the flag for installing on external
8886                            // media is unset
8887                            installFlags |= PackageManager.INSTALL_INTERNAL;
8888                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8889                        }
8890                    }
8891                }
8892            }
8893
8894            final InstallArgs args = createInstallArgs(this);
8895            mArgs = args;
8896
8897            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8898                 /*
8899                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8900                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8901                 */
8902                int userIdentifier = getUser().getIdentifier();
8903                if (userIdentifier == UserHandle.USER_ALL
8904                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8905                    userIdentifier = UserHandle.USER_OWNER;
8906                }
8907
8908                /*
8909                 * Determine if we have any installed package verifiers. If we
8910                 * do, then we'll defer to them to verify the packages.
8911                 */
8912                final int requiredUid = mRequiredVerifierPackage == null ? -1
8913                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8914                if (!origin.existing && requiredUid != -1
8915                        && isVerificationEnabled(userIdentifier, installFlags)) {
8916                    final Intent verification = new Intent(
8917                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8918                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8919                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8920                            PACKAGE_MIME_TYPE);
8921                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8922
8923                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8924                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8925                            0 /* TODO: Which userId? */);
8926
8927                    if (DEBUG_VERIFY) {
8928                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8929                                + verification.toString() + " with " + pkgLite.verifiers.length
8930                                + " optional verifiers");
8931                    }
8932
8933                    final int verificationId = mPendingVerificationToken++;
8934
8935                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8936
8937                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8938                            installerPackageName);
8939
8940                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8941                            installFlags);
8942
8943                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8944                            pkgLite.packageName);
8945
8946                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8947                            pkgLite.versionCode);
8948
8949                    if (verificationParams != null) {
8950                        if (verificationParams.getVerificationURI() != null) {
8951                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8952                                 verificationParams.getVerificationURI());
8953                        }
8954                        if (verificationParams.getOriginatingURI() != null) {
8955                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8956                                  verificationParams.getOriginatingURI());
8957                        }
8958                        if (verificationParams.getReferrer() != null) {
8959                            verification.putExtra(Intent.EXTRA_REFERRER,
8960                                  verificationParams.getReferrer());
8961                        }
8962                        if (verificationParams.getOriginatingUid() >= 0) {
8963                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8964                                  verificationParams.getOriginatingUid());
8965                        }
8966                        if (verificationParams.getInstallerUid() >= 0) {
8967                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8968                                  verificationParams.getInstallerUid());
8969                        }
8970                    }
8971
8972                    final PackageVerificationState verificationState = new PackageVerificationState(
8973                            requiredUid, args);
8974
8975                    mPendingVerification.append(verificationId, verificationState);
8976
8977                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8978                            receivers, verificationState);
8979
8980                    /*
8981                     * If any sufficient verifiers were listed in the package
8982                     * manifest, attempt to ask them.
8983                     */
8984                    if (sufficientVerifiers != null) {
8985                        final int N = sufficientVerifiers.size();
8986                        if (N == 0) {
8987                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8988                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8989                        } else {
8990                            for (int i = 0; i < N; i++) {
8991                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8992
8993                                final Intent sufficientIntent = new Intent(verification);
8994                                sufficientIntent.setComponent(verifierComponent);
8995
8996                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8997                            }
8998                        }
8999                    }
9000
9001                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9002                            mRequiredVerifierPackage, receivers);
9003                    if (ret == PackageManager.INSTALL_SUCCEEDED
9004                            && mRequiredVerifierPackage != null) {
9005                        /*
9006                         * Send the intent to the required verification agent,
9007                         * but only start the verification timeout after the
9008                         * target BroadcastReceivers have run.
9009                         */
9010                        verification.setComponent(requiredVerifierComponent);
9011                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9012                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9013                                new BroadcastReceiver() {
9014                                    @Override
9015                                    public void onReceive(Context context, Intent intent) {
9016                                        final Message msg = mHandler
9017                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9018                                        msg.arg1 = verificationId;
9019                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9020                                    }
9021                                }, null, 0, null, null);
9022
9023                        /*
9024                         * We don't want the copy to proceed until verification
9025                         * succeeds, so null out this field.
9026                         */
9027                        mArgs = null;
9028                    }
9029                } else {
9030                    /*
9031                     * No package verification is enabled, so immediately start
9032                     * the remote call to initiate copy using temporary file.
9033                     */
9034                    ret = args.copyApk(mContainerService, true);
9035                }
9036            }
9037
9038            mRet = ret;
9039        }
9040
9041        @Override
9042        void handleReturnCode() {
9043            // If mArgs is null, then MCS couldn't be reached. When it
9044            // reconnects, it will try again to install. At that point, this
9045            // will succeed.
9046            if (mArgs != null) {
9047                processPendingInstall(mArgs, mRet);
9048            }
9049        }
9050
9051        @Override
9052        void handleServiceError() {
9053            mArgs = createInstallArgs(this);
9054            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9055        }
9056
9057        public boolean isForwardLocked() {
9058            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9059        }
9060    }
9061
9062    /**
9063     * Used during creation of InstallArgs
9064     *
9065     * @param installFlags package installation flags
9066     * @return true if should be installed on external storage
9067     */
9068    private static boolean installOnSd(int installFlags) {
9069        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9070            return false;
9071        }
9072        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9073            return true;
9074        }
9075        return false;
9076    }
9077
9078    /**
9079     * Used during creation of InstallArgs
9080     *
9081     * @param installFlags package installation flags
9082     * @return true if should be installed as forward locked
9083     */
9084    private static boolean installForwardLocked(int installFlags) {
9085        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9086    }
9087
9088    private InstallArgs createInstallArgs(InstallParams params) {
9089        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9090            return new AsecInstallArgs(params);
9091        } else {
9092            return new FileInstallArgs(params);
9093        }
9094    }
9095
9096    /**
9097     * Create args that describe an existing installed package. Typically used
9098     * when cleaning up old installs, or used as a move source.
9099     */
9100    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9101            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9102        final boolean isInAsec;
9103        if (installOnSd(installFlags)) {
9104            /* Apps on SD card are always in ASEC containers. */
9105            isInAsec = true;
9106        } else if (installForwardLocked(installFlags)
9107                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9108            /*
9109             * Forward-locked apps are only in ASEC containers if they're the
9110             * new style
9111             */
9112            isInAsec = true;
9113        } else {
9114            isInAsec = false;
9115        }
9116
9117        if (isInAsec) {
9118            return new AsecInstallArgs(codePath, instructionSets,
9119                    installOnSd(installFlags), installForwardLocked(installFlags));
9120        } else {
9121            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9122                    instructionSets);
9123        }
9124    }
9125
9126    static abstract class InstallArgs {
9127        /** @see InstallParams#origin */
9128        final OriginInfo origin;
9129
9130        final IPackageInstallObserver2 observer;
9131        // Always refers to PackageManager flags only
9132        final int installFlags;
9133        final String installerPackageName;
9134        final ManifestDigest manifestDigest;
9135        final UserHandle user;
9136        final String abiOverride;
9137
9138        // The list of instruction sets supported by this app. This is currently
9139        // only used during the rmdex() phase to clean up resources. We can get rid of this
9140        // if we move dex files under the common app path.
9141        /* nullable */ String[] instructionSets;
9142
9143        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9144                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9145                String[] instructionSets, String abiOverride) {
9146            this.origin = origin;
9147            this.installFlags = installFlags;
9148            this.observer = observer;
9149            this.installerPackageName = installerPackageName;
9150            this.manifestDigest = manifestDigest;
9151            this.user = user;
9152            this.instructionSets = instructionSets;
9153            this.abiOverride = abiOverride;
9154        }
9155
9156        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9157        abstract int doPreInstall(int status);
9158
9159        /**
9160         * Rename package into final resting place. All paths on the given
9161         * scanned package should be updated to reflect the rename.
9162         */
9163        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9164        abstract int doPostInstall(int status, int uid);
9165
9166        /** @see PackageSettingBase#codePathString */
9167        abstract String getCodePath();
9168        /** @see PackageSettingBase#resourcePathString */
9169        abstract String getResourcePath();
9170        abstract String getLegacyNativeLibraryPath();
9171
9172        // Need installer lock especially for dex file removal.
9173        abstract void cleanUpResourcesLI();
9174        abstract boolean doPostDeleteLI(boolean delete);
9175        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9176
9177        /**
9178         * Called before the source arguments are copied. This is used mostly
9179         * for MoveParams when it needs to read the source file to put it in the
9180         * destination.
9181         */
9182        int doPreCopy() {
9183            return PackageManager.INSTALL_SUCCEEDED;
9184        }
9185
9186        /**
9187         * Called after the source arguments are copied. This is used mostly for
9188         * MoveParams when it needs to read the source file to put it in the
9189         * destination.
9190         *
9191         * @return
9192         */
9193        int doPostCopy(int uid) {
9194            return PackageManager.INSTALL_SUCCEEDED;
9195        }
9196
9197        protected boolean isFwdLocked() {
9198            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9199        }
9200
9201        protected boolean isExternal() {
9202            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9203        }
9204
9205        UserHandle getUser() {
9206            return user;
9207        }
9208    }
9209
9210    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9211        if (!allCodePaths.isEmpty()) {
9212            if (instructionSets == null) {
9213                throw new IllegalStateException("instructionSet == null");
9214            }
9215            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9216            for (String codePath : allCodePaths) {
9217                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9218                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9219                    if (retCode < 0) {
9220                        Slog.w(TAG, "Couldn't remove dex file for package: "
9221                                + " at location " + codePath + ", retcode=" + retCode);
9222                        // we don't consider this to be a failure of the core package deletion
9223                    }
9224                }
9225            }
9226        }
9227    }
9228
9229    /**
9230     * Logic to handle installation of non-ASEC applications, including copying
9231     * and renaming logic.
9232     */
9233    class FileInstallArgs extends InstallArgs {
9234        private File codeFile;
9235        private File resourceFile;
9236        private File legacyNativeLibraryPath;
9237
9238        // Example topology:
9239        // /data/app/com.example/base.apk
9240        // /data/app/com.example/split_foo.apk
9241        // /data/app/com.example/lib/arm/libfoo.so
9242        // /data/app/com.example/lib/arm64/libfoo.so
9243        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9244
9245        /** New install */
9246        FileInstallArgs(InstallParams params) {
9247            super(params.origin, params.observer, params.installFlags,
9248                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9249                    null /* instruction sets */, params.packageAbiOverride);
9250            if (isFwdLocked()) {
9251                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9252            }
9253        }
9254
9255        /** Existing install */
9256        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9257                String[] instructionSets) {
9258            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9259            this.codeFile = (codePath != null) ? new File(codePath) : null;
9260            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9261            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9262                    new File(legacyNativeLibraryPath) : null;
9263        }
9264
9265        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9266            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9267                    isFwdLocked(), abiOverride);
9268
9269            final StorageManager storage = StorageManager.from(mContext);
9270            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9271        }
9272
9273        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9274            if (origin.staged) {
9275                Slog.d(TAG, origin.file + " already staged; skipping copy");
9276                codeFile = origin.file;
9277                resourceFile = origin.file;
9278                return PackageManager.INSTALL_SUCCEEDED;
9279            }
9280
9281            try {
9282                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9283                codeFile = tempDir;
9284                resourceFile = tempDir;
9285            } catch (IOException e) {
9286                Slog.w(TAG, "Failed to create copy file: " + e);
9287                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9288            }
9289
9290            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9291                @Override
9292                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9293                    if (!FileUtils.isValidExtFilename(name)) {
9294                        throw new IllegalArgumentException("Invalid filename: " + name);
9295                    }
9296                    try {
9297                        final File file = new File(codeFile, name);
9298                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9299                                O_RDWR | O_CREAT, 0644);
9300                        Os.chmod(file.getAbsolutePath(), 0644);
9301                        return new ParcelFileDescriptor(fd);
9302                    } catch (ErrnoException e) {
9303                        throw new RemoteException("Failed to open: " + e.getMessage());
9304                    }
9305                }
9306            };
9307
9308            int ret = PackageManager.INSTALL_SUCCEEDED;
9309            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9310            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9311                Slog.e(TAG, "Failed to copy package");
9312                return ret;
9313            }
9314
9315            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9316            NativeLibraryHelper.Handle handle = null;
9317            try {
9318                handle = NativeLibraryHelper.Handle.create(codeFile);
9319                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9320                        abiOverride);
9321            } catch (IOException e) {
9322                Slog.e(TAG, "Copying native libraries failed", e);
9323                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9324            } finally {
9325                IoUtils.closeQuietly(handle);
9326            }
9327
9328            return ret;
9329        }
9330
9331        int doPreInstall(int status) {
9332            if (status != PackageManager.INSTALL_SUCCEEDED) {
9333                cleanUp();
9334            }
9335            return status;
9336        }
9337
9338        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9339            if (status != PackageManager.INSTALL_SUCCEEDED) {
9340                cleanUp();
9341                return false;
9342            } else {
9343                final File beforeCodeFile = codeFile;
9344                final File afterCodeFile = getNextCodePath(pkg.packageName);
9345
9346                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9347                try {
9348                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9349                } catch (ErrnoException e) {
9350                    Slog.d(TAG, "Failed to rename", e);
9351                    return false;
9352                }
9353
9354                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9355                    Slog.d(TAG, "Failed to restorecon");
9356                    return false;
9357                }
9358
9359                // Reflect the rename internally
9360                codeFile = afterCodeFile;
9361                resourceFile = afterCodeFile;
9362
9363                // Reflect the rename in scanned details
9364                pkg.codePath = afterCodeFile.getAbsolutePath();
9365                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9366                        pkg.baseCodePath);
9367                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9368                        pkg.splitCodePaths);
9369
9370                // Reflect the rename in app info
9371                pkg.applicationInfo.setCodePath(pkg.codePath);
9372                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9373                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9374                pkg.applicationInfo.setResourcePath(pkg.codePath);
9375                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9376                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9377
9378                return true;
9379            }
9380        }
9381
9382        int doPostInstall(int status, int uid) {
9383            if (status != PackageManager.INSTALL_SUCCEEDED) {
9384                cleanUp();
9385            }
9386            return status;
9387        }
9388
9389        @Override
9390        String getCodePath() {
9391            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9392        }
9393
9394        @Override
9395        String getResourcePath() {
9396            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9397        }
9398
9399        @Override
9400        String getLegacyNativeLibraryPath() {
9401            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9402        }
9403
9404        private boolean cleanUp() {
9405            if (codeFile == null || !codeFile.exists()) {
9406                return false;
9407            }
9408
9409            if (codeFile.isDirectory()) {
9410                FileUtils.deleteContents(codeFile);
9411            }
9412            codeFile.delete();
9413
9414            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9415                resourceFile.delete();
9416            }
9417
9418            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9419                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9420                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9421                }
9422                legacyNativeLibraryPath.delete();
9423            }
9424
9425            return true;
9426        }
9427
9428        void cleanUpResourcesLI() {
9429            // Try enumerating all code paths before deleting
9430            List<String> allCodePaths = Collections.EMPTY_LIST;
9431            if (codeFile != null && codeFile.exists()) {
9432                try {
9433                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9434                    allCodePaths = pkg.getAllCodePaths();
9435                } catch (PackageParserException e) {
9436                    // Ignored; we tried our best
9437                }
9438            }
9439
9440            cleanUp();
9441            removeDexFiles(allCodePaths, instructionSets);
9442        }
9443
9444        boolean doPostDeleteLI(boolean delete) {
9445            // XXX err, shouldn't we respect the delete flag?
9446            cleanUpResourcesLI();
9447            return true;
9448        }
9449    }
9450
9451    private boolean isAsecExternal(String cid) {
9452        final String asecPath = PackageHelper.getSdFilesystem(cid);
9453        return !asecPath.startsWith(mAsecInternalPath);
9454    }
9455
9456    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9457            PackageManagerException {
9458        if (copyRet < 0) {
9459            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9460                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9461                throw new PackageManagerException(copyRet, message);
9462            }
9463        }
9464    }
9465
9466    /**
9467     * Extract the MountService "container ID" from the full code path of an
9468     * .apk.
9469     */
9470    static String cidFromCodePath(String fullCodePath) {
9471        int eidx = fullCodePath.lastIndexOf("/");
9472        String subStr1 = fullCodePath.substring(0, eidx);
9473        int sidx = subStr1.lastIndexOf("/");
9474        return subStr1.substring(sidx+1, eidx);
9475    }
9476
9477    /**
9478     * Logic to handle installation of ASEC applications, including copying and
9479     * renaming logic.
9480     */
9481    class AsecInstallArgs extends InstallArgs {
9482        static final String RES_FILE_NAME = "pkg.apk";
9483        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9484
9485        String cid;
9486        String packagePath;
9487        String resourcePath;
9488        String legacyNativeLibraryDir;
9489
9490        /** New install */
9491        AsecInstallArgs(InstallParams params) {
9492            super(params.origin, params.observer, params.installFlags,
9493                    params.installerPackageName, params.getManifestDigest(),
9494                    params.getUser(), null /* instruction sets */,
9495                    params.packageAbiOverride);
9496        }
9497
9498        /** Existing install */
9499        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9500                        boolean isExternal, boolean isForwardLocked) {
9501            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9502                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9503                    instructionSets, null);
9504            // Hackily pretend we're still looking at a full code path
9505            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9506                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9507            }
9508
9509            // Extract cid from fullCodePath
9510            int eidx = fullCodePath.lastIndexOf("/");
9511            String subStr1 = fullCodePath.substring(0, eidx);
9512            int sidx = subStr1.lastIndexOf("/");
9513            cid = subStr1.substring(sidx+1, eidx);
9514            setMountPath(subStr1);
9515        }
9516
9517        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9518            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9519                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9520                    instructionSets, null);
9521            this.cid = cid;
9522            setMountPath(PackageHelper.getSdDir(cid));
9523        }
9524
9525        void createCopyFile() {
9526            cid = mInstallerService.allocateExternalStageCidLegacy();
9527        }
9528
9529        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9530            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9531                    abiOverride);
9532
9533            final File target;
9534            if (isExternal()) {
9535                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9536            } else {
9537                target = Environment.getDataDirectory();
9538            }
9539
9540            final StorageManager storage = StorageManager.from(mContext);
9541            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9542        }
9543
9544        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9545            if (origin.staged) {
9546                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9547                cid = origin.cid;
9548                setMountPath(PackageHelper.getSdDir(cid));
9549                return PackageManager.INSTALL_SUCCEEDED;
9550            }
9551
9552            if (temp) {
9553                createCopyFile();
9554            } else {
9555                /*
9556                 * Pre-emptively destroy the container since it's destroyed if
9557                 * copying fails due to it existing anyway.
9558                 */
9559                PackageHelper.destroySdDir(cid);
9560            }
9561
9562            final String newMountPath = imcs.copyPackageToContainer(
9563                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9564                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9565
9566            if (newMountPath != null) {
9567                setMountPath(newMountPath);
9568                return PackageManager.INSTALL_SUCCEEDED;
9569            } else {
9570                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9571            }
9572        }
9573
9574        @Override
9575        String getCodePath() {
9576            return packagePath;
9577        }
9578
9579        @Override
9580        String getResourcePath() {
9581            return resourcePath;
9582        }
9583
9584        @Override
9585        String getLegacyNativeLibraryPath() {
9586            return legacyNativeLibraryDir;
9587        }
9588
9589        int doPreInstall(int status) {
9590            if (status != PackageManager.INSTALL_SUCCEEDED) {
9591                // Destroy container
9592                PackageHelper.destroySdDir(cid);
9593            } else {
9594                boolean mounted = PackageHelper.isContainerMounted(cid);
9595                if (!mounted) {
9596                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9597                            Process.SYSTEM_UID);
9598                    if (newMountPath != null) {
9599                        setMountPath(newMountPath);
9600                    } else {
9601                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9602                    }
9603                }
9604            }
9605            return status;
9606        }
9607
9608        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9609            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9610            String newMountPath = null;
9611            if (PackageHelper.isContainerMounted(cid)) {
9612                // Unmount the container
9613                if (!PackageHelper.unMountSdDir(cid)) {
9614                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9615                    return false;
9616                }
9617            }
9618            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9619                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9620                        " which might be stale. Will try to clean up.");
9621                // Clean up the stale container and proceed to recreate.
9622                if (!PackageHelper.destroySdDir(newCacheId)) {
9623                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9624                    return false;
9625                }
9626                // Successfully cleaned up stale container. Try to rename again.
9627                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9628                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9629                            + " inspite of cleaning it up.");
9630                    return false;
9631                }
9632            }
9633            if (!PackageHelper.isContainerMounted(newCacheId)) {
9634                Slog.w(TAG, "Mounting container " + newCacheId);
9635                newMountPath = PackageHelper.mountSdDir(newCacheId,
9636                        getEncryptKey(), Process.SYSTEM_UID);
9637            } else {
9638                newMountPath = PackageHelper.getSdDir(newCacheId);
9639            }
9640            if (newMountPath == null) {
9641                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9642                return false;
9643            }
9644            Log.i(TAG, "Succesfully renamed " + cid +
9645                    " to " + newCacheId +
9646                    " at new path: " + newMountPath);
9647            cid = newCacheId;
9648
9649            final File beforeCodeFile = new File(packagePath);
9650            setMountPath(newMountPath);
9651            final File afterCodeFile = new File(packagePath);
9652
9653            // Reflect the rename in scanned details
9654            pkg.codePath = afterCodeFile.getAbsolutePath();
9655            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9656                    pkg.baseCodePath);
9657            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9658                    pkg.splitCodePaths);
9659
9660            // Reflect the rename in app info
9661            pkg.applicationInfo.setCodePath(pkg.codePath);
9662            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9663            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9664            pkg.applicationInfo.setResourcePath(pkg.codePath);
9665            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9666            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9667
9668            return true;
9669        }
9670
9671        private void setMountPath(String mountPath) {
9672            final File mountFile = new File(mountPath);
9673
9674            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9675            if (monolithicFile.exists()) {
9676                packagePath = monolithicFile.getAbsolutePath();
9677                if (isFwdLocked()) {
9678                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9679                } else {
9680                    resourcePath = packagePath;
9681                }
9682            } else {
9683                packagePath = mountFile.getAbsolutePath();
9684                resourcePath = packagePath;
9685            }
9686
9687            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9688        }
9689
9690        int doPostInstall(int status, int uid) {
9691            if (status != PackageManager.INSTALL_SUCCEEDED) {
9692                cleanUp();
9693            } else {
9694                final int groupOwner;
9695                final String protectedFile;
9696                if (isFwdLocked()) {
9697                    groupOwner = UserHandle.getSharedAppGid(uid);
9698                    protectedFile = RES_FILE_NAME;
9699                } else {
9700                    groupOwner = -1;
9701                    protectedFile = null;
9702                }
9703
9704                if (uid < Process.FIRST_APPLICATION_UID
9705                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9706                    Slog.e(TAG, "Failed to finalize " + cid);
9707                    PackageHelper.destroySdDir(cid);
9708                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9709                }
9710
9711                boolean mounted = PackageHelper.isContainerMounted(cid);
9712                if (!mounted) {
9713                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9714                }
9715            }
9716            return status;
9717        }
9718
9719        private void cleanUp() {
9720            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9721
9722            // Destroy secure container
9723            PackageHelper.destroySdDir(cid);
9724        }
9725
9726        private List<String> getAllCodePaths() {
9727            final File codeFile = new File(getCodePath());
9728            if (codeFile != null && codeFile.exists()) {
9729                try {
9730                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9731                    return pkg.getAllCodePaths();
9732                } catch (PackageParserException e) {
9733                    // Ignored; we tried our best
9734                }
9735            }
9736            return Collections.EMPTY_LIST;
9737        }
9738
9739        void cleanUpResourcesLI() {
9740            // Enumerate all code paths before deleting
9741            cleanUpResourcesLI(getAllCodePaths());
9742        }
9743
9744        private void cleanUpResourcesLI(List<String> allCodePaths) {
9745            cleanUp();
9746            removeDexFiles(allCodePaths, instructionSets);
9747        }
9748
9749
9750
9751        String getPackageName() {
9752            return getAsecPackageName(cid);
9753        }
9754
9755        boolean doPostDeleteLI(boolean delete) {
9756            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9757            final List<String> allCodePaths = getAllCodePaths();
9758            boolean mounted = PackageHelper.isContainerMounted(cid);
9759            if (mounted) {
9760                // Unmount first
9761                if (PackageHelper.unMountSdDir(cid)) {
9762                    mounted = false;
9763                }
9764            }
9765            if (!mounted && delete) {
9766                cleanUpResourcesLI(allCodePaths);
9767            }
9768            return !mounted;
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 scanFlags, UserHandle user,
9930            String installerPackageName, PackageInstalledInfo res) {
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)) {
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, scanFlags,
9957                    System.currentTimeMillis(), user);
9958
9959            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
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 scanFlags, UserHandle user,
9993            String installerPackageName, PackageInstalledInfo res) {
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_FAILED_UPDATE_INCOMPATIBLE,
10009                            "New package has a different signature: " + pkgName);
10010                    return;
10011                }
10012            } else {
10013                if(!checkUpgradeKeySetLP(ps, pkg)) {
10014                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
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, scanFlags,
10032                    user, allUsers, perUserInstalled, installerPackageName, res);
10033        } else {
10034            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10035                    user, allUsers, perUserInstalled, installerPackageName, res);
10036        }
10037    }
10038
10039    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10040            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10041            int[] allUsers, boolean[] perUserInstalled,
10042            String installerPackageName, PackageInstalledInfo res) {
10043        String pkgName = deletedPackage.packageName;
10044        boolean deletedPkg = true;
10045        boolean updatedSettings = false;
10046
10047        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10048                + deletedPackage);
10049        long origUpdateTime;
10050        if (pkg.mExtras != null) {
10051            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10052        } else {
10053            origUpdateTime = 0;
10054        }
10055
10056        // First delete the existing package while retaining the data directory
10057        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10058                res.removedInfo, true)) {
10059            // If the existing package wasn't successfully deleted
10060            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10061            deletedPkg = false;
10062        } else {
10063            // Successfully deleted the old package; proceed with replace.
10064
10065            // If deleted package lived in a container, give users a chance to
10066            // relinquish resources before killing.
10067            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10068                if (DEBUG_INSTALL) {
10069                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10070                }
10071                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10072                final ArrayList<String> pkgList = new ArrayList<String>(1);
10073                pkgList.add(deletedPackage.applicationInfo.packageName);
10074                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10075            }
10076
10077            deleteCodeCacheDirsLI(pkgName);
10078            try {
10079                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10080                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10081                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10082                        user);
10083                updatedSettings = true;
10084            } catch (PackageManagerException e) {
10085                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10086            }
10087        }
10088
10089        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10090            // remove package from internal structures.  Note that we want deletePackageX to
10091            // delete the package data and cache directories that it created in
10092            // scanPackageLocked, unless those directories existed before we even tried to
10093            // install.
10094            if(updatedSettings) {
10095                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10096                deletePackageLI(
10097                        pkgName, null, true, allUsers, perUserInstalled,
10098                        PackageManager.DELETE_KEEP_DATA,
10099                                res.removedInfo, true);
10100            }
10101            // Since we failed to install the new package we need to restore the old
10102            // package that we deleted.
10103            if (deletedPkg) {
10104                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10105                File restoreFile = new File(deletedPackage.codePath);
10106                // Parse old package
10107                boolean oldOnSd = isExternal(deletedPackage);
10108                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10109                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10110                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10111                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10112                try {
10113                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10114                } catch (PackageManagerException e) {
10115                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10116                            + e.getMessage());
10117                    return;
10118                }
10119                // Restore of old package succeeded. Update permissions.
10120                // writer
10121                synchronized (mPackages) {
10122                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10123                            UPDATE_PERMISSIONS_ALL);
10124                    // can downgrade to reader
10125                    mSettings.writeLPr();
10126                }
10127                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10128            }
10129        }
10130    }
10131
10132    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10133            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10134            int[] allUsers, boolean[] perUserInstalled,
10135            String installerPackageName, PackageInstalledInfo res) {
10136        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10137                + ", old=" + deletedPackage);
10138        boolean disabledSystem = false;
10139        boolean updatedSettings = false;
10140        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10141        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10142                != 0) {
10143            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10144        }
10145        String packageName = deletedPackage.packageName;
10146        if (packageName == null) {
10147            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10148                    "Attempt to delete null packageName.");
10149            return;
10150        }
10151        PackageParser.Package oldPkg;
10152        PackageSetting oldPkgSetting;
10153        // reader
10154        synchronized (mPackages) {
10155            oldPkg = mPackages.get(packageName);
10156            oldPkgSetting = mSettings.mPackages.get(packageName);
10157            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10158                    (oldPkgSetting == null)) {
10159                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10160                        "Couldn't find package:" + packageName + " information");
10161                return;
10162            }
10163        }
10164
10165        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10166
10167        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10168        res.removedInfo.removedPackage = packageName;
10169        // Remove existing system package
10170        removePackageLI(oldPkgSetting, true);
10171        // writer
10172        synchronized (mPackages) {
10173            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10174            if (!disabledSystem && deletedPackage != null) {
10175                // We didn't need to disable the .apk as a current system package,
10176                // which means we are replacing another update that is already
10177                // installed.  We need to make sure to delete the older one's .apk.
10178                res.removedInfo.args = createInstallArgsForExisting(0,
10179                        deletedPackage.applicationInfo.getCodePath(),
10180                        deletedPackage.applicationInfo.getResourcePath(),
10181                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10182                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10183            } else {
10184                res.removedInfo.args = null;
10185            }
10186        }
10187
10188        // Successfully disabled the old package. Now proceed with re-installation
10189        deleteCodeCacheDirsLI(packageName);
10190
10191        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10192        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10193
10194        PackageParser.Package newPackage = null;
10195        try {
10196            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10197            if (newPackage.mExtras != null) {
10198                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10199                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10200                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10201
10202                // is the update attempting to change shared user? that isn't going to work...
10203                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10204                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10205                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10206                            + " to " + newPkgSetting.sharedUser);
10207                    updatedSettings = true;
10208                }
10209            }
10210
10211            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10212                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10213                        user);
10214                updatedSettings = true;
10215            }
10216
10217        } catch (PackageManagerException e) {
10218            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10219        }
10220
10221        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10222            // Re installation failed. Restore old information
10223            // Remove new pkg information
10224            if (newPackage != null) {
10225                removeInstalledPackageLI(newPackage, true);
10226            }
10227            // Add back the old system package
10228            try {
10229                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10230            } catch (PackageManagerException e) {
10231                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10232            }
10233            // Restore the old system information in Settings
10234            synchronized (mPackages) {
10235                if (disabledSystem) {
10236                    mSettings.enableSystemPackageLPw(packageName);
10237                }
10238                if (updatedSettings) {
10239                    mSettings.setInstallerPackageName(packageName,
10240                            oldPkgSetting.installerPackageName);
10241                }
10242                mSettings.writeLPr();
10243            }
10244        }
10245    }
10246
10247    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10248            int[] allUsers, boolean[] perUserInstalled,
10249            PackageInstalledInfo res, UserHandle user) {
10250        String pkgName = newPackage.packageName;
10251        synchronized (mPackages) {
10252            //write settings. the installStatus will be incomplete at this stage.
10253            //note that the new package setting would have already been
10254            //added to mPackages. It hasn't been persisted yet.
10255            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10256            mSettings.writeLPr();
10257        }
10258
10259        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10260
10261        synchronized (mPackages) {
10262            updatePermissionsLPw(newPackage.packageName, newPackage,
10263                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10264                            ? UPDATE_PERMISSIONS_ALL : 0));
10265            // For system-bundled packages, we assume that installing an upgraded version
10266            // of the package implies that the user actually wants to run that new code,
10267            // so we enable the package.
10268            PackageSetting ps = mSettings.mPackages.get(pkgName);
10269            if (ps != null) {
10270                if (isSystemApp(newPackage)) {
10271                    // NB: implicit assumption that system package upgrades apply to all users
10272                    if (DEBUG_INSTALL) {
10273                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10274                    }
10275                    if (res.origUsers != null) {
10276                        for (int userHandle : res.origUsers) {
10277                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10278                                    userHandle, installerPackageName);
10279                        }
10280                    }
10281                    // Also convey the prior install/uninstall state
10282                    if (allUsers != null && perUserInstalled != null) {
10283                        for (int i = 0; i < allUsers.length; i++) {
10284                            if (DEBUG_INSTALL) {
10285                                Slog.d(TAG, "    user " + allUsers[i]
10286                                        + " => " + perUserInstalled[i]);
10287                            }
10288                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10289                        }
10290                        // these install state changes will be persisted in the
10291                        // upcoming call to mSettings.writeLPr().
10292                    }
10293                }
10294                // It's implied that when a user requests installation, they want the app to be
10295                // installed and enabled.
10296                int userId = user.getIdentifier();
10297                if (userId != UserHandle.USER_ALL) {
10298                    ps.setInstalled(true, userId);
10299                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10300                }
10301            }
10302            res.name = pkgName;
10303            res.uid = newPackage.applicationInfo.uid;
10304            res.pkg = newPackage;
10305            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10306            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10307            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10308            //to update install status
10309            mSettings.writeLPr();
10310        }
10311    }
10312
10313    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10314        final int installFlags = args.installFlags;
10315        String installerPackageName = args.installerPackageName;
10316        File tmpPackageFile = new File(args.getCodePath());
10317        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10318        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10319        boolean replace = false;
10320        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10321        // Result object to be returned
10322        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10323
10324        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10325        // Retrieve PackageSettings and parse package
10326        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10327                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10328                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10329        PackageParser pp = new PackageParser();
10330        pp.setSeparateProcesses(mSeparateProcesses);
10331        pp.setDisplayMetrics(mMetrics);
10332
10333        final PackageParser.Package pkg;
10334        try {
10335            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10336        } catch (PackageParserException e) {
10337            res.setError("Failed parse during installPackageLI", e);
10338            return;
10339        }
10340
10341        // Mark that we have an install time CPU ABI override.
10342        pkg.cpuAbiOverride = args.abiOverride;
10343
10344        String pkgName = res.name = pkg.packageName;
10345        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10346            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10347                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10348                return;
10349            }
10350        }
10351
10352        try {
10353            pp.collectCertificates(pkg, parseFlags);
10354            pp.collectManifestDigest(pkg);
10355        } catch (PackageParserException e) {
10356            res.setError("Failed collect during installPackageLI", e);
10357            return;
10358        }
10359
10360        /* If the installer passed in a manifest digest, compare it now. */
10361        if (args.manifestDigest != null) {
10362            if (DEBUG_INSTALL) {
10363                final String parsedManifest = pkg.manifestDigest == null ? "null"
10364                        : pkg.manifestDigest.toString();
10365                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10366                        + parsedManifest);
10367            }
10368
10369            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10370                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10371                return;
10372            }
10373        } else if (DEBUG_INSTALL) {
10374            final String parsedManifest = pkg.manifestDigest == null
10375                    ? "null" : pkg.manifestDigest.toString();
10376            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10377        }
10378
10379        // Get rid of all references to package scan path via parser.
10380        pp = null;
10381        String oldCodePath = null;
10382        boolean systemApp = false;
10383        synchronized (mPackages) {
10384            // Check if installing already existing package
10385            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10386                String oldName = mSettings.mRenamedPackages.get(pkgName);
10387                if (pkg.mOriginalPackages != null
10388                        && pkg.mOriginalPackages.contains(oldName)
10389                        && mPackages.containsKey(oldName)) {
10390                    // This package is derived from an original package,
10391                    // and this device has been updating from that original
10392                    // name.  We must continue using the original name, so
10393                    // rename the new package here.
10394                    pkg.setPackageName(oldName);
10395                    pkgName = pkg.packageName;
10396                    replace = true;
10397                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10398                            + oldName + " pkgName=" + pkgName);
10399                } else if (mPackages.containsKey(pkgName)) {
10400                    // This package, under its official name, already exists
10401                    // on the device; we should replace it.
10402                    replace = true;
10403                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10404                }
10405            }
10406
10407            PackageSetting ps = mSettings.mPackages.get(pkgName);
10408            if (ps != null) {
10409                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10410
10411                // Quick sanity check that we're signed correctly if updating;
10412                // we'll check this again later when scanning, but we want to
10413                // bail early here before tripping over redefined permissions.
10414                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10415                    try {
10416                        verifySignaturesLP(ps, pkg);
10417                    } catch (PackageManagerException e) {
10418                        res.setError(e.error, e.getMessage());
10419                        return;
10420                    }
10421                } else {
10422                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10423                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10424                                + pkg.packageName + " upgrade keys do not match the "
10425                                + "previously installed version");
10426                        return;
10427                    }
10428                }
10429
10430                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10431                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10432                    systemApp = (ps.pkg.applicationInfo.flags &
10433                            ApplicationInfo.FLAG_SYSTEM) != 0;
10434                }
10435                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10436            }
10437
10438            // Check whether the newly-scanned package wants to define an already-defined perm
10439            int N = pkg.permissions.size();
10440            for (int i = N-1; i >= 0; i--) {
10441                PackageParser.Permission perm = pkg.permissions.get(i);
10442                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10443                if (bp != null) {
10444                    // If the defining package is signed with our cert, it's okay.  This
10445                    // also includes the "updating the same package" case, of course.
10446                    // "updating same package" could also involve key-rotation.
10447                    final boolean sigsOk;
10448                    if (!bp.sourcePackage.equals(pkg.packageName)
10449                            || !(bp.packageSetting instanceof PackageSetting)
10450                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10451                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10452                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10453                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10454                    } else {
10455                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10456                    }
10457                    if (!sigsOk) {
10458                        // If the owning package is the system itself, we log but allow
10459                        // install to proceed; we fail the install on all other permission
10460                        // redefinitions.
10461                        if (!bp.sourcePackage.equals("android")) {
10462                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10463                                    + pkg.packageName + " attempting to redeclare permission "
10464                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10465                            res.origPermission = perm.info.name;
10466                            res.origPackage = bp.sourcePackage;
10467                            return;
10468                        } else {
10469                            Slog.w(TAG, "Package " + pkg.packageName
10470                                    + " attempting to redeclare system permission "
10471                                    + perm.info.name + "; ignoring new declaration");
10472                            pkg.permissions.remove(i);
10473                        }
10474                    }
10475                }
10476            }
10477
10478        }
10479
10480        if (systemApp && onSd) {
10481            // Disable updates to system apps on sdcard
10482            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10483                    "Cannot install updates to system apps on sdcard");
10484            return;
10485        }
10486
10487        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10488            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10489            return;
10490        }
10491
10492        if (replace) {
10493            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10494                    installerPackageName, res);
10495        } else {
10496            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10497                    args.user, installerPackageName, res);
10498        }
10499        synchronized (mPackages) {
10500            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10501            if (ps != null) {
10502                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10503            }
10504        }
10505    }
10506
10507    private static boolean isMultiArch(PackageSetting ps) {
10508        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10509    }
10510
10511    private static boolean isMultiArch(ApplicationInfo info) {
10512        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10513    }
10514
10515    private static boolean isExternal(PackageParser.Package pkg) {
10516        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10517    }
10518
10519    private static boolean isExternal(PackageSetting ps) {
10520        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10521    }
10522
10523    private static boolean isExternal(ApplicationInfo info) {
10524        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10525    }
10526
10527    private static boolean isSystemApp(PackageParser.Package pkg) {
10528        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10529    }
10530
10531    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10532        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10533    }
10534
10535    private static boolean isSystemApp(ApplicationInfo info) {
10536        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10537    }
10538
10539    private static boolean isSystemApp(PackageSetting ps) {
10540        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10541    }
10542
10543    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10544        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10545    }
10546
10547    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10548        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10549    }
10550
10551    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10552        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10553    }
10554
10555    private int packageFlagsToInstallFlags(PackageSetting ps) {
10556        int installFlags = 0;
10557        if (isExternal(ps)) {
10558            installFlags |= PackageManager.INSTALL_EXTERNAL;
10559        }
10560        if (ps.isForwardLocked()) {
10561            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10562        }
10563        return installFlags;
10564    }
10565
10566    private void deleteTempPackageFiles() {
10567        final FilenameFilter filter = new FilenameFilter() {
10568            public boolean accept(File dir, String name) {
10569                return name.startsWith("vmdl") && name.endsWith(".tmp");
10570            }
10571        };
10572        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10573            file.delete();
10574        }
10575    }
10576
10577    @Override
10578    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10579            int flags) {
10580        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10581                flags);
10582    }
10583
10584    @Override
10585    public void deletePackage(final String packageName,
10586            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10587        mContext.enforceCallingOrSelfPermission(
10588                android.Manifest.permission.DELETE_PACKAGES, null);
10589        final int uid = Binder.getCallingUid();
10590        if (UserHandle.getUserId(uid) != userId) {
10591            mContext.enforceCallingPermission(
10592                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10593                    "deletePackage for user " + userId);
10594        }
10595        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10596            try {
10597                observer.onPackageDeleted(packageName,
10598                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10599            } catch (RemoteException re) {
10600            }
10601            return;
10602        }
10603
10604        boolean uninstallBlocked = false;
10605        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10606            int[] users = sUserManager.getUserIds();
10607            for (int i = 0; i < users.length; ++i) {
10608                if (getBlockUninstallForUser(packageName, users[i])) {
10609                    uninstallBlocked = true;
10610                    break;
10611                }
10612            }
10613        } else {
10614            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10615        }
10616        if (uninstallBlocked) {
10617            try {
10618                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10619                        null);
10620            } catch (RemoteException re) {
10621            }
10622            return;
10623        }
10624
10625        if (DEBUG_REMOVE) {
10626            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10627        }
10628        // Queue up an async operation since the package deletion may take a little while.
10629        mHandler.post(new Runnable() {
10630            public void run() {
10631                mHandler.removeCallbacks(this);
10632                final int returnCode = deletePackageX(packageName, userId, flags);
10633                if (observer != null) {
10634                    try {
10635                        observer.onPackageDeleted(packageName, returnCode, null);
10636                    } catch (RemoteException e) {
10637                        Log.i(TAG, "Observer no longer exists.");
10638                    } //end catch
10639                } //end if
10640            } //end run
10641        });
10642    }
10643
10644    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10645        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10646                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10647        try {
10648            if (dpm != null) {
10649                if (dpm.isDeviceOwner(packageName)) {
10650                    return true;
10651                }
10652                int[] users;
10653                if (userId == UserHandle.USER_ALL) {
10654                    users = sUserManager.getUserIds();
10655                } else {
10656                    users = new int[]{userId};
10657                }
10658                for (int i = 0; i < users.length; ++i) {
10659                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10660                        return true;
10661                    }
10662                }
10663            }
10664        } catch (RemoteException e) {
10665        }
10666        return false;
10667    }
10668
10669    /**
10670     *  This method is an internal method that could be get invoked either
10671     *  to delete an installed package or to clean up a failed installation.
10672     *  After deleting an installed package, a broadcast is sent to notify any
10673     *  listeners that the package has been installed. For cleaning up a failed
10674     *  installation, the broadcast is not necessary since the package's
10675     *  installation wouldn't have sent the initial broadcast either
10676     *  The key steps in deleting a package are
10677     *  deleting the package information in internal structures like mPackages,
10678     *  deleting the packages base directories through installd
10679     *  updating mSettings to reflect current status
10680     *  persisting settings for later use
10681     *  sending a broadcast if necessary
10682     */
10683    private int deletePackageX(String packageName, int userId, int flags) {
10684        final PackageRemovedInfo info = new PackageRemovedInfo();
10685        final boolean res;
10686
10687        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10688                ? UserHandle.ALL : new UserHandle(userId);
10689
10690        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10691            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10692            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10693        }
10694
10695        boolean removedForAllUsers = false;
10696        boolean systemUpdate = false;
10697
10698        // for the uninstall-updates case and restricted profiles, remember the per-
10699        // userhandle installed state
10700        int[] allUsers;
10701        boolean[] perUserInstalled;
10702        synchronized (mPackages) {
10703            PackageSetting ps = mSettings.mPackages.get(packageName);
10704            allUsers = sUserManager.getUserIds();
10705            perUserInstalled = new boolean[allUsers.length];
10706            for (int i = 0; i < allUsers.length; i++) {
10707                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10708            }
10709        }
10710
10711        synchronized (mInstallLock) {
10712            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10713            res = deletePackageLI(packageName, removeForUser,
10714                    true, allUsers, perUserInstalled,
10715                    flags | REMOVE_CHATTY, info, true);
10716            systemUpdate = info.isRemovedPackageSystemUpdate;
10717            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10718                removedForAllUsers = true;
10719            }
10720            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10721                    + " removedForAllUsers=" + removedForAllUsers);
10722        }
10723
10724        if (res) {
10725            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10726
10727            // If the removed package was a system update, the old system package
10728            // was re-enabled; we need to broadcast this information
10729            if (systemUpdate) {
10730                Bundle extras = new Bundle(1);
10731                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10732                        ? info.removedAppId : info.uid);
10733                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10734
10735                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10736                        extras, null, null, null);
10737                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10738                        extras, null, null, null);
10739                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10740                        null, packageName, null, null);
10741            }
10742        }
10743        // Force a gc here.
10744        Runtime.getRuntime().gc();
10745        // Delete the resources here after sending the broadcast to let
10746        // other processes clean up before deleting resources.
10747        if (info.args != null) {
10748            synchronized (mInstallLock) {
10749                info.args.doPostDeleteLI(true);
10750            }
10751        }
10752
10753        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10754    }
10755
10756    static class PackageRemovedInfo {
10757        String removedPackage;
10758        int uid = -1;
10759        int removedAppId = -1;
10760        int[] removedUsers = null;
10761        boolean isRemovedPackageSystemUpdate = false;
10762        // Clean up resources deleted packages.
10763        InstallArgs args = null;
10764
10765        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10766            Bundle extras = new Bundle(1);
10767            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10768            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10769            if (replacing) {
10770                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10771            }
10772            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10773            if (removedPackage != null) {
10774                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10775                        extras, null, null, removedUsers);
10776                if (fullRemove && !replacing) {
10777                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10778                            extras, null, null, removedUsers);
10779                }
10780            }
10781            if (removedAppId >= 0) {
10782                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10783                        removedUsers);
10784            }
10785        }
10786    }
10787
10788    /*
10789     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10790     * flag is not set, the data directory is removed as well.
10791     * make sure this flag is set for partially installed apps. If not its meaningless to
10792     * delete a partially installed application.
10793     */
10794    private void removePackageDataLI(PackageSetting ps,
10795            int[] allUserHandles, boolean[] perUserInstalled,
10796            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10797        String packageName = ps.name;
10798        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10799        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10800        // Retrieve object to delete permissions for shared user later on
10801        final PackageSetting deletedPs;
10802        // reader
10803        synchronized (mPackages) {
10804            deletedPs = mSettings.mPackages.get(packageName);
10805            if (outInfo != null) {
10806                outInfo.removedPackage = packageName;
10807                outInfo.removedUsers = deletedPs != null
10808                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10809                        : null;
10810            }
10811        }
10812        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10813            removeDataDirsLI(packageName);
10814            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10815        }
10816        // writer
10817        synchronized (mPackages) {
10818            if (deletedPs != null) {
10819                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10820                    if (outInfo != null) {
10821                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10822                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10823                    }
10824                    if (deletedPs != null) {
10825                        updatePermissionsLPw(deletedPs.name, null, 0);
10826                        if (deletedPs.sharedUser != null) {
10827                            // remove permissions associated with package
10828                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10829                        }
10830                    }
10831                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10832                }
10833                // make sure to preserve per-user disabled state if this removal was just
10834                // a downgrade of a system app to the factory package
10835                if (allUserHandles != null && perUserInstalled != null) {
10836                    if (DEBUG_REMOVE) {
10837                        Slog.d(TAG, "Propagating install state across downgrade");
10838                    }
10839                    for (int i = 0; i < allUserHandles.length; i++) {
10840                        if (DEBUG_REMOVE) {
10841                            Slog.d(TAG, "    user " + allUserHandles[i]
10842                                    + " => " + perUserInstalled[i]);
10843                        }
10844                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10845                    }
10846                }
10847            }
10848            // can downgrade to reader
10849            if (writeSettings) {
10850                // Save settings now
10851                mSettings.writeLPr();
10852            }
10853        }
10854        if (outInfo != null) {
10855            // A user ID was deleted here. Go through all users and remove it
10856            // from KeyStore.
10857            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10858        }
10859    }
10860
10861    static boolean locationIsPrivileged(File path) {
10862        try {
10863            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10864                    .getCanonicalPath();
10865            return path.getCanonicalPath().startsWith(privilegedAppDir);
10866        } catch (IOException e) {
10867            Slog.e(TAG, "Unable to access code path " + path);
10868        }
10869        return false;
10870    }
10871
10872    /*
10873     * Tries to delete system package.
10874     */
10875    private boolean deleteSystemPackageLI(PackageSetting newPs,
10876            int[] allUserHandles, boolean[] perUserInstalled,
10877            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10878        final boolean applyUserRestrictions
10879                = (allUserHandles != null) && (perUserInstalled != null);
10880        PackageSetting disabledPs = null;
10881        // Confirm if the system package has been updated
10882        // An updated system app can be deleted. This will also have to restore
10883        // the system pkg from system partition
10884        // reader
10885        synchronized (mPackages) {
10886            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10887        }
10888        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10889                + " disabledPs=" + disabledPs);
10890        if (disabledPs == null) {
10891            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10892            return false;
10893        } else if (DEBUG_REMOVE) {
10894            Slog.d(TAG, "Deleting system pkg from data partition");
10895        }
10896        if (DEBUG_REMOVE) {
10897            if (applyUserRestrictions) {
10898                Slog.d(TAG, "Remembering install states:");
10899                for (int i = 0; i < allUserHandles.length; i++) {
10900                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10901                }
10902            }
10903        }
10904        // Delete the updated package
10905        outInfo.isRemovedPackageSystemUpdate = true;
10906        if (disabledPs.versionCode < newPs.versionCode) {
10907            // Delete data for downgrades
10908            flags &= ~PackageManager.DELETE_KEEP_DATA;
10909        } else {
10910            // Preserve data by setting flag
10911            flags |= PackageManager.DELETE_KEEP_DATA;
10912        }
10913        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10914                allUserHandles, perUserInstalled, outInfo, writeSettings);
10915        if (!ret) {
10916            return false;
10917        }
10918        // writer
10919        synchronized (mPackages) {
10920            // Reinstate the old system package
10921            mSettings.enableSystemPackageLPw(newPs.name);
10922            // Remove any native libraries from the upgraded package.
10923            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10924        }
10925        // Install the system package
10926        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10927        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10928        if (locationIsPrivileged(disabledPs.codePath)) {
10929            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10930        }
10931
10932        final PackageParser.Package newPkg;
10933        try {
10934            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10935        } catch (PackageManagerException e) {
10936            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10937            return false;
10938        }
10939
10940        // writer
10941        synchronized (mPackages) {
10942            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10943            updatePermissionsLPw(newPkg.packageName, newPkg,
10944                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10945            if (applyUserRestrictions) {
10946                if (DEBUG_REMOVE) {
10947                    Slog.d(TAG, "Propagating install state across reinstall");
10948                }
10949                for (int i = 0; i < allUserHandles.length; i++) {
10950                    if (DEBUG_REMOVE) {
10951                        Slog.d(TAG, "    user " + allUserHandles[i]
10952                                + " => " + perUserInstalled[i]);
10953                    }
10954                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10955                }
10956                // Regardless of writeSettings we need to ensure that this restriction
10957                // state propagation is persisted
10958                mSettings.writeAllUsersPackageRestrictionsLPr();
10959            }
10960            // can downgrade to reader here
10961            if (writeSettings) {
10962                mSettings.writeLPr();
10963            }
10964        }
10965        return true;
10966    }
10967
10968    private boolean deleteInstalledPackageLI(PackageSetting ps,
10969            boolean deleteCodeAndResources, int flags,
10970            int[] allUserHandles, boolean[] perUserInstalled,
10971            PackageRemovedInfo outInfo, boolean writeSettings) {
10972        if (outInfo != null) {
10973            outInfo.uid = ps.appId;
10974        }
10975
10976        // Delete package data from internal structures and also remove data if flag is set
10977        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10978
10979        // Delete application code and resources
10980        if (deleteCodeAndResources && (outInfo != null)) {
10981            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10982                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10983                    getAppDexInstructionSets(ps));
10984            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10985        }
10986        return true;
10987    }
10988
10989    @Override
10990    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10991            int userId) {
10992        mContext.enforceCallingOrSelfPermission(
10993                android.Manifest.permission.DELETE_PACKAGES, null);
10994        synchronized (mPackages) {
10995            PackageSetting ps = mSettings.mPackages.get(packageName);
10996            if (ps == null) {
10997                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10998                return false;
10999            }
11000            if (!ps.getInstalled(userId)) {
11001                // Can't block uninstall for an app that is not installed or enabled.
11002                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11003                return false;
11004            }
11005            ps.setBlockUninstall(blockUninstall, userId);
11006            mSettings.writePackageRestrictionsLPr(userId);
11007        }
11008        return true;
11009    }
11010
11011    @Override
11012    public boolean getBlockUninstallForUser(String packageName, int userId) {
11013        synchronized (mPackages) {
11014            PackageSetting ps = mSettings.mPackages.get(packageName);
11015            if (ps == null) {
11016                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11017                return false;
11018            }
11019            return ps.getBlockUninstall(userId);
11020        }
11021    }
11022
11023    /*
11024     * This method handles package deletion in general
11025     */
11026    private boolean deletePackageLI(String packageName, UserHandle user,
11027            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11028            int flags, PackageRemovedInfo outInfo,
11029            boolean writeSettings) {
11030        if (packageName == null) {
11031            Slog.w(TAG, "Attempt to delete null packageName.");
11032            return false;
11033        }
11034        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11035        PackageSetting ps;
11036        boolean dataOnly = false;
11037        int removeUser = -1;
11038        int appId = -1;
11039        synchronized (mPackages) {
11040            ps = mSettings.mPackages.get(packageName);
11041            if (ps == null) {
11042                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11043                return false;
11044            }
11045            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11046                    && user.getIdentifier() != UserHandle.USER_ALL) {
11047                // The caller is asking that the package only be deleted for a single
11048                // user.  To do this, we just mark its uninstalled state and delete
11049                // its data.  If this is a system app, we only allow this to happen if
11050                // they have set the special DELETE_SYSTEM_APP which requests different
11051                // semantics than normal for uninstalling system apps.
11052                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11053                ps.setUserState(user.getIdentifier(),
11054                        COMPONENT_ENABLED_STATE_DEFAULT,
11055                        false, //installed
11056                        true,  //stopped
11057                        true,  //notLaunched
11058                        false, //hidden
11059                        null, null, null,
11060                        false // blockUninstall
11061                        );
11062                if (!isSystemApp(ps)) {
11063                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11064                        // Other user still have this package installed, so all
11065                        // we need to do is clear this user's data and save that
11066                        // it is uninstalled.
11067                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11068                        removeUser = user.getIdentifier();
11069                        appId = ps.appId;
11070                        mSettings.writePackageRestrictionsLPr(removeUser);
11071                    } else {
11072                        // We need to set it back to 'installed' so the uninstall
11073                        // broadcasts will be sent correctly.
11074                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11075                        ps.setInstalled(true, user.getIdentifier());
11076                    }
11077                } else {
11078                    // This is a system app, so we assume that the
11079                    // other users still have this package installed, so all
11080                    // we need to do is clear this user's data and save that
11081                    // it is uninstalled.
11082                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11083                    removeUser = user.getIdentifier();
11084                    appId = ps.appId;
11085                    mSettings.writePackageRestrictionsLPr(removeUser);
11086                }
11087            }
11088        }
11089
11090        if (removeUser >= 0) {
11091            // From above, we determined that we are deleting this only
11092            // for a single user.  Continue the work here.
11093            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11094            if (outInfo != null) {
11095                outInfo.removedPackage = packageName;
11096                outInfo.removedAppId = appId;
11097                outInfo.removedUsers = new int[] {removeUser};
11098            }
11099            mInstaller.clearUserData(packageName, removeUser);
11100            removeKeystoreDataIfNeeded(removeUser, appId);
11101            schedulePackageCleaning(packageName, removeUser, false);
11102            return true;
11103        }
11104
11105        if (dataOnly) {
11106            // Delete application data first
11107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11108            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11109            return true;
11110        }
11111
11112        boolean ret = false;
11113        if (isSystemApp(ps)) {
11114            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11115            // When an updated system application is deleted we delete the existing resources as well and
11116            // fall back to existing code in system partition
11117            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11118                    flags, outInfo, writeSettings);
11119        } else {
11120            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11121            // Kill application pre-emptively especially for apps on sd.
11122            killApplication(packageName, ps.appId, "uninstall pkg");
11123            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11124                    allUserHandles, perUserInstalled,
11125                    outInfo, writeSettings);
11126        }
11127
11128        return ret;
11129    }
11130
11131    private final class ClearStorageConnection implements ServiceConnection {
11132        IMediaContainerService mContainerService;
11133
11134        @Override
11135        public void onServiceConnected(ComponentName name, IBinder service) {
11136            synchronized (this) {
11137                mContainerService = IMediaContainerService.Stub.asInterface(service);
11138                notifyAll();
11139            }
11140        }
11141
11142        @Override
11143        public void onServiceDisconnected(ComponentName name) {
11144        }
11145    }
11146
11147    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11148        final boolean mounted;
11149        if (Environment.isExternalStorageEmulated()) {
11150            mounted = true;
11151        } else {
11152            final String status = Environment.getExternalStorageState();
11153
11154            mounted = status.equals(Environment.MEDIA_MOUNTED)
11155                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11156        }
11157
11158        if (!mounted) {
11159            return;
11160        }
11161
11162        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11163        int[] users;
11164        if (userId == UserHandle.USER_ALL) {
11165            users = sUserManager.getUserIds();
11166        } else {
11167            users = new int[] { userId };
11168        }
11169        final ClearStorageConnection conn = new ClearStorageConnection();
11170        if (mContext.bindServiceAsUser(
11171                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11172            try {
11173                for (int curUser : users) {
11174                    long timeout = SystemClock.uptimeMillis() + 5000;
11175                    synchronized (conn) {
11176                        long now = SystemClock.uptimeMillis();
11177                        while (conn.mContainerService == null && now < timeout) {
11178                            try {
11179                                conn.wait(timeout - now);
11180                            } catch (InterruptedException e) {
11181                            }
11182                        }
11183                    }
11184                    if (conn.mContainerService == null) {
11185                        return;
11186                    }
11187
11188                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11189                    clearDirectory(conn.mContainerService,
11190                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11191                    if (allData) {
11192                        clearDirectory(conn.mContainerService,
11193                                userEnv.buildExternalStorageAppDataDirs(packageName));
11194                        clearDirectory(conn.mContainerService,
11195                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11196                    }
11197                }
11198            } finally {
11199                mContext.unbindService(conn);
11200            }
11201        }
11202    }
11203
11204    @Override
11205    public void clearApplicationUserData(final String packageName,
11206            final IPackageDataObserver observer, final int userId) {
11207        mContext.enforceCallingOrSelfPermission(
11208                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11209        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11210        // Queue up an async operation since the package deletion may take a little while.
11211        mHandler.post(new Runnable() {
11212            public void run() {
11213                mHandler.removeCallbacks(this);
11214                final boolean succeeded;
11215                synchronized (mInstallLock) {
11216                    succeeded = clearApplicationUserDataLI(packageName, userId);
11217                }
11218                clearExternalStorageDataSync(packageName, userId, true);
11219                if (succeeded) {
11220                    // invoke DeviceStorageMonitor's update method to clear any notifications
11221                    DeviceStorageMonitorInternal
11222                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11223                    if (dsm != null) {
11224                        dsm.checkMemory();
11225                    }
11226                }
11227                if(observer != null) {
11228                    try {
11229                        observer.onRemoveCompleted(packageName, succeeded);
11230                    } catch (RemoteException e) {
11231                        Log.i(TAG, "Observer no longer exists.");
11232                    }
11233                } //end if observer
11234            } //end run
11235        });
11236    }
11237
11238    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11239        if (packageName == null) {
11240            Slog.w(TAG, "Attempt to delete null packageName.");
11241            return false;
11242        }
11243
11244        // Try finding details about the requested package
11245        PackageParser.Package pkg;
11246        synchronized (mPackages) {
11247            pkg = mPackages.get(packageName);
11248            if (pkg == null) {
11249                final PackageSetting ps = mSettings.mPackages.get(packageName);
11250                if (ps != null) {
11251                    pkg = ps.pkg;
11252                }
11253            }
11254        }
11255
11256        if (pkg == null) {
11257            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11258        }
11259
11260        // Always delete data directories for package, even if we found no other
11261        // record of app. This helps users recover from UID mismatches without
11262        // resorting to a full data wipe.
11263        int retCode = mInstaller.clearUserData(packageName, userId);
11264        if (retCode < 0) {
11265            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11266            return false;
11267        }
11268
11269        if (pkg == null) {
11270            return false;
11271        }
11272
11273        if (pkg != null && pkg.applicationInfo != null) {
11274            final int appId = pkg.applicationInfo.uid;
11275            removeKeystoreDataIfNeeded(userId, appId);
11276        }
11277
11278        // Create a native library symlink only if we have native libraries
11279        // and if the native libraries are 32 bit libraries. We do not provide
11280        // this symlink for 64 bit libraries.
11281        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11282                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11283            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11284            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11285                Slog.w(TAG, "Failed linking native library dir");
11286                return false;
11287            }
11288        }
11289
11290        return true;
11291    }
11292
11293    /**
11294     * Remove entries from the keystore daemon. Will only remove it if the
11295     * {@code appId} is valid.
11296     */
11297    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11298        if (appId < 0) {
11299            return;
11300        }
11301
11302        final KeyStore keyStore = KeyStore.getInstance();
11303        if (keyStore != null) {
11304            if (userId == UserHandle.USER_ALL) {
11305                for (final int individual : sUserManager.getUserIds()) {
11306                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11307                }
11308            } else {
11309                keyStore.clearUid(UserHandle.getUid(userId, appId));
11310            }
11311        } else {
11312            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11313        }
11314    }
11315
11316    @Override
11317    public void deleteApplicationCacheFiles(final String packageName,
11318            final IPackageDataObserver observer) {
11319        mContext.enforceCallingOrSelfPermission(
11320                android.Manifest.permission.DELETE_CACHE_FILES, null);
11321        // Queue up an async operation since the package deletion may take a little while.
11322        final int userId = UserHandle.getCallingUserId();
11323        mHandler.post(new Runnable() {
11324            public void run() {
11325                mHandler.removeCallbacks(this);
11326                final boolean succeded;
11327                synchronized (mInstallLock) {
11328                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11329                }
11330                clearExternalStorageDataSync(packageName, userId, false);
11331                if(observer != null) {
11332                    try {
11333                        observer.onRemoveCompleted(packageName, succeded);
11334                    } catch (RemoteException e) {
11335                        Log.i(TAG, "Observer no longer exists.");
11336                    }
11337                } //end if observer
11338            } //end run
11339        });
11340    }
11341
11342    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11343        if (packageName == null) {
11344            Slog.w(TAG, "Attempt to delete null packageName.");
11345            return false;
11346        }
11347        PackageParser.Package p;
11348        synchronized (mPackages) {
11349            p = mPackages.get(packageName);
11350        }
11351        if (p == null) {
11352            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11353            return false;
11354        }
11355        final ApplicationInfo applicationInfo = p.applicationInfo;
11356        if (applicationInfo == null) {
11357            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11358            return false;
11359        }
11360        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11361        if (retCode < 0) {
11362            Slog.w(TAG, "Couldn't remove cache files for package: "
11363                       + packageName + " u" + userId);
11364            return false;
11365        }
11366        return true;
11367    }
11368
11369    @Override
11370    public void getPackageSizeInfo(final String packageName, int userHandle,
11371            final IPackageStatsObserver observer) {
11372        mContext.enforceCallingOrSelfPermission(
11373                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11374        if (packageName == null) {
11375            throw new IllegalArgumentException("Attempt to get size of null packageName");
11376        }
11377
11378        PackageStats stats = new PackageStats(packageName, userHandle);
11379
11380        /*
11381         * Queue up an async operation since the package measurement may take a
11382         * little while.
11383         */
11384        Message msg = mHandler.obtainMessage(INIT_COPY);
11385        msg.obj = new MeasureParams(stats, observer);
11386        mHandler.sendMessage(msg);
11387    }
11388
11389    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11390            PackageStats pStats) {
11391        if (packageName == null) {
11392            Slog.w(TAG, "Attempt to get size of null packageName.");
11393            return false;
11394        }
11395        PackageParser.Package p;
11396        boolean dataOnly = false;
11397        String libDirRoot = null;
11398        String asecPath = null;
11399        PackageSetting ps = null;
11400        synchronized (mPackages) {
11401            p = mPackages.get(packageName);
11402            ps = mSettings.mPackages.get(packageName);
11403            if(p == null) {
11404                dataOnly = true;
11405                if((ps == null) || (ps.pkg == null)) {
11406                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11407                    return false;
11408                }
11409                p = ps.pkg;
11410            }
11411            if (ps != null) {
11412                libDirRoot = ps.legacyNativeLibraryPathString;
11413            }
11414            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11415                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11416                if (secureContainerId != null) {
11417                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11418                }
11419            }
11420        }
11421        String publicSrcDir = null;
11422        if(!dataOnly) {
11423            final ApplicationInfo applicationInfo = p.applicationInfo;
11424            if (applicationInfo == null) {
11425                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11426                return false;
11427            }
11428            if (p.isForwardLocked()) {
11429                publicSrcDir = applicationInfo.getBaseResourcePath();
11430            }
11431        }
11432        // TODO: extend to measure size of split APKs
11433        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11434        // not just the first level.
11435        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11436        // just the primary.
11437        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11438        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11439                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11440        if (res < 0) {
11441            return false;
11442        }
11443
11444        // Fix-up for forward-locked applications in ASEC containers.
11445        if (!isExternal(p)) {
11446            pStats.codeSize += pStats.externalCodeSize;
11447            pStats.externalCodeSize = 0L;
11448        }
11449
11450        return true;
11451    }
11452
11453
11454    @Override
11455    public void addPackageToPreferred(String packageName) {
11456        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11457    }
11458
11459    @Override
11460    public void removePackageFromPreferred(String packageName) {
11461        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11462    }
11463
11464    @Override
11465    public List<PackageInfo> getPreferredPackages(int flags) {
11466        return new ArrayList<PackageInfo>();
11467    }
11468
11469    private int getUidTargetSdkVersionLockedLPr(int uid) {
11470        Object obj = mSettings.getUserIdLPr(uid);
11471        if (obj instanceof SharedUserSetting) {
11472            final SharedUserSetting sus = (SharedUserSetting) obj;
11473            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11474            final Iterator<PackageSetting> it = sus.packages.iterator();
11475            while (it.hasNext()) {
11476                final PackageSetting ps = it.next();
11477                if (ps.pkg != null) {
11478                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11479                    if (v < vers) vers = v;
11480                }
11481            }
11482            return vers;
11483        } else if (obj instanceof PackageSetting) {
11484            final PackageSetting ps = (PackageSetting) obj;
11485            if (ps.pkg != null) {
11486                return ps.pkg.applicationInfo.targetSdkVersion;
11487            }
11488        }
11489        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11490    }
11491
11492    @Override
11493    public void addPreferredActivity(IntentFilter filter, int match,
11494            ComponentName[] set, ComponentName activity, int userId) {
11495        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11496                "Adding preferred");
11497    }
11498
11499    private void addPreferredActivityInternal(IntentFilter filter, int match,
11500            ComponentName[] set, ComponentName activity, boolean always, int userId,
11501            String opname) {
11502        // writer
11503        int callingUid = Binder.getCallingUid();
11504        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11505        if (filter.countActions() == 0) {
11506            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11507            return;
11508        }
11509        synchronized (mPackages) {
11510            if (mContext.checkCallingOrSelfPermission(
11511                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11512                    != PackageManager.PERMISSION_GRANTED) {
11513                if (getUidTargetSdkVersionLockedLPr(callingUid)
11514                        < Build.VERSION_CODES.FROYO) {
11515                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11516                            + callingUid);
11517                    return;
11518                }
11519                mContext.enforceCallingOrSelfPermission(
11520                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11521            }
11522
11523            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11524            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11525                    + userId + ":");
11526            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11527            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11528            scheduleWritePackageRestrictionsLocked(userId);
11529        }
11530    }
11531
11532    @Override
11533    public void replacePreferredActivity(IntentFilter filter, int match,
11534            ComponentName[] set, ComponentName activity, int userId) {
11535        if (filter.countActions() != 1) {
11536            throw new IllegalArgumentException(
11537                    "replacePreferredActivity expects filter to have only 1 action.");
11538        }
11539        if (filter.countDataAuthorities() != 0
11540                || filter.countDataPaths() != 0
11541                || filter.countDataSchemes() > 1
11542                || filter.countDataTypes() != 0) {
11543            throw new IllegalArgumentException(
11544                    "replacePreferredActivity expects filter to have no data authorities, " +
11545                    "paths, or types; and at most one scheme.");
11546        }
11547
11548        final int callingUid = Binder.getCallingUid();
11549        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11550        synchronized (mPackages) {
11551            if (mContext.checkCallingOrSelfPermission(
11552                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11553                    != PackageManager.PERMISSION_GRANTED) {
11554                if (getUidTargetSdkVersionLockedLPr(callingUid)
11555                        < Build.VERSION_CODES.FROYO) {
11556                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11557                            + Binder.getCallingUid());
11558                    return;
11559                }
11560                mContext.enforceCallingOrSelfPermission(
11561                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11562            }
11563
11564            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11565            if (pir != null) {
11566                // Get all of the existing entries that exactly match this filter.
11567                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11568                if (existing != null && existing.size() == 1) {
11569                    PreferredActivity cur = existing.get(0);
11570                    if (DEBUG_PREFERRED) {
11571                        Slog.i(TAG, "Checking replace of preferred:");
11572                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11573                        if (!cur.mPref.mAlways) {
11574                            Slog.i(TAG, "  -- CUR; not mAlways!");
11575                        } else {
11576                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11577                            Slog.i(TAG, "  -- CUR: mSet="
11578                                    + Arrays.toString(cur.mPref.mSetComponents));
11579                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11580                            Slog.i(TAG, "  -- NEW: mMatch="
11581                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11582                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11583                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11584                        }
11585                    }
11586                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11587                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11588                            && cur.mPref.sameSet(set)) {
11589                        // Setting the preferred activity to what it happens to be already
11590                        if (DEBUG_PREFERRED) {
11591                            Slog.i(TAG, "Replacing with same preferred activity "
11592                                    + cur.mPref.mShortComponent + " for user "
11593                                    + userId + ":");
11594                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11595                        }
11596                        return;
11597                    }
11598                }
11599
11600                if (existing != null) {
11601                    if (DEBUG_PREFERRED) {
11602                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11603                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11604                    }
11605                    for (int i = 0; i < existing.size(); i++) {
11606                        PreferredActivity pa = existing.get(i);
11607                        if (DEBUG_PREFERRED) {
11608                            Slog.i(TAG, "Removing existing preferred activity "
11609                                    + pa.mPref.mComponent + ":");
11610                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11611                        }
11612                        pir.removeFilter(pa);
11613                    }
11614                }
11615            }
11616            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11617                    "Replacing preferred");
11618        }
11619    }
11620
11621    @Override
11622    public void clearPackagePreferredActivities(String packageName) {
11623        final int uid = Binder.getCallingUid();
11624        // writer
11625        synchronized (mPackages) {
11626            PackageParser.Package pkg = mPackages.get(packageName);
11627            if (pkg == null || pkg.applicationInfo.uid != uid) {
11628                if (mContext.checkCallingOrSelfPermission(
11629                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11630                        != PackageManager.PERMISSION_GRANTED) {
11631                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11632                            < Build.VERSION_CODES.FROYO) {
11633                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11634                                + Binder.getCallingUid());
11635                        return;
11636                    }
11637                    mContext.enforceCallingOrSelfPermission(
11638                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11639                }
11640            }
11641
11642            int user = UserHandle.getCallingUserId();
11643            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11644                scheduleWritePackageRestrictionsLocked(user);
11645            }
11646        }
11647    }
11648
11649    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11650    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11651        ArrayList<PreferredActivity> removed = null;
11652        boolean changed = false;
11653        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11654            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11655            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11656            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11657                continue;
11658            }
11659            Iterator<PreferredActivity> it = pir.filterIterator();
11660            while (it.hasNext()) {
11661                PreferredActivity pa = it.next();
11662                // Mark entry for removal only if it matches the package name
11663                // and the entry is of type "always".
11664                if (packageName == null ||
11665                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11666                                && pa.mPref.mAlways)) {
11667                    if (removed == null) {
11668                        removed = new ArrayList<PreferredActivity>();
11669                    }
11670                    removed.add(pa);
11671                }
11672            }
11673            if (removed != null) {
11674                for (int j=0; j<removed.size(); j++) {
11675                    PreferredActivity pa = removed.get(j);
11676                    pir.removeFilter(pa);
11677                }
11678                changed = true;
11679            }
11680        }
11681        return changed;
11682    }
11683
11684    @Override
11685    public void resetPreferredActivities(int userId) {
11686        /* TODO: Actually use userId. Why is it being passed in? */
11687        mContext.enforceCallingOrSelfPermission(
11688                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11689        // writer
11690        synchronized (mPackages) {
11691            int user = UserHandle.getCallingUserId();
11692            clearPackagePreferredActivitiesLPw(null, user);
11693            mSettings.readDefaultPreferredAppsLPw(this, user);
11694            scheduleWritePackageRestrictionsLocked(user);
11695        }
11696    }
11697
11698    @Override
11699    public int getPreferredActivities(List<IntentFilter> outFilters,
11700            List<ComponentName> outActivities, String packageName) {
11701
11702        int num = 0;
11703        final int userId = UserHandle.getCallingUserId();
11704        // reader
11705        synchronized (mPackages) {
11706            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11707            if (pir != null) {
11708                final Iterator<PreferredActivity> it = pir.filterIterator();
11709                while (it.hasNext()) {
11710                    final PreferredActivity pa = it.next();
11711                    if (packageName == null
11712                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11713                                    && pa.mPref.mAlways)) {
11714                        if (outFilters != null) {
11715                            outFilters.add(new IntentFilter(pa));
11716                        }
11717                        if (outActivities != null) {
11718                            outActivities.add(pa.mPref.mComponent);
11719                        }
11720                    }
11721                }
11722            }
11723        }
11724
11725        return num;
11726    }
11727
11728    @Override
11729    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11730            int userId) {
11731        int callingUid = Binder.getCallingUid();
11732        if (callingUid != Process.SYSTEM_UID) {
11733            throw new SecurityException(
11734                    "addPersistentPreferredActivity can only be run by the system");
11735        }
11736        if (filter.countActions() == 0) {
11737            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11738            return;
11739        }
11740        synchronized (mPackages) {
11741            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11742                    " :");
11743            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11744            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11745                    new PersistentPreferredActivity(filter, activity));
11746            scheduleWritePackageRestrictionsLocked(userId);
11747        }
11748    }
11749
11750    @Override
11751    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11752        int callingUid = Binder.getCallingUid();
11753        if (callingUid != Process.SYSTEM_UID) {
11754            throw new SecurityException(
11755                    "clearPackagePersistentPreferredActivities can only be run by the system");
11756        }
11757        ArrayList<PersistentPreferredActivity> removed = null;
11758        boolean changed = false;
11759        synchronized (mPackages) {
11760            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11761                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11762                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11763                        .valueAt(i);
11764                if (userId != thisUserId) {
11765                    continue;
11766                }
11767                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11768                while (it.hasNext()) {
11769                    PersistentPreferredActivity ppa = it.next();
11770                    // Mark entry for removal only if it matches the package name.
11771                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11772                        if (removed == null) {
11773                            removed = new ArrayList<PersistentPreferredActivity>();
11774                        }
11775                        removed.add(ppa);
11776                    }
11777                }
11778                if (removed != null) {
11779                    for (int j=0; j<removed.size(); j++) {
11780                        PersistentPreferredActivity ppa = removed.get(j);
11781                        ppir.removeFilter(ppa);
11782                    }
11783                    changed = true;
11784                }
11785            }
11786
11787            if (changed) {
11788                scheduleWritePackageRestrictionsLocked(userId);
11789            }
11790        }
11791    }
11792
11793    @Override
11794    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11795            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11796        mContext.enforceCallingOrSelfPermission(
11797                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11798        int callingUid = Binder.getCallingUid();
11799        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11800        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11801        if (intentFilter.countActions() == 0) {
11802            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11803            return;
11804        }
11805        synchronized (mPackages) {
11806            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11807                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11808            CrossProfileIntentResolver resolver =
11809                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11810            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11811            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11812            if (existing != null) {
11813                int size = existing.size();
11814                for (int i = 0; i < size; i++) {
11815                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11816                        return;
11817                    }
11818                }
11819            }
11820            resolver.addFilter(newFilter);
11821            scheduleWritePackageRestrictionsLocked(sourceUserId);
11822        }
11823    }
11824
11825    @Override
11826    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11827            int ownerUserId) {
11828        mContext.enforceCallingOrSelfPermission(
11829                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11830        int callingUid = Binder.getCallingUid();
11831        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11832        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11833        int callingUserId = UserHandle.getUserId(callingUid);
11834        synchronized (mPackages) {
11835            CrossProfileIntentResolver resolver =
11836                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11837            ArraySet<CrossProfileIntentFilter> set =
11838                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11839            for (CrossProfileIntentFilter filter : set) {
11840                if (filter.getOwnerPackage().equals(ownerPackage)
11841                        && filter.getOwnerUserId() == callingUserId) {
11842                    resolver.removeFilter(filter);
11843                }
11844            }
11845            scheduleWritePackageRestrictionsLocked(sourceUserId);
11846        }
11847    }
11848
11849    // Enforcing that callingUid is owning pkg on userId
11850    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11851        // The system owns everything.
11852        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11853            return;
11854        }
11855        int callingUserId = UserHandle.getUserId(callingUid);
11856        if (callingUserId != userId) {
11857            throw new SecurityException("calling uid " + callingUid
11858                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11859                    + callingUserId);
11860        }
11861        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11862        if (pi == null) {
11863            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11864                    + callingUserId);
11865        }
11866        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11867            throw new SecurityException("Calling uid " + callingUid
11868                    + " does not own package " + pkg);
11869        }
11870    }
11871
11872    @Override
11873    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11874        Intent intent = new Intent(Intent.ACTION_MAIN);
11875        intent.addCategory(Intent.CATEGORY_HOME);
11876
11877        final int callingUserId = UserHandle.getCallingUserId();
11878        List<ResolveInfo> list = queryIntentActivities(intent, null,
11879                PackageManager.GET_META_DATA, callingUserId);
11880        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11881                true, false, false, callingUserId);
11882
11883        allHomeCandidates.clear();
11884        if (list != null) {
11885            for (ResolveInfo ri : list) {
11886                allHomeCandidates.add(ri);
11887            }
11888        }
11889        return (preferred == null || preferred.activityInfo == null)
11890                ? null
11891                : new ComponentName(preferred.activityInfo.packageName,
11892                        preferred.activityInfo.name);
11893    }
11894
11895    @Override
11896    public void setApplicationEnabledSetting(String appPackageName,
11897            int newState, int flags, int userId, String callingPackage) {
11898        if (!sUserManager.exists(userId)) return;
11899        if (callingPackage == null) {
11900            callingPackage = Integer.toString(Binder.getCallingUid());
11901        }
11902        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11903    }
11904
11905    @Override
11906    public void setComponentEnabledSetting(ComponentName componentName,
11907            int newState, int flags, int userId) {
11908        if (!sUserManager.exists(userId)) return;
11909        setEnabledSetting(componentName.getPackageName(),
11910                componentName.getClassName(), newState, flags, userId, null);
11911    }
11912
11913    private void setEnabledSetting(final String packageName, String className, int newState,
11914            final int flags, int userId, String callingPackage) {
11915        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11916              || newState == COMPONENT_ENABLED_STATE_ENABLED
11917              || newState == COMPONENT_ENABLED_STATE_DISABLED
11918              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11919              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11920            throw new IllegalArgumentException("Invalid new component state: "
11921                    + newState);
11922        }
11923        PackageSetting pkgSetting;
11924        final int uid = Binder.getCallingUid();
11925        final int permission = mContext.checkCallingOrSelfPermission(
11926                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11927        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11928        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11929        boolean sendNow = false;
11930        boolean isApp = (className == null);
11931        String componentName = isApp ? packageName : className;
11932        int packageUid = -1;
11933        ArrayList<String> components;
11934
11935        // writer
11936        synchronized (mPackages) {
11937            pkgSetting = mSettings.mPackages.get(packageName);
11938            if (pkgSetting == null) {
11939                if (className == null) {
11940                    throw new IllegalArgumentException(
11941                            "Unknown package: " + packageName);
11942                }
11943                throw new IllegalArgumentException(
11944                        "Unknown component: " + packageName
11945                        + "/" + className);
11946            }
11947            // Allow root and verify that userId is not being specified by a different user
11948            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11949                throw new SecurityException(
11950                        "Permission Denial: attempt to change component state from pid="
11951                        + Binder.getCallingPid()
11952                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11953            }
11954            if (className == null) {
11955                // We're dealing with an application/package level state change
11956                if (pkgSetting.getEnabled(userId) == newState) {
11957                    // Nothing to do
11958                    return;
11959                }
11960                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11961                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11962                    // Don't care about who enables an app.
11963                    callingPackage = null;
11964                }
11965                pkgSetting.setEnabled(newState, userId, callingPackage);
11966                // pkgSetting.pkg.mSetEnabled = newState;
11967            } else {
11968                // We're dealing with a component level state change
11969                // First, verify that this is a valid class name.
11970                PackageParser.Package pkg = pkgSetting.pkg;
11971                if (pkg == null || !pkg.hasComponentClassName(className)) {
11972                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11973                        throw new IllegalArgumentException("Component class " + className
11974                                + " does not exist in " + packageName);
11975                    } else {
11976                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11977                                + className + " does not exist in " + packageName);
11978                    }
11979                }
11980                switch (newState) {
11981                case COMPONENT_ENABLED_STATE_ENABLED:
11982                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11983                        return;
11984                    }
11985                    break;
11986                case COMPONENT_ENABLED_STATE_DISABLED:
11987                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11988                        return;
11989                    }
11990                    break;
11991                case COMPONENT_ENABLED_STATE_DEFAULT:
11992                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11993                        return;
11994                    }
11995                    break;
11996                default:
11997                    Slog.e(TAG, "Invalid new component state: " + newState);
11998                    return;
11999                }
12000            }
12001            scheduleWritePackageRestrictionsLocked(userId);
12002            components = mPendingBroadcasts.get(userId, packageName);
12003            final boolean newPackage = components == null;
12004            if (newPackage) {
12005                components = new ArrayList<String>();
12006            }
12007            if (!components.contains(componentName)) {
12008                components.add(componentName);
12009            }
12010            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12011                sendNow = true;
12012                // Purge entry from pending broadcast list if another one exists already
12013                // since we are sending one right away.
12014                mPendingBroadcasts.remove(userId, packageName);
12015            } else {
12016                if (newPackage) {
12017                    mPendingBroadcasts.put(userId, packageName, components);
12018                }
12019                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12020                    // Schedule a message
12021                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12022                }
12023            }
12024        }
12025
12026        long callingId = Binder.clearCallingIdentity();
12027        try {
12028            if (sendNow) {
12029                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12030                sendPackageChangedBroadcast(packageName,
12031                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12032            }
12033        } finally {
12034            Binder.restoreCallingIdentity(callingId);
12035        }
12036    }
12037
12038    private void sendPackageChangedBroadcast(String packageName,
12039            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12040        if (DEBUG_INSTALL)
12041            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12042                    + componentNames);
12043        Bundle extras = new Bundle(4);
12044        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12045        String nameList[] = new String[componentNames.size()];
12046        componentNames.toArray(nameList);
12047        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12048        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12049        extras.putInt(Intent.EXTRA_UID, packageUid);
12050        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12051                new int[] {UserHandle.getUserId(packageUid)});
12052    }
12053
12054    @Override
12055    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12056        if (!sUserManager.exists(userId)) return;
12057        final int uid = Binder.getCallingUid();
12058        final int permission = mContext.checkCallingOrSelfPermission(
12059                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12060        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12061        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12062        // writer
12063        synchronized (mPackages) {
12064            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12065                    uid, userId)) {
12066                scheduleWritePackageRestrictionsLocked(userId);
12067            }
12068        }
12069    }
12070
12071    @Override
12072    public String getInstallerPackageName(String packageName) {
12073        // reader
12074        synchronized (mPackages) {
12075            return mSettings.getInstallerPackageNameLPr(packageName);
12076        }
12077    }
12078
12079    @Override
12080    public int getApplicationEnabledSetting(String packageName, int userId) {
12081        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12082        int uid = Binder.getCallingUid();
12083        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12084        // reader
12085        synchronized (mPackages) {
12086            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12087        }
12088    }
12089
12090    @Override
12091    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12092        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12093        int uid = Binder.getCallingUid();
12094        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12095        // reader
12096        synchronized (mPackages) {
12097            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12098        }
12099    }
12100
12101    @Override
12102    public void enterSafeMode() {
12103        enforceSystemOrRoot("Only the system can request entering safe mode");
12104
12105        if (!mSystemReady) {
12106            mSafeMode = true;
12107        }
12108    }
12109
12110    @Override
12111    public void systemReady() {
12112        mSystemReady = true;
12113
12114        // Read the compatibilty setting when the system is ready.
12115        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12116                mContext.getContentResolver(),
12117                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12118        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12119        if (DEBUG_SETTINGS) {
12120            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12121        }
12122
12123        synchronized (mPackages) {
12124            // Verify that all of the preferred activity components actually
12125            // exist.  It is possible for applications to be updated and at
12126            // that point remove a previously declared activity component that
12127            // had been set as a preferred activity.  We try to clean this up
12128            // the next time we encounter that preferred activity, but it is
12129            // possible for the user flow to never be able to return to that
12130            // situation so here we do a sanity check to make sure we haven't
12131            // left any junk around.
12132            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12133            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12134                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12135                removed.clear();
12136                for (PreferredActivity pa : pir.filterSet()) {
12137                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12138                        removed.add(pa);
12139                    }
12140                }
12141                if (removed.size() > 0) {
12142                    for (int r=0; r<removed.size(); r++) {
12143                        PreferredActivity pa = removed.get(r);
12144                        Slog.w(TAG, "Removing dangling preferred activity: "
12145                                + pa.mPref.mComponent);
12146                        pir.removeFilter(pa);
12147                    }
12148                    mSettings.writePackageRestrictionsLPr(
12149                            mSettings.mPreferredActivities.keyAt(i));
12150                }
12151            }
12152        }
12153        sUserManager.systemReady();
12154
12155        // Kick off any messages waiting for system ready
12156        if (mPostSystemReadyMessages != null) {
12157            for (Message msg : mPostSystemReadyMessages) {
12158                msg.sendToTarget();
12159            }
12160            mPostSystemReadyMessages = null;
12161        }
12162    }
12163
12164    @Override
12165    public boolean isSafeMode() {
12166        return mSafeMode;
12167    }
12168
12169    @Override
12170    public boolean hasSystemUidErrors() {
12171        return mHasSystemUidErrors;
12172    }
12173
12174    static String arrayToString(int[] array) {
12175        StringBuffer buf = new StringBuffer(128);
12176        buf.append('[');
12177        if (array != null) {
12178            for (int i=0; i<array.length; i++) {
12179                if (i > 0) buf.append(", ");
12180                buf.append(array[i]);
12181            }
12182        }
12183        buf.append(']');
12184        return buf.toString();
12185    }
12186
12187    static class DumpState {
12188        public static final int DUMP_LIBS = 1 << 0;
12189        public static final int DUMP_FEATURES = 1 << 1;
12190        public static final int DUMP_RESOLVERS = 1 << 2;
12191        public static final int DUMP_PERMISSIONS = 1 << 3;
12192        public static final int DUMP_PACKAGES = 1 << 4;
12193        public static final int DUMP_SHARED_USERS = 1 << 5;
12194        public static final int DUMP_MESSAGES = 1 << 6;
12195        public static final int DUMP_PROVIDERS = 1 << 7;
12196        public static final int DUMP_VERIFIERS = 1 << 8;
12197        public static final int DUMP_PREFERRED = 1 << 9;
12198        public static final int DUMP_PREFERRED_XML = 1 << 10;
12199        public static final int DUMP_KEYSETS = 1 << 11;
12200        public static final int DUMP_VERSION = 1 << 12;
12201        public static final int DUMP_INSTALLS = 1 << 13;
12202
12203        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12204
12205        private int mTypes;
12206
12207        private int mOptions;
12208
12209        private boolean mTitlePrinted;
12210
12211        private SharedUserSetting mSharedUser;
12212
12213        public boolean isDumping(int type) {
12214            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12215                return true;
12216            }
12217
12218            return (mTypes & type) != 0;
12219        }
12220
12221        public void setDump(int type) {
12222            mTypes |= type;
12223        }
12224
12225        public boolean isOptionEnabled(int option) {
12226            return (mOptions & option) != 0;
12227        }
12228
12229        public void setOptionEnabled(int option) {
12230            mOptions |= option;
12231        }
12232
12233        public boolean onTitlePrinted() {
12234            final boolean printed = mTitlePrinted;
12235            mTitlePrinted = true;
12236            return printed;
12237        }
12238
12239        public boolean getTitlePrinted() {
12240            return mTitlePrinted;
12241        }
12242
12243        public void setTitlePrinted(boolean enabled) {
12244            mTitlePrinted = enabled;
12245        }
12246
12247        public SharedUserSetting getSharedUser() {
12248            return mSharedUser;
12249        }
12250
12251        public void setSharedUser(SharedUserSetting user) {
12252            mSharedUser = user;
12253        }
12254    }
12255
12256    @Override
12257    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12258        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12259                != PackageManager.PERMISSION_GRANTED) {
12260            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12261                    + Binder.getCallingPid()
12262                    + ", uid=" + Binder.getCallingUid()
12263                    + " without permission "
12264                    + android.Manifest.permission.DUMP);
12265            return;
12266        }
12267
12268        DumpState dumpState = new DumpState();
12269        boolean fullPreferred = false;
12270        boolean checkin = false;
12271
12272        String packageName = null;
12273
12274        int opti = 0;
12275        while (opti < args.length) {
12276            String opt = args[opti];
12277            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12278                break;
12279            }
12280            opti++;
12281
12282            if ("-a".equals(opt)) {
12283                // Right now we only know how to print all.
12284            } else if ("-h".equals(opt)) {
12285                pw.println("Package manager dump options:");
12286                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12287                pw.println("    --checkin: dump for a checkin");
12288                pw.println("    -f: print details of intent filters");
12289                pw.println("    -h: print this help");
12290                pw.println("  cmd may be one of:");
12291                pw.println("    l[ibraries]: list known shared libraries");
12292                pw.println("    f[ibraries]: list device features");
12293                pw.println("    k[eysets]: print known keysets");
12294                pw.println("    r[esolvers]: dump intent resolvers");
12295                pw.println("    perm[issions]: dump permissions");
12296                pw.println("    pref[erred]: print preferred package settings");
12297                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12298                pw.println("    prov[iders]: dump content providers");
12299                pw.println("    p[ackages]: dump installed packages");
12300                pw.println("    s[hared-users]: dump shared user IDs");
12301                pw.println("    m[essages]: print collected runtime messages");
12302                pw.println("    v[erifiers]: print package verifier info");
12303                pw.println("    version: print database version info");
12304                pw.println("    write: write current settings now");
12305                pw.println("    <package.name>: info about given package");
12306                pw.println("    installs: details about install sessions");
12307                return;
12308            } else if ("--checkin".equals(opt)) {
12309                checkin = true;
12310            } else if ("-f".equals(opt)) {
12311                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12312            } else {
12313                pw.println("Unknown argument: " + opt + "; use -h for help");
12314            }
12315        }
12316
12317        // Is the caller requesting to dump a particular piece of data?
12318        if (opti < args.length) {
12319            String cmd = args[opti];
12320            opti++;
12321            // Is this a package name?
12322            if ("android".equals(cmd) || cmd.contains(".")) {
12323                packageName = cmd;
12324                // When dumping a single package, we always dump all of its
12325                // filter information since the amount of data will be reasonable.
12326                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12327            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12328                dumpState.setDump(DumpState.DUMP_LIBS);
12329            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12330                dumpState.setDump(DumpState.DUMP_FEATURES);
12331            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12332                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12333            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12334                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12335            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12336                dumpState.setDump(DumpState.DUMP_PREFERRED);
12337            } else if ("preferred-xml".equals(cmd)) {
12338                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12339                if (opti < args.length && "--full".equals(args[opti])) {
12340                    fullPreferred = true;
12341                    opti++;
12342                }
12343            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12344                dumpState.setDump(DumpState.DUMP_PACKAGES);
12345            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12346                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12347            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12348                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12349            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12350                dumpState.setDump(DumpState.DUMP_MESSAGES);
12351            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12352                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12353            } else if ("version".equals(cmd)) {
12354                dumpState.setDump(DumpState.DUMP_VERSION);
12355            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12356                dumpState.setDump(DumpState.DUMP_KEYSETS);
12357            } else if ("installs".equals(cmd)) {
12358                dumpState.setDump(DumpState.DUMP_INSTALLS);
12359            } else if ("write".equals(cmd)) {
12360                synchronized (mPackages) {
12361                    mSettings.writeLPr();
12362                    pw.println("Settings written.");
12363                    return;
12364                }
12365            }
12366        }
12367
12368        if (checkin) {
12369            pw.println("vers,1");
12370        }
12371
12372        // reader
12373        synchronized (mPackages) {
12374            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12375                if (!checkin) {
12376                    if (dumpState.onTitlePrinted())
12377                        pw.println();
12378                    pw.println("Database versions:");
12379                    pw.print("  SDK Version:");
12380                    pw.print(" internal=");
12381                    pw.print(mSettings.mInternalSdkPlatform);
12382                    pw.print(" external=");
12383                    pw.println(mSettings.mExternalSdkPlatform);
12384                    pw.print("  DB Version:");
12385                    pw.print(" internal=");
12386                    pw.print(mSettings.mInternalDatabaseVersion);
12387                    pw.print(" external=");
12388                    pw.println(mSettings.mExternalDatabaseVersion);
12389                }
12390            }
12391
12392            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12393                if (!checkin) {
12394                    if (dumpState.onTitlePrinted())
12395                        pw.println();
12396                    pw.println("Verifiers:");
12397                    pw.print("  Required: ");
12398                    pw.print(mRequiredVerifierPackage);
12399                    pw.print(" (uid=");
12400                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12401                    pw.println(")");
12402                } else if (mRequiredVerifierPackage != null) {
12403                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12404                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12405                }
12406            }
12407
12408            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12409                boolean printedHeader = false;
12410                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12411                while (it.hasNext()) {
12412                    String name = it.next();
12413                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12414                    if (!checkin) {
12415                        if (!printedHeader) {
12416                            if (dumpState.onTitlePrinted())
12417                                pw.println();
12418                            pw.println("Libraries:");
12419                            printedHeader = true;
12420                        }
12421                        pw.print("  ");
12422                    } else {
12423                        pw.print("lib,");
12424                    }
12425                    pw.print(name);
12426                    if (!checkin) {
12427                        pw.print(" -> ");
12428                    }
12429                    if (ent.path != null) {
12430                        if (!checkin) {
12431                            pw.print("(jar) ");
12432                            pw.print(ent.path);
12433                        } else {
12434                            pw.print(",jar,");
12435                            pw.print(ent.path);
12436                        }
12437                    } else {
12438                        if (!checkin) {
12439                            pw.print("(apk) ");
12440                            pw.print(ent.apk);
12441                        } else {
12442                            pw.print(",apk,");
12443                            pw.print(ent.apk);
12444                        }
12445                    }
12446                    pw.println();
12447                }
12448            }
12449
12450            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12451                if (dumpState.onTitlePrinted())
12452                    pw.println();
12453                if (!checkin) {
12454                    pw.println("Features:");
12455                }
12456                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12457                while (it.hasNext()) {
12458                    String name = it.next();
12459                    if (!checkin) {
12460                        pw.print("  ");
12461                    } else {
12462                        pw.print("feat,");
12463                    }
12464                    pw.println(name);
12465                }
12466            }
12467
12468            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12469                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12470                        : "Activity Resolver Table:", "  ", packageName,
12471                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12472                    dumpState.setTitlePrinted(true);
12473                }
12474                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12475                        : "Receiver Resolver Table:", "  ", packageName,
12476                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12477                    dumpState.setTitlePrinted(true);
12478                }
12479                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12480                        : "Service Resolver Table:", "  ", packageName,
12481                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12482                    dumpState.setTitlePrinted(true);
12483                }
12484                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12485                        : "Provider Resolver Table:", "  ", packageName,
12486                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12487                    dumpState.setTitlePrinted(true);
12488                }
12489            }
12490
12491            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12492                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12493                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12494                    int user = mSettings.mPreferredActivities.keyAt(i);
12495                    if (pir.dump(pw,
12496                            dumpState.getTitlePrinted()
12497                                ? "\nPreferred Activities User " + user + ":"
12498                                : "Preferred Activities User " + user + ":", "  ",
12499                            packageName, true, false)) {
12500                        dumpState.setTitlePrinted(true);
12501                    }
12502                }
12503            }
12504
12505            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12506                pw.flush();
12507                FileOutputStream fout = new FileOutputStream(fd);
12508                BufferedOutputStream str = new BufferedOutputStream(fout);
12509                XmlSerializer serializer = new FastXmlSerializer();
12510                try {
12511                    serializer.setOutput(str, "utf-8");
12512                    serializer.startDocument(null, true);
12513                    serializer.setFeature(
12514                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12515                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12516                    serializer.endDocument();
12517                    serializer.flush();
12518                } catch (IllegalArgumentException e) {
12519                    pw.println("Failed writing: " + e);
12520                } catch (IllegalStateException e) {
12521                    pw.println("Failed writing: " + e);
12522                } catch (IOException e) {
12523                    pw.println("Failed writing: " + e);
12524                }
12525            }
12526
12527            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12528                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12529                if (packageName == null) {
12530                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12531                        if (iperm == 0) {
12532                            if (dumpState.onTitlePrinted())
12533                                pw.println();
12534                            pw.println("AppOp Permissions:");
12535                        }
12536                        pw.print("  AppOp Permission ");
12537                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12538                        pw.println(":");
12539                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12540                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12541                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12542                        }
12543                    }
12544                }
12545            }
12546
12547            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12548                boolean printedSomething = false;
12549                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12550                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12551                        continue;
12552                    }
12553                    if (!printedSomething) {
12554                        if (dumpState.onTitlePrinted())
12555                            pw.println();
12556                        pw.println("Registered ContentProviders:");
12557                        printedSomething = true;
12558                    }
12559                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12560                    pw.print("    "); pw.println(p.toString());
12561                }
12562                printedSomething = false;
12563                for (Map.Entry<String, PackageParser.Provider> entry :
12564                        mProvidersByAuthority.entrySet()) {
12565                    PackageParser.Provider p = entry.getValue();
12566                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12567                        continue;
12568                    }
12569                    if (!printedSomething) {
12570                        if (dumpState.onTitlePrinted())
12571                            pw.println();
12572                        pw.println("ContentProvider Authorities:");
12573                        printedSomething = true;
12574                    }
12575                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12576                    pw.print("    "); pw.println(p.toString());
12577                    if (p.info != null && p.info.applicationInfo != null) {
12578                        final String appInfo = p.info.applicationInfo.toString();
12579                        pw.print("      applicationInfo="); pw.println(appInfo);
12580                    }
12581                }
12582            }
12583
12584            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12585                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12586            }
12587
12588            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12589                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12590            }
12591
12592            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12593                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12594            }
12595
12596            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12597                // XXX should handle packageName != null by dumping only install data that
12598                // the given package is involved with.
12599                if (dumpState.onTitlePrinted()) pw.println();
12600                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12601            }
12602
12603            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12604                if (dumpState.onTitlePrinted()) pw.println();
12605                mSettings.dumpReadMessagesLPr(pw, dumpState);
12606
12607                pw.println();
12608                pw.println("Package warning messages:");
12609                BufferedReader in = null;
12610                String line = null;
12611                try {
12612                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12613                    while ((line = in.readLine()) != null) {
12614                        if (line.contains("ignored: updated version")) continue;
12615                        pw.println(line);
12616                    }
12617                } catch (IOException ignored) {
12618                } finally {
12619                    IoUtils.closeQuietly(in);
12620                }
12621            }
12622
12623            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12624                BufferedReader in = null;
12625                String line = null;
12626                try {
12627                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12628                    while ((line = in.readLine()) != null) {
12629                        if (line.contains("ignored: updated version")) continue;
12630                        pw.print("msg,");
12631                        pw.println(line);
12632                    }
12633                } catch (IOException ignored) {
12634                } finally {
12635                    IoUtils.closeQuietly(in);
12636                }
12637            }
12638        }
12639    }
12640
12641    // ------- apps on sdcard specific code -------
12642    static final boolean DEBUG_SD_INSTALL = false;
12643
12644    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12645
12646    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12647
12648    private boolean mMediaMounted = false;
12649
12650    static String getEncryptKey() {
12651        try {
12652            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12653                    SD_ENCRYPTION_KEYSTORE_NAME);
12654            if (sdEncKey == null) {
12655                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12656                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12657                if (sdEncKey == null) {
12658                    Slog.e(TAG, "Failed to create encryption keys");
12659                    return null;
12660                }
12661            }
12662            return sdEncKey;
12663        } catch (NoSuchAlgorithmException nsae) {
12664            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12665            return null;
12666        } catch (IOException ioe) {
12667            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12668            return null;
12669        }
12670    }
12671
12672    /*
12673     * Update media status on PackageManager.
12674     */
12675    @Override
12676    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12677        int callingUid = Binder.getCallingUid();
12678        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12679            throw new SecurityException("Media status can only be updated by the system");
12680        }
12681        // reader; this apparently protects mMediaMounted, but should probably
12682        // be a different lock in that case.
12683        synchronized (mPackages) {
12684            Log.i(TAG, "Updating external media status from "
12685                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12686                    + (mediaStatus ? "mounted" : "unmounted"));
12687            if (DEBUG_SD_INSTALL)
12688                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12689                        + ", mMediaMounted=" + mMediaMounted);
12690            if (mediaStatus == mMediaMounted) {
12691                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12692                        : 0, -1);
12693                mHandler.sendMessage(msg);
12694                return;
12695            }
12696            mMediaMounted = mediaStatus;
12697        }
12698        // Queue up an async operation since the package installation may take a
12699        // little while.
12700        mHandler.post(new Runnable() {
12701            public void run() {
12702                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12703            }
12704        });
12705    }
12706
12707    /**
12708     * Called by MountService when the initial ASECs to scan are available.
12709     * Should block until all the ASEC containers are finished being scanned.
12710     */
12711    public void scanAvailableAsecs() {
12712        updateExternalMediaStatusInner(true, false, false);
12713        if (mShouldRestoreconData) {
12714            SELinuxMMAC.setRestoreconDone();
12715            mShouldRestoreconData = false;
12716        }
12717    }
12718
12719    /*
12720     * Collect information of applications on external media, map them against
12721     * existing containers and update information based on current mount status.
12722     * Please note that we always have to report status if reportStatus has been
12723     * set to true especially when unloading packages.
12724     */
12725    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12726            boolean externalStorage) {
12727        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12728        int[] uidArr = EmptyArray.INT;
12729
12730        final String[] list = PackageHelper.getSecureContainerList();
12731        if (ArrayUtils.isEmpty(list)) {
12732            Log.i(TAG, "No secure containers found");
12733        } else {
12734            // Process list of secure containers and categorize them
12735            // as active or stale based on their package internal state.
12736
12737            // reader
12738            synchronized (mPackages) {
12739                for (String cid : list) {
12740                    // Leave stages untouched for now; installer service owns them
12741                    if (PackageInstallerService.isStageName(cid)) continue;
12742
12743                    if (DEBUG_SD_INSTALL)
12744                        Log.i(TAG, "Processing container " + cid);
12745                    String pkgName = getAsecPackageName(cid);
12746                    if (pkgName == null) {
12747                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12748                        continue;
12749                    }
12750                    if (DEBUG_SD_INSTALL)
12751                        Log.i(TAG, "Looking for pkg : " + pkgName);
12752
12753                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12754                    if (ps == null) {
12755                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12756                        continue;
12757                    }
12758
12759                    /*
12760                     * Skip packages that are not external if we're unmounting
12761                     * external storage.
12762                     */
12763                    if (externalStorage && !isMounted && !isExternal(ps)) {
12764                        continue;
12765                    }
12766
12767                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12768                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12769                    // The package status is changed only if the code path
12770                    // matches between settings and the container id.
12771                    if (ps.codePathString != null
12772                            && ps.codePathString.startsWith(args.getCodePath())) {
12773                        if (DEBUG_SD_INSTALL) {
12774                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12775                                    + " at code path: " + ps.codePathString);
12776                        }
12777
12778                        // We do have a valid package installed on sdcard
12779                        processCids.put(args, ps.codePathString);
12780                        final int uid = ps.appId;
12781                        if (uid != -1) {
12782                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12783                        }
12784                    } else {
12785                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12786                                + ps.codePathString);
12787                    }
12788                }
12789            }
12790
12791            Arrays.sort(uidArr);
12792        }
12793
12794        // Process packages with valid entries.
12795        if (isMounted) {
12796            if (DEBUG_SD_INSTALL)
12797                Log.i(TAG, "Loading packages");
12798            loadMediaPackages(processCids, uidArr);
12799            startCleaningPackages();
12800            mInstallerService.onSecureContainersAvailable();
12801        } else {
12802            if (DEBUG_SD_INSTALL)
12803                Log.i(TAG, "Unloading packages");
12804            unloadMediaPackages(processCids, uidArr, reportStatus);
12805        }
12806    }
12807
12808    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12809            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12810        int size = pkgList.size();
12811        if (size > 0) {
12812            // Send broadcasts here
12813            Bundle extras = new Bundle();
12814            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12815                    .toArray(new String[size]));
12816            if (uidArr != null) {
12817                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12818            }
12819            if (replacing) {
12820                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12821            }
12822            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12823                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12824            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12825        }
12826    }
12827
12828   /*
12829     * Look at potentially valid container ids from processCids If package
12830     * information doesn't match the one on record or package scanning fails,
12831     * the cid is added to list of removeCids. We currently don't delete stale
12832     * containers.
12833     */
12834    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12835        ArrayList<String> pkgList = new ArrayList<String>();
12836        Set<AsecInstallArgs> keys = processCids.keySet();
12837
12838        for (AsecInstallArgs args : keys) {
12839            String codePath = processCids.get(args);
12840            if (DEBUG_SD_INSTALL)
12841                Log.i(TAG, "Loading container : " + args.cid);
12842            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12843            try {
12844                // Make sure there are no container errors first.
12845                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12846                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12847                            + " when installing from sdcard");
12848                    continue;
12849                }
12850                // Check code path here.
12851                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12852                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12853                            + " does not match one in settings " + codePath);
12854                    continue;
12855                }
12856                // Parse package
12857                int parseFlags = mDefParseFlags;
12858                if (args.isExternal()) {
12859                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12860                }
12861                if (args.isFwdLocked()) {
12862                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12863                }
12864
12865                synchronized (mInstallLock) {
12866                    PackageParser.Package pkg = null;
12867                    try {
12868                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12869                    } catch (PackageManagerException e) {
12870                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12871                    }
12872                    // Scan the package
12873                    if (pkg != null) {
12874                        /*
12875                         * TODO why is the lock being held? doPostInstall is
12876                         * called in other places without the lock. This needs
12877                         * to be straightened out.
12878                         */
12879                        // writer
12880                        synchronized (mPackages) {
12881                            retCode = PackageManager.INSTALL_SUCCEEDED;
12882                            pkgList.add(pkg.packageName);
12883                            // Post process args
12884                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12885                                    pkg.applicationInfo.uid);
12886                        }
12887                    } else {
12888                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12889                    }
12890                }
12891
12892            } finally {
12893                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12894                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12895                }
12896            }
12897        }
12898        // writer
12899        synchronized (mPackages) {
12900            // If the platform SDK has changed since the last time we booted,
12901            // we need to re-grant app permission to catch any new ones that
12902            // appear. This is really a hack, and means that apps can in some
12903            // cases get permissions that the user didn't initially explicitly
12904            // allow... it would be nice to have some better way to handle
12905            // this situation.
12906            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12907            if (regrantPermissions)
12908                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12909                        + mSdkVersion + "; regranting permissions for external storage");
12910            mSettings.mExternalSdkPlatform = mSdkVersion;
12911
12912            // Make sure group IDs have been assigned, and any permission
12913            // changes in other apps are accounted for
12914            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12915                    | (regrantPermissions
12916                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12917                            : 0));
12918
12919            mSettings.updateExternalDatabaseVersion();
12920
12921            // can downgrade to reader
12922            // Persist settings
12923            mSettings.writeLPr();
12924        }
12925        // Send a broadcast to let everyone know we are done processing
12926        if (pkgList.size() > 0) {
12927            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12928        }
12929    }
12930
12931   /*
12932     * Utility method to unload a list of specified containers
12933     */
12934    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12935        // Just unmount all valid containers.
12936        for (AsecInstallArgs arg : cidArgs) {
12937            synchronized (mInstallLock) {
12938                arg.doPostDeleteLI(false);
12939           }
12940       }
12941   }
12942
12943    /*
12944     * Unload packages mounted on external media. This involves deleting package
12945     * data from internal structures, sending broadcasts about diabled packages,
12946     * gc'ing to free up references, unmounting all secure containers
12947     * corresponding to packages on external media, and posting a
12948     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12949     * that we always have to post this message if status has been requested no
12950     * matter what.
12951     */
12952    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12953            final boolean reportStatus) {
12954        if (DEBUG_SD_INSTALL)
12955            Log.i(TAG, "unloading media packages");
12956        ArrayList<String> pkgList = new ArrayList<String>();
12957        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12958        final Set<AsecInstallArgs> keys = processCids.keySet();
12959        for (AsecInstallArgs args : keys) {
12960            String pkgName = args.getPackageName();
12961            if (DEBUG_SD_INSTALL)
12962                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12963            // Delete package internally
12964            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12965            synchronized (mInstallLock) {
12966                boolean res = deletePackageLI(pkgName, null, false, null, null,
12967                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12968                if (res) {
12969                    pkgList.add(pkgName);
12970                } else {
12971                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12972                    failedList.add(args);
12973                }
12974            }
12975        }
12976
12977        // reader
12978        synchronized (mPackages) {
12979            // We didn't update the settings after removing each package;
12980            // write them now for all packages.
12981            mSettings.writeLPr();
12982        }
12983
12984        // We have to absolutely send UPDATED_MEDIA_STATUS only
12985        // after confirming that all the receivers processed the ordered
12986        // broadcast when packages get disabled, force a gc to clean things up.
12987        // and unload all the containers.
12988        if (pkgList.size() > 0) {
12989            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12990                    new IIntentReceiver.Stub() {
12991                public void performReceive(Intent intent, int resultCode, String data,
12992                        Bundle extras, boolean ordered, boolean sticky,
12993                        int sendingUser) throws RemoteException {
12994                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12995                            reportStatus ? 1 : 0, 1, keys);
12996                    mHandler.sendMessage(msg);
12997                }
12998            });
12999        } else {
13000            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13001                    keys);
13002            mHandler.sendMessage(msg);
13003        }
13004    }
13005
13006    /** Binder call */
13007    @Override
13008    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13009            final int flags) {
13010        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13011        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13012        int returnCode = PackageManager.MOVE_SUCCEEDED;
13013        int currInstallFlags = 0;
13014        int newInstallFlags = 0;
13015
13016        File codeFile = null;
13017        String installerPackageName = null;
13018        String packageAbiOverride = null;
13019
13020        // reader
13021        synchronized (mPackages) {
13022            final PackageParser.Package pkg = mPackages.get(packageName);
13023            final PackageSetting ps = mSettings.mPackages.get(packageName);
13024            if (pkg == null || ps == null) {
13025                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13026            } else {
13027                // Disable moving fwd locked apps and system packages
13028                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13029                    Slog.w(TAG, "Cannot move system application");
13030                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13031                } else if (pkg.mOperationPending) {
13032                    Slog.w(TAG, "Attempt to move package which has pending operations");
13033                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13034                } else {
13035                    // Find install location first
13036                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13037                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13038                        Slog.w(TAG, "Ambigous flags specified for move location.");
13039                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13040                    } else {
13041                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13042                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13043                        currInstallFlags = isExternal(pkg)
13044                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13045
13046                        if (newInstallFlags == currInstallFlags) {
13047                            Slog.w(TAG, "No move required. Trying to move to same location");
13048                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13049                        } else {
13050                            if (pkg.isForwardLocked()) {
13051                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13052                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13053                            }
13054                        }
13055                    }
13056                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13057                        pkg.mOperationPending = true;
13058                    }
13059                }
13060
13061                codeFile = new File(pkg.codePath);
13062                installerPackageName = ps.installerPackageName;
13063                packageAbiOverride = ps.cpuAbiOverrideString;
13064            }
13065        }
13066
13067        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13068            try {
13069                observer.packageMoved(packageName, returnCode);
13070            } catch (RemoteException ignored) {
13071            }
13072            return;
13073        }
13074
13075        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13076            @Override
13077            public void onUserActionRequired(Intent intent) throws RemoteException {
13078                throw new IllegalStateException();
13079            }
13080
13081            @Override
13082            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13083                    Bundle extras) throws RemoteException {
13084                Slog.d(TAG, "Install result for move: "
13085                        + PackageManager.installStatusToString(returnCode, msg));
13086
13087                // We usually have a new package now after the install, but if
13088                // we failed we need to clear the pending flag on the original
13089                // package object.
13090                synchronized (mPackages) {
13091                    final PackageParser.Package pkg = mPackages.get(packageName);
13092                    if (pkg != null) {
13093                        pkg.mOperationPending = false;
13094                    }
13095                }
13096
13097                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13098                switch (status) {
13099                    case PackageInstaller.STATUS_SUCCESS:
13100                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13101                        break;
13102                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13103                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13104                        break;
13105                    default:
13106                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13107                        break;
13108                }
13109            }
13110        };
13111
13112        // Treat a move like reinstalling an existing app, which ensures that we
13113        // process everythign uniformly, like unpacking native libraries.
13114        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13115
13116        final Message msg = mHandler.obtainMessage(INIT_COPY);
13117        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13118        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13119                installerPackageName, null, user, packageAbiOverride);
13120        mHandler.sendMessage(msg);
13121    }
13122
13123    @Override
13124    public boolean setInstallLocation(int loc) {
13125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13126                null);
13127        if (getInstallLocation() == loc) {
13128            return true;
13129        }
13130        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13131                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13132            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13133                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13134            return true;
13135        }
13136        return false;
13137   }
13138
13139    @Override
13140    public int getInstallLocation() {
13141        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13142                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13143                PackageHelper.APP_INSTALL_AUTO);
13144    }
13145
13146    /** Called by UserManagerService */
13147    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13148        mDirtyUsers.remove(userHandle);
13149        mSettings.removeUserLPw(userHandle);
13150        mPendingBroadcasts.remove(userHandle);
13151        if (mInstaller != null) {
13152            // Technically, we shouldn't be doing this with the package lock
13153            // held.  However, this is very rare, and there is already so much
13154            // other disk I/O going on, that we'll let it slide for now.
13155            mInstaller.removeUserDataDirs(userHandle);
13156        }
13157        mUserNeedsBadging.delete(userHandle);
13158        removeUnusedPackagesLILPw(userManager, userHandle);
13159    }
13160
13161    /**
13162     * We're removing userHandle and would like to remove any downloaded packages
13163     * that are no longer in use by any other user.
13164     * @param userHandle the user being removed
13165     */
13166    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13167        final boolean DEBUG_CLEAN_APKS = false;
13168        int [] users = userManager.getUserIdsLPr();
13169        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13170        while (psit.hasNext()) {
13171            PackageSetting ps = psit.next();
13172            if (ps.pkg == null) {
13173                continue;
13174            }
13175            final String packageName = ps.pkg.packageName;
13176            // Skip over if system app
13177            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13178                continue;
13179            }
13180            if (DEBUG_CLEAN_APKS) {
13181                Slog.i(TAG, "Checking package " + packageName);
13182            }
13183            boolean keep = false;
13184            for (int i = 0; i < users.length; i++) {
13185                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13186                    keep = true;
13187                    if (DEBUG_CLEAN_APKS) {
13188                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13189                                + users[i]);
13190                    }
13191                    break;
13192                }
13193            }
13194            if (!keep) {
13195                if (DEBUG_CLEAN_APKS) {
13196                    Slog.i(TAG, "  Removing package " + packageName);
13197                }
13198                mHandler.post(new Runnable() {
13199                    public void run() {
13200                        deletePackageX(packageName, userHandle, 0);
13201                    } //end run
13202                });
13203            }
13204        }
13205    }
13206
13207    /** Called by UserManagerService */
13208    void createNewUserLILPw(int userHandle, File path) {
13209        if (mInstaller != null) {
13210            mInstaller.createUserConfig(userHandle);
13211            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13212        }
13213    }
13214
13215    @Override
13216    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13217        mContext.enforceCallingOrSelfPermission(
13218                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13219                "Only package verification agents can read the verifier device identity");
13220
13221        synchronized (mPackages) {
13222            return mSettings.getVerifierDeviceIdentityLPw();
13223        }
13224    }
13225
13226    @Override
13227    public void setPermissionEnforced(String permission, boolean enforced) {
13228        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13229        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13230            synchronized (mPackages) {
13231                if (mSettings.mReadExternalStorageEnforced == null
13232                        || mSettings.mReadExternalStorageEnforced != enforced) {
13233                    mSettings.mReadExternalStorageEnforced = enforced;
13234                    mSettings.writeLPr();
13235                }
13236            }
13237            // kill any non-foreground processes so we restart them and
13238            // grant/revoke the GID.
13239            final IActivityManager am = ActivityManagerNative.getDefault();
13240            if (am != null) {
13241                final long token = Binder.clearCallingIdentity();
13242                try {
13243                    am.killProcessesBelowForeground("setPermissionEnforcement");
13244                } catch (RemoteException e) {
13245                } finally {
13246                    Binder.restoreCallingIdentity(token);
13247                }
13248            }
13249        } else {
13250            throw new IllegalArgumentException("No selective enforcement for " + permission);
13251        }
13252    }
13253
13254    @Override
13255    @Deprecated
13256    public boolean isPermissionEnforced(String permission) {
13257        return true;
13258    }
13259
13260    @Override
13261    public boolean isStorageLow() {
13262        final long token = Binder.clearCallingIdentity();
13263        try {
13264            final DeviceStorageMonitorInternal
13265                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13266            if (dsm != null) {
13267                return dsm.isMemoryLow();
13268            } else {
13269                return false;
13270            }
13271        } finally {
13272            Binder.restoreCallingIdentity(token);
13273        }
13274    }
13275
13276    @Override
13277    public IPackageInstaller getPackageInstaller() {
13278        return mInstallerService;
13279    }
13280
13281    private boolean userNeedsBadging(int userId) {
13282        int index = mUserNeedsBadging.indexOfKey(userId);
13283        if (index < 0) {
13284            final UserInfo userInfo;
13285            final long token = Binder.clearCallingIdentity();
13286            try {
13287                userInfo = sUserManager.getUserInfo(userId);
13288            } finally {
13289                Binder.restoreCallingIdentity(token);
13290            }
13291            final boolean b;
13292            if (userInfo != null && userInfo.isManagedProfile()) {
13293                b = true;
13294            } else {
13295                b = false;
13296            }
13297            mUserNeedsBadging.put(userId, b);
13298            return b;
13299        }
13300        return mUserNeedsBadging.valueAt(index);
13301    }
13302
13303    @Override
13304    public KeySet getKeySetByAlias(String packageName, String alias) {
13305        if (packageName == null || alias == null) {
13306            return null;
13307        }
13308        synchronized(mPackages) {
13309            final PackageParser.Package pkg = mPackages.get(packageName);
13310            if (pkg == null) {
13311                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13312                throw new IllegalArgumentException("Unknown package: " + packageName);
13313            }
13314            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13315            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13316        }
13317    }
13318
13319    @Override
13320    public KeySet getSigningKeySet(String packageName) {
13321        if (packageName == null) {
13322            return null;
13323        }
13324        synchronized(mPackages) {
13325            final PackageParser.Package pkg = mPackages.get(packageName);
13326            if (pkg == null) {
13327                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13328                throw new IllegalArgumentException("Unknown package: " + packageName);
13329            }
13330            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13331                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13332                throw new SecurityException("May not access signing KeySet of other apps.");
13333            }
13334            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13335            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13336        }
13337    }
13338
13339    @Override
13340    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13341        if (packageName == null || ks == null) {
13342            return false;
13343        }
13344        synchronized(mPackages) {
13345            final PackageParser.Package pkg = mPackages.get(packageName);
13346            if (pkg == null) {
13347                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13348                throw new IllegalArgumentException("Unknown package: " + packageName);
13349            }
13350            IBinder ksh = ks.getToken();
13351            if (ksh instanceof KeySetHandle) {
13352                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13353                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13354            }
13355            return false;
13356        }
13357    }
13358
13359    @Override
13360    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13361        if (packageName == null || ks == null) {
13362            return false;
13363        }
13364        synchronized(mPackages) {
13365            final PackageParser.Package pkg = mPackages.get(packageName);
13366            if (pkg == null) {
13367                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13368                throw new IllegalArgumentException("Unknown package: " + packageName);
13369            }
13370            IBinder ksh = ks.getToken();
13371            if (ksh instanceof KeySetHandle) {
13372                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13373                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13374            }
13375            return false;
13376        }
13377    }
13378
13379    public void getUsageStatsIfNoPackageUsageInfo() {
13380        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13381            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13382            if (usm == null) {
13383                throw new IllegalStateException("UsageStatsManager must be initialized");
13384            }
13385            long now = System.currentTimeMillis();
13386            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13387            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13388                String packageName = entry.getKey();
13389                PackageParser.Package pkg = mPackages.get(packageName);
13390                if (pkg == null) {
13391                    continue;
13392                }
13393                UsageStats usage = entry.getValue();
13394                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13395                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13396            }
13397        }
13398    }
13399
13400    /**
13401     * Check and throw if the given before/after packages would be considered a
13402     * downgrade.
13403     */
13404    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13405            throws PackageManagerException {
13406        if (after.versionCode < before.mVersionCode) {
13407            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13408                    "Update version code " + after.versionCode + " is older than current "
13409                    + before.mVersionCode);
13410        } else if (after.versionCode == before.mVersionCode) {
13411            if (after.baseRevisionCode < before.baseRevisionCode) {
13412                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13413                        "Update base revision code " + after.baseRevisionCode
13414                        + " is older than current " + before.baseRevisionCode);
13415            }
13416
13417            if (!ArrayUtils.isEmpty(after.splitNames)) {
13418                for (int i = 0; i < after.splitNames.length; i++) {
13419                    final String splitName = after.splitNames[i];
13420                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13421                    if (j != -1) {
13422                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13423                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13424                                    "Update split " + splitName + " revision code "
13425                                    + after.splitRevisionCodes[i] + " is older than current "
13426                                    + before.splitRevisionCodes[j]);
13427                        }
13428                    }
13429                }
13430            }
13431        }
13432    }
13433}
13434