PackageManagerService.java revision e87dc6dba58e55c60f387a86468a57a5109a97ac
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
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.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = false;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REQUIRE_KNOWN = 1<<12;
327    static final int SCAN_MOVE = 1<<13;
328    static final int SCAN_INITIAL = 1<<14;
329
330    static final int REMOVE_CHATTY = 1<<16;
331
332    private static final int[] EMPTY_INT_ARRAY = new int[0];
333
334    /**
335     * Timeout (in milliseconds) after which the watchdog should declare that
336     * our handler thread is wedged.  The usual default for such things is one
337     * minute but we sometimes do very lengthy I/O operations on this thread,
338     * such as installing multi-gigabyte applications, so ours needs to be longer.
339     */
340    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
341
342    /**
343     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
344     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
345     * settings entry if available, otherwise we use the hardcoded default.  If it's been
346     * more than this long since the last fstrim, we force one during the boot sequence.
347     *
348     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
349     * one gets run at the next available charging+idle time.  This final mandatory
350     * no-fstrim check kicks in only of the other scheduling criteria is never met.
351     */
352    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
353
354    /**
355     * Whether verification is enabled by default.
356     */
357    private static final boolean DEFAULT_VERIFY_ENABLE = true;
358
359    /**
360     * The default maximum time to wait for the verification agent to return in
361     * milliseconds.
362     */
363    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
364
365    /**
366     * The default response for package verification timeout.
367     *
368     * This can be either PackageManager.VERIFICATION_ALLOW or
369     * PackageManager.VERIFICATION_REJECT.
370     */
371    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
372
373    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
374
375    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
376            DEFAULT_CONTAINER_PACKAGE,
377            "com.android.defcontainer.DefaultContainerService");
378
379    private static final String KILL_APP_REASON_GIDS_CHANGED =
380            "permission grant or revoke changed gids";
381
382    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
383            "permissions revoked";
384
385    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
386
387    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
388
389    /** Permission grant: not grant the permission. */
390    private static final int GRANT_DENIED = 1;
391
392    /** Permission grant: grant the permission as an install permission. */
393    private static final int GRANT_INSTALL = 2;
394
395    /** Permission grant: grant the permission as an install permission for a legacy app. */
396    private static final int GRANT_INSTALL_LEGACY = 3;
397
398    /** Permission grant: grant the permission as a runtime one. */
399    private static final int GRANT_RUNTIME = 4;
400
401    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
402    private static final int GRANT_UPGRADE = 5;
403
404    /** Canonical intent used to identify what counts as a "web browser" app */
405    private static final Intent sBrowserIntent;
406    static {
407        sBrowserIntent = new Intent();
408        sBrowserIntent.setAction(Intent.ACTION_VIEW);
409        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
410        sBrowserIntent.setData(Uri.parse("http:"));
411    }
412
413    final ServiceThread mHandlerThread;
414
415    final PackageHandler mHandler;
416
417    /**
418     * Messages for {@link #mHandler} that need to wait for system ready before
419     * being dispatched.
420     */
421    private ArrayList<Message> mPostSystemReadyMessages;
422
423    final int mSdkVersion = Build.VERSION.SDK_INT;
424
425    final Context mContext;
426    final boolean mFactoryTest;
427    final boolean mOnlyCore;
428    final boolean mLazyDexOpt;
429    final long mDexOptLRUThresholdInMills;
430    final DisplayMetrics mMetrics;
431    final int mDefParseFlags;
432    final String[] mSeparateProcesses;
433    final boolean mIsUpgrade;
434
435    // This is where all application persistent data goes.
436    final File mAppDataDir;
437
438    // This is where all application persistent data goes for secondary users.
439    final File mUserAppDataDir;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451
452    /**
453     * Directory to which applications installed internally have their
454     * 32 bit native libraries copied.
455     */
456    private File mAppLib32InstallDir;
457
458    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
459    // apps.
460    final File mDrmAppPrivateInstallDir;
461
462    // ----------------------------------------------------------------
463
464    // Lock for state used when installing and doing other long running
465    // operations.  Methods that must be called with this lock held have
466    // the suffix "LI".
467    final Object mInstallLock = new Object();
468
469    // ----------------------------------------------------------------
470
471    // Keys are String (package name), values are Package.  This also serves
472    // as the lock for the global state.  Methods that must be called with
473    // this lock held have the prefix "LP".
474    @GuardedBy("mPackages")
475    final ArrayMap<String, PackageParser.Package> mPackages =
476            new ArrayMap<String, PackageParser.Package>();
477
478    // Tracks available target package names -> overlay package paths.
479    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
480        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
481
482    /**
483     * Tracks new system packages [receiving in an OTA] that we expect to
484     * find updated user-installed versions. Keys are package name, values
485     * are package location.
486     */
487    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
488
489    final Settings mSettings;
490    boolean mRestoredSettings;
491
492    // System configuration read by SystemConfig.
493    final int[] mGlobalGids;
494    final SparseArray<ArraySet<String>> mSystemPermissions;
495    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
496
497    // If mac_permissions.xml was found for seinfo labeling.
498    boolean mFoundPolicyFile;
499
500    // If a recursive restorecon of /data/data/<pkg> is needed.
501    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
502
503    public static final class SharedLibraryEntry {
504        public final String path;
505        public final String apk;
506
507        SharedLibraryEntry(String _path, String _apk) {
508            path = _path;
509            apk = _apk;
510        }
511    }
512
513    // Currently known shared libraries.
514    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
515            new ArrayMap<String, SharedLibraryEntry>();
516
517    // All available activities, for your resolving pleasure.
518    final ActivityIntentResolver mActivities =
519            new ActivityIntentResolver();
520
521    // All available receivers, for your resolving pleasure.
522    final ActivityIntentResolver mReceivers =
523            new ActivityIntentResolver();
524
525    // All available services, for your resolving pleasure.
526    final ServiceIntentResolver mServices = new ServiceIntentResolver();
527
528    // All available providers, for your resolving pleasure.
529    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
530
531    // Mapping from provider base names (first directory in content URI codePath)
532    // to the provider information.
533    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
534            new ArrayMap<String, PackageParser.Provider>();
535
536    // Mapping from instrumentation class names to info about them.
537    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
538            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
539
540    // Mapping from permission names to info about them.
541    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
542            new ArrayMap<String, PackageParser.PermissionGroup>();
543
544    // Packages whose data we have transfered into another package, thus
545    // should no longer exist.
546    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
547
548    // Broadcast actions that are only available to the system.
549    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
550
551    /** List of packages waiting for verification. */
552    final SparseArray<PackageVerificationState> mPendingVerification
553            = new SparseArray<PackageVerificationState>();
554
555    /** Set of packages associated with each app op permission. */
556    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
557
558    final PackageInstallerService mInstallerService;
559
560    private final PackageDexOptimizer mPackageDexOptimizer;
561
562    private AtomicInteger mNextMoveId = new AtomicInteger();
563    private final MoveCallbacks mMoveCallbacks;
564
565    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
566
567    // Cache of users who need badging.
568    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
569
570    /** Token for keys in mPendingVerification. */
571    private int mPendingVerificationToken = 0;
572
573    volatile boolean mSystemReady;
574    volatile boolean mSafeMode;
575    volatile boolean mHasSystemUidErrors;
576
577    ApplicationInfo mAndroidApplication;
578    final ActivityInfo mResolveActivity = new ActivityInfo();
579    final ResolveInfo mResolveInfo = new ResolveInfo();
580    ComponentName mResolveComponentName;
581    PackageParser.Package mPlatformPackage;
582    ComponentName mCustomResolverComponentName;
583
584    boolean mResolverReplaced = false;
585
586    private final ComponentName mIntentFilterVerifierComponent;
587    private int mIntentFilterVerificationToken = 0;
588
589    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
590            = new SparseArray<IntentFilterVerificationState>();
591
592    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
593            new DefaultPermissionGrantPolicy(this);
594
595    private static class IFVerificationParams {
596        PackageParser.Package pkg;
597        boolean replacing;
598        int userId;
599        int verifierUid;
600
601        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
602                int _userId, int _verifierUid) {
603            pkg = _pkg;
604            replacing = _replacing;
605            userId = _userId;
606            replacing = _replacing;
607            verifierUid = _verifierUid;
608        }
609    }
610
611    private interface IntentFilterVerifier<T extends IntentFilter> {
612        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
613                                               T filter, String packageName);
614        void startVerifications(int userId);
615        void receiveVerificationResponse(int verificationId);
616    }
617
618    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
619        private Context mContext;
620        private ComponentName mIntentFilterVerifierComponent;
621        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
622
623        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
624            mContext = context;
625            mIntentFilterVerifierComponent = verifierComponent;
626        }
627
628        private String getDefaultScheme() {
629            return IntentFilter.SCHEME_HTTPS;
630        }
631
632        @Override
633        public void startVerifications(int userId) {
634            // Launch verifications requests
635            int count = mCurrentIntentFilterVerifications.size();
636            for (int n=0; n<count; n++) {
637                int verificationId = mCurrentIntentFilterVerifications.get(n);
638                final IntentFilterVerificationState ivs =
639                        mIntentFilterVerificationStates.get(verificationId);
640
641                String packageName = ivs.getPackageName();
642
643                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
644                final int filterCount = filters.size();
645                ArraySet<String> domainsSet = new ArraySet<>();
646                for (int m=0; m<filterCount; m++) {
647                    PackageParser.ActivityIntentInfo filter = filters.get(m);
648                    domainsSet.addAll(filter.getHostsList());
649                }
650                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
651                synchronized (mPackages) {
652                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
653                            packageName, domainsList) != null) {
654                        scheduleWriteSettingsLocked();
655                    }
656                }
657                sendVerificationRequest(userId, verificationId, ivs);
658            }
659            mCurrentIntentFilterVerifications.clear();
660        }
661
662        private void sendVerificationRequest(int userId, int verificationId,
663                IntentFilterVerificationState ivs) {
664
665            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
668                    verificationId);
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
671                    getDefaultScheme());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
674                    ivs.getHostsString());
675            verificationIntent.putExtra(
676                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
677                    ivs.getPackageName());
678            verificationIntent.setComponent(mIntentFilterVerifierComponent);
679            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680
681            UserHandle user = new UserHandle(userId);
682            mContext.sendBroadcastAsUser(verificationIntent, user);
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Sending IntentFilter verification broadcast");
685        }
686
687        public void receiveVerificationResponse(int verificationId) {
688            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
689
690            final boolean verified = ivs.isVerified();
691
692            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
693            final int count = filters.size();
694            if (DEBUG_DOMAIN_VERIFICATION) {
695                Slog.i(TAG, "Received verification response " + verificationId
696                        + " for " + count + " filters, verified=" + verified);
697            }
698            for (int n=0; n<count; n++) {
699                PackageParser.ActivityIntentInfo filter = filters.get(n);
700                filter.setVerified(verified);
701
702                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
703                        + " verified with result:" + verified + " and hosts:"
704                        + ivs.getHostsString());
705            }
706
707            mIntentFilterVerificationStates.remove(verificationId);
708
709            final String packageName = ivs.getPackageName();
710            IntentFilterVerificationInfo ivi = null;
711
712            synchronized (mPackages) {
713                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
714            }
715            if (ivi == null) {
716                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
717                        + verificationId + " packageName:" + packageName);
718                return;
719            }
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Updating IntentFilterVerificationInfo for package " + packageName
722                            +" verificationId:" + verificationId);
723
724            synchronized (mPackages) {
725                if (verified) {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
727                } else {
728                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
729                }
730                scheduleWriteSettingsLocked();
731
732                final int userId = ivs.getUserId();
733                if (userId != UserHandle.USER_ALL) {
734                    final int userStatus =
735                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
736
737                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
738                    boolean needUpdate = false;
739
740                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
741                    // already been set by the User thru the Disambiguation dialog
742                    switch (userStatus) {
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                            } else {
747                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
748                            }
749                            needUpdate = true;
750                            break;
751
752                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
753                            if (verified) {
754                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
755                                needUpdate = true;
756                            }
757                            break;
758
759                        default:
760                            // Nothing to do
761                    }
762
763                    if (needUpdate) {
764                        mSettings.updateIntentFilterVerificationStatusLPw(
765                                packageName, updatedStatus, userId);
766                        scheduleWritePackageRestrictionsLocked(userId);
767                    }
768                }
769            }
770        }
771
772        @Override
773        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
774                    ActivityIntentInfo filter, String packageName) {
775            if (!hasValidDomains(filter)) {
776                return false;
777            }
778            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
779            if (ivs == null) {
780                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
781                        packageName);
782            }
783            if (DEBUG_DOMAIN_VERIFICATION) {
784                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
785            }
786            ivs.addFilter(filter);
787            return true;
788        }
789
790        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
791                int userId, int verificationId, String packageName) {
792            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
793                    verifierUid, userId, packageName);
794            ivs.setPendingState();
795            synchronized (mPackages) {
796                mIntentFilterVerificationStates.append(verificationId, ivs);
797                mCurrentIntentFilterVerifications.add(verificationId);
798            }
799            return ivs;
800        }
801    }
802
803    private static boolean hasValidDomains(ActivityIntentInfo filter) {
804        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
805                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
806                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
807    }
808
809    private IntentFilterVerifier mIntentFilterVerifier;
810
811    // Set of pending broadcasts for aggregating enable/disable of components.
812    static class PendingPackageBroadcasts {
813        // for each user id, a map of <package name -> components within that package>
814        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
815
816        public PendingPackageBroadcasts() {
817            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
818        }
819
820        public ArrayList<String> get(int userId, String packageName) {
821            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822            return packages.get(packageName);
823        }
824
825        public void put(int userId, String packageName, ArrayList<String> components) {
826            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
827            packages.put(packageName, components);
828        }
829
830        public void remove(int userId, String packageName) {
831            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
832            if (packages != null) {
833                packages.remove(packageName);
834            }
835        }
836
837        public void remove(int userId) {
838            mUidMap.remove(userId);
839        }
840
841        public int userIdCount() {
842            return mUidMap.size();
843        }
844
845        public int userIdAt(int n) {
846            return mUidMap.keyAt(n);
847        }
848
849        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
850            return mUidMap.get(userId);
851        }
852
853        public int size() {
854            // total number of pending broadcast entries across all userIds
855            int num = 0;
856            for (int i = 0; i< mUidMap.size(); i++) {
857                num += mUidMap.valueAt(i).size();
858            }
859            return num;
860        }
861
862        public void clear() {
863            mUidMap.clear();
864        }
865
866        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
867            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
868            if (map == null) {
869                map = new ArrayMap<String, ArrayList<String>>();
870                mUidMap.put(userId, map);
871            }
872            return map;
873        }
874    }
875    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
876
877    // Service Connection to remote media container service to copy
878    // package uri's from external media onto secure containers
879    // or internal storage.
880    private IMediaContainerService mContainerService = null;
881
882    static final int SEND_PENDING_BROADCAST = 1;
883    static final int MCS_BOUND = 3;
884    static final int END_COPY = 4;
885    static final int INIT_COPY = 5;
886    static final int MCS_UNBIND = 6;
887    static final int START_CLEANING_PACKAGE = 7;
888    static final int FIND_INSTALL_LOC = 8;
889    static final int POST_INSTALL = 9;
890    static final int MCS_RECONNECT = 10;
891    static final int MCS_GIVE_UP = 11;
892    static final int UPDATED_MEDIA_STATUS = 12;
893    static final int WRITE_SETTINGS = 13;
894    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
895    static final int PACKAGE_VERIFIED = 15;
896    static final int CHECK_PENDING_VERIFICATION = 16;
897    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
898    static final int INTENT_FILTER_VERIFIED = 18;
899
900    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
901
902    // Delay time in millisecs
903    static final int BROADCAST_DELAY = 10 * 1000;
904
905    static UserManagerService sUserManager;
906
907    // Stores a list of users whose package restrictions file needs to be updated
908    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
909
910    final private DefaultContainerConnection mDefContainerConn =
911            new DefaultContainerConnection();
912    class DefaultContainerConnection implements ServiceConnection {
913        public void onServiceConnected(ComponentName name, IBinder service) {
914            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
915            IMediaContainerService imcs =
916                IMediaContainerService.Stub.asInterface(service);
917            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
918        }
919
920        public void onServiceDisconnected(ComponentName name) {
921            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
922        }
923    }
924
925    // Recordkeeping of restore-after-install operations that are currently in flight
926    // between the Package Manager and the Backup Manager
927    class PostInstallData {
928        public InstallArgs args;
929        public PackageInstalledInfo res;
930
931        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
932            args = _a;
933            res = _r;
934        }
935    }
936
937    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
938    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
939
940    // XML tags for backup/restore of various bits of state
941    private static final String TAG_PREFERRED_BACKUP = "pa";
942    private static final String TAG_DEFAULT_APPS = "da";
943    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
944
945    final String mRequiredVerifierPackage;
946    final String mRequiredInstallerPackage;
947
948    private final PackageUsage mPackageUsage = new PackageUsage();
949
950    private class PackageUsage {
951        private static final int WRITE_INTERVAL
952            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
953
954        private final Object mFileLock = new Object();
955        private final AtomicLong mLastWritten = new AtomicLong(0);
956        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
957
958        private boolean mIsHistoricalPackageUsageAvailable = true;
959
960        boolean isHistoricalPackageUsageAvailable() {
961            return mIsHistoricalPackageUsageAvailable;
962        }
963
964        void write(boolean force) {
965            if (force) {
966                writeInternal();
967                return;
968            }
969            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
970                && !DEBUG_DEXOPT) {
971                return;
972            }
973            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
974                new Thread("PackageUsage_DiskWriter") {
975                    @Override
976                    public void run() {
977                        try {
978                            writeInternal();
979                        } finally {
980                            mBackgroundWriteRunning.set(false);
981                        }
982                    }
983                }.start();
984            }
985        }
986
987        private void writeInternal() {
988            synchronized (mPackages) {
989                synchronized (mFileLock) {
990                    AtomicFile file = getFile();
991                    FileOutputStream f = null;
992                    try {
993                        f = file.startWrite();
994                        BufferedOutputStream out = new BufferedOutputStream(f);
995                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
996                        StringBuilder sb = new StringBuilder();
997                        for (PackageParser.Package pkg : mPackages.values()) {
998                            if (pkg.mLastPackageUsageTimeInMills == 0) {
999                                continue;
1000                            }
1001                            sb.setLength(0);
1002                            sb.append(pkg.packageName);
1003                            sb.append(' ');
1004                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1005                            sb.append('\n');
1006                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1007                        }
1008                        out.flush();
1009                        file.finishWrite(f);
1010                    } catch (IOException e) {
1011                        if (f != null) {
1012                            file.failWrite(f);
1013                        }
1014                        Log.e(TAG, "Failed to write package usage times", e);
1015                    }
1016                }
1017            }
1018            mLastWritten.set(SystemClock.elapsedRealtime());
1019        }
1020
1021        void readLP() {
1022            synchronized (mFileLock) {
1023                AtomicFile file = getFile();
1024                BufferedInputStream in = null;
1025                try {
1026                    in = new BufferedInputStream(file.openRead());
1027                    StringBuffer sb = new StringBuffer();
1028                    while (true) {
1029                        String packageName = readToken(in, sb, ' ');
1030                        if (packageName == null) {
1031                            break;
1032                        }
1033                        String timeInMillisString = readToken(in, sb, '\n');
1034                        if (timeInMillisString == null) {
1035                            throw new IOException("Failed to find last usage time for package "
1036                                                  + packageName);
1037                        }
1038                        PackageParser.Package pkg = mPackages.get(packageName);
1039                        if (pkg == null) {
1040                            continue;
1041                        }
1042                        long timeInMillis;
1043                        try {
1044                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1045                        } catch (NumberFormatException e) {
1046                            throw new IOException("Failed to parse " + timeInMillisString
1047                                                  + " as a long.", e);
1048                        }
1049                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1050                    }
1051                } catch (FileNotFoundException expected) {
1052                    mIsHistoricalPackageUsageAvailable = false;
1053                } catch (IOException e) {
1054                    Log.w(TAG, "Failed to read package usage times", e);
1055                } finally {
1056                    IoUtils.closeQuietly(in);
1057                }
1058            }
1059            mLastWritten.set(SystemClock.elapsedRealtime());
1060        }
1061
1062        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1063                throws IOException {
1064            sb.setLength(0);
1065            while (true) {
1066                int ch = in.read();
1067                if (ch == -1) {
1068                    if (sb.length() == 0) {
1069                        return null;
1070                    }
1071                    throw new IOException("Unexpected EOF");
1072                }
1073                if (ch == endOfToken) {
1074                    return sb.toString();
1075                }
1076                sb.append((char)ch);
1077            }
1078        }
1079
1080        private AtomicFile getFile() {
1081            File dataDir = Environment.getDataDirectory();
1082            File systemDir = new File(dataDir, "system");
1083            File fname = new File(systemDir, "package-usage.list");
1084            return new AtomicFile(fname);
1085        }
1086    }
1087
1088    class PackageHandler extends Handler {
1089        private boolean mBound = false;
1090        final ArrayList<HandlerParams> mPendingInstalls =
1091            new ArrayList<HandlerParams>();
1092
1093        private boolean connectToService() {
1094            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1095                    " DefaultContainerService");
1096            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1099                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1100                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1101                mBound = true;
1102                return true;
1103            }
1104            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105            return false;
1106        }
1107
1108        private void disconnectService() {
1109            mContainerService = null;
1110            mBound = false;
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112            mContext.unbindService(mDefContainerConn);
1113            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114        }
1115
1116        PackageHandler(Looper looper) {
1117            super(looper);
1118        }
1119
1120        public void handleMessage(Message msg) {
1121            try {
1122                doHandleMessage(msg);
1123            } finally {
1124                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125            }
1126        }
1127
1128        void doHandleMessage(Message msg) {
1129            switch (msg.what) {
1130                case INIT_COPY: {
1131                    HandlerParams params = (HandlerParams) msg.obj;
1132                    int idx = mPendingInstalls.size();
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1134                    // If a bind was already initiated we dont really
1135                    // need to do anything. The pending install
1136                    // will be processed later on.
1137                    if (!mBound) {
1138                        // If this is the only one pending we might
1139                        // have to bind to the service again.
1140                        if (!connectToService()) {
1141                            Slog.e(TAG, "Failed to bind to media container service");
1142                            params.serviceError();
1143                            return;
1144                        } else {
1145                            // Once we bind to the service, the first
1146                            // pending request will be processed.
1147                            mPendingInstalls.add(idx, params);
1148                        }
1149                    } else {
1150                        mPendingInstalls.add(idx, params);
1151                        // Already bound to the service. Just make
1152                        // sure we trigger off processing the first request.
1153                        if (idx == 0) {
1154                            mHandler.sendEmptyMessage(MCS_BOUND);
1155                        }
1156                    }
1157                    break;
1158                }
1159                case MCS_BOUND: {
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1161                    if (msg.obj != null) {
1162                        mContainerService = (IMediaContainerService) msg.obj;
1163                    }
1164                    if (mContainerService == null) {
1165                        if (!mBound) {
1166                            // Something seriously wrong since we are not bound and we are not
1167                            // waiting for connection. Bail out.
1168                            Slog.e(TAG, "Cannot bind to media container service");
1169                            for (HandlerParams params : mPendingInstalls) {
1170                                // Indicate service bind error
1171                                params.serviceError();
1172                            }
1173                            mPendingInstalls.clear();
1174                        } else {
1175                            Slog.w(TAG, "Waiting to connect to media container service");
1176                        }
1177                    } else if (mPendingInstalls.size() > 0) {
1178                        HandlerParams params = mPendingInstalls.get(0);
1179                        if (params != null) {
1180                            if (params.startCopy()) {
1181                                // We are done...  look for more work or to
1182                                // go idle.
1183                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1184                                        "Checking for more work or unbind...");
1185                                // Delete pending install
1186                                if (mPendingInstalls.size() > 0) {
1187                                    mPendingInstalls.remove(0);
1188                                }
1189                                if (mPendingInstalls.size() == 0) {
1190                                    if (mBound) {
1191                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1192                                                "Posting delayed MCS_UNBIND");
1193                                        removeMessages(MCS_UNBIND);
1194                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1195                                        // Unbind after a little delay, to avoid
1196                                        // continual thrashing.
1197                                        sendMessageDelayed(ubmsg, 10000);
1198                                    }
1199                                } else {
1200                                    // There are more pending requests in queue.
1201                                    // Just post MCS_BOUND message to trigger processing
1202                                    // of next pending install.
1203                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                            "Posting MCS_BOUND for next work");
1205                                    mHandler.sendEmptyMessage(MCS_BOUND);
1206                                }
1207                            }
1208                        }
1209                    } else {
1210                        // Should never happen ideally.
1211                        Slog.w(TAG, "Empty queue");
1212                    }
1213                    break;
1214                }
1215                case MCS_RECONNECT: {
1216                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1217                    if (mPendingInstalls.size() > 0) {
1218                        if (mBound) {
1219                            disconnectService();
1220                        }
1221                        if (!connectToService()) {
1222                            Slog.e(TAG, "Failed to bind to media container service");
1223                            for (HandlerParams params : mPendingInstalls) {
1224                                // Indicate service bind error
1225                                params.serviceError();
1226                            }
1227                            mPendingInstalls.clear();
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_UNBIND: {
1233                    // If there is no actual work left, then time to unbind.
1234                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1235
1236                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1237                        if (mBound) {
1238                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1239
1240                            disconnectService();
1241                        }
1242                    } else if (mPendingInstalls.size() > 0) {
1243                        // There are more pending requests in queue.
1244                        // Just post MCS_BOUND message to trigger processing
1245                        // of next pending install.
1246                        mHandler.sendEmptyMessage(MCS_BOUND);
1247                    }
1248
1249                    break;
1250                }
1251                case MCS_GIVE_UP: {
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1253                    mPendingInstalls.remove(0);
1254                    break;
1255                }
1256                case SEND_PENDING_BROADCAST: {
1257                    String packages[];
1258                    ArrayList<String> components[];
1259                    int size = 0;
1260                    int uids[];
1261                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262                    synchronized (mPackages) {
1263                        if (mPendingBroadcasts == null) {
1264                            return;
1265                        }
1266                        size = mPendingBroadcasts.size();
1267                        if (size <= 0) {
1268                            // Nothing to be done. Just return
1269                            return;
1270                        }
1271                        packages = new String[size];
1272                        components = new ArrayList[size];
1273                        uids = new int[size];
1274                        int i = 0;  // filling out the above arrays
1275
1276                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1277                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1278                            Iterator<Map.Entry<String, ArrayList<String>>> it
1279                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1280                                            .entrySet().iterator();
1281                            while (it.hasNext() && i < size) {
1282                                Map.Entry<String, ArrayList<String>> ent = it.next();
1283                                packages[i] = ent.getKey();
1284                                components[i] = ent.getValue();
1285                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1286                                uids[i] = (ps != null)
1287                                        ? UserHandle.getUid(packageUserId, ps.appId)
1288                                        : -1;
1289                                i++;
1290                            }
1291                        }
1292                        size = i;
1293                        mPendingBroadcasts.clear();
1294                    }
1295                    // Send broadcasts
1296                    for (int i = 0; i < size; i++) {
1297                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1298                    }
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300                    break;
1301                }
1302                case START_CLEANING_PACKAGE: {
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1304                    final String packageName = (String)msg.obj;
1305                    final int userId = msg.arg1;
1306                    final boolean andCode = msg.arg2 != 0;
1307                    synchronized (mPackages) {
1308                        if (userId == UserHandle.USER_ALL) {
1309                            int[] users = sUserManager.getUserIds();
1310                            for (int user : users) {
1311                                mSettings.addPackageToCleanLPw(
1312                                        new PackageCleanItem(user, packageName, andCode));
1313                            }
1314                        } else {
1315                            mSettings.addPackageToCleanLPw(
1316                                    new PackageCleanItem(userId, packageName, andCode));
1317                        }
1318                    }
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                    startCleaningPackages();
1321                } break;
1322                case POST_INSTALL: {
1323                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1324                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1325                    mRunningInstalls.delete(msg.arg1);
1326                    boolean deleteOld = false;
1327
1328                    if (data != null) {
1329                        InstallArgs args = data.args;
1330                        PackageInstalledInfo res = data.res;
1331
1332                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1333                            final String packageName = res.pkg.applicationInfo.packageName;
1334                            res.removedInfo.sendBroadcast(false, true, false);
1335                            Bundle extras = new Bundle(1);
1336                            extras.putInt(Intent.EXTRA_UID, res.uid);
1337
1338                            // Now that we successfully installed the package, grant runtime
1339                            // permissions if requested before broadcasting the install.
1340                            if ((args.installFlags
1341                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1342                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1343                                        args.installGrantPermissions);
1344                            }
1345
1346                            // Determine the set of users who are adding this
1347                            // package for the first time vs. those who are seeing
1348                            // an update.
1349                            int[] firstUsers;
1350                            int[] updateUsers = new int[0];
1351                            if (res.origUsers == null || res.origUsers.length == 0) {
1352                                firstUsers = res.newUsers;
1353                            } else {
1354                                firstUsers = new int[0];
1355                                for (int i=0; i<res.newUsers.length; i++) {
1356                                    int user = res.newUsers[i];
1357                                    boolean isNew = true;
1358                                    for (int j=0; j<res.origUsers.length; j++) {
1359                                        if (res.origUsers[j] == user) {
1360                                            isNew = false;
1361                                            break;
1362                                        }
1363                                    }
1364                                    if (isNew) {
1365                                        int[] newFirst = new int[firstUsers.length+1];
1366                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1367                                                firstUsers.length);
1368                                        newFirst[firstUsers.length] = user;
1369                                        firstUsers = newFirst;
1370                                    } else {
1371                                        int[] newUpdate = new int[updateUsers.length+1];
1372                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1373                                                updateUsers.length);
1374                                        newUpdate[updateUsers.length] = user;
1375                                        updateUsers = newUpdate;
1376                                    }
1377                                }
1378                            }
1379                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                    packageName, extras, null, null, firstUsers);
1381                            final boolean update = res.removedInfo.removedPackage != null;
1382                            if (update) {
1383                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1384                            }
1385                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1386                                    packageName, extras, null, null, updateUsers);
1387                            if (update) {
1388                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1389                                        packageName, extras, null, null, updateUsers);
1390                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1391                                        null, null, packageName, null, updateUsers);
1392
1393                                // treat asec-hosted packages like removable media on upgrade
1394                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1395                                    if (DEBUG_INSTALL) {
1396                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1397                                                + " is ASEC-hosted -> AVAILABLE");
1398                                    }
1399                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1400                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1401                                    pkgList.add(packageName);
1402                                    sendResourcesChangedBroadcast(true, true,
1403                                            pkgList,uidArray, null);
1404                                }
1405                            }
1406                            if (res.removedInfo.args != null) {
1407                                // Remove the replaced package's older resources safely now
1408                                deleteOld = true;
1409                            }
1410
1411                            // If this app is a browser and it's newly-installed for some
1412                            // users, clear any default-browser state in those users
1413                            if (firstUsers.length > 0) {
1414                                // the app's nature doesn't depend on the user, so we can just
1415                                // check its browser nature in any user and generalize.
1416                                if (packageIsBrowser(packageName, firstUsers[0])) {
1417                                    synchronized (mPackages) {
1418                                        for (int userId : firstUsers) {
1419                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1420                                        }
1421                                    }
1422                                }
1423                            }
1424                            // Log current value of "unknown sources" setting
1425                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1426                                getUnknownSourcesSettings());
1427                        }
1428                        // Force a gc to clear up things
1429                        Runtime.getRuntime().gc();
1430                        // We delete after a gc for applications  on sdcard.
1431                        if (deleteOld) {
1432                            synchronized (mInstallLock) {
1433                                res.removedInfo.args.doPostDeleteLI(true);
1434                            }
1435                        }
1436                        if (args.observer != null) {
1437                            try {
1438                                Bundle extras = extrasForInstallResult(res);
1439                                args.observer.onPackageInstalled(res.name, res.returnCode,
1440                                        res.returnMsg, extras);
1441                            } catch (RemoteException e) {
1442                                Slog.i(TAG, "Observer no longer exists.");
1443                            }
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448                } break;
1449                case UPDATED_MEDIA_STATUS: {
1450                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1451                    boolean reportStatus = msg.arg1 == 1;
1452                    boolean doGc = msg.arg2 == 1;
1453                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1454                    if (doGc) {
1455                        // Force a gc to clear up stale containers.
1456                        Runtime.getRuntime().gc();
1457                    }
1458                    if (msg.obj != null) {
1459                        @SuppressWarnings("unchecked")
1460                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1461                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1462                        // Unload containers
1463                        unloadAllContainers(args);
1464                    }
1465                    if (reportStatus) {
1466                        try {
1467                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1468                            PackageHelper.getMountService().finishMediaUpdate();
1469                        } catch (RemoteException e) {
1470                            Log.e(TAG, "MountService not running?");
1471                        }
1472                    }
1473                } break;
1474                case WRITE_SETTINGS: {
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476                    synchronized (mPackages) {
1477                        removeMessages(WRITE_SETTINGS);
1478                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                        mSettings.writeLPr();
1480                        mDirtyUsers.clear();
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                } break;
1484                case WRITE_PACKAGE_RESTRICTIONS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                        for (int userId : mDirtyUsers) {
1489                            mSettings.writePackageRestrictionsLPr(userId);
1490                        }
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case CHECK_PENDING_VERIFICATION: {
1496                    final int verificationId = msg.arg1;
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                    if ((state != null) && !state.timeoutExtended()) {
1500                        final InstallArgs args = state.getInstallArgs();
1501                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                        Slog.i(TAG, "Verification timed out for " + originUri);
1504                        mPendingVerification.remove(verificationId);
1505
1506                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                            Slog.i(TAG, "Continuing with installation of " + originUri);
1510                            state.setVerifierResponse(Binder.getCallingUid(),
1511                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_ALLOW,
1514                                    state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            broadcastPackageVerified(verificationId, originUri,
1522                                    PackageManager.VERIFICATION_REJECT,
1523                                    state.getInstallArgs().getUser());
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527                        mHandler.sendEmptyMessage(MCS_UNBIND);
1528                    }
1529                    break;
1530                }
1531                case PACKAGE_VERIFIED: {
1532                    final int verificationId = msg.arg1;
1533
1534                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1535                    if (state == null) {
1536                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1537                        break;
1538                    }
1539
1540                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1541
1542                    state.setVerifierResponse(response.callerUid, response.code);
1543
1544                    if (state.isVerificationComplete()) {
1545                        mPendingVerification.remove(verificationId);
1546
1547                        final InstallArgs args = state.getInstallArgs();
1548                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                        int ret;
1551                        if (state.isInstallAllowed()) {
1552                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1553                            broadcastPackageVerified(verificationId, originUri,
1554                                    response.code, state.getInstallArgs().getUser());
1555                            try {
1556                                ret = args.copyApk(mContainerService, true);
1557                            } catch (RemoteException e) {
1558                                Slog.e(TAG, "Could not contact the ContainerService");
1559                            }
1560                        } else {
1561                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1562                        }
1563
1564                        processPendingInstall(args, ret);
1565
1566                        mHandler.sendEmptyMessage(MCS_UNBIND);
1567                    }
1568
1569                    break;
1570                }
1571                case START_INTENT_FILTER_VERIFICATIONS: {
1572                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                            params.replacing, params.pkg);
1575                    break;
1576                }
1577                case INTENT_FILTER_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                            verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final int userId = state.getUserId();
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "Processing IntentFilter verification with token:"
1592                            + verificationId + " and userId:" + userId);
1593
1594                    final IntentFilterVerificationResponse response =
1595                            (IntentFilterVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                            "IntentFilter verification with token:" + verificationId
1601                            + " and userId:" + userId
1602                            + " is settings verifier response with response code:"
1603                            + response.code);
1604
1605                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                + response.getFailedDomainsString());
1608                    }
1609
1610                    if (state.isVerificationComplete()) {
1611                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                    } else {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                "IntentFilter verification with token:" + verificationId
1615                                + " was not said to be complete");
1616                    }
1617
1618                    break;
1619                }
1620            }
1621        }
1622    }
1623
1624    private StorageEventListener mStorageListener = new StorageEventListener() {
1625        @Override
1626        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1627            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1628                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1629                    final String volumeUuid = vol.getFsUuid();
1630
1631                    // Clean up any users or apps that were removed or recreated
1632                    // while this volume was missing
1633                    reconcileUsers(volumeUuid);
1634                    reconcileApps(volumeUuid);
1635
1636                    // Clean up any install sessions that expired or were
1637                    // cancelled while this volume was missing
1638                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1639
1640                    loadPrivatePackages(vol);
1641
1642                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1643                    unloadPrivatePackages(vol);
1644                }
1645            }
1646
1647            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1648                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1649                    updateExternalMediaStatus(true, false);
1650                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1651                    updateExternalMediaStatus(false, false);
1652                }
1653            }
1654        }
1655
1656        @Override
1657        public void onVolumeForgotten(String fsUuid) {
1658            if (TextUtils.isEmpty(fsUuid)) {
1659                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1660                return;
1661            }
1662
1663            // Remove any apps installed on the forgotten volume
1664            synchronized (mPackages) {
1665                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1666                for (PackageSetting ps : packages) {
1667                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1668                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1669                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1670                }
1671
1672                mSettings.onVolumeForgotten(fsUuid);
1673                mSettings.writeLPr();
1674            }
1675        }
1676    };
1677
1678    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1679            String[] grantedPermissions) {
1680        if (userId >= UserHandle.USER_OWNER) {
1681            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1682        } else if (userId == UserHandle.USER_ALL) {
1683            final int[] userIds;
1684            synchronized (mPackages) {
1685                userIds = UserManagerService.getInstance().getUserIds();
1686            }
1687            for (int someUserId : userIds) {
1688                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1689            }
1690        }
1691
1692        // We could have touched GID membership, so flush out packages.list
1693        synchronized (mPackages) {
1694            mSettings.writePackageListLPr();
1695        }
1696    }
1697
1698    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1699            String[] grantedPermissions) {
1700        SettingBase sb = (SettingBase) pkg.mExtras;
1701        if (sb == null) {
1702            return;
1703        }
1704
1705        PermissionsState permissionsState = sb.getPermissionsState();
1706
1707        for (String permission : pkg.requestedPermissions) {
1708            BasePermission bp = mSettings.mPermissions.get(permission);
1709            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1710                    || ArrayUtils.contains(grantedPermissions, permission))) {
1711                permissionsState.grantRuntimePermission(bp, userId);
1712            }
1713        }
1714    }
1715
1716    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1717        Bundle extras = null;
1718        switch (res.returnCode) {
1719            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1720                extras = new Bundle();
1721                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1722                        res.origPermission);
1723                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1724                        res.origPackage);
1725                break;
1726            }
1727            case PackageManager.INSTALL_SUCCEEDED: {
1728                extras = new Bundle();
1729                extras.putBoolean(Intent.EXTRA_REPLACING,
1730                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1731                break;
1732            }
1733        }
1734        return extras;
1735    }
1736
1737    void scheduleWriteSettingsLocked() {
1738        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1739            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1740        }
1741    }
1742
1743    void scheduleWritePackageRestrictionsLocked(int userId) {
1744        if (!sUserManager.exists(userId)) return;
1745        mDirtyUsers.add(userId);
1746        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1747            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1748        }
1749    }
1750
1751    public static PackageManagerService main(Context context, Installer installer,
1752            boolean factoryTest, boolean onlyCore) {
1753        PackageManagerService m = new PackageManagerService(context, installer,
1754                factoryTest, onlyCore);
1755        ServiceManager.addService("package", m);
1756        return m;
1757    }
1758
1759    static String[] splitString(String str, char sep) {
1760        int count = 1;
1761        int i = 0;
1762        while ((i=str.indexOf(sep, i)) >= 0) {
1763            count++;
1764            i++;
1765        }
1766
1767        String[] res = new String[count];
1768        i=0;
1769        count = 0;
1770        int lastI=0;
1771        while ((i=str.indexOf(sep, i)) >= 0) {
1772            res[count] = str.substring(lastI, i);
1773            count++;
1774            i++;
1775            lastI = i;
1776        }
1777        res[count] = str.substring(lastI, str.length());
1778        return res;
1779    }
1780
1781    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1782        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1783                Context.DISPLAY_SERVICE);
1784        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1785    }
1786
1787    public PackageManagerService(Context context, Installer installer,
1788            boolean factoryTest, boolean onlyCore) {
1789        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1790                SystemClock.uptimeMillis());
1791
1792        if (mSdkVersion <= 0) {
1793            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1794        }
1795
1796        mContext = context;
1797        mFactoryTest = factoryTest;
1798        mOnlyCore = onlyCore;
1799        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1800        mMetrics = new DisplayMetrics();
1801        mSettings = new Settings(mPackages);
1802        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1811                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1812        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1813                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1814
1815        // TODO: add a property to control this?
1816        long dexOptLRUThresholdInMinutes;
1817        if (mLazyDexOpt) {
1818            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1819        } else {
1820            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1821        }
1822        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1823
1824        String separateProcesses = SystemProperties.get("debug.separate_processes");
1825        if (separateProcesses != null && separateProcesses.length() > 0) {
1826            if ("*".equals(separateProcesses)) {
1827                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1828                mSeparateProcesses = null;
1829                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1830            } else {
1831                mDefParseFlags = 0;
1832                mSeparateProcesses = separateProcesses.split(",");
1833                Slog.w(TAG, "Running with debug.separate_processes: "
1834                        + separateProcesses);
1835            }
1836        } else {
1837            mDefParseFlags = 0;
1838            mSeparateProcesses = null;
1839        }
1840
1841        mInstaller = installer;
1842        mPackageDexOptimizer = new PackageDexOptimizer(this);
1843        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1844
1845        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1846                FgThread.get().getLooper());
1847
1848        getDefaultDisplayMetrics(context, mMetrics);
1849
1850        SystemConfig systemConfig = SystemConfig.getInstance();
1851        mGlobalGids = systemConfig.getGlobalGids();
1852        mSystemPermissions = systemConfig.getSystemPermissions();
1853        mAvailableFeatures = systemConfig.getAvailableFeatures();
1854
1855        synchronized (mInstallLock) {
1856        // writer
1857        synchronized (mPackages) {
1858            mHandlerThread = new ServiceThread(TAG,
1859                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1860            mHandlerThread.start();
1861            mHandler = new PackageHandler(mHandlerThread.getLooper());
1862            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1863
1864            File dataDir = Environment.getDataDirectory();
1865            mAppDataDir = new File(dataDir, "data");
1866            mAppInstallDir = new File(dataDir, "app");
1867            mAppLib32InstallDir = new File(dataDir, "app-lib");
1868            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1869            mUserAppDataDir = new File(dataDir, "user");
1870            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1871
1872            sUserManager = new UserManagerService(context, this,
1873                    mInstallLock, mPackages);
1874
1875            // Propagate permission configuration in to package manager.
1876            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1877                    = systemConfig.getPermissions();
1878            for (int i=0; i<permConfig.size(); i++) {
1879                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1880                BasePermission bp = mSettings.mPermissions.get(perm.name);
1881                if (bp == null) {
1882                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1883                    mSettings.mPermissions.put(perm.name, bp);
1884                }
1885                if (perm.gids != null) {
1886                    bp.setGids(perm.gids, perm.perUser);
1887                }
1888            }
1889
1890            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1891            for (int i=0; i<libConfig.size(); i++) {
1892                mSharedLibraries.put(libConfig.keyAt(i),
1893                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1894            }
1895
1896            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1897
1898            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1899                    mSdkVersion, mOnlyCore);
1900
1901            String customResolverActivity = Resources.getSystem().getString(
1902                    R.string.config_customResolverActivity);
1903            if (TextUtils.isEmpty(customResolverActivity)) {
1904                customResolverActivity = null;
1905            } else {
1906                mCustomResolverComponentName = ComponentName.unflattenFromString(
1907                        customResolverActivity);
1908            }
1909
1910            long startTime = SystemClock.uptimeMillis();
1911
1912            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1913                    startTime);
1914
1915            // Set flag to monitor and not change apk file paths when
1916            // scanning install directories.
1917            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1918
1919            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1920
1921            /**
1922             * Add everything in the in the boot class path to the
1923             * list of process files because dexopt will have been run
1924             * if necessary during zygote startup.
1925             */
1926            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1927            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1928
1929            if (bootClassPath != null) {
1930                String[] bootClassPathElements = splitString(bootClassPath, ':');
1931                for (String element : bootClassPathElements) {
1932                    alreadyDexOpted.add(element);
1933                }
1934            } else {
1935                Slog.w(TAG, "No BOOTCLASSPATH found!");
1936            }
1937
1938            if (systemServerClassPath != null) {
1939                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1940                for (String element : systemServerClassPathElements) {
1941                    alreadyDexOpted.add(element);
1942                }
1943            } else {
1944                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1945            }
1946
1947            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1948            final String[] dexCodeInstructionSets =
1949                    getDexCodeInstructionSets(
1950                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1951
1952            /**
1953             * Ensure all external libraries have had dexopt run on them.
1954             */
1955            if (mSharedLibraries.size() > 0) {
1956                // NOTE: For now, we're compiling these system "shared libraries"
1957                // (and framework jars) into all available architectures. It's possible
1958                // to compile them only when we come across an app that uses them (there's
1959                // already logic for that in scanPackageLI) but that adds some complexity.
1960                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1961                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1962                        final String lib = libEntry.path;
1963                        if (lib == null) {
1964                            continue;
1965                        }
1966
1967                        try {
1968                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1969                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1970                                alreadyDexOpted.add(lib);
1971                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1972                            }
1973                        } catch (FileNotFoundException e) {
1974                            Slog.w(TAG, "Library not found: " + lib);
1975                        } catch (IOException e) {
1976                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1977                                    + e.getMessage());
1978                        }
1979                    }
1980                }
1981            }
1982
1983            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1984
1985            // Gross hack for now: we know this file doesn't contain any
1986            // code, so don't dexopt it to avoid the resulting log spew.
1987            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1988
1989            // Gross hack for now: we know this file is only part of
1990            // the boot class path for art, so don't dexopt it to
1991            // avoid the resulting log spew.
1992            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1993
1994            /**
1995             * There are a number of commands implemented in Java, which
1996             * we currently need to do the dexopt on so that they can be
1997             * run from a non-root shell.
1998             */
1999            String[] frameworkFiles = frameworkDir.list();
2000            if (frameworkFiles != null) {
2001                // TODO: We could compile these only for the most preferred ABI. We should
2002                // first double check that the dex files for these commands are not referenced
2003                // by other system apps.
2004                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2005                    for (int i=0; i<frameworkFiles.length; i++) {
2006                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2007                        String path = libPath.getPath();
2008                        // Skip the file if we already did it.
2009                        if (alreadyDexOpted.contains(path)) {
2010                            continue;
2011                        }
2012                        // Skip the file if it is not a type we want to dexopt.
2013                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2014                            continue;
2015                        }
2016                        try {
2017                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2018                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2019                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2020                            }
2021                        } catch (FileNotFoundException e) {
2022                            Slog.w(TAG, "Jar not found: " + path);
2023                        } catch (IOException e) {
2024                            Slog.w(TAG, "Exception reading jar: " + path, e);
2025                        }
2026                    }
2027                }
2028            }
2029
2030            // Collect vendor overlay packages.
2031            // (Do this before scanning any apps.)
2032            // For security and version matching reason, only consider
2033            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2034            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2035            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2037
2038            // Find base frameworks (resource packages without code).
2039            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR
2041                    | PackageParser.PARSE_IS_PRIVILEGED,
2042                    scanFlags | SCAN_NO_DEX, 0);
2043
2044            // Collected privileged system packages.
2045            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2046            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2047                    | PackageParser.PARSE_IS_SYSTEM_DIR
2048                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2049
2050            // Collect ordinary system packages.
2051            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2052            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2053                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2054
2055            // Collect all vendor packages.
2056            File vendorAppDir = new File("/vendor/app");
2057            try {
2058                vendorAppDir = vendorAppDir.getCanonicalFile();
2059            } catch (IOException e) {
2060                // failed to look up canonical path, continue with original one
2061            }
2062            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2063                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2064
2065            // Collect all OEM packages.
2066            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2067            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2069
2070            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2071            mInstaller.moveFiles();
2072
2073            // Prune any system packages that no longer exist.
2074            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2075            if (!mOnlyCore) {
2076                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2077                while (psit.hasNext()) {
2078                    PackageSetting ps = psit.next();
2079
2080                    /*
2081                     * If this is not a system app, it can't be a
2082                     * disable system app.
2083                     */
2084                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2085                        continue;
2086                    }
2087
2088                    /*
2089                     * If the package is scanned, it's not erased.
2090                     */
2091                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2092                    if (scannedPkg != null) {
2093                        /*
2094                         * If the system app is both scanned and in the
2095                         * disabled packages list, then it must have been
2096                         * added via OTA. Remove it from the currently
2097                         * scanned package so the previously user-installed
2098                         * application can be scanned.
2099                         */
2100                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2102                                    + ps.name + "; removing system app.  Last known codePath="
2103                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2104                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2105                                    + scannedPkg.mVersionCode);
2106                            removePackageLI(ps, true);
2107                            mExpectingBetter.put(ps.name, ps.codePath);
2108                        }
2109
2110                        continue;
2111                    }
2112
2113                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2114                        psit.remove();
2115                        logCriticalInfo(Log.WARN, "System package " + ps.name
2116                                + " no longer exists; wiping its data");
2117                        removeDataDirsLI(null, ps.name);
2118                    } else {
2119                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2120                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2121                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2122                        }
2123                    }
2124                }
2125            }
2126
2127            //look for any incomplete package installations
2128            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2129            //clean up list
2130            for(int i = 0; i < deletePkgsList.size(); i++) {
2131                //clean up here
2132                cleanupInstallFailedPackage(deletePkgsList.get(i));
2133            }
2134            //delete tmp files
2135            deleteTempPackageFiles();
2136
2137            // Remove any shared userIDs that have no associated packages
2138            mSettings.pruneSharedUsersLPw();
2139
2140            if (!mOnlyCore) {
2141                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2142                        SystemClock.uptimeMillis());
2143                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2144
2145                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2146                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2147
2148                /**
2149                 * Remove disable package settings for any updated system
2150                 * apps that were removed via an OTA. If they're not a
2151                 * previously-updated app, remove them completely.
2152                 * Otherwise, just revoke their system-level permissions.
2153                 */
2154                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2155                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2156                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2157
2158                    String msg;
2159                    if (deletedPkg == null) {
2160                        msg = "Updated system package " + deletedAppName
2161                                + " no longer exists; wiping its data";
2162                        removeDataDirsLI(null, deletedAppName);
2163                    } else {
2164                        msg = "Updated system app + " + deletedAppName
2165                                + " no longer present; removing system privileges for "
2166                                + deletedAppName;
2167
2168                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2169
2170                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2171                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2172                    }
2173                    logCriticalInfo(Log.WARN, msg);
2174                }
2175
2176                /**
2177                 * Make sure all system apps that we expected to appear on
2178                 * the userdata partition actually showed up. If they never
2179                 * appeared, crawl back and revive the system version.
2180                 */
2181                for (int i = 0; i < mExpectingBetter.size(); i++) {
2182                    final String packageName = mExpectingBetter.keyAt(i);
2183                    if (!mPackages.containsKey(packageName)) {
2184                        final File scanFile = mExpectingBetter.valueAt(i);
2185
2186                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2187                                + " but never showed up; reverting to system");
2188
2189                        final int reparseFlags;
2190                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2191                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2192                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2193                                    | PackageParser.PARSE_IS_PRIVILEGED;
2194                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2195                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2196                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2197                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2198                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2199                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2200                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2201                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2202                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2203                        } else {
2204                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2205                            continue;
2206                        }
2207
2208                        mSettings.enableSystemPackageLPw(packageName);
2209
2210                        try {
2211                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2212                        } catch (PackageManagerException e) {
2213                            Slog.e(TAG, "Failed to parse original system package: "
2214                                    + e.getMessage());
2215                        }
2216                    }
2217                }
2218            }
2219            mExpectingBetter.clear();
2220
2221            // Now that we know all of the shared libraries, update all clients to have
2222            // the correct library paths.
2223            updateAllSharedLibrariesLPw();
2224
2225            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2226                // NOTE: We ignore potential failures here during a system scan (like
2227                // the rest of the commands above) because there's precious little we
2228                // can do about it. A settings error is reported, though.
2229                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2230                        false /* force dexopt */, false /* defer dexopt */);
2231            }
2232
2233            // Now that we know all the packages we are keeping,
2234            // read and update their last usage times.
2235            mPackageUsage.readLP();
2236
2237            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2238                    SystemClock.uptimeMillis());
2239            Slog.i(TAG, "Time to scan packages: "
2240                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2241                    + " seconds");
2242
2243            // If the platform SDK has changed since the last time we booted,
2244            // we need to re-grant app permission to catch any new ones that
2245            // appear.  This is really a hack, and means that apps can in some
2246            // cases get permissions that the user didn't initially explicitly
2247            // allow...  it would be nice to have some better way to handle
2248            // this situation.
2249            final VersionInfo ver = mSettings.getInternalVersion();
2250
2251            int updateFlags = UPDATE_PERMISSIONS_ALL;
2252            if (ver.sdkVersion != mSdkVersion) {
2253                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2254                        + mSdkVersion + "; regranting permissions for internal storage");
2255                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2256            }
2257            updatePermissionsLPw(null, null, updateFlags);
2258            ver.sdkVersion = mSdkVersion;
2259
2260            // If this is the first boot, and it is a normal boot, then
2261            // we need to initialize the default preferred apps.
2262            if (!mRestoredSettings && !onlyCore) {
2263                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2264                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2265                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2266            }
2267
2268            // If this is first boot after an OTA, and a normal boot, then
2269            // we need to clear code cache directories.
2270            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2271            if (mIsUpgrade && !onlyCore) {
2272                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2273                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2274                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2275                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2276                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2277                    }
2278                }
2279                ver.fingerprint = Build.FINGERPRINT;
2280            }
2281
2282            checkDefaultBrowser();
2283
2284            // All the changes are done during package scanning.
2285            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2286
2287            // can downgrade to reader
2288            mSettings.writeLPr();
2289
2290            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2291                    SystemClock.uptimeMillis());
2292
2293            mRequiredVerifierPackage = getRequiredVerifierLPr();
2294            mRequiredInstallerPackage = getRequiredInstallerLPr();
2295
2296            mInstallerService = new PackageInstallerService(context, this);
2297
2298            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2299            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2300                    mIntentFilterVerifierComponent);
2301
2302        } // synchronized (mPackages)
2303        } // synchronized (mInstallLock)
2304
2305        // Now after opening every single application zip, make sure they
2306        // are all flushed.  Not really needed, but keeps things nice and
2307        // tidy.
2308        Runtime.getRuntime().gc();
2309
2310        // Expose private service for system components to use.
2311        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2312    }
2313
2314    @Override
2315    public boolean isFirstBoot() {
2316        return !mRestoredSettings;
2317    }
2318
2319    @Override
2320    public boolean isOnlyCoreApps() {
2321        return mOnlyCore;
2322    }
2323
2324    @Override
2325    public boolean isUpgrade() {
2326        return mIsUpgrade;
2327    }
2328
2329    private String getRequiredVerifierLPr() {
2330        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2331        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2332                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2333
2334        String requiredVerifier = null;
2335
2336        final int N = receivers.size();
2337        for (int i = 0; i < N; i++) {
2338            final ResolveInfo info = receivers.get(i);
2339
2340            if (info.activityInfo == null) {
2341                continue;
2342            }
2343
2344            final String packageName = info.activityInfo.packageName;
2345
2346            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2347                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2348                continue;
2349            }
2350
2351            if (requiredVerifier != null) {
2352                throw new RuntimeException("There can be only one required verifier");
2353            }
2354
2355            requiredVerifier = packageName;
2356        }
2357
2358        return requiredVerifier;
2359    }
2360
2361    private String getRequiredInstallerLPr() {
2362        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2363        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2364        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2365
2366        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2367                PACKAGE_MIME_TYPE, 0, 0);
2368
2369        String requiredInstaller = null;
2370
2371        final int N = installers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = installers.get(i);
2374            final String packageName = info.activityInfo.packageName;
2375
2376            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2377                continue;
2378            }
2379
2380            if (requiredInstaller != null) {
2381                throw new RuntimeException("There must be one required installer");
2382            }
2383
2384            requiredInstaller = packageName;
2385        }
2386
2387        if (requiredInstaller == null) {
2388            throw new RuntimeException("There must be one required installer");
2389        }
2390
2391        return requiredInstaller;
2392    }
2393
2394    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2395        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2396        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2397                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2398
2399        ComponentName verifierComponentName = null;
2400
2401        int priority = -1000;
2402        final int N = receivers.size();
2403        for (int i = 0; i < N; i++) {
2404            final ResolveInfo info = receivers.get(i);
2405
2406            if (info.activityInfo == null) {
2407                continue;
2408            }
2409
2410            final String packageName = info.activityInfo.packageName;
2411
2412            final PackageSetting ps = mSettings.mPackages.get(packageName);
2413            if (ps == null) {
2414                continue;
2415            }
2416
2417            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2418                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2419                continue;
2420            }
2421
2422            // Select the IntentFilterVerifier with the highest priority
2423            if (priority < info.priority) {
2424                priority = info.priority;
2425                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2426                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2427                        + verifierComponentName + " with priority: " + info.priority);
2428            }
2429        }
2430
2431        return verifierComponentName;
2432    }
2433
2434    private void primeDomainVerificationsLPw(int userId) {
2435        if (DEBUG_DOMAIN_VERIFICATION) {
2436            Slog.d(TAG, "Priming domain verifications in user " + userId);
2437        }
2438
2439        SystemConfig systemConfig = SystemConfig.getInstance();
2440        ArraySet<String> packages = systemConfig.getLinkedApps();
2441        ArraySet<String> domains = new ArraySet<String>();
2442
2443        for (String packageName : packages) {
2444            PackageParser.Package pkg = mPackages.get(packageName);
2445            if (pkg != null) {
2446                if (!pkg.isSystemApp()) {
2447                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2448                    continue;
2449                }
2450
2451                domains.clear();
2452                for (PackageParser.Activity a : pkg.activities) {
2453                    for (ActivityIntentInfo filter : a.intents) {
2454                        if (hasValidDomains(filter)) {
2455                            domains.addAll(filter.getHostsList());
2456                        }
2457                    }
2458                }
2459
2460                if (domains.size() > 0) {
2461                    if (DEBUG_DOMAIN_VERIFICATION) {
2462                        Slog.v(TAG, "      + " + packageName);
2463                    }
2464                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2465                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2466                    // and then 'always' in the per-user state actually used for intent resolution.
2467                    final IntentFilterVerificationInfo ivi;
2468                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2469                            new ArrayList<String>(domains));
2470                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2471                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2472                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2473                } else {
2474                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2475                            + "' does not handle web links");
2476                }
2477            } else {
2478                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2479            }
2480        }
2481
2482        scheduleWritePackageRestrictionsLocked(userId);
2483        scheduleWriteSettingsLocked();
2484    }
2485
2486    private void applyFactoryDefaultBrowserLPw(int userId) {
2487        // The default browser app's package name is stored in a string resource,
2488        // with a product-specific overlay used for vendor customization.
2489        String browserPkg = mContext.getResources().getString(
2490                com.android.internal.R.string.default_browser);
2491        if (!TextUtils.isEmpty(browserPkg)) {
2492            // non-empty string => required to be a known package
2493            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2494            if (ps == null) {
2495                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2496                browserPkg = null;
2497            } else {
2498                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499            }
2500        }
2501
2502        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2503        // default.  If there's more than one, just leave everything alone.
2504        if (browserPkg == null) {
2505            calculateDefaultBrowserLPw(userId);
2506        }
2507    }
2508
2509    private void calculateDefaultBrowserLPw(int userId) {
2510        List<String> allBrowsers = resolveAllBrowserApps(userId);
2511        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2512        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2513    }
2514
2515    private List<String> resolveAllBrowserApps(int userId) {
2516        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2517        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2518                PackageManager.MATCH_ALL, userId);
2519
2520        final int count = list.size();
2521        List<String> result = new ArrayList<String>(count);
2522        for (int i=0; i<count; i++) {
2523            ResolveInfo info = list.get(i);
2524            if (info.activityInfo == null
2525                    || !info.handleAllWebDataURI
2526                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2527                    || result.contains(info.activityInfo.packageName)) {
2528                continue;
2529            }
2530            result.add(info.activityInfo.packageName);
2531        }
2532
2533        return result;
2534    }
2535
2536    private boolean packageIsBrowser(String packageName, int userId) {
2537        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2538                PackageManager.MATCH_ALL, userId);
2539        final int N = list.size();
2540        for (int i = 0; i < N; i++) {
2541            ResolveInfo info = list.get(i);
2542            if (packageName.equals(info.activityInfo.packageName)) {
2543                return true;
2544            }
2545        }
2546        return false;
2547    }
2548
2549    private void checkDefaultBrowser() {
2550        final int myUserId = UserHandle.myUserId();
2551        final String packageName = getDefaultBrowserPackageName(myUserId);
2552        if (packageName != null) {
2553            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2554            if (info == null) {
2555                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2556                synchronized (mPackages) {
2557                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2558                }
2559            }
2560        }
2561    }
2562
2563    @Override
2564    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2565            throws RemoteException {
2566        try {
2567            return super.onTransact(code, data, reply, flags);
2568        } catch (RuntimeException e) {
2569            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2570                Slog.wtf(TAG, "Package Manager Crash", e);
2571            }
2572            throw e;
2573        }
2574    }
2575
2576    void cleanupInstallFailedPackage(PackageSetting ps) {
2577        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2578
2579        removeDataDirsLI(ps.volumeUuid, ps.name);
2580        if (ps.codePath != null) {
2581            if (ps.codePath.isDirectory()) {
2582                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2583            } else {
2584                ps.codePath.delete();
2585            }
2586        }
2587        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2588            if (ps.resourcePath.isDirectory()) {
2589                FileUtils.deleteContents(ps.resourcePath);
2590            }
2591            ps.resourcePath.delete();
2592        }
2593        mSettings.removePackageLPw(ps.name);
2594    }
2595
2596    static int[] appendInts(int[] cur, int[] add) {
2597        if (add == null) return cur;
2598        if (cur == null) return add;
2599        final int N = add.length;
2600        for (int i=0; i<N; i++) {
2601            cur = appendInt(cur, add[i]);
2602        }
2603        return cur;
2604    }
2605
2606    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2607        if (!sUserManager.exists(userId)) return null;
2608        final PackageSetting ps = (PackageSetting) p.mExtras;
2609        if (ps == null) {
2610            return null;
2611        }
2612
2613        final PermissionsState permissionsState = ps.getPermissionsState();
2614
2615        final int[] gids = permissionsState.computeGids(userId);
2616        final Set<String> permissions = permissionsState.getPermissions(userId);
2617        final PackageUserState state = ps.readUserState(userId);
2618
2619        return PackageParser.generatePackageInfo(p, gids, flags,
2620                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2621    }
2622
2623    @Override
2624    public boolean isPackageFrozen(String packageName) {
2625        synchronized (mPackages) {
2626            final PackageSetting ps = mSettings.mPackages.get(packageName);
2627            if (ps != null) {
2628                return ps.frozen;
2629            }
2630        }
2631        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2632        return true;
2633    }
2634
2635    @Override
2636    public boolean isPackageAvailable(String packageName, int userId) {
2637        if (!sUserManager.exists(userId)) return false;
2638        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2639        synchronized (mPackages) {
2640            PackageParser.Package p = mPackages.get(packageName);
2641            if (p != null) {
2642                final PackageSetting ps = (PackageSetting) p.mExtras;
2643                if (ps != null) {
2644                    final PackageUserState state = ps.readUserState(userId);
2645                    if (state != null) {
2646                        return PackageParser.isAvailable(state);
2647                    }
2648                }
2649            }
2650        }
2651        return false;
2652    }
2653
2654    @Override
2655    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2656        if (!sUserManager.exists(userId)) return null;
2657        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2658        // reader
2659        synchronized (mPackages) {
2660            PackageParser.Package p = mPackages.get(packageName);
2661            if (DEBUG_PACKAGE_INFO)
2662                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2663            if (p != null) {
2664                return generatePackageInfo(p, flags, userId);
2665            }
2666            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2667                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2668            }
2669        }
2670        return null;
2671    }
2672
2673    @Override
2674    public String[] currentToCanonicalPackageNames(String[] names) {
2675        String[] out = new String[names.length];
2676        // reader
2677        synchronized (mPackages) {
2678            for (int i=names.length-1; i>=0; i--) {
2679                PackageSetting ps = mSettings.mPackages.get(names[i]);
2680                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2681            }
2682        }
2683        return out;
2684    }
2685
2686    @Override
2687    public String[] canonicalToCurrentPackageNames(String[] names) {
2688        String[] out = new String[names.length];
2689        // reader
2690        synchronized (mPackages) {
2691            for (int i=names.length-1; i>=0; i--) {
2692                String cur = mSettings.mRenamedPackages.get(names[i]);
2693                out[i] = cur != null ? cur : names[i];
2694            }
2695        }
2696        return out;
2697    }
2698
2699    @Override
2700    public int getPackageUid(String packageName, int userId) {
2701        if (!sUserManager.exists(userId)) return -1;
2702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2703
2704        // reader
2705        synchronized (mPackages) {
2706            PackageParser.Package p = mPackages.get(packageName);
2707            if(p != null) {
2708                return UserHandle.getUid(userId, p.applicationInfo.uid);
2709            }
2710            PackageSetting ps = mSettings.mPackages.get(packageName);
2711            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2712                return -1;
2713            }
2714            p = ps.pkg;
2715            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2716        }
2717    }
2718
2719    @Override
2720    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2721        if (!sUserManager.exists(userId)) {
2722            return null;
2723        }
2724
2725        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2726                "getPackageGids");
2727
2728        // reader
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (DEBUG_PACKAGE_INFO) {
2732                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2733            }
2734            if (p != null) {
2735                PackageSetting ps = (PackageSetting) p.mExtras;
2736                return ps.getPermissionsState().computeGids(userId);
2737            }
2738        }
2739
2740        return null;
2741    }
2742
2743    static PermissionInfo generatePermissionInfo(
2744            BasePermission bp, int flags) {
2745        if (bp.perm != null) {
2746            return PackageParser.generatePermissionInfo(bp.perm, flags);
2747        }
2748        PermissionInfo pi = new PermissionInfo();
2749        pi.name = bp.name;
2750        pi.packageName = bp.sourcePackage;
2751        pi.nonLocalizedLabel = bp.name;
2752        pi.protectionLevel = bp.protectionLevel;
2753        return pi;
2754    }
2755
2756    @Override
2757    public PermissionInfo getPermissionInfo(String name, int flags) {
2758        // reader
2759        synchronized (mPackages) {
2760            final BasePermission p = mSettings.mPermissions.get(name);
2761            if (p != null) {
2762                return generatePermissionInfo(p, flags);
2763            }
2764            return null;
2765        }
2766    }
2767
2768    @Override
2769    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2770        // reader
2771        synchronized (mPackages) {
2772            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2773            for (BasePermission p : mSettings.mPermissions.values()) {
2774                if (group == null) {
2775                    if (p.perm == null || p.perm.info.group == null) {
2776                        out.add(generatePermissionInfo(p, flags));
2777                    }
2778                } else {
2779                    if (p.perm != null && group.equals(p.perm.info.group)) {
2780                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2781                    }
2782                }
2783            }
2784
2785            if (out.size() > 0) {
2786                return out;
2787            }
2788            return mPermissionGroups.containsKey(group) ? out : null;
2789        }
2790    }
2791
2792    @Override
2793    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2794        // reader
2795        synchronized (mPackages) {
2796            return PackageParser.generatePermissionGroupInfo(
2797                    mPermissionGroups.get(name), flags);
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            final int N = mPermissionGroups.size();
2806            ArrayList<PermissionGroupInfo> out
2807                    = new ArrayList<PermissionGroupInfo>(N);
2808            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2809                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2810            }
2811            return out;
2812        }
2813    }
2814
2815    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2816            int userId) {
2817        if (!sUserManager.exists(userId)) return null;
2818        PackageSetting ps = mSettings.mPackages.get(packageName);
2819        if (ps != null) {
2820            if (ps.pkg == null) {
2821                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2822                        flags, userId);
2823                if (pInfo != null) {
2824                    return pInfo.applicationInfo;
2825                }
2826                return null;
2827            }
2828            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2829                    ps.readUserState(userId), userId);
2830        }
2831        return null;
2832    }
2833
2834    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2835            int userId) {
2836        if (!sUserManager.exists(userId)) return null;
2837        PackageSetting ps = mSettings.mPackages.get(packageName);
2838        if (ps != null) {
2839            PackageParser.Package pkg = ps.pkg;
2840            if (pkg == null) {
2841                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2842                    return null;
2843                }
2844                // Only data remains, so we aren't worried about code paths
2845                pkg = new PackageParser.Package(packageName);
2846                pkg.applicationInfo.packageName = packageName;
2847                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2848                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2849                pkg.applicationInfo.dataDir = Environment
2850                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2851                        .getAbsolutePath();
2852                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2853                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2854            }
2855            return generatePackageInfo(pkg, flags, userId);
2856        }
2857        return null;
2858    }
2859
2860    @Override
2861    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2862        if (!sUserManager.exists(userId)) return null;
2863        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2864        // writer
2865        synchronized (mPackages) {
2866            PackageParser.Package p = mPackages.get(packageName);
2867            if (DEBUG_PACKAGE_INFO) Log.v(
2868                    TAG, "getApplicationInfo " + packageName
2869                    + ": " + p);
2870            if (p != null) {
2871                PackageSetting ps = mSettings.mPackages.get(packageName);
2872                if (ps == null) return null;
2873                // Note: isEnabledLP() does not apply here - always return info
2874                return PackageParser.generateApplicationInfo(
2875                        p, flags, ps.readUserState(userId), userId);
2876            }
2877            if ("android".equals(packageName)||"system".equals(packageName)) {
2878                return mAndroidApplication;
2879            }
2880            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2881                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2889            final IPackageDataObserver observer) {
2890        mContext.enforceCallingOrSelfPermission(
2891                android.Manifest.permission.CLEAR_APP_CACHE, null);
2892        // Queue up an async operation since clearing cache may take a little while.
2893        mHandler.post(new Runnable() {
2894            public void run() {
2895                mHandler.removeCallbacks(this);
2896                int retCode = -1;
2897                synchronized (mInstallLock) {
2898                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2899                    if (retCode < 0) {
2900                        Slog.w(TAG, "Couldn't clear application caches");
2901                    }
2902                }
2903                if (observer != null) {
2904                    try {
2905                        observer.onRemoveCompleted(null, (retCode >= 0));
2906                    } catch (RemoteException e) {
2907                        Slog.w(TAG, "RemoveException when invoking call back");
2908                    }
2909                }
2910            }
2911        });
2912    }
2913
2914    @Override
2915    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2916            final IntentSender pi) {
2917        mContext.enforceCallingOrSelfPermission(
2918                android.Manifest.permission.CLEAR_APP_CACHE, null);
2919        // Queue up an async operation since clearing cache may take a little while.
2920        mHandler.post(new Runnable() {
2921            public void run() {
2922                mHandler.removeCallbacks(this);
2923                int retCode = -1;
2924                synchronized (mInstallLock) {
2925                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2926                    if (retCode < 0) {
2927                        Slog.w(TAG, "Couldn't clear application caches");
2928                    }
2929                }
2930                if(pi != null) {
2931                    try {
2932                        // Callback via pending intent
2933                        int code = (retCode >= 0) ? 1 : 0;
2934                        pi.sendIntent(null, code, null,
2935                                null, null);
2936                    } catch (SendIntentException e1) {
2937                        Slog.i(TAG, "Failed to send pending intent");
2938                    }
2939                }
2940            }
2941        });
2942    }
2943
2944    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2945        synchronized (mInstallLock) {
2946            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2947                throw new IOException("Failed to free enough space");
2948            }
2949        }
2950    }
2951
2952    @Override
2953    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2954        if (!sUserManager.exists(userId)) return null;
2955        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2956        synchronized (mPackages) {
2957            PackageParser.Activity a = mActivities.mActivities.get(component);
2958
2959            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2960            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2961                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2962                if (ps == null) return null;
2963                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2964                        userId);
2965            }
2966            if (mResolveComponentName.equals(component)) {
2967                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2968                        new PackageUserState(), userId);
2969            }
2970        }
2971        return null;
2972    }
2973
2974    @Override
2975    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2976            String resolvedType) {
2977        synchronized (mPackages) {
2978            if (component.equals(mResolveComponentName)) {
2979                // The resolver supports EVERYTHING!
2980                return true;
2981            }
2982            PackageParser.Activity a = mActivities.mActivities.get(component);
2983            if (a == null) {
2984                return false;
2985            }
2986            for (int i=0; i<a.intents.size(); i++) {
2987                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2988                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2989                    return true;
2990                }
2991            }
2992            return false;
2993        }
2994    }
2995
2996    @Override
2997    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2998        if (!sUserManager.exists(userId)) return null;
2999        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3000        synchronized (mPackages) {
3001            PackageParser.Activity a = mReceivers.mActivities.get(component);
3002            if (DEBUG_PACKAGE_INFO) Log.v(
3003                TAG, "getReceiverInfo " + component + ": " + a);
3004            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3006                if (ps == null) return null;
3007                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3008                        userId);
3009            }
3010        }
3011        return null;
3012    }
3013
3014    @Override
3015    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3016        if (!sUserManager.exists(userId)) return null;
3017        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3018        synchronized (mPackages) {
3019            PackageParser.Service s = mServices.mServices.get(component);
3020            if (DEBUG_PACKAGE_INFO) Log.v(
3021                TAG, "getServiceInfo " + component + ": " + s);
3022            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3023                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3024                if (ps == null) return null;
3025                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3026                        userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3034        if (!sUserManager.exists(userId)) return null;
3035        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3036        synchronized (mPackages) {
3037            PackageParser.Provider p = mProviders.mProviders.get(component);
3038            if (DEBUG_PACKAGE_INFO) Log.v(
3039                TAG, "getProviderInfo " + component + ": " + p);
3040            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3041                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3042                if (ps == null) return null;
3043                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3044                        userId);
3045            }
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public String[] getSystemSharedLibraryNames() {
3052        Set<String> libSet;
3053        synchronized (mPackages) {
3054            libSet = mSharedLibraries.keySet();
3055            int size = libSet.size();
3056            if (size > 0) {
3057                String[] libs = new String[size];
3058                libSet.toArray(libs);
3059                return libs;
3060            }
3061        }
3062        return null;
3063    }
3064
3065    /**
3066     * @hide
3067     */
3068    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3069        synchronized (mPackages) {
3070            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3071            if (lib != null && lib.apk != null) {
3072                return mPackages.get(lib.apk);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public FeatureInfo[] getSystemAvailableFeatures() {
3080        Collection<FeatureInfo> featSet;
3081        synchronized (mPackages) {
3082            featSet = mAvailableFeatures.values();
3083            int size = featSet.size();
3084            if (size > 0) {
3085                FeatureInfo[] features = new FeatureInfo[size+1];
3086                featSet.toArray(features);
3087                FeatureInfo fi = new FeatureInfo();
3088                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3089                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3090                features[size] = fi;
3091                return features;
3092            }
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public boolean hasSystemFeature(String name) {
3099        synchronized (mPackages) {
3100            return mAvailableFeatures.containsKey(name);
3101        }
3102    }
3103
3104    private void checkValidCaller(int uid, int userId) {
3105        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3106            return;
3107
3108        throw new SecurityException("Caller uid=" + uid
3109                + " is not privileged to communicate with user=" + userId);
3110    }
3111
3112    @Override
3113    public int checkPermission(String permName, String pkgName, int userId) {
3114        if (!sUserManager.exists(userId)) {
3115            return PackageManager.PERMISSION_DENIED;
3116        }
3117
3118        synchronized (mPackages) {
3119            final PackageParser.Package p = mPackages.get(pkgName);
3120            if (p != null && p.mExtras != null) {
3121                final PackageSetting ps = (PackageSetting) p.mExtras;
3122                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3123                    return PackageManager.PERMISSION_GRANTED;
3124                }
3125            }
3126        }
3127
3128        return PackageManager.PERMISSION_DENIED;
3129    }
3130
3131    @Override
3132    public int checkUidPermission(String permName, int uid) {
3133        final int userId = UserHandle.getUserId(uid);
3134
3135        if (!sUserManager.exists(userId)) {
3136            return PackageManager.PERMISSION_DENIED;
3137        }
3138
3139        synchronized (mPackages) {
3140            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3141            if (obj != null) {
3142                final SettingBase ps = (SettingBase) obj;
3143                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3144                    return PackageManager.PERMISSION_GRANTED;
3145                }
3146            } else {
3147                ArraySet<String> perms = mSystemPermissions.get(uid);
3148                if (perms != null && perms.contains(permName)) {
3149                    return PackageManager.PERMISSION_GRANTED;
3150                }
3151            }
3152        }
3153
3154        return PackageManager.PERMISSION_DENIED;
3155    }
3156
3157    @Override
3158    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3159        if (UserHandle.getCallingUserId() != userId) {
3160            mContext.enforceCallingPermission(
3161                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3162                    "isPermissionRevokedByPolicy for user " + userId);
3163        }
3164
3165        if (checkPermission(permission, packageName, userId)
3166                == PackageManager.PERMISSION_GRANTED) {
3167            return false;
3168        }
3169
3170        final long identity = Binder.clearCallingIdentity();
3171        try {
3172            final int flags = getPermissionFlags(permission, packageName, userId);
3173            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3174        } finally {
3175            Binder.restoreCallingIdentity(identity);
3176        }
3177    }
3178
3179    /**
3180     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3181     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3182     * @param checkShell TODO(yamasani):
3183     * @param message the message to log on security exception
3184     */
3185    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3186            boolean checkShell, String message) {
3187        if (userId < 0) {
3188            throw new IllegalArgumentException("Invalid userId " + userId);
3189        }
3190        if (checkShell) {
3191            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3192        }
3193        if (userId == UserHandle.getUserId(callingUid)) return;
3194        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3195            if (requireFullPermission) {
3196                mContext.enforceCallingOrSelfPermission(
3197                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3198            } else {
3199                try {
3200                    mContext.enforceCallingOrSelfPermission(
3201                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3202                } catch (SecurityException se) {
3203                    mContext.enforceCallingOrSelfPermission(
3204                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3205                }
3206            }
3207        }
3208    }
3209
3210    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3211        if (callingUid == Process.SHELL_UID) {
3212            if (userHandle >= 0
3213                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3214                throw new SecurityException("Shell does not have permission to access user "
3215                        + userHandle);
3216            } else if (userHandle < 0) {
3217                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3218                        + Debug.getCallers(3));
3219            }
3220        }
3221    }
3222
3223    private BasePermission findPermissionTreeLP(String permName) {
3224        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3225            if (permName.startsWith(bp.name) &&
3226                    permName.length() > bp.name.length() &&
3227                    permName.charAt(bp.name.length()) == '.') {
3228                return bp;
3229            }
3230        }
3231        return null;
3232    }
3233
3234    private BasePermission checkPermissionTreeLP(String permName) {
3235        if (permName != null) {
3236            BasePermission bp = findPermissionTreeLP(permName);
3237            if (bp != null) {
3238                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3239                    return bp;
3240                }
3241                throw new SecurityException("Calling uid "
3242                        + Binder.getCallingUid()
3243                        + " is not allowed to add to permission tree "
3244                        + bp.name + " owned by uid " + bp.uid);
3245            }
3246        }
3247        throw new SecurityException("No permission tree found for " + permName);
3248    }
3249
3250    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3251        if (s1 == null) {
3252            return s2 == null;
3253        }
3254        if (s2 == null) {
3255            return false;
3256        }
3257        if (s1.getClass() != s2.getClass()) {
3258            return false;
3259        }
3260        return s1.equals(s2);
3261    }
3262
3263    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3264        if (pi1.icon != pi2.icon) return false;
3265        if (pi1.logo != pi2.logo) return false;
3266        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3267        if (!compareStrings(pi1.name, pi2.name)) return false;
3268        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3269        // We'll take care of setting this one.
3270        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3271        // These are not currently stored in settings.
3272        //if (!compareStrings(pi1.group, pi2.group)) return false;
3273        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3274        //if (pi1.labelRes != pi2.labelRes) return false;
3275        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3276        return true;
3277    }
3278
3279    int permissionInfoFootprint(PermissionInfo info) {
3280        int size = info.name.length();
3281        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3282        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3283        return size;
3284    }
3285
3286    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3287        int size = 0;
3288        for (BasePermission perm : mSettings.mPermissions.values()) {
3289            if (perm.uid == tree.uid) {
3290                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3291            }
3292        }
3293        return size;
3294    }
3295
3296    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3297        // We calculate the max size of permissions defined by this uid and throw
3298        // if that plus the size of 'info' would exceed our stated maximum.
3299        if (tree.uid != Process.SYSTEM_UID) {
3300            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3301            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3302                throw new SecurityException("Permission tree size cap exceeded");
3303            }
3304        }
3305    }
3306
3307    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3308        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3309            throw new SecurityException("Label must be specified in permission");
3310        }
3311        BasePermission tree = checkPermissionTreeLP(info.name);
3312        BasePermission bp = mSettings.mPermissions.get(info.name);
3313        boolean added = bp == null;
3314        boolean changed = true;
3315        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3316        if (added) {
3317            enforcePermissionCapLocked(info, tree);
3318            bp = new BasePermission(info.name, tree.sourcePackage,
3319                    BasePermission.TYPE_DYNAMIC);
3320        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3321            throw new SecurityException(
3322                    "Not allowed to modify non-dynamic permission "
3323                    + info.name);
3324        } else {
3325            if (bp.protectionLevel == fixedLevel
3326                    && bp.perm.owner.equals(tree.perm.owner)
3327                    && bp.uid == tree.uid
3328                    && comparePermissionInfos(bp.perm.info, info)) {
3329                changed = false;
3330            }
3331        }
3332        bp.protectionLevel = fixedLevel;
3333        info = new PermissionInfo(info);
3334        info.protectionLevel = fixedLevel;
3335        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3336        bp.perm.info.packageName = tree.perm.info.packageName;
3337        bp.uid = tree.uid;
3338        if (added) {
3339            mSettings.mPermissions.put(info.name, bp);
3340        }
3341        if (changed) {
3342            if (!async) {
3343                mSettings.writeLPr();
3344            } else {
3345                scheduleWriteSettingsLocked();
3346            }
3347        }
3348        return added;
3349    }
3350
3351    @Override
3352    public boolean addPermission(PermissionInfo info) {
3353        synchronized (mPackages) {
3354            return addPermissionLocked(info, false);
3355        }
3356    }
3357
3358    @Override
3359    public boolean addPermissionAsync(PermissionInfo info) {
3360        synchronized (mPackages) {
3361            return addPermissionLocked(info, true);
3362        }
3363    }
3364
3365    @Override
3366    public void removePermission(String name) {
3367        synchronized (mPackages) {
3368            checkPermissionTreeLP(name);
3369            BasePermission bp = mSettings.mPermissions.get(name);
3370            if (bp != null) {
3371                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3372                    throw new SecurityException(
3373                            "Not allowed to modify non-dynamic permission "
3374                            + name);
3375                }
3376                mSettings.mPermissions.remove(name);
3377                mSettings.writeLPr();
3378            }
3379        }
3380    }
3381
3382    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3383            BasePermission bp) {
3384        int index = pkg.requestedPermissions.indexOf(bp.name);
3385        if (index == -1) {
3386            throw new SecurityException("Package " + pkg.packageName
3387                    + " has not requested permission " + bp.name);
3388        }
3389        if (!bp.isRuntime()) {
3390            throw new SecurityException("Permission " + bp.name
3391                    + " is not a changeable permission type");
3392        }
3393    }
3394
3395    @Override
3396    public void grantRuntimePermission(String packageName, String name, final int userId) {
3397        if (!sUserManager.exists(userId)) {
3398            Log.e(TAG, "No such user:" + userId);
3399            return;
3400        }
3401
3402        mContext.enforceCallingOrSelfPermission(
3403                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3404                "grantRuntimePermission");
3405
3406        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3407                "grantRuntimePermission");
3408
3409        final int uid;
3410        final SettingBase sb;
3411
3412        synchronized (mPackages) {
3413            final PackageParser.Package pkg = mPackages.get(packageName);
3414            if (pkg == null) {
3415                throw new IllegalArgumentException("Unknown package: " + packageName);
3416            }
3417
3418            final BasePermission bp = mSettings.mPermissions.get(name);
3419            if (bp == null) {
3420                throw new IllegalArgumentException("Unknown permission: " + name);
3421            }
3422
3423            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3424
3425            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3426            sb = (SettingBase) pkg.mExtras;
3427            if (sb == null) {
3428                throw new IllegalArgumentException("Unknown package: " + packageName);
3429            }
3430
3431            final PermissionsState permissionsState = sb.getPermissionsState();
3432
3433            final int flags = permissionsState.getPermissionFlags(name, userId);
3434            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3435                throw new SecurityException("Cannot grant system fixed permission: "
3436                        + name + " for package: " + packageName);
3437            }
3438
3439            final int result = permissionsState.grantRuntimePermission(bp, userId);
3440            switch (result) {
3441                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3442                    return;
3443                }
3444
3445                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3446                    mHandler.post(new Runnable() {
3447                        @Override
3448                        public void run() {
3449                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3450                        }
3451                    });
3452                } break;
3453            }
3454
3455            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3456
3457            // Not critical if that is lost - app has to request again.
3458            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3459        }
3460
3461        // Only need to do this if user is initialized. Otherwise it's a new user
3462        // and there are no processes running as the user yet and there's no need
3463        // to make an expensive call to remount processes for the changed permissions.
3464        if (READ_EXTERNAL_STORAGE.equals(name)
3465                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3466            final long token = Binder.clearCallingIdentity();
3467            try {
3468                if (sUserManager.isInitialized(userId)) {
3469                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3470                            MountServiceInternal.class);
3471                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3472                }
3473            } finally {
3474                Binder.restoreCallingIdentity(token);
3475            }
3476        }
3477    }
3478
3479    @Override
3480    public void revokeRuntimePermission(String packageName, String name, int userId) {
3481        if (!sUserManager.exists(userId)) {
3482            Log.e(TAG, "No such user:" + userId);
3483            return;
3484        }
3485
3486        mContext.enforceCallingOrSelfPermission(
3487                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3488                "revokeRuntimePermission");
3489
3490        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3491                "revokeRuntimePermission");
3492
3493        final SettingBase sb;
3494
3495        synchronized (mPackages) {
3496            final PackageParser.Package pkg = mPackages.get(packageName);
3497            if (pkg == null) {
3498                throw new IllegalArgumentException("Unknown package: " + packageName);
3499            }
3500
3501            final BasePermission bp = mSettings.mPermissions.get(name);
3502            if (bp == null) {
3503                throw new IllegalArgumentException("Unknown permission: " + name);
3504            }
3505
3506            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3507
3508            sb = (SettingBase) pkg.mExtras;
3509            if (sb == null) {
3510                throw new IllegalArgumentException("Unknown package: " + packageName);
3511            }
3512
3513            final PermissionsState permissionsState = sb.getPermissionsState();
3514
3515            final int flags = permissionsState.getPermissionFlags(name, userId);
3516            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3517                throw new SecurityException("Cannot revoke system fixed permission: "
3518                        + name + " for package: " + packageName);
3519            }
3520
3521            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3522                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3523                return;
3524            }
3525
3526            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3527
3528            // Critical, after this call app should never have the permission.
3529            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3530        }
3531
3532        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3533    }
3534
3535    @Override
3536    public void resetRuntimePermissions() {
3537        mContext.enforceCallingOrSelfPermission(
3538                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3539                "revokeRuntimePermission");
3540
3541        int callingUid = Binder.getCallingUid();
3542        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3543            mContext.enforceCallingOrSelfPermission(
3544                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3545                    "resetRuntimePermissions");
3546        }
3547
3548        synchronized (mPackages) {
3549            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3550            for (int userId : UserManagerService.getInstance().getUserIds()) {
3551                final int packageCount = mPackages.size();
3552                for (int i = 0; i < packageCount; i++) {
3553                    PackageParser.Package pkg = mPackages.valueAt(i);
3554                    if (!(pkg.mExtras instanceof PackageSetting)) {
3555                        continue;
3556                    }
3557                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3558                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3559                }
3560            }
3561        }
3562    }
3563
3564    @Override
3565    public int getPermissionFlags(String name, String packageName, int userId) {
3566        if (!sUserManager.exists(userId)) {
3567            return 0;
3568        }
3569
3570        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3571
3572        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3573                "getPermissionFlags");
3574
3575        synchronized (mPackages) {
3576            final PackageParser.Package pkg = mPackages.get(packageName);
3577            if (pkg == null) {
3578                throw new IllegalArgumentException("Unknown package: " + packageName);
3579            }
3580
3581            final BasePermission bp = mSettings.mPermissions.get(name);
3582            if (bp == null) {
3583                throw new IllegalArgumentException("Unknown permission: " + name);
3584            }
3585
3586            SettingBase sb = (SettingBase) pkg.mExtras;
3587            if (sb == null) {
3588                throw new IllegalArgumentException("Unknown package: " + packageName);
3589            }
3590
3591            PermissionsState permissionsState = sb.getPermissionsState();
3592            return permissionsState.getPermissionFlags(name, userId);
3593        }
3594    }
3595
3596    @Override
3597    public void updatePermissionFlags(String name, String packageName, int flagMask,
3598            int flagValues, int userId) {
3599        if (!sUserManager.exists(userId)) {
3600            return;
3601        }
3602
3603        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3604
3605        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3606                "updatePermissionFlags");
3607
3608        // Only the system can change system fixed flags.
3609        if (getCallingUid() != Process.SYSTEM_UID) {
3610            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3612        }
3613
3614        synchronized (mPackages) {
3615            final PackageParser.Package pkg = mPackages.get(packageName);
3616            if (pkg == null) {
3617                throw new IllegalArgumentException("Unknown package: " + packageName);
3618            }
3619
3620            final BasePermission bp = mSettings.mPermissions.get(name);
3621            if (bp == null) {
3622                throw new IllegalArgumentException("Unknown permission: " + name);
3623            }
3624
3625            SettingBase sb = (SettingBase) pkg.mExtras;
3626            if (sb == null) {
3627                throw new IllegalArgumentException("Unknown package: " + packageName);
3628            }
3629
3630            PermissionsState permissionsState = sb.getPermissionsState();
3631
3632            // Only the package manager can change flags for system component permissions.
3633            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3634            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3635                return;
3636            }
3637
3638            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3639
3640            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3641                // Install and runtime permissions are stored in different places,
3642                // so figure out what permission changed and persist the change.
3643                if (permissionsState.getInstallPermissionState(name) != null) {
3644                    scheduleWriteSettingsLocked();
3645                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3646                        || hadState) {
3647                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3648                }
3649            }
3650        }
3651    }
3652
3653    /**
3654     * Update the permission flags for all packages and runtime permissions of a user in order
3655     * to allow device or profile owner to remove POLICY_FIXED.
3656     */
3657    @Override
3658    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3659        if (!sUserManager.exists(userId)) {
3660            return;
3661        }
3662
3663        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3664
3665        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3666                "updatePermissionFlagsForAllApps");
3667
3668        // Only the system can change system fixed flags.
3669        if (getCallingUid() != Process.SYSTEM_UID) {
3670            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3671            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3672        }
3673
3674        synchronized (mPackages) {
3675            boolean changed = false;
3676            final int packageCount = mPackages.size();
3677            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3678                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3679                SettingBase sb = (SettingBase) pkg.mExtras;
3680                if (sb == null) {
3681                    continue;
3682                }
3683                PermissionsState permissionsState = sb.getPermissionsState();
3684                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3685                        userId, flagMask, flagValues);
3686            }
3687            if (changed) {
3688                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3689            }
3690        }
3691    }
3692
3693    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3694        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3695                != PackageManager.PERMISSION_GRANTED
3696            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3697                != PackageManager.PERMISSION_GRANTED) {
3698            throw new SecurityException(message + " requires "
3699                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3700                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3701        }
3702    }
3703
3704    @Override
3705    public boolean shouldShowRequestPermissionRationale(String permissionName,
3706            String packageName, int userId) {
3707        if (UserHandle.getCallingUserId() != userId) {
3708            mContext.enforceCallingPermission(
3709                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3710                    "canShowRequestPermissionRationale for user " + userId);
3711        }
3712
3713        final int uid = getPackageUid(packageName, userId);
3714        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3715            return false;
3716        }
3717
3718        if (checkPermission(permissionName, packageName, userId)
3719                == PackageManager.PERMISSION_GRANTED) {
3720            return false;
3721        }
3722
3723        final int flags;
3724
3725        final long identity = Binder.clearCallingIdentity();
3726        try {
3727            flags = getPermissionFlags(permissionName,
3728                    packageName, userId);
3729        } finally {
3730            Binder.restoreCallingIdentity(identity);
3731        }
3732
3733        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3734                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3735                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3736
3737        if ((flags & fixedFlags) != 0) {
3738            return false;
3739        }
3740
3741        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3742    }
3743
3744    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3745        BasePermission bp = mSettings.mPermissions.get(permission);
3746        if (bp == null) {
3747            throw new SecurityException("Missing " + permission + " permission");
3748        }
3749
3750        SettingBase sb = (SettingBase) pkg.mExtras;
3751        PermissionsState permissionsState = sb.getPermissionsState();
3752
3753        if (permissionsState.grantInstallPermission(bp) !=
3754                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3755            scheduleWriteSettingsLocked();
3756        }
3757    }
3758
3759    @Override
3760    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3761        mContext.enforceCallingOrSelfPermission(
3762                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3763                "addOnPermissionsChangeListener");
3764
3765        synchronized (mPackages) {
3766            mOnPermissionChangeListeners.addListenerLocked(listener);
3767        }
3768    }
3769
3770    @Override
3771    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3772        synchronized (mPackages) {
3773            mOnPermissionChangeListeners.removeListenerLocked(listener);
3774        }
3775    }
3776
3777    @Override
3778    public boolean isProtectedBroadcast(String actionName) {
3779        synchronized (mPackages) {
3780            return mProtectedBroadcasts.contains(actionName);
3781        }
3782    }
3783
3784    @Override
3785    public int checkSignatures(String pkg1, String pkg2) {
3786        synchronized (mPackages) {
3787            final PackageParser.Package p1 = mPackages.get(pkg1);
3788            final PackageParser.Package p2 = mPackages.get(pkg2);
3789            if (p1 == null || p1.mExtras == null
3790                    || p2 == null || p2.mExtras == null) {
3791                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3792            }
3793            return compareSignatures(p1.mSignatures, p2.mSignatures);
3794        }
3795    }
3796
3797    @Override
3798    public int checkUidSignatures(int uid1, int uid2) {
3799        // Map to base uids.
3800        uid1 = UserHandle.getAppId(uid1);
3801        uid2 = UserHandle.getAppId(uid2);
3802        // reader
3803        synchronized (mPackages) {
3804            Signature[] s1;
3805            Signature[] s2;
3806            Object obj = mSettings.getUserIdLPr(uid1);
3807            if (obj != null) {
3808                if (obj instanceof SharedUserSetting) {
3809                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3810                } else if (obj instanceof PackageSetting) {
3811                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3812                } else {
3813                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3814                }
3815            } else {
3816                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3817            }
3818            obj = mSettings.getUserIdLPr(uid2);
3819            if (obj != null) {
3820                if (obj instanceof SharedUserSetting) {
3821                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3822                } else if (obj instanceof PackageSetting) {
3823                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3824                } else {
3825                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3826                }
3827            } else {
3828                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3829            }
3830            return compareSignatures(s1, s2);
3831        }
3832    }
3833
3834    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3835        final long identity = Binder.clearCallingIdentity();
3836        try {
3837            if (sb instanceof SharedUserSetting) {
3838                SharedUserSetting sus = (SharedUserSetting) sb;
3839                final int packageCount = sus.packages.size();
3840                for (int i = 0; i < packageCount; i++) {
3841                    PackageSetting susPs = sus.packages.valueAt(i);
3842                    if (userId == UserHandle.USER_ALL) {
3843                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3844                    } else {
3845                        final int uid = UserHandle.getUid(userId, susPs.appId);
3846                        killUid(uid, reason);
3847                    }
3848                }
3849            } else if (sb instanceof PackageSetting) {
3850                PackageSetting ps = (PackageSetting) sb;
3851                if (userId == UserHandle.USER_ALL) {
3852                    killApplication(ps.pkg.packageName, ps.appId, reason);
3853                } else {
3854                    final int uid = UserHandle.getUid(userId, ps.appId);
3855                    killUid(uid, reason);
3856                }
3857            }
3858        } finally {
3859            Binder.restoreCallingIdentity(identity);
3860        }
3861    }
3862
3863    private static void killUid(int uid, String reason) {
3864        IActivityManager am = ActivityManagerNative.getDefault();
3865        if (am != null) {
3866            try {
3867                am.killUid(uid, reason);
3868            } catch (RemoteException e) {
3869                /* ignore - same process */
3870            }
3871        }
3872    }
3873
3874    /**
3875     * Compares two sets of signatures. Returns:
3876     * <br />
3877     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3878     * <br />
3879     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3880     * <br />
3881     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3882     * <br />
3883     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3884     * <br />
3885     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3886     */
3887    static int compareSignatures(Signature[] s1, Signature[] s2) {
3888        if (s1 == null) {
3889            return s2 == null
3890                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3891                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3892        }
3893
3894        if (s2 == null) {
3895            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3896        }
3897
3898        if (s1.length != s2.length) {
3899            return PackageManager.SIGNATURE_NO_MATCH;
3900        }
3901
3902        // Since both signature sets are of size 1, we can compare without HashSets.
3903        if (s1.length == 1) {
3904            return s1[0].equals(s2[0]) ?
3905                    PackageManager.SIGNATURE_MATCH :
3906                    PackageManager.SIGNATURE_NO_MATCH;
3907        }
3908
3909        ArraySet<Signature> set1 = new ArraySet<Signature>();
3910        for (Signature sig : s1) {
3911            set1.add(sig);
3912        }
3913        ArraySet<Signature> set2 = new ArraySet<Signature>();
3914        for (Signature sig : s2) {
3915            set2.add(sig);
3916        }
3917        // Make sure s2 contains all signatures in s1.
3918        if (set1.equals(set2)) {
3919            return PackageManager.SIGNATURE_MATCH;
3920        }
3921        return PackageManager.SIGNATURE_NO_MATCH;
3922    }
3923
3924    /**
3925     * If the database version for this type of package (internal storage or
3926     * external storage) is less than the version where package signatures
3927     * were updated, return true.
3928     */
3929    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3930        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3931        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3932    }
3933
3934    /**
3935     * Used for backward compatibility to make sure any packages with
3936     * certificate chains get upgraded to the new style. {@code existingSigs}
3937     * will be in the old format (since they were stored on disk from before the
3938     * system upgrade) and {@code scannedSigs} will be in the newer format.
3939     */
3940    private int compareSignaturesCompat(PackageSignatures existingSigs,
3941            PackageParser.Package scannedPkg) {
3942        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3943            return PackageManager.SIGNATURE_NO_MATCH;
3944        }
3945
3946        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3947        for (Signature sig : existingSigs.mSignatures) {
3948            existingSet.add(sig);
3949        }
3950        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3951        for (Signature sig : scannedPkg.mSignatures) {
3952            try {
3953                Signature[] chainSignatures = sig.getChainSignatures();
3954                for (Signature chainSig : chainSignatures) {
3955                    scannedCompatSet.add(chainSig);
3956                }
3957            } catch (CertificateEncodingException e) {
3958                scannedCompatSet.add(sig);
3959            }
3960        }
3961        /*
3962         * Make sure the expanded scanned set contains all signatures in the
3963         * existing one.
3964         */
3965        if (scannedCompatSet.equals(existingSet)) {
3966            // Migrate the old signatures to the new scheme.
3967            existingSigs.assignSignatures(scannedPkg.mSignatures);
3968            // The new KeySets will be re-added later in the scanning process.
3969            synchronized (mPackages) {
3970                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3971            }
3972            return PackageManager.SIGNATURE_MATCH;
3973        }
3974        return PackageManager.SIGNATURE_NO_MATCH;
3975    }
3976
3977    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3978        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3979        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3980    }
3981
3982    private int compareSignaturesRecover(PackageSignatures existingSigs,
3983            PackageParser.Package scannedPkg) {
3984        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3985            return PackageManager.SIGNATURE_NO_MATCH;
3986        }
3987
3988        String msg = null;
3989        try {
3990            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3991                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3992                        + scannedPkg.packageName);
3993                return PackageManager.SIGNATURE_MATCH;
3994            }
3995        } catch (CertificateException e) {
3996            msg = e.getMessage();
3997        }
3998
3999        logCriticalInfo(Log.INFO,
4000                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4001        return PackageManager.SIGNATURE_NO_MATCH;
4002    }
4003
4004    @Override
4005    public String[] getPackagesForUid(int uid) {
4006        uid = UserHandle.getAppId(uid);
4007        // reader
4008        synchronized (mPackages) {
4009            Object obj = mSettings.getUserIdLPr(uid);
4010            if (obj instanceof SharedUserSetting) {
4011                final SharedUserSetting sus = (SharedUserSetting) obj;
4012                final int N = sus.packages.size();
4013                final String[] res = new String[N];
4014                final Iterator<PackageSetting> it = sus.packages.iterator();
4015                int i = 0;
4016                while (it.hasNext()) {
4017                    res[i++] = it.next().name;
4018                }
4019                return res;
4020            } else if (obj instanceof PackageSetting) {
4021                final PackageSetting ps = (PackageSetting) obj;
4022                return new String[] { ps.name };
4023            }
4024        }
4025        return null;
4026    }
4027
4028    @Override
4029    public String getNameForUid(int uid) {
4030        // reader
4031        synchronized (mPackages) {
4032            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4033            if (obj instanceof SharedUserSetting) {
4034                final SharedUserSetting sus = (SharedUserSetting) obj;
4035                return sus.name + ":" + sus.userId;
4036            } else if (obj instanceof PackageSetting) {
4037                final PackageSetting ps = (PackageSetting) obj;
4038                return ps.name;
4039            }
4040        }
4041        return null;
4042    }
4043
4044    @Override
4045    public int getUidForSharedUser(String sharedUserName) {
4046        if(sharedUserName == null) {
4047            return -1;
4048        }
4049        // reader
4050        synchronized (mPackages) {
4051            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4052            if (suid == null) {
4053                return -1;
4054            }
4055            return suid.userId;
4056        }
4057    }
4058
4059    @Override
4060    public int getFlagsForUid(int uid) {
4061        synchronized (mPackages) {
4062            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4063            if (obj instanceof SharedUserSetting) {
4064                final SharedUserSetting sus = (SharedUserSetting) obj;
4065                return sus.pkgFlags;
4066            } else if (obj instanceof PackageSetting) {
4067                final PackageSetting ps = (PackageSetting) obj;
4068                return ps.pkgFlags;
4069            }
4070        }
4071        return 0;
4072    }
4073
4074    @Override
4075    public int getPrivateFlagsForUid(int uid) {
4076        synchronized (mPackages) {
4077            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4078            if (obj instanceof SharedUserSetting) {
4079                final SharedUserSetting sus = (SharedUserSetting) obj;
4080                return sus.pkgPrivateFlags;
4081            } else if (obj instanceof PackageSetting) {
4082                final PackageSetting ps = (PackageSetting) obj;
4083                return ps.pkgPrivateFlags;
4084            }
4085        }
4086        return 0;
4087    }
4088
4089    @Override
4090    public boolean isUidPrivileged(int uid) {
4091        uid = UserHandle.getAppId(uid);
4092        // reader
4093        synchronized (mPackages) {
4094            Object obj = mSettings.getUserIdLPr(uid);
4095            if (obj instanceof SharedUserSetting) {
4096                final SharedUserSetting sus = (SharedUserSetting) obj;
4097                final Iterator<PackageSetting> it = sus.packages.iterator();
4098                while (it.hasNext()) {
4099                    if (it.next().isPrivileged()) {
4100                        return true;
4101                    }
4102                }
4103            } else if (obj instanceof PackageSetting) {
4104                final PackageSetting ps = (PackageSetting) obj;
4105                return ps.isPrivileged();
4106            }
4107        }
4108        return false;
4109    }
4110
4111    @Override
4112    public String[] getAppOpPermissionPackages(String permissionName) {
4113        synchronized (mPackages) {
4114            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4115            if (pkgs == null) {
4116                return null;
4117            }
4118            return pkgs.toArray(new String[pkgs.size()]);
4119        }
4120    }
4121
4122    @Override
4123    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4124            int flags, int userId) {
4125        if (!sUserManager.exists(userId)) return null;
4126        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4127        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4128        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4129    }
4130
4131    @Override
4132    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4133            IntentFilter filter, int match, ComponentName activity) {
4134        final int userId = UserHandle.getCallingUserId();
4135        if (DEBUG_PREFERRED) {
4136            Log.v(TAG, "setLastChosenActivity intent=" + intent
4137                + " resolvedType=" + resolvedType
4138                + " flags=" + flags
4139                + " filter=" + filter
4140                + " match=" + match
4141                + " activity=" + activity);
4142            filter.dump(new PrintStreamPrinter(System.out), "    ");
4143        }
4144        intent.setComponent(null);
4145        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4146        // Find any earlier preferred or last chosen entries and nuke them
4147        findPreferredActivity(intent, resolvedType,
4148                flags, query, 0, false, true, false, userId);
4149        // Add the new activity as the last chosen for this filter
4150        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4151                "Setting last chosen");
4152    }
4153
4154    @Override
4155    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4156        final int userId = UserHandle.getCallingUserId();
4157        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4158        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4159        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4160                false, false, false, userId);
4161    }
4162
4163    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4164            int flags, List<ResolveInfo> query, int userId) {
4165        if (query != null) {
4166            final int N = query.size();
4167            if (N == 1) {
4168                return query.get(0);
4169            } else if (N > 1) {
4170                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4171                // If there is more than one activity with the same priority,
4172                // then let the user decide between them.
4173                ResolveInfo r0 = query.get(0);
4174                ResolveInfo r1 = query.get(1);
4175                if (DEBUG_INTENT_MATCHING || debug) {
4176                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4177                            + r1.activityInfo.name + "=" + r1.priority);
4178                }
4179                // If the first activity has a higher priority, or a different
4180                // default, then it is always desireable to pick it.
4181                if (r0.priority != r1.priority
4182                        || r0.preferredOrder != r1.preferredOrder
4183                        || r0.isDefault != r1.isDefault) {
4184                    return query.get(0);
4185                }
4186                // If we have saved a preference for a preferred activity for
4187                // this Intent, use that.
4188                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4189                        flags, query, r0.priority, true, false, debug, userId);
4190                if (ri != null) {
4191                    return ri;
4192                }
4193                if (userId != 0) {
4194                    ri = new ResolveInfo(mResolveInfo);
4195                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4196                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4197                            ri.activityInfo.applicationInfo);
4198                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4199                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4200                    return ri;
4201                }
4202                return mResolveInfo;
4203            }
4204        }
4205        return null;
4206    }
4207
4208    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4209            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4210        final int N = query.size();
4211        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4212                .get(userId);
4213        // Get the list of persistent preferred activities that handle the intent
4214        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4215        List<PersistentPreferredActivity> pprefs = ppir != null
4216                ? ppir.queryIntent(intent, resolvedType,
4217                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4218                : null;
4219        if (pprefs != null && pprefs.size() > 0) {
4220            final int M = pprefs.size();
4221            for (int i=0; i<M; i++) {
4222                final PersistentPreferredActivity ppa = pprefs.get(i);
4223                if (DEBUG_PREFERRED || debug) {
4224                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4225                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4226                            + "\n  component=" + ppa.mComponent);
4227                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4228                }
4229                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4230                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4231                if (DEBUG_PREFERRED || debug) {
4232                    Slog.v(TAG, "Found persistent preferred activity:");
4233                    if (ai != null) {
4234                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4235                    } else {
4236                        Slog.v(TAG, "  null");
4237                    }
4238                }
4239                if (ai == null) {
4240                    // This previously registered persistent preferred activity
4241                    // component is no longer known. Ignore it and do NOT remove it.
4242                    continue;
4243                }
4244                for (int j=0; j<N; j++) {
4245                    final ResolveInfo ri = query.get(j);
4246                    if (!ri.activityInfo.applicationInfo.packageName
4247                            .equals(ai.applicationInfo.packageName)) {
4248                        continue;
4249                    }
4250                    if (!ri.activityInfo.name.equals(ai.name)) {
4251                        continue;
4252                    }
4253                    //  Found a persistent preference that can handle the intent.
4254                    if (DEBUG_PREFERRED || debug) {
4255                        Slog.v(TAG, "Returning persistent preferred activity: " +
4256                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4257                    }
4258                    return ri;
4259                }
4260            }
4261        }
4262        return null;
4263    }
4264
4265    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4266            List<ResolveInfo> query, int priority, boolean always,
4267            boolean removeMatches, boolean debug, int userId) {
4268        if (!sUserManager.exists(userId)) return null;
4269        // writer
4270        synchronized (mPackages) {
4271            if (intent.getSelector() != null) {
4272                intent = intent.getSelector();
4273            }
4274            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4275
4276            // Try to find a matching persistent preferred activity.
4277            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4278                    debug, userId);
4279
4280            // If a persistent preferred activity matched, use it.
4281            if (pri != null) {
4282                return pri;
4283            }
4284
4285            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4286            // Get the list of preferred activities that handle the intent
4287            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4288            List<PreferredActivity> prefs = pir != null
4289                    ? pir.queryIntent(intent, resolvedType,
4290                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4291                    : null;
4292            if (prefs != null && prefs.size() > 0) {
4293                boolean changed = false;
4294                try {
4295                    // First figure out how good the original match set is.
4296                    // We will only allow preferred activities that came
4297                    // from the same match quality.
4298                    int match = 0;
4299
4300                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4301
4302                    final int N = query.size();
4303                    for (int j=0; j<N; j++) {
4304                        final ResolveInfo ri = query.get(j);
4305                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4306                                + ": 0x" + Integer.toHexString(match));
4307                        if (ri.match > match) {
4308                            match = ri.match;
4309                        }
4310                    }
4311
4312                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4313                            + Integer.toHexString(match));
4314
4315                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4316                    final int M = prefs.size();
4317                    for (int i=0; i<M; i++) {
4318                        final PreferredActivity pa = prefs.get(i);
4319                        if (DEBUG_PREFERRED || debug) {
4320                            Slog.v(TAG, "Checking PreferredActivity ds="
4321                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4322                                    + "\n  component=" + pa.mPref.mComponent);
4323                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4324                        }
4325                        if (pa.mPref.mMatch != match) {
4326                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4327                                    + Integer.toHexString(pa.mPref.mMatch));
4328                            continue;
4329                        }
4330                        // If it's not an "always" type preferred activity and that's what we're
4331                        // looking for, skip it.
4332                        if (always && !pa.mPref.mAlways) {
4333                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4334                            continue;
4335                        }
4336                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4337                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4338                        if (DEBUG_PREFERRED || debug) {
4339                            Slog.v(TAG, "Found preferred activity:");
4340                            if (ai != null) {
4341                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4342                            } else {
4343                                Slog.v(TAG, "  null");
4344                            }
4345                        }
4346                        if (ai == null) {
4347                            // This previously registered preferred activity
4348                            // component is no longer known.  Most likely an update
4349                            // to the app was installed and in the new version this
4350                            // component no longer exists.  Clean it up by removing
4351                            // it from the preferred activities list, and skip it.
4352                            Slog.w(TAG, "Removing dangling preferred activity: "
4353                                    + pa.mPref.mComponent);
4354                            pir.removeFilter(pa);
4355                            changed = true;
4356                            continue;
4357                        }
4358                        for (int j=0; j<N; j++) {
4359                            final ResolveInfo ri = query.get(j);
4360                            if (!ri.activityInfo.applicationInfo.packageName
4361                                    .equals(ai.applicationInfo.packageName)) {
4362                                continue;
4363                            }
4364                            if (!ri.activityInfo.name.equals(ai.name)) {
4365                                continue;
4366                            }
4367
4368                            if (removeMatches) {
4369                                pir.removeFilter(pa);
4370                                changed = true;
4371                                if (DEBUG_PREFERRED) {
4372                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4373                                }
4374                                break;
4375                            }
4376
4377                            // Okay we found a previously set preferred or last chosen app.
4378                            // If the result set is different from when this
4379                            // was created, we need to clear it and re-ask the
4380                            // user their preference, if we're looking for an "always" type entry.
4381                            if (always && !pa.mPref.sameSet(query)) {
4382                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4383                                        + intent + " type " + resolvedType);
4384                                if (DEBUG_PREFERRED) {
4385                                    Slog.v(TAG, "Removing preferred activity since set changed "
4386                                            + pa.mPref.mComponent);
4387                                }
4388                                pir.removeFilter(pa);
4389                                // Re-add the filter as a "last chosen" entry (!always)
4390                                PreferredActivity lastChosen = new PreferredActivity(
4391                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4392                                pir.addFilter(lastChosen);
4393                                changed = true;
4394                                return null;
4395                            }
4396
4397                            // Yay! Either the set matched or we're looking for the last chosen
4398                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4399                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4400                            return ri;
4401                        }
4402                    }
4403                } finally {
4404                    if (changed) {
4405                        if (DEBUG_PREFERRED) {
4406                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4407                        }
4408                        scheduleWritePackageRestrictionsLocked(userId);
4409                    }
4410                }
4411            }
4412        }
4413        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4414        return null;
4415    }
4416
4417    /*
4418     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4419     */
4420    @Override
4421    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4422            int targetUserId) {
4423        mContext.enforceCallingOrSelfPermission(
4424                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4425        List<CrossProfileIntentFilter> matches =
4426                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4427        if (matches != null) {
4428            int size = matches.size();
4429            for (int i = 0; i < size; i++) {
4430                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4431            }
4432        }
4433        if (hasWebURI(intent)) {
4434            // cross-profile app linking works only towards the parent.
4435            final UserInfo parent = getProfileParent(sourceUserId);
4436            synchronized(mPackages) {
4437                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4438                        intent, resolvedType, 0, sourceUserId, parent.id);
4439                return xpDomainInfo != null;
4440            }
4441        }
4442        return false;
4443    }
4444
4445    private UserInfo getProfileParent(int userId) {
4446        final long identity = Binder.clearCallingIdentity();
4447        try {
4448            return sUserManager.getProfileParent(userId);
4449        } finally {
4450            Binder.restoreCallingIdentity(identity);
4451        }
4452    }
4453
4454    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4455            String resolvedType, int userId) {
4456        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4457        if (resolver != null) {
4458            return resolver.queryIntent(intent, resolvedType, false, userId);
4459        }
4460        return null;
4461    }
4462
4463    @Override
4464    public List<ResolveInfo> queryIntentActivities(Intent intent,
4465            String resolvedType, int flags, int userId) {
4466        if (!sUserManager.exists(userId)) return Collections.emptyList();
4467        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4468        ComponentName comp = intent.getComponent();
4469        if (comp == null) {
4470            if (intent.getSelector() != null) {
4471                intent = intent.getSelector();
4472                comp = intent.getComponent();
4473            }
4474        }
4475
4476        if (comp != null) {
4477            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4478            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4479            if (ai != null) {
4480                final ResolveInfo ri = new ResolveInfo();
4481                ri.activityInfo = ai;
4482                list.add(ri);
4483            }
4484            return list;
4485        }
4486
4487        // reader
4488        synchronized (mPackages) {
4489            final String pkgName = intent.getPackage();
4490            if (pkgName == null) {
4491                List<CrossProfileIntentFilter> matchingFilters =
4492                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4493                // Check for results that need to skip the current profile.
4494                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4495                        resolvedType, flags, userId);
4496                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4497                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4498                    result.add(xpResolveInfo);
4499                    return filterIfNotPrimaryUser(result, userId);
4500                }
4501
4502                // Check for results in the current profile.
4503                List<ResolveInfo> result = mActivities.queryIntent(
4504                        intent, resolvedType, flags, userId);
4505
4506                // Check for cross profile results.
4507                xpResolveInfo = queryCrossProfileIntents(
4508                        matchingFilters, intent, resolvedType, flags, userId);
4509                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4510                    result.add(xpResolveInfo);
4511                    Collections.sort(result, mResolvePrioritySorter);
4512                }
4513                result = filterIfNotPrimaryUser(result, userId);
4514                if (hasWebURI(intent)) {
4515                    CrossProfileDomainInfo xpDomainInfo = null;
4516                    final UserInfo parent = getProfileParent(userId);
4517                    if (parent != null) {
4518                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4519                                flags, userId, parent.id);
4520                    }
4521                    if (xpDomainInfo != null) {
4522                        if (xpResolveInfo != null) {
4523                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4524                            // in the result.
4525                            result.remove(xpResolveInfo);
4526                        }
4527                        if (result.size() == 0) {
4528                            result.add(xpDomainInfo.resolveInfo);
4529                            return result;
4530                        }
4531                    } else if (result.size() <= 1) {
4532                        return result;
4533                    }
4534                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4535                            xpDomainInfo, userId);
4536                    Collections.sort(result, mResolvePrioritySorter);
4537                }
4538                return result;
4539            }
4540            final PackageParser.Package pkg = mPackages.get(pkgName);
4541            if (pkg != null) {
4542                return filterIfNotPrimaryUser(
4543                        mActivities.queryIntentForPackage(
4544                                intent, resolvedType, flags, pkg.activities, userId),
4545                        userId);
4546            }
4547            return new ArrayList<ResolveInfo>();
4548        }
4549    }
4550
4551    private static class CrossProfileDomainInfo {
4552        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4553        ResolveInfo resolveInfo;
4554        /* Best domain verification status of the activities found in the other profile */
4555        int bestDomainVerificationStatus;
4556    }
4557
4558    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4559            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4560        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4561                sourceUserId)) {
4562            return null;
4563        }
4564        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4565                resolvedType, flags, parentUserId);
4566
4567        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4568            return null;
4569        }
4570        CrossProfileDomainInfo result = null;
4571        int size = resultTargetUser.size();
4572        for (int i = 0; i < size; i++) {
4573            ResolveInfo riTargetUser = resultTargetUser.get(i);
4574            // Intent filter verification is only for filters that specify a host. So don't return
4575            // those that handle all web uris.
4576            if (riTargetUser.handleAllWebDataURI) {
4577                continue;
4578            }
4579            String packageName = riTargetUser.activityInfo.packageName;
4580            PackageSetting ps = mSettings.mPackages.get(packageName);
4581            if (ps == null) {
4582                continue;
4583            }
4584            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4585            int status = (int)(verificationState >> 32);
4586            if (result == null) {
4587                result = new CrossProfileDomainInfo();
4588                result.resolveInfo =
4589                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4590                result.bestDomainVerificationStatus = status;
4591            } else {
4592                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4593                        result.bestDomainVerificationStatus);
4594            }
4595        }
4596        // Don't consider matches with status NEVER across profiles.
4597        if (result != null && result.bestDomainVerificationStatus
4598                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4599            return null;
4600        }
4601        return result;
4602    }
4603
4604    /**
4605     * Verification statuses are ordered from the worse to the best, except for
4606     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4607     */
4608    private int bestDomainVerificationStatus(int status1, int status2) {
4609        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4610            return status2;
4611        }
4612        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4613            return status1;
4614        }
4615        return (int) MathUtils.max(status1, status2);
4616    }
4617
4618    private boolean isUserEnabled(int userId) {
4619        long callingId = Binder.clearCallingIdentity();
4620        try {
4621            UserInfo userInfo = sUserManager.getUserInfo(userId);
4622            return userInfo != null && userInfo.isEnabled();
4623        } finally {
4624            Binder.restoreCallingIdentity(callingId);
4625        }
4626    }
4627
4628    /**
4629     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4630     *
4631     * @return filtered list
4632     */
4633    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4634        if (userId == UserHandle.USER_OWNER) {
4635            return resolveInfos;
4636        }
4637        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4638            ResolveInfo info = resolveInfos.get(i);
4639            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4640                resolveInfos.remove(i);
4641            }
4642        }
4643        return resolveInfos;
4644    }
4645
4646    private static boolean hasWebURI(Intent intent) {
4647        if (intent.getData() == null) {
4648            return false;
4649        }
4650        final String scheme = intent.getScheme();
4651        if (TextUtils.isEmpty(scheme)) {
4652            return false;
4653        }
4654        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4655    }
4656
4657    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4658            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4659            int userId) {
4660        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4661
4662        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4663            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4664                    candidates.size());
4665        }
4666
4667        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4668        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4669        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4670        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4671        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4672
4673        synchronized (mPackages) {
4674            final int count = candidates.size();
4675            // First, try to use linked apps. Partition the candidates into four lists:
4676            // one for the final results, one for the "do not use ever", one for "undefined status"
4677            // and finally one for "browser app type".
4678            for (int n=0; n<count; n++) {
4679                ResolveInfo info = candidates.get(n);
4680                String packageName = info.activityInfo.packageName;
4681                PackageSetting ps = mSettings.mPackages.get(packageName);
4682                if (ps != null) {
4683                    // Add to the special match all list (Browser use case)
4684                    if (info.handleAllWebDataURI) {
4685                        matchAllList.add(info);
4686                        continue;
4687                    }
4688                    // Try to get the status from User settings first
4689                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4690                    int status = (int)(packedStatus >> 32);
4691                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4692                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4693                        if (DEBUG_DOMAIN_VERIFICATION) {
4694                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4695                                    + " : linkgen=" + linkGeneration);
4696                        }
4697                        // Use link-enabled generation as preferredOrder, i.e.
4698                        // prefer newly-enabled over earlier-enabled.
4699                        info.preferredOrder = linkGeneration;
4700                        alwaysList.add(info);
4701                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4702                        if (DEBUG_DOMAIN_VERIFICATION) {
4703                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4704                        }
4705                        neverList.add(info);
4706                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4707                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4708                        if (DEBUG_DOMAIN_VERIFICATION) {
4709                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4710                        }
4711                        undefinedList.add(info);
4712                    }
4713                }
4714            }
4715            // First try to add the "always" resolution(s) for the current user, if any
4716            if (alwaysList.size() > 0) {
4717                result.addAll(alwaysList);
4718            // if there is an "always" for the parent user, add it.
4719            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4720                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4721                result.add(xpDomainInfo.resolveInfo);
4722            } else {
4723                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4724                result.addAll(undefinedList);
4725                if (xpDomainInfo != null && (
4726                        xpDomainInfo.bestDomainVerificationStatus
4727                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4728                        || xpDomainInfo.bestDomainVerificationStatus
4729                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4730                    result.add(xpDomainInfo.resolveInfo);
4731                }
4732                // Also add Browsers (all of them or only the default one)
4733                if ((matchFlags & MATCH_ALL) != 0) {
4734                    result.addAll(matchAllList);
4735                } else {
4736                    // Browser/generic handling case.  If there's a default browser, go straight
4737                    // to that (but only if there is no other higher-priority match).
4738                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4739                    int maxMatchPrio = 0;
4740                    ResolveInfo defaultBrowserMatch = null;
4741                    final int numCandidates = matchAllList.size();
4742                    for (int n = 0; n < numCandidates; n++) {
4743                        ResolveInfo info = matchAllList.get(n);
4744                        // track the highest overall match priority...
4745                        if (info.priority > maxMatchPrio) {
4746                            maxMatchPrio = info.priority;
4747                        }
4748                        // ...and the highest-priority default browser match
4749                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4750                            if (defaultBrowserMatch == null
4751                                    || (defaultBrowserMatch.priority < info.priority)) {
4752                                if (debug) {
4753                                    Slog.v(TAG, "Considering default browser match " + info);
4754                                }
4755                                defaultBrowserMatch = info;
4756                            }
4757                        }
4758                    }
4759                    if (defaultBrowserMatch != null
4760                            && defaultBrowserMatch.priority >= maxMatchPrio
4761                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4762                    {
4763                        if (debug) {
4764                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4765                        }
4766                        result.add(defaultBrowserMatch);
4767                    } else {
4768                        result.addAll(matchAllList);
4769                    }
4770                }
4771
4772                // If there is nothing selected, add all candidates and remove the ones that the user
4773                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4774                if (result.size() == 0) {
4775                    result.addAll(candidates);
4776                    result.removeAll(neverList);
4777                }
4778            }
4779        }
4780        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4781            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4782                    result.size());
4783            for (ResolveInfo info : result) {
4784                Slog.v(TAG, "  + " + info.activityInfo);
4785            }
4786        }
4787        return result;
4788    }
4789
4790    // Returns a packed value as a long:
4791    //
4792    // high 'int'-sized word: link status: undefined/ask/never/always.
4793    // low 'int'-sized word: relative priority among 'always' results.
4794    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4795        long result = ps.getDomainVerificationStatusForUser(userId);
4796        // if none available, get the master status
4797        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4798            if (ps.getIntentFilterVerificationInfo() != null) {
4799                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4800            }
4801        }
4802        return result;
4803    }
4804
4805    private ResolveInfo querySkipCurrentProfileIntents(
4806            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4807            int flags, int sourceUserId) {
4808        if (matchingFilters != null) {
4809            int size = matchingFilters.size();
4810            for (int i = 0; i < size; i ++) {
4811                CrossProfileIntentFilter filter = matchingFilters.get(i);
4812                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4813                    // Checking if there are activities in the target user that can handle the
4814                    // intent.
4815                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4816                            flags, sourceUserId);
4817                    if (resolveInfo != null) {
4818                        return resolveInfo;
4819                    }
4820                }
4821            }
4822        }
4823        return null;
4824    }
4825
4826    // Return matching ResolveInfo if any for skip current profile intent filters.
4827    private ResolveInfo queryCrossProfileIntents(
4828            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4829            int flags, int sourceUserId) {
4830        if (matchingFilters != null) {
4831            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4832            // match the same intent. For performance reasons, it is better not to
4833            // run queryIntent twice for the same userId
4834            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4835            int size = matchingFilters.size();
4836            for (int i = 0; i < size; i++) {
4837                CrossProfileIntentFilter filter = matchingFilters.get(i);
4838                int targetUserId = filter.getTargetUserId();
4839                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4840                        && !alreadyTriedUserIds.get(targetUserId)) {
4841                    // Checking if there are activities in the target user that can handle the
4842                    // intent.
4843                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4844                            flags, sourceUserId);
4845                    if (resolveInfo != null) return resolveInfo;
4846                    alreadyTriedUserIds.put(targetUserId, true);
4847                }
4848            }
4849        }
4850        return null;
4851    }
4852
4853    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4854            String resolvedType, int flags, int sourceUserId) {
4855        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4856                resolvedType, flags, filter.getTargetUserId());
4857        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4858            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4859        }
4860        return null;
4861    }
4862
4863    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4864            int sourceUserId, int targetUserId) {
4865        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4866        String className;
4867        if (targetUserId == UserHandle.USER_OWNER) {
4868            className = FORWARD_INTENT_TO_USER_OWNER;
4869        } else {
4870            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4871        }
4872        ComponentName forwardingActivityComponentName = new ComponentName(
4873                mAndroidApplication.packageName, className);
4874        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4875                sourceUserId);
4876        if (targetUserId == UserHandle.USER_OWNER) {
4877            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4878            forwardingResolveInfo.noResourceId = true;
4879        }
4880        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4881        forwardingResolveInfo.priority = 0;
4882        forwardingResolveInfo.preferredOrder = 0;
4883        forwardingResolveInfo.match = 0;
4884        forwardingResolveInfo.isDefault = true;
4885        forwardingResolveInfo.filter = filter;
4886        forwardingResolveInfo.targetUserId = targetUserId;
4887        return forwardingResolveInfo;
4888    }
4889
4890    @Override
4891    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4892            Intent[] specifics, String[] specificTypes, Intent intent,
4893            String resolvedType, int flags, int userId) {
4894        if (!sUserManager.exists(userId)) return Collections.emptyList();
4895        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4896                false, "query intent activity options");
4897        final String resultsAction = intent.getAction();
4898
4899        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4900                | PackageManager.GET_RESOLVED_FILTER, userId);
4901
4902        if (DEBUG_INTENT_MATCHING) {
4903            Log.v(TAG, "Query " + intent + ": " + results);
4904        }
4905
4906        int specificsPos = 0;
4907        int N;
4908
4909        // todo: note that the algorithm used here is O(N^2).  This
4910        // isn't a problem in our current environment, but if we start running
4911        // into situations where we have more than 5 or 10 matches then this
4912        // should probably be changed to something smarter...
4913
4914        // First we go through and resolve each of the specific items
4915        // that were supplied, taking care of removing any corresponding
4916        // duplicate items in the generic resolve list.
4917        if (specifics != null) {
4918            for (int i=0; i<specifics.length; i++) {
4919                final Intent sintent = specifics[i];
4920                if (sintent == null) {
4921                    continue;
4922                }
4923
4924                if (DEBUG_INTENT_MATCHING) {
4925                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4926                }
4927
4928                String action = sintent.getAction();
4929                if (resultsAction != null && resultsAction.equals(action)) {
4930                    // If this action was explicitly requested, then don't
4931                    // remove things that have it.
4932                    action = null;
4933                }
4934
4935                ResolveInfo ri = null;
4936                ActivityInfo ai = null;
4937
4938                ComponentName comp = sintent.getComponent();
4939                if (comp == null) {
4940                    ri = resolveIntent(
4941                        sintent,
4942                        specificTypes != null ? specificTypes[i] : null,
4943                            flags, userId);
4944                    if (ri == null) {
4945                        continue;
4946                    }
4947                    if (ri == mResolveInfo) {
4948                        // ACK!  Must do something better with this.
4949                    }
4950                    ai = ri.activityInfo;
4951                    comp = new ComponentName(ai.applicationInfo.packageName,
4952                            ai.name);
4953                } else {
4954                    ai = getActivityInfo(comp, flags, userId);
4955                    if (ai == null) {
4956                        continue;
4957                    }
4958                }
4959
4960                // Look for any generic query activities that are duplicates
4961                // of this specific one, and remove them from the results.
4962                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4963                N = results.size();
4964                int j;
4965                for (j=specificsPos; j<N; j++) {
4966                    ResolveInfo sri = results.get(j);
4967                    if ((sri.activityInfo.name.equals(comp.getClassName())
4968                            && sri.activityInfo.applicationInfo.packageName.equals(
4969                                    comp.getPackageName()))
4970                        || (action != null && sri.filter.matchAction(action))) {
4971                        results.remove(j);
4972                        if (DEBUG_INTENT_MATCHING) Log.v(
4973                            TAG, "Removing duplicate item from " + j
4974                            + " due to specific " + specificsPos);
4975                        if (ri == null) {
4976                            ri = sri;
4977                        }
4978                        j--;
4979                        N--;
4980                    }
4981                }
4982
4983                // Add this specific item to its proper place.
4984                if (ri == null) {
4985                    ri = new ResolveInfo();
4986                    ri.activityInfo = ai;
4987                }
4988                results.add(specificsPos, ri);
4989                ri.specificIndex = i;
4990                specificsPos++;
4991            }
4992        }
4993
4994        // Now we go through the remaining generic results and remove any
4995        // duplicate actions that are found here.
4996        N = results.size();
4997        for (int i=specificsPos; i<N-1; i++) {
4998            final ResolveInfo rii = results.get(i);
4999            if (rii.filter == null) {
5000                continue;
5001            }
5002
5003            // Iterate over all of the actions of this result's intent
5004            // filter...  typically this should be just one.
5005            final Iterator<String> it = rii.filter.actionsIterator();
5006            if (it == null) {
5007                continue;
5008            }
5009            while (it.hasNext()) {
5010                final String action = it.next();
5011                if (resultsAction != null && resultsAction.equals(action)) {
5012                    // If this action was explicitly requested, then don't
5013                    // remove things that have it.
5014                    continue;
5015                }
5016                for (int j=i+1; j<N; j++) {
5017                    final ResolveInfo rij = results.get(j);
5018                    if (rij.filter != null && rij.filter.hasAction(action)) {
5019                        results.remove(j);
5020                        if (DEBUG_INTENT_MATCHING) Log.v(
5021                            TAG, "Removing duplicate item from " + j
5022                            + " due to action " + action + " at " + i);
5023                        j--;
5024                        N--;
5025                    }
5026                }
5027            }
5028
5029            // If the caller didn't request filter information, drop it now
5030            // so we don't have to marshall/unmarshall it.
5031            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5032                rii.filter = null;
5033            }
5034        }
5035
5036        // Filter out the caller activity if so requested.
5037        if (caller != null) {
5038            N = results.size();
5039            for (int i=0; i<N; i++) {
5040                ActivityInfo ainfo = results.get(i).activityInfo;
5041                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5042                        && caller.getClassName().equals(ainfo.name)) {
5043                    results.remove(i);
5044                    break;
5045                }
5046            }
5047        }
5048
5049        // If the caller didn't request filter information,
5050        // drop them now so we don't have to
5051        // marshall/unmarshall it.
5052        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5053            N = results.size();
5054            for (int i=0; i<N; i++) {
5055                results.get(i).filter = null;
5056            }
5057        }
5058
5059        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5060        return results;
5061    }
5062
5063    @Override
5064    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5065            int userId) {
5066        if (!sUserManager.exists(userId)) return Collections.emptyList();
5067        ComponentName comp = intent.getComponent();
5068        if (comp == null) {
5069            if (intent.getSelector() != null) {
5070                intent = intent.getSelector();
5071                comp = intent.getComponent();
5072            }
5073        }
5074        if (comp != null) {
5075            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5076            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5077            if (ai != null) {
5078                ResolveInfo ri = new ResolveInfo();
5079                ri.activityInfo = ai;
5080                list.add(ri);
5081            }
5082            return list;
5083        }
5084
5085        // reader
5086        synchronized (mPackages) {
5087            String pkgName = intent.getPackage();
5088            if (pkgName == null) {
5089                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5090            }
5091            final PackageParser.Package pkg = mPackages.get(pkgName);
5092            if (pkg != null) {
5093                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5094                        userId);
5095            }
5096            return null;
5097        }
5098    }
5099
5100    @Override
5101    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5102        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5103        if (!sUserManager.exists(userId)) return null;
5104        if (query != null) {
5105            if (query.size() >= 1) {
5106                // If there is more than one service with the same priority,
5107                // just arbitrarily pick the first one.
5108                return query.get(0);
5109            }
5110        }
5111        return null;
5112    }
5113
5114    @Override
5115    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5116            int userId) {
5117        if (!sUserManager.exists(userId)) return Collections.emptyList();
5118        ComponentName comp = intent.getComponent();
5119        if (comp == null) {
5120            if (intent.getSelector() != null) {
5121                intent = intent.getSelector();
5122                comp = intent.getComponent();
5123            }
5124        }
5125        if (comp != null) {
5126            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5127            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5128            if (si != null) {
5129                final ResolveInfo ri = new ResolveInfo();
5130                ri.serviceInfo = si;
5131                list.add(ri);
5132            }
5133            return list;
5134        }
5135
5136        // reader
5137        synchronized (mPackages) {
5138            String pkgName = intent.getPackage();
5139            if (pkgName == null) {
5140                return mServices.queryIntent(intent, resolvedType, flags, userId);
5141            }
5142            final PackageParser.Package pkg = mPackages.get(pkgName);
5143            if (pkg != null) {
5144                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5145                        userId);
5146            }
5147            return null;
5148        }
5149    }
5150
5151    @Override
5152    public List<ResolveInfo> queryIntentContentProviders(
5153            Intent intent, String resolvedType, int flags, int userId) {
5154        if (!sUserManager.exists(userId)) return Collections.emptyList();
5155        ComponentName comp = intent.getComponent();
5156        if (comp == null) {
5157            if (intent.getSelector() != null) {
5158                intent = intent.getSelector();
5159                comp = intent.getComponent();
5160            }
5161        }
5162        if (comp != null) {
5163            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5164            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5165            if (pi != null) {
5166                final ResolveInfo ri = new ResolveInfo();
5167                ri.providerInfo = pi;
5168                list.add(ri);
5169            }
5170            return list;
5171        }
5172
5173        // reader
5174        synchronized (mPackages) {
5175            String pkgName = intent.getPackage();
5176            if (pkgName == null) {
5177                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5178            }
5179            final PackageParser.Package pkg = mPackages.get(pkgName);
5180            if (pkg != null) {
5181                return mProviders.queryIntentForPackage(
5182                        intent, resolvedType, flags, pkg.providers, userId);
5183            }
5184            return null;
5185        }
5186    }
5187
5188    @Override
5189    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5190        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5191
5192        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5193
5194        // writer
5195        synchronized (mPackages) {
5196            ArrayList<PackageInfo> list;
5197            if (listUninstalled) {
5198                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5199                for (PackageSetting ps : mSettings.mPackages.values()) {
5200                    PackageInfo pi;
5201                    if (ps.pkg != null) {
5202                        pi = generatePackageInfo(ps.pkg, flags, userId);
5203                    } else {
5204                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5205                    }
5206                    if (pi != null) {
5207                        list.add(pi);
5208                    }
5209                }
5210            } else {
5211                list = new ArrayList<PackageInfo>(mPackages.size());
5212                for (PackageParser.Package p : mPackages.values()) {
5213                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5214                    if (pi != null) {
5215                        list.add(pi);
5216                    }
5217                }
5218            }
5219
5220            return new ParceledListSlice<PackageInfo>(list);
5221        }
5222    }
5223
5224    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5225            String[] permissions, boolean[] tmp, int flags, int userId) {
5226        int numMatch = 0;
5227        final PermissionsState permissionsState = ps.getPermissionsState();
5228        for (int i=0; i<permissions.length; i++) {
5229            final String permission = permissions[i];
5230            if (permissionsState.hasPermission(permission, userId)) {
5231                tmp[i] = true;
5232                numMatch++;
5233            } else {
5234                tmp[i] = false;
5235            }
5236        }
5237        if (numMatch == 0) {
5238            return;
5239        }
5240        PackageInfo pi;
5241        if (ps.pkg != null) {
5242            pi = generatePackageInfo(ps.pkg, flags, userId);
5243        } else {
5244            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5245        }
5246        // The above might return null in cases of uninstalled apps or install-state
5247        // skew across users/profiles.
5248        if (pi != null) {
5249            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5250                if (numMatch == permissions.length) {
5251                    pi.requestedPermissions = permissions;
5252                } else {
5253                    pi.requestedPermissions = new String[numMatch];
5254                    numMatch = 0;
5255                    for (int i=0; i<permissions.length; i++) {
5256                        if (tmp[i]) {
5257                            pi.requestedPermissions[numMatch] = permissions[i];
5258                            numMatch++;
5259                        }
5260                    }
5261                }
5262            }
5263            list.add(pi);
5264        }
5265    }
5266
5267    @Override
5268    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5269            String[] permissions, int flags, int userId) {
5270        if (!sUserManager.exists(userId)) return null;
5271        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5272
5273        // writer
5274        synchronized (mPackages) {
5275            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5276            boolean[] tmpBools = new boolean[permissions.length];
5277            if (listUninstalled) {
5278                for (PackageSetting ps : mSettings.mPackages.values()) {
5279                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5280                }
5281            } else {
5282                for (PackageParser.Package pkg : mPackages.values()) {
5283                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5284                    if (ps != null) {
5285                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5286                                userId);
5287                    }
5288                }
5289            }
5290
5291            return new ParceledListSlice<PackageInfo>(list);
5292        }
5293    }
5294
5295    @Override
5296    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5297        if (!sUserManager.exists(userId)) return null;
5298        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5299
5300        // writer
5301        synchronized (mPackages) {
5302            ArrayList<ApplicationInfo> list;
5303            if (listUninstalled) {
5304                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5305                for (PackageSetting ps : mSettings.mPackages.values()) {
5306                    ApplicationInfo ai;
5307                    if (ps.pkg != null) {
5308                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5309                                ps.readUserState(userId), userId);
5310                    } else {
5311                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5312                    }
5313                    if (ai != null) {
5314                        list.add(ai);
5315                    }
5316                }
5317            } else {
5318                list = new ArrayList<ApplicationInfo>(mPackages.size());
5319                for (PackageParser.Package p : mPackages.values()) {
5320                    if (p.mExtras != null) {
5321                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5322                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5323                        if (ai != null) {
5324                            list.add(ai);
5325                        }
5326                    }
5327                }
5328            }
5329
5330            return new ParceledListSlice<ApplicationInfo>(list);
5331        }
5332    }
5333
5334    public List<ApplicationInfo> getPersistentApplications(int flags) {
5335        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5336
5337        // reader
5338        synchronized (mPackages) {
5339            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5340            final int userId = UserHandle.getCallingUserId();
5341            while (i.hasNext()) {
5342                final PackageParser.Package p = i.next();
5343                if (p.applicationInfo != null
5344                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5345                        && (!mSafeMode || isSystemApp(p))) {
5346                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5347                    if (ps != null) {
5348                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5349                                ps.readUserState(userId), userId);
5350                        if (ai != null) {
5351                            finalList.add(ai);
5352                        }
5353                    }
5354                }
5355            }
5356        }
5357
5358        return finalList;
5359    }
5360
5361    @Override
5362    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5363        if (!sUserManager.exists(userId)) return null;
5364        // reader
5365        synchronized (mPackages) {
5366            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5367            PackageSetting ps = provider != null
5368                    ? mSettings.mPackages.get(provider.owner.packageName)
5369                    : null;
5370            return ps != null
5371                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5372                    && (!mSafeMode || (provider.info.applicationInfo.flags
5373                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5374                    ? PackageParser.generateProviderInfo(provider, flags,
5375                            ps.readUserState(userId), userId)
5376                    : null;
5377        }
5378    }
5379
5380    /**
5381     * @deprecated
5382     */
5383    @Deprecated
5384    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5385        // reader
5386        synchronized (mPackages) {
5387            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5388                    .entrySet().iterator();
5389            final int userId = UserHandle.getCallingUserId();
5390            while (i.hasNext()) {
5391                Map.Entry<String, PackageParser.Provider> entry = i.next();
5392                PackageParser.Provider p = entry.getValue();
5393                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5394
5395                if (ps != null && p.syncable
5396                        && (!mSafeMode || (p.info.applicationInfo.flags
5397                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5398                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5399                            ps.readUserState(userId), userId);
5400                    if (info != null) {
5401                        outNames.add(entry.getKey());
5402                        outInfo.add(info);
5403                    }
5404                }
5405            }
5406        }
5407    }
5408
5409    @Override
5410    public List<ProviderInfo> queryContentProviders(String processName,
5411            int uid, int flags) {
5412        ArrayList<ProviderInfo> finalList = null;
5413        // reader
5414        synchronized (mPackages) {
5415            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5416            final int userId = processName != null ?
5417                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5418            while (i.hasNext()) {
5419                final PackageParser.Provider p = i.next();
5420                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5421                if (ps != null && p.info.authority != null
5422                        && (processName == null
5423                                || (p.info.processName.equals(processName)
5424                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5425                        && mSettings.isEnabledLPr(p.info, flags, userId)
5426                        && (!mSafeMode
5427                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5428                    if (finalList == null) {
5429                        finalList = new ArrayList<ProviderInfo>(3);
5430                    }
5431                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5432                            ps.readUserState(userId), userId);
5433                    if (info != null) {
5434                        finalList.add(info);
5435                    }
5436                }
5437            }
5438        }
5439
5440        if (finalList != null) {
5441            Collections.sort(finalList, mProviderInitOrderSorter);
5442        }
5443
5444        return finalList;
5445    }
5446
5447    @Override
5448    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5449            int flags) {
5450        // reader
5451        synchronized (mPackages) {
5452            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5453            return PackageParser.generateInstrumentationInfo(i, flags);
5454        }
5455    }
5456
5457    @Override
5458    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5459            int flags) {
5460        ArrayList<InstrumentationInfo> finalList =
5461            new ArrayList<InstrumentationInfo>();
5462
5463        // reader
5464        synchronized (mPackages) {
5465            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5466            while (i.hasNext()) {
5467                final PackageParser.Instrumentation p = i.next();
5468                if (targetPackage == null
5469                        || targetPackage.equals(p.info.targetPackage)) {
5470                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5471                            flags);
5472                    if (ii != null) {
5473                        finalList.add(ii);
5474                    }
5475                }
5476            }
5477        }
5478
5479        return finalList;
5480    }
5481
5482    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5483        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5484        if (overlays == null) {
5485            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5486            return;
5487        }
5488        for (PackageParser.Package opkg : overlays.values()) {
5489            // Not much to do if idmap fails: we already logged the error
5490            // and we certainly don't want to abort installation of pkg simply
5491            // because an overlay didn't fit properly. For these reasons,
5492            // ignore the return value of createIdmapForPackagePairLI.
5493            createIdmapForPackagePairLI(pkg, opkg);
5494        }
5495    }
5496
5497    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5498            PackageParser.Package opkg) {
5499        if (!opkg.mTrustedOverlay) {
5500            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5501                    opkg.baseCodePath + ": overlay not trusted");
5502            return false;
5503        }
5504        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5505        if (overlaySet == null) {
5506            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5507                    opkg.baseCodePath + " but target package has no known overlays");
5508            return false;
5509        }
5510        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5511        // TODO: generate idmap for split APKs
5512        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5513            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5514                    + opkg.baseCodePath);
5515            return false;
5516        }
5517        PackageParser.Package[] overlayArray =
5518            overlaySet.values().toArray(new PackageParser.Package[0]);
5519        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5520            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5521                return p1.mOverlayPriority - p2.mOverlayPriority;
5522            }
5523        };
5524        Arrays.sort(overlayArray, cmp);
5525
5526        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5527        int i = 0;
5528        for (PackageParser.Package p : overlayArray) {
5529            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5530        }
5531        return true;
5532    }
5533
5534    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5535        final File[] files = dir.listFiles();
5536        if (ArrayUtils.isEmpty(files)) {
5537            Log.d(TAG, "No files in app dir " + dir);
5538            return;
5539        }
5540
5541        if (DEBUG_PACKAGE_SCANNING) {
5542            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5543                    + " flags=0x" + Integer.toHexString(parseFlags));
5544        }
5545
5546        for (File file : files) {
5547            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5548                    && !PackageInstallerService.isStageName(file.getName());
5549            if (!isPackage) {
5550                // Ignore entries which are not packages
5551                continue;
5552            }
5553            try {
5554                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5555                        scanFlags, currentTime, null);
5556            } catch (PackageManagerException e) {
5557                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5558
5559                // Delete invalid userdata apps
5560                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5561                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5562                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5563                    if (file.isDirectory()) {
5564                        mInstaller.rmPackageDir(file.getAbsolutePath());
5565                    } else {
5566                        file.delete();
5567                    }
5568                }
5569            }
5570        }
5571    }
5572
5573    private static File getSettingsProblemFile() {
5574        File dataDir = Environment.getDataDirectory();
5575        File systemDir = new File(dataDir, "system");
5576        File fname = new File(systemDir, "uiderrors.txt");
5577        return fname;
5578    }
5579
5580    static void reportSettingsProblem(int priority, String msg) {
5581        logCriticalInfo(priority, msg);
5582    }
5583
5584    static void logCriticalInfo(int priority, String msg) {
5585        Slog.println(priority, TAG, msg);
5586        EventLogTags.writePmCriticalInfo(msg);
5587        try {
5588            File fname = getSettingsProblemFile();
5589            FileOutputStream out = new FileOutputStream(fname, true);
5590            PrintWriter pw = new FastPrintWriter(out);
5591            SimpleDateFormat formatter = new SimpleDateFormat();
5592            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5593            pw.println(dateString + ": " + msg);
5594            pw.close();
5595            FileUtils.setPermissions(
5596                    fname.toString(),
5597                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5598                    -1, -1);
5599        } catch (java.io.IOException e) {
5600        }
5601    }
5602
5603    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5604            PackageParser.Package pkg, File srcFile, int parseFlags)
5605            throws PackageManagerException {
5606        if (ps != null
5607                && ps.codePath.equals(srcFile)
5608                && ps.timeStamp == srcFile.lastModified()
5609                && !isCompatSignatureUpdateNeeded(pkg)
5610                && !isRecoverSignatureUpdateNeeded(pkg)) {
5611            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5612            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5613            ArraySet<PublicKey> signingKs;
5614            synchronized (mPackages) {
5615                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5616            }
5617            if (ps.signatures.mSignatures != null
5618                    && ps.signatures.mSignatures.length != 0
5619                    && signingKs != null) {
5620                // Optimization: reuse the existing cached certificates
5621                // if the package appears to be unchanged.
5622                pkg.mSignatures = ps.signatures.mSignatures;
5623                pkg.mSigningKeys = signingKs;
5624                return;
5625            }
5626
5627            Slog.w(TAG, "PackageSetting for " + ps.name
5628                    + " is missing signatures.  Collecting certs again to recover them.");
5629        } else {
5630            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5631        }
5632
5633        try {
5634            pp.collectCertificates(pkg, parseFlags);
5635            pp.collectManifestDigest(pkg);
5636        } catch (PackageParserException e) {
5637            throw PackageManagerException.from(e);
5638        }
5639    }
5640
5641    /*
5642     *  Scan a package and return the newly parsed package.
5643     *  Returns null in case of errors and the error code is stored in mLastScanError
5644     */
5645    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5646            long currentTime, UserHandle user) throws PackageManagerException {
5647        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5648        parseFlags |= mDefParseFlags;
5649        PackageParser pp = new PackageParser();
5650        pp.setSeparateProcesses(mSeparateProcesses);
5651        pp.setOnlyCoreApps(mOnlyCore);
5652        pp.setDisplayMetrics(mMetrics);
5653
5654        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5655            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5656        }
5657
5658        final PackageParser.Package pkg;
5659        try {
5660            pkg = pp.parsePackage(scanFile, parseFlags);
5661        } catch (PackageParserException e) {
5662            throw PackageManagerException.from(e);
5663        }
5664
5665        PackageSetting ps = null;
5666        PackageSetting updatedPkg;
5667        // reader
5668        synchronized (mPackages) {
5669            // Look to see if we already know about this package.
5670            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5671            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5672                // This package has been renamed to its original name.  Let's
5673                // use that.
5674                ps = mSettings.peekPackageLPr(oldName);
5675            }
5676            // If there was no original package, see one for the real package name.
5677            if (ps == null) {
5678                ps = mSettings.peekPackageLPr(pkg.packageName);
5679            }
5680            // Check to see if this package could be hiding/updating a system
5681            // package.  Must look for it either under the original or real
5682            // package name depending on our state.
5683            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5684            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5685        }
5686        boolean updatedPkgBetter = false;
5687        // First check if this is a system package that may involve an update
5688        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5689            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5690            // it needs to drop FLAG_PRIVILEGED.
5691            if (locationIsPrivileged(scanFile)) {
5692                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5693            } else {
5694                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5695            }
5696
5697            if (ps != null && !ps.codePath.equals(scanFile)) {
5698                // The path has changed from what was last scanned...  check the
5699                // version of the new path against what we have stored to determine
5700                // what to do.
5701                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5702                if (pkg.mVersionCode <= ps.versionCode) {
5703                    // The system package has been updated and the code path does not match
5704                    // Ignore entry. Skip it.
5705                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5706                            + " ignored: updated version " + ps.versionCode
5707                            + " better than this " + pkg.mVersionCode);
5708                    if (!updatedPkg.codePath.equals(scanFile)) {
5709                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5710                                + ps.name + " changing from " + updatedPkg.codePathString
5711                                + " to " + scanFile);
5712                        updatedPkg.codePath = scanFile;
5713                        updatedPkg.codePathString = scanFile.toString();
5714                        updatedPkg.resourcePath = scanFile;
5715                        updatedPkg.resourcePathString = scanFile.toString();
5716                    }
5717                    updatedPkg.pkg = pkg;
5718                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5719                            "Package " + ps.name + " at " + scanFile
5720                                    + " ignored: updated version " + ps.versionCode
5721                                    + " better than this " + pkg.mVersionCode);
5722                } else {
5723                    // The current app on the system partition is better than
5724                    // what we have updated to on the data partition; switch
5725                    // back to the system partition version.
5726                    // At this point, its safely assumed that package installation for
5727                    // apps in system partition will go through. If not there won't be a working
5728                    // version of the app
5729                    // writer
5730                    synchronized (mPackages) {
5731                        // Just remove the loaded entries from package lists.
5732                        mPackages.remove(ps.name);
5733                    }
5734
5735                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5736                            + " reverting from " + ps.codePathString
5737                            + ": new version " + pkg.mVersionCode
5738                            + " better than installed " + ps.versionCode);
5739
5740                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5741                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5742                    synchronized (mInstallLock) {
5743                        args.cleanUpResourcesLI();
5744                    }
5745                    synchronized (mPackages) {
5746                        mSettings.enableSystemPackageLPw(ps.name);
5747                    }
5748                    updatedPkgBetter = true;
5749                }
5750            }
5751        }
5752
5753        if (updatedPkg != null) {
5754            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5755            // initially
5756            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5757
5758            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5759            // flag set initially
5760            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5761                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5762            }
5763        }
5764
5765        // Verify certificates against what was last scanned
5766        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5767
5768        /*
5769         * A new system app appeared, but we already had a non-system one of the
5770         * same name installed earlier.
5771         */
5772        boolean shouldHideSystemApp = false;
5773        if (updatedPkg == null && ps != null
5774                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5775            /*
5776             * Check to make sure the signatures match first. If they don't,
5777             * wipe the installed application and its data.
5778             */
5779            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5780                    != PackageManager.SIGNATURE_MATCH) {
5781                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5782                        + " signatures don't match existing userdata copy; removing");
5783                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5784                ps = null;
5785            } else {
5786                /*
5787                 * If the newly-added system app is an older version than the
5788                 * already installed version, hide it. It will be scanned later
5789                 * and re-added like an update.
5790                 */
5791                if (pkg.mVersionCode <= ps.versionCode) {
5792                    shouldHideSystemApp = true;
5793                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5794                            + " but new version " + pkg.mVersionCode + " better than installed "
5795                            + ps.versionCode + "; hiding system");
5796                } else {
5797                    /*
5798                     * The newly found system app is a newer version that the
5799                     * one previously installed. Simply remove the
5800                     * already-installed application and replace it with our own
5801                     * while keeping the application data.
5802                     */
5803                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5804                            + " reverting from " + ps.codePathString + ": new version "
5805                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5806                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5807                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5808                    synchronized (mInstallLock) {
5809                        args.cleanUpResourcesLI();
5810                    }
5811                }
5812            }
5813        }
5814
5815        // The apk is forward locked (not public) if its code and resources
5816        // are kept in different files. (except for app in either system or
5817        // vendor path).
5818        // TODO grab this value from PackageSettings
5819        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5820            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5821                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5822            }
5823        }
5824
5825        // TODO: extend to support forward-locked splits
5826        String resourcePath = null;
5827        String baseResourcePath = null;
5828        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5829            if (ps != null && ps.resourcePathString != null) {
5830                resourcePath = ps.resourcePathString;
5831                baseResourcePath = ps.resourcePathString;
5832            } else {
5833                // Should not happen at all. Just log an error.
5834                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5835            }
5836        } else {
5837            resourcePath = pkg.codePath;
5838            baseResourcePath = pkg.baseCodePath;
5839        }
5840
5841        // Set application objects path explicitly.
5842        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5843        pkg.applicationInfo.setCodePath(pkg.codePath);
5844        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5845        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5846        pkg.applicationInfo.setResourcePath(resourcePath);
5847        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5848        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5849
5850        // Note that we invoke the following method only if we are about to unpack an application
5851        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5852                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5853
5854        /*
5855         * If the system app should be overridden by a previously installed
5856         * data, hide the system app now and let the /data/app scan pick it up
5857         * again.
5858         */
5859        if (shouldHideSystemApp) {
5860            synchronized (mPackages) {
5861                /*
5862                 * We have to grant systems permissions before we hide, because
5863                 * grantPermissions will assume the package update is trying to
5864                 * expand its permissions.
5865                 */
5866                grantPermissionsLPw(pkg, true, pkg.packageName);
5867                mSettings.disableSystemPackageLPw(pkg.packageName);
5868            }
5869        }
5870
5871        return scannedPkg;
5872    }
5873
5874    private static String fixProcessName(String defProcessName,
5875            String processName, int uid) {
5876        if (processName == null) {
5877            return defProcessName;
5878        }
5879        return processName;
5880    }
5881
5882    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5883            throws PackageManagerException {
5884        if (pkgSetting.signatures.mSignatures != null) {
5885            // Already existing package. Make sure signatures match
5886            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5887                    == PackageManager.SIGNATURE_MATCH;
5888            if (!match) {
5889                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5890                        == PackageManager.SIGNATURE_MATCH;
5891            }
5892            if (!match) {
5893                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5894                        == PackageManager.SIGNATURE_MATCH;
5895            }
5896            if (!match) {
5897                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5898                        + pkg.packageName + " signatures do not match the "
5899                        + "previously installed version; ignoring!");
5900            }
5901        }
5902
5903        // Check for shared user signatures
5904        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5905            // Already existing package. Make sure signatures match
5906            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5907                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5908            if (!match) {
5909                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5910                        == PackageManager.SIGNATURE_MATCH;
5911            }
5912            if (!match) {
5913                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5914                        == PackageManager.SIGNATURE_MATCH;
5915            }
5916            if (!match) {
5917                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5918                        "Package " + pkg.packageName
5919                        + " has no signatures that match those in shared user "
5920                        + pkgSetting.sharedUser.name + "; ignoring!");
5921            }
5922        }
5923    }
5924
5925    /**
5926     * Enforces that only the system UID or root's UID can call a method exposed
5927     * via Binder.
5928     *
5929     * @param message used as message if SecurityException is thrown
5930     * @throws SecurityException if the caller is not system or root
5931     */
5932    private static final void enforceSystemOrRoot(String message) {
5933        final int uid = Binder.getCallingUid();
5934        if (uid != Process.SYSTEM_UID && uid != 0) {
5935            throw new SecurityException(message);
5936        }
5937    }
5938
5939    @Override
5940    public void performBootDexOpt() {
5941        enforceSystemOrRoot("Only the system can request dexopt be performed");
5942
5943        // Before everything else, see whether we need to fstrim.
5944        try {
5945            IMountService ms = PackageHelper.getMountService();
5946            if (ms != null) {
5947                final boolean isUpgrade = isUpgrade();
5948                boolean doTrim = isUpgrade;
5949                if (doTrim) {
5950                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5951                } else {
5952                    final long interval = android.provider.Settings.Global.getLong(
5953                            mContext.getContentResolver(),
5954                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5955                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5956                    if (interval > 0) {
5957                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5958                        if (timeSinceLast > interval) {
5959                            doTrim = true;
5960                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5961                                    + "; running immediately");
5962                        }
5963                    }
5964                }
5965                if (doTrim) {
5966                    if (!isFirstBoot()) {
5967                        try {
5968                            ActivityManagerNative.getDefault().showBootMessage(
5969                                    mContext.getResources().getString(
5970                                            R.string.android_upgrading_fstrim), true);
5971                        } catch (RemoteException e) {
5972                        }
5973                    }
5974                    ms.runMaintenance();
5975                }
5976            } else {
5977                Slog.e(TAG, "Mount service unavailable!");
5978            }
5979        } catch (RemoteException e) {
5980            // Can't happen; MountService is local
5981        }
5982
5983        final ArraySet<PackageParser.Package> pkgs;
5984        synchronized (mPackages) {
5985            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5986        }
5987
5988        if (pkgs != null) {
5989            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5990            // in case the device runs out of space.
5991            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5992            // Give priority to core apps.
5993            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5994                PackageParser.Package pkg = it.next();
5995                if (pkg.coreApp) {
5996                    if (DEBUG_DEXOPT) {
5997                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5998                    }
5999                    sortedPkgs.add(pkg);
6000                    it.remove();
6001                }
6002            }
6003            // Give priority to system apps that listen for pre boot complete.
6004            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6005            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6006            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6007                PackageParser.Package pkg = it.next();
6008                if (pkgNames.contains(pkg.packageName)) {
6009                    if (DEBUG_DEXOPT) {
6010                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6011                    }
6012                    sortedPkgs.add(pkg);
6013                    it.remove();
6014                }
6015            }
6016            // Give priority to system apps.
6017            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6018                PackageParser.Package pkg = it.next();
6019                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6020                    if (DEBUG_DEXOPT) {
6021                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6022                    }
6023                    sortedPkgs.add(pkg);
6024                    it.remove();
6025                }
6026            }
6027            // Give priority to updated system apps.
6028            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6029                PackageParser.Package pkg = it.next();
6030                if (pkg.isUpdatedSystemApp()) {
6031                    if (DEBUG_DEXOPT) {
6032                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6033                    }
6034                    sortedPkgs.add(pkg);
6035                    it.remove();
6036                }
6037            }
6038            // Give priority to apps that listen for boot complete.
6039            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6040            pkgNames = getPackageNamesForIntent(intent);
6041            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6042                PackageParser.Package pkg = it.next();
6043                if (pkgNames.contains(pkg.packageName)) {
6044                    if (DEBUG_DEXOPT) {
6045                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6046                    }
6047                    sortedPkgs.add(pkg);
6048                    it.remove();
6049                }
6050            }
6051            // Filter out packages that aren't recently used.
6052            filterRecentlyUsedApps(pkgs);
6053            // Add all remaining apps.
6054            for (PackageParser.Package pkg : pkgs) {
6055                if (DEBUG_DEXOPT) {
6056                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6057                }
6058                sortedPkgs.add(pkg);
6059            }
6060
6061            // If we want to be lazy, filter everything that wasn't recently used.
6062            if (mLazyDexOpt) {
6063                filterRecentlyUsedApps(sortedPkgs);
6064            }
6065
6066            int i = 0;
6067            int total = sortedPkgs.size();
6068            File dataDir = Environment.getDataDirectory();
6069            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6070            if (lowThreshold == 0) {
6071                throw new IllegalStateException("Invalid low memory threshold");
6072            }
6073            for (PackageParser.Package pkg : sortedPkgs) {
6074                long usableSpace = dataDir.getUsableSpace();
6075                if (usableSpace < lowThreshold) {
6076                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6077                    break;
6078                }
6079                performBootDexOpt(pkg, ++i, total);
6080            }
6081        }
6082    }
6083
6084    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6085        // Filter out packages that aren't recently used.
6086        //
6087        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6088        // should do a full dexopt.
6089        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6090            int total = pkgs.size();
6091            int skipped = 0;
6092            long now = System.currentTimeMillis();
6093            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6094                PackageParser.Package pkg = i.next();
6095                long then = pkg.mLastPackageUsageTimeInMills;
6096                if (then + mDexOptLRUThresholdInMills < now) {
6097                    if (DEBUG_DEXOPT) {
6098                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6099                              ((then == 0) ? "never" : new Date(then)));
6100                    }
6101                    i.remove();
6102                    skipped++;
6103                }
6104            }
6105            if (DEBUG_DEXOPT) {
6106                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6107            }
6108        }
6109    }
6110
6111    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6112        List<ResolveInfo> ris = null;
6113        try {
6114            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6115                    intent, null, 0, UserHandle.USER_OWNER);
6116        } catch (RemoteException e) {
6117        }
6118        ArraySet<String> pkgNames = new ArraySet<String>();
6119        if (ris != null) {
6120            for (ResolveInfo ri : ris) {
6121                pkgNames.add(ri.activityInfo.packageName);
6122            }
6123        }
6124        return pkgNames;
6125    }
6126
6127    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6128        if (DEBUG_DEXOPT) {
6129            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6130        }
6131        if (!isFirstBoot()) {
6132            try {
6133                ActivityManagerNative.getDefault().showBootMessage(
6134                        mContext.getResources().getString(R.string.android_upgrading_apk,
6135                                curr, total), true);
6136            } catch (RemoteException e) {
6137            }
6138        }
6139        PackageParser.Package p = pkg;
6140        synchronized (mInstallLock) {
6141            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6142                    false /* force dex */, false /* defer */, true /* include dependencies */);
6143        }
6144    }
6145
6146    @Override
6147    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6148        return performDexOpt(packageName, instructionSet, false);
6149    }
6150
6151    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6152        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6153        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6154        if (!dexopt && !updateUsage) {
6155            // We aren't going to dexopt or update usage, so bail early.
6156            return false;
6157        }
6158        PackageParser.Package p;
6159        final String targetInstructionSet;
6160        synchronized (mPackages) {
6161            p = mPackages.get(packageName);
6162            if (p == null) {
6163                return false;
6164            }
6165            if (updateUsage) {
6166                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6167            }
6168            mPackageUsage.write(false);
6169            if (!dexopt) {
6170                // We aren't going to dexopt, so bail early.
6171                return false;
6172            }
6173
6174            targetInstructionSet = instructionSet != null ? instructionSet :
6175                    getPrimaryInstructionSet(p.applicationInfo);
6176            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6177                return false;
6178            }
6179        }
6180        long callingId = Binder.clearCallingIdentity();
6181        try {
6182            synchronized (mInstallLock) {
6183                final String[] instructionSets = new String[] { targetInstructionSet };
6184                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6185                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6186                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6187            }
6188        } finally {
6189            Binder.restoreCallingIdentity(callingId);
6190        }
6191    }
6192
6193    public ArraySet<String> getPackagesThatNeedDexOpt() {
6194        ArraySet<String> pkgs = null;
6195        synchronized (mPackages) {
6196            for (PackageParser.Package p : mPackages.values()) {
6197                if (DEBUG_DEXOPT) {
6198                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6199                }
6200                if (!p.mDexOptPerformed.isEmpty()) {
6201                    continue;
6202                }
6203                if (pkgs == null) {
6204                    pkgs = new ArraySet<String>();
6205                }
6206                pkgs.add(p.packageName);
6207            }
6208        }
6209        return pkgs;
6210    }
6211
6212    public void shutdown() {
6213        mPackageUsage.write(true);
6214    }
6215
6216    @Override
6217    public void forceDexOpt(String packageName) {
6218        enforceSystemOrRoot("forceDexOpt");
6219
6220        PackageParser.Package pkg;
6221        synchronized (mPackages) {
6222            pkg = mPackages.get(packageName);
6223            if (pkg == null) {
6224                throw new IllegalArgumentException("Missing package: " + packageName);
6225            }
6226        }
6227
6228        synchronized (mInstallLock) {
6229            final String[] instructionSets = new String[] {
6230                    getPrimaryInstructionSet(pkg.applicationInfo) };
6231            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6232                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6233            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6234                throw new IllegalStateException("Failed to dexopt: " + res);
6235            }
6236        }
6237    }
6238
6239    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6240        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6241            Slog.w(TAG, "Unable to update from " + oldPkg.name
6242                    + " to " + newPkg.packageName
6243                    + ": old package not in system partition");
6244            return false;
6245        } else if (mPackages.get(oldPkg.name) != null) {
6246            Slog.w(TAG, "Unable to update from " + oldPkg.name
6247                    + " to " + newPkg.packageName
6248                    + ": old package still exists");
6249            return false;
6250        }
6251        return true;
6252    }
6253
6254    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6255        int[] users = sUserManager.getUserIds();
6256        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6257        if (res < 0) {
6258            return res;
6259        }
6260        for (int user : users) {
6261            if (user != 0) {
6262                res = mInstaller.createUserData(volumeUuid, packageName,
6263                        UserHandle.getUid(user, uid), user, seinfo);
6264                if (res < 0) {
6265                    return res;
6266                }
6267            }
6268        }
6269        return res;
6270    }
6271
6272    private int removeDataDirsLI(String volumeUuid, String packageName) {
6273        int[] users = sUserManager.getUserIds();
6274        int res = 0;
6275        for (int user : users) {
6276            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6277            if (resInner < 0) {
6278                res = resInner;
6279            }
6280        }
6281
6282        return res;
6283    }
6284
6285    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6286        int[] users = sUserManager.getUserIds();
6287        int res = 0;
6288        for (int user : users) {
6289            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6290            if (resInner < 0) {
6291                res = resInner;
6292            }
6293        }
6294        return res;
6295    }
6296
6297    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6298            PackageParser.Package changingLib) {
6299        if (file.path != null) {
6300            usesLibraryFiles.add(file.path);
6301            return;
6302        }
6303        PackageParser.Package p = mPackages.get(file.apk);
6304        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6305            // If we are doing this while in the middle of updating a library apk,
6306            // then we need to make sure to use that new apk for determining the
6307            // dependencies here.  (We haven't yet finished committing the new apk
6308            // to the package manager state.)
6309            if (p == null || p.packageName.equals(changingLib.packageName)) {
6310                p = changingLib;
6311            }
6312        }
6313        if (p != null) {
6314            usesLibraryFiles.addAll(p.getAllCodePaths());
6315        }
6316    }
6317
6318    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6319            PackageParser.Package changingLib) throws PackageManagerException {
6320        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6321            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6322            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6323            for (int i=0; i<N; i++) {
6324                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6325                if (file == null) {
6326                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6327                            "Package " + pkg.packageName + " requires unavailable shared library "
6328                            + pkg.usesLibraries.get(i) + "; failing!");
6329                }
6330                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6331            }
6332            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6333            for (int i=0; i<N; i++) {
6334                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6335                if (file == null) {
6336                    Slog.w(TAG, "Package " + pkg.packageName
6337                            + " desires unavailable shared library "
6338                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6339                } else {
6340                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6341                }
6342            }
6343            N = usesLibraryFiles.size();
6344            if (N > 0) {
6345                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6346            } else {
6347                pkg.usesLibraryFiles = null;
6348            }
6349        }
6350    }
6351
6352    private static boolean hasString(List<String> list, List<String> which) {
6353        if (list == null) {
6354            return false;
6355        }
6356        for (int i=list.size()-1; i>=0; i--) {
6357            for (int j=which.size()-1; j>=0; j--) {
6358                if (which.get(j).equals(list.get(i))) {
6359                    return true;
6360                }
6361            }
6362        }
6363        return false;
6364    }
6365
6366    private void updateAllSharedLibrariesLPw() {
6367        for (PackageParser.Package pkg : mPackages.values()) {
6368            try {
6369                updateSharedLibrariesLPw(pkg, null);
6370            } catch (PackageManagerException e) {
6371                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6372            }
6373        }
6374    }
6375
6376    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6377            PackageParser.Package changingPkg) {
6378        ArrayList<PackageParser.Package> res = null;
6379        for (PackageParser.Package pkg : mPackages.values()) {
6380            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6381                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6382                if (res == null) {
6383                    res = new ArrayList<PackageParser.Package>();
6384                }
6385                res.add(pkg);
6386                try {
6387                    updateSharedLibrariesLPw(pkg, changingPkg);
6388                } catch (PackageManagerException e) {
6389                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6390                }
6391            }
6392        }
6393        return res;
6394    }
6395
6396    /**
6397     * Derive the value of the {@code cpuAbiOverride} based on the provided
6398     * value and an optional stored value from the package settings.
6399     */
6400    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6401        String cpuAbiOverride = null;
6402
6403        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6404            cpuAbiOverride = null;
6405        } else if (abiOverride != null) {
6406            cpuAbiOverride = abiOverride;
6407        } else if (settings != null) {
6408            cpuAbiOverride = settings.cpuAbiOverrideString;
6409        }
6410
6411        return cpuAbiOverride;
6412    }
6413
6414    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6415            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6416        boolean success = false;
6417        try {
6418            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6419                    currentTime, user);
6420            success = true;
6421            return res;
6422        } finally {
6423            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6424                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6425            }
6426        }
6427    }
6428
6429    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6430            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6431        final File scanFile = new File(pkg.codePath);
6432        if (pkg.applicationInfo.getCodePath() == null ||
6433                pkg.applicationInfo.getResourcePath() == null) {
6434            // Bail out. The resource and code paths haven't been set.
6435            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6436                    "Code and resource paths haven't been set correctly");
6437        }
6438
6439        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6440            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6441        } else {
6442            // Only allow system apps to be flagged as core apps.
6443            pkg.coreApp = false;
6444        }
6445
6446        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6447            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6448        }
6449
6450        if (mCustomResolverComponentName != null &&
6451                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6452            setUpCustomResolverActivity(pkg);
6453        }
6454
6455        if (pkg.packageName.equals("android")) {
6456            synchronized (mPackages) {
6457                if (mAndroidApplication != null) {
6458                    Slog.w(TAG, "*************************************************");
6459                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6460                    Slog.w(TAG, " file=" + scanFile);
6461                    Slog.w(TAG, "*************************************************");
6462                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6463                            "Core android package being redefined.  Skipping.");
6464                }
6465
6466                // Set up information for our fall-back user intent resolution activity.
6467                mPlatformPackage = pkg;
6468                pkg.mVersionCode = mSdkVersion;
6469                mAndroidApplication = pkg.applicationInfo;
6470
6471                if (!mResolverReplaced) {
6472                    mResolveActivity.applicationInfo = mAndroidApplication;
6473                    mResolveActivity.name = ResolverActivity.class.getName();
6474                    mResolveActivity.packageName = mAndroidApplication.packageName;
6475                    mResolveActivity.processName = "system:ui";
6476                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6477                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6478                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6479                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6480                    mResolveActivity.exported = true;
6481                    mResolveActivity.enabled = true;
6482                    mResolveInfo.activityInfo = mResolveActivity;
6483                    mResolveInfo.priority = 0;
6484                    mResolveInfo.preferredOrder = 0;
6485                    mResolveInfo.match = 0;
6486                    mResolveComponentName = new ComponentName(
6487                            mAndroidApplication.packageName, mResolveActivity.name);
6488                }
6489            }
6490        }
6491
6492        if (DEBUG_PACKAGE_SCANNING) {
6493            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6494                Log.d(TAG, "Scanning package " + pkg.packageName);
6495        }
6496
6497        if (mPackages.containsKey(pkg.packageName)
6498                || mSharedLibraries.containsKey(pkg.packageName)) {
6499            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6500                    "Application package " + pkg.packageName
6501                    + " already installed.  Skipping duplicate.");
6502        }
6503
6504        // If we're only installing presumed-existing packages, require that the
6505        // scanned APK is both already known and at the path previously established
6506        // for it.  Previously unknown packages we pick up normally, but if we have an
6507        // a priori expectation about this package's install presence, enforce it.
6508        // With a singular exception for new system packages. When an OTA contains
6509        // a new system package, we allow the codepath to change from a system location
6510        // to the user-installed location. If we don't allow this change, any newer,
6511        // user-installed version of the application will be ignored.
6512        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6513            if (mExpectingBetter.containsKey(pkg.packageName)) {
6514                logCriticalInfo(Log.WARN,
6515                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6516            } else {
6517                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6518                if (known != null) {
6519                    if (DEBUG_PACKAGE_SCANNING) {
6520                        Log.d(TAG, "Examining " + pkg.codePath
6521                                + " and requiring known paths " + known.codePathString
6522                                + " & " + known.resourcePathString);
6523                    }
6524                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6525                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6526                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6527                                "Application package " + pkg.packageName
6528                                + " found at " + pkg.applicationInfo.getCodePath()
6529                                + " but expected at " + known.codePathString + "; ignoring.");
6530                    }
6531                }
6532            }
6533        }
6534
6535        // Initialize package source and resource directories
6536        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6537        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6538
6539        SharedUserSetting suid = null;
6540        PackageSetting pkgSetting = null;
6541
6542        if (!isSystemApp(pkg)) {
6543            // Only system apps can use these features.
6544            pkg.mOriginalPackages = null;
6545            pkg.mRealPackage = null;
6546            pkg.mAdoptPermissions = null;
6547        }
6548
6549        // writer
6550        synchronized (mPackages) {
6551            if (pkg.mSharedUserId != null) {
6552                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6553                if (suid == null) {
6554                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6555                            "Creating application package " + pkg.packageName
6556                            + " for shared user failed");
6557                }
6558                if (DEBUG_PACKAGE_SCANNING) {
6559                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6560                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6561                                + "): packages=" + suid.packages);
6562                }
6563            }
6564
6565            // Check if we are renaming from an original package name.
6566            PackageSetting origPackage = null;
6567            String realName = null;
6568            if (pkg.mOriginalPackages != null) {
6569                // This package may need to be renamed to a previously
6570                // installed name.  Let's check on that...
6571                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6572                if (pkg.mOriginalPackages.contains(renamed)) {
6573                    // This package had originally been installed as the
6574                    // original name, and we have already taken care of
6575                    // transitioning to the new one.  Just update the new
6576                    // one to continue using the old name.
6577                    realName = pkg.mRealPackage;
6578                    if (!pkg.packageName.equals(renamed)) {
6579                        // Callers into this function may have already taken
6580                        // care of renaming the package; only do it here if
6581                        // it is not already done.
6582                        pkg.setPackageName(renamed);
6583                    }
6584
6585                } else {
6586                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6587                        if ((origPackage = mSettings.peekPackageLPr(
6588                                pkg.mOriginalPackages.get(i))) != null) {
6589                            // We do have the package already installed under its
6590                            // original name...  should we use it?
6591                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6592                                // New package is not compatible with original.
6593                                origPackage = null;
6594                                continue;
6595                            } else if (origPackage.sharedUser != null) {
6596                                // Make sure uid is compatible between packages.
6597                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6598                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6599                                            + " to " + pkg.packageName + ": old uid "
6600                                            + origPackage.sharedUser.name
6601                                            + " differs from " + pkg.mSharedUserId);
6602                                    origPackage = null;
6603                                    continue;
6604                                }
6605                            } else {
6606                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6607                                        + pkg.packageName + " to old name " + origPackage.name);
6608                            }
6609                            break;
6610                        }
6611                    }
6612                }
6613            }
6614
6615            if (mTransferedPackages.contains(pkg.packageName)) {
6616                Slog.w(TAG, "Package " + pkg.packageName
6617                        + " was transferred to another, but its .apk remains");
6618            }
6619
6620            // Just create the setting, don't add it yet. For already existing packages
6621            // the PkgSetting exists already and doesn't have to be created.
6622            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6623                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6624                    pkg.applicationInfo.primaryCpuAbi,
6625                    pkg.applicationInfo.secondaryCpuAbi,
6626                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6627                    user, false);
6628            if (pkgSetting == null) {
6629                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6630                        "Creating application package " + pkg.packageName + " failed");
6631            }
6632
6633            if (pkgSetting.origPackage != null) {
6634                // If we are first transitioning from an original package,
6635                // fix up the new package's name now.  We need to do this after
6636                // looking up the package under its new name, so getPackageLP
6637                // can take care of fiddling things correctly.
6638                pkg.setPackageName(origPackage.name);
6639
6640                // File a report about this.
6641                String msg = "New package " + pkgSetting.realName
6642                        + " renamed to replace old package " + pkgSetting.name;
6643                reportSettingsProblem(Log.WARN, msg);
6644
6645                // Make a note of it.
6646                mTransferedPackages.add(origPackage.name);
6647
6648                // No longer need to retain this.
6649                pkgSetting.origPackage = null;
6650            }
6651
6652            if (realName != null) {
6653                // Make a note of it.
6654                mTransferedPackages.add(pkg.packageName);
6655            }
6656
6657            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6658                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6659            }
6660
6661            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6662                // Check all shared libraries and map to their actual file path.
6663                // We only do this here for apps not on a system dir, because those
6664                // are the only ones that can fail an install due to this.  We
6665                // will take care of the system apps by updating all of their
6666                // library paths after the scan is done.
6667                updateSharedLibrariesLPw(pkg, null);
6668            }
6669
6670            if (mFoundPolicyFile) {
6671                SELinuxMMAC.assignSeinfoValue(pkg);
6672            }
6673
6674            pkg.applicationInfo.uid = pkgSetting.appId;
6675            pkg.mExtras = pkgSetting;
6676            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6677                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6678                    // We just determined the app is signed correctly, so bring
6679                    // over the latest parsed certs.
6680                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6681                } else {
6682                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6683                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6684                                "Package " + pkg.packageName + " upgrade keys do not match the "
6685                                + "previously installed version");
6686                    } else {
6687                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6688                        String msg = "System package " + pkg.packageName
6689                            + " signature changed; retaining data.";
6690                        reportSettingsProblem(Log.WARN, msg);
6691                    }
6692                }
6693            } else {
6694                try {
6695                    verifySignaturesLP(pkgSetting, pkg);
6696                    // We just determined the app is signed correctly, so bring
6697                    // over the latest parsed certs.
6698                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6699                } catch (PackageManagerException e) {
6700                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6701                        throw e;
6702                    }
6703                    // The signature has changed, but this package is in the system
6704                    // image...  let's recover!
6705                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6706                    // However...  if this package is part of a shared user, but it
6707                    // doesn't match the signature of the shared user, let's fail.
6708                    // What this means is that you can't change the signatures
6709                    // associated with an overall shared user, which doesn't seem all
6710                    // that unreasonable.
6711                    if (pkgSetting.sharedUser != null) {
6712                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6713                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6714                            throw new PackageManagerException(
6715                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6716                                            "Signature mismatch for shared user : "
6717                                            + pkgSetting.sharedUser);
6718                        }
6719                    }
6720                    // File a report about this.
6721                    String msg = "System package " + pkg.packageName
6722                        + " signature changed; retaining data.";
6723                    reportSettingsProblem(Log.WARN, msg);
6724                }
6725            }
6726            // Verify that this new package doesn't have any content providers
6727            // that conflict with existing packages.  Only do this if the
6728            // package isn't already installed, since we don't want to break
6729            // things that are installed.
6730            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6731                final int N = pkg.providers.size();
6732                int i;
6733                for (i=0; i<N; i++) {
6734                    PackageParser.Provider p = pkg.providers.get(i);
6735                    if (p.info.authority != null) {
6736                        String names[] = p.info.authority.split(";");
6737                        for (int j = 0; j < names.length; j++) {
6738                            if (mProvidersByAuthority.containsKey(names[j])) {
6739                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6740                                final String otherPackageName =
6741                                        ((other != null && other.getComponentName() != null) ?
6742                                                other.getComponentName().getPackageName() : "?");
6743                                throw new PackageManagerException(
6744                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6745                                                "Can't install because provider name " + names[j]
6746                                                + " (in package " + pkg.applicationInfo.packageName
6747                                                + ") is already used by " + otherPackageName);
6748                            }
6749                        }
6750                    }
6751                }
6752            }
6753
6754            if (pkg.mAdoptPermissions != null) {
6755                // This package wants to adopt ownership of permissions from
6756                // another package.
6757                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6758                    final String origName = pkg.mAdoptPermissions.get(i);
6759                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6760                    if (orig != null) {
6761                        if (verifyPackageUpdateLPr(orig, pkg)) {
6762                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6763                                    + pkg.packageName);
6764                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6765                        }
6766                    }
6767                }
6768            }
6769        }
6770
6771        final String pkgName = pkg.packageName;
6772
6773        final long scanFileTime = scanFile.lastModified();
6774        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6775        pkg.applicationInfo.processName = fixProcessName(
6776                pkg.applicationInfo.packageName,
6777                pkg.applicationInfo.processName,
6778                pkg.applicationInfo.uid);
6779
6780        File dataPath;
6781        if (mPlatformPackage == pkg) {
6782            // The system package is special.
6783            dataPath = new File(Environment.getDataDirectory(), "system");
6784
6785            pkg.applicationInfo.dataDir = dataPath.getPath();
6786
6787        } else {
6788            // This is a normal package, need to make its data directory.
6789            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6790                    UserHandle.USER_OWNER, pkg.packageName);
6791
6792            boolean uidError = false;
6793            if (dataPath.exists()) {
6794                int currentUid = 0;
6795                try {
6796                    StructStat stat = Os.stat(dataPath.getPath());
6797                    currentUid = stat.st_uid;
6798                } catch (ErrnoException e) {
6799                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6800                }
6801
6802                // If we have mismatched owners for the data path, we have a problem.
6803                if (currentUid != pkg.applicationInfo.uid) {
6804                    boolean recovered = false;
6805                    if (currentUid == 0) {
6806                        // The directory somehow became owned by root.  Wow.
6807                        // This is probably because the system was stopped while
6808                        // installd was in the middle of messing with its libs
6809                        // directory.  Ask installd to fix that.
6810                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6811                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6812                        if (ret >= 0) {
6813                            recovered = true;
6814                            String msg = "Package " + pkg.packageName
6815                                    + " unexpectedly changed to uid 0; recovered to " +
6816                                    + pkg.applicationInfo.uid;
6817                            reportSettingsProblem(Log.WARN, msg);
6818                        }
6819                    }
6820                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6821                            || (scanFlags&SCAN_BOOTING) != 0)) {
6822                        // If this is a system app, we can at least delete its
6823                        // current data so the application will still work.
6824                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6825                        if (ret >= 0) {
6826                            // TODO: Kill the processes first
6827                            // Old data gone!
6828                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6829                                    ? "System package " : "Third party package ";
6830                            String msg = prefix + pkg.packageName
6831                                    + " has changed from uid: "
6832                                    + currentUid + " to "
6833                                    + pkg.applicationInfo.uid + "; old data erased";
6834                            reportSettingsProblem(Log.WARN, msg);
6835                            recovered = true;
6836
6837                            // And now re-install the app.
6838                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6839                                    pkg.applicationInfo.seinfo);
6840                            if (ret == -1) {
6841                                // Ack should not happen!
6842                                msg = prefix + pkg.packageName
6843                                        + " could not have data directory re-created after delete.";
6844                                reportSettingsProblem(Log.WARN, msg);
6845                                throw new PackageManagerException(
6846                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6847                            }
6848                        }
6849                        if (!recovered) {
6850                            mHasSystemUidErrors = true;
6851                        }
6852                    } else if (!recovered) {
6853                        // If we allow this install to proceed, we will be broken.
6854                        // Abort, abort!
6855                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6856                                "scanPackageLI");
6857                    }
6858                    if (!recovered) {
6859                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6860                            + pkg.applicationInfo.uid + "/fs_"
6861                            + currentUid;
6862                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6863                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6864                        String msg = "Package " + pkg.packageName
6865                                + " has mismatched uid: "
6866                                + currentUid + " on disk, "
6867                                + pkg.applicationInfo.uid + " in settings";
6868                        // writer
6869                        synchronized (mPackages) {
6870                            mSettings.mReadMessages.append(msg);
6871                            mSettings.mReadMessages.append('\n');
6872                            uidError = true;
6873                            if (!pkgSetting.uidError) {
6874                                reportSettingsProblem(Log.ERROR, msg);
6875                            }
6876                        }
6877                    }
6878                }
6879                pkg.applicationInfo.dataDir = dataPath.getPath();
6880                if (mShouldRestoreconData) {
6881                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6882                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6883                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6884                }
6885            } else {
6886                if (DEBUG_PACKAGE_SCANNING) {
6887                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6888                        Log.v(TAG, "Want this data dir: " + dataPath);
6889                }
6890                //invoke installer to do the actual installation
6891                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6892                        pkg.applicationInfo.seinfo);
6893                if (ret < 0) {
6894                    // Error from installer
6895                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6896                            "Unable to create data dirs [errorCode=" + ret + "]");
6897                }
6898
6899                if (dataPath.exists()) {
6900                    pkg.applicationInfo.dataDir = dataPath.getPath();
6901                } else {
6902                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6903                    pkg.applicationInfo.dataDir = null;
6904                }
6905            }
6906
6907            pkgSetting.uidError = uidError;
6908        }
6909
6910        final String path = scanFile.getPath();
6911        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6912
6913        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6914            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6915
6916            // Some system apps still use directory structure for native libraries
6917            // in which case we might end up not detecting abi solely based on apk
6918            // structure. Try to detect abi based on directory structure.
6919            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6920                    pkg.applicationInfo.primaryCpuAbi == null) {
6921                setBundledAppAbisAndRoots(pkg, pkgSetting);
6922                setNativeLibraryPaths(pkg);
6923            }
6924
6925        } else {
6926            if ((scanFlags & SCAN_MOVE) != 0) {
6927                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6928                // but we already have this packages package info in the PackageSetting. We just
6929                // use that and derive the native library path based on the new codepath.
6930                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6931                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6932            }
6933
6934            // Set native library paths again. For moves, the path will be updated based on the
6935            // ABIs we've determined above. For non-moves, the path will be updated based on the
6936            // ABIs we determined during compilation, but the path will depend on the final
6937            // package path (after the rename away from the stage path).
6938            setNativeLibraryPaths(pkg);
6939        }
6940
6941        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6942        final int[] userIds = sUserManager.getUserIds();
6943        synchronized (mInstallLock) {
6944            // Make sure all user data directories are ready to roll; we're okay
6945            // if they already exist
6946            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6947                for (int userId : userIds) {
6948                    if (userId != 0) {
6949                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6950                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6951                                pkg.applicationInfo.seinfo);
6952                    }
6953                }
6954            }
6955
6956            // Create a native library symlink only if we have native libraries
6957            // and if the native libraries are 32 bit libraries. We do not provide
6958            // this symlink for 64 bit libraries.
6959            if (pkg.applicationInfo.primaryCpuAbi != null &&
6960                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6961                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6962                for (int userId : userIds) {
6963                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6964                            nativeLibPath, userId) < 0) {
6965                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6966                                "Failed linking native library dir (user=" + userId + ")");
6967                    }
6968                }
6969            }
6970        }
6971
6972        // This is a special case for the "system" package, where the ABI is
6973        // dictated by the zygote configuration (and init.rc). We should keep track
6974        // of this ABI so that we can deal with "normal" applications that run under
6975        // the same UID correctly.
6976        if (mPlatformPackage == pkg) {
6977            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6978                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6979        }
6980
6981        // If there's a mismatch between the abi-override in the package setting
6982        // and the abiOverride specified for the install. Warn about this because we
6983        // would've already compiled the app without taking the package setting into
6984        // account.
6985        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6986            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6987                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6988                        " for package: " + pkg.packageName);
6989            }
6990        }
6991
6992        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6993        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6994        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6995
6996        // Copy the derived override back to the parsed package, so that we can
6997        // update the package settings accordingly.
6998        pkg.cpuAbiOverride = cpuAbiOverride;
6999
7000        if (DEBUG_ABI_SELECTION) {
7001            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7002                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7003                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7004        }
7005
7006        // Push the derived path down into PackageSettings so we know what to
7007        // clean up at uninstall time.
7008        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7009
7010        if (DEBUG_ABI_SELECTION) {
7011            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7012                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7013                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7014        }
7015
7016        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7017            // We don't do this here during boot because we can do it all
7018            // at once after scanning all existing packages.
7019            //
7020            // We also do this *before* we perform dexopt on this package, so that
7021            // we can avoid redundant dexopts, and also to make sure we've got the
7022            // code and package path correct.
7023            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7024                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7025        }
7026
7027        if ((scanFlags & SCAN_NO_DEX) == 0) {
7028            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7029                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7030            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7031                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7032            }
7033        }
7034        if (mFactoryTest && pkg.requestedPermissions.contains(
7035                android.Manifest.permission.FACTORY_TEST)) {
7036            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7037        }
7038
7039        ArrayList<PackageParser.Package> clientLibPkgs = null;
7040
7041        // writer
7042        synchronized (mPackages) {
7043            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7044                // Only system apps can add new shared libraries.
7045                if (pkg.libraryNames != null) {
7046                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7047                        String name = pkg.libraryNames.get(i);
7048                        boolean allowed = false;
7049                        if (pkg.isUpdatedSystemApp()) {
7050                            // New library entries can only be added through the
7051                            // system image.  This is important to get rid of a lot
7052                            // of nasty edge cases: for example if we allowed a non-
7053                            // system update of the app to add a library, then uninstalling
7054                            // the update would make the library go away, and assumptions
7055                            // we made such as through app install filtering would now
7056                            // have allowed apps on the device which aren't compatible
7057                            // with it.  Better to just have the restriction here, be
7058                            // conservative, and create many fewer cases that can negatively
7059                            // impact the user experience.
7060                            final PackageSetting sysPs = mSettings
7061                                    .getDisabledSystemPkgLPr(pkg.packageName);
7062                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7063                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7064                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7065                                        allowed = true;
7066                                        allowed = true;
7067                                        break;
7068                                    }
7069                                }
7070                            }
7071                        } else {
7072                            allowed = true;
7073                        }
7074                        if (allowed) {
7075                            if (!mSharedLibraries.containsKey(name)) {
7076                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7077                            } else if (!name.equals(pkg.packageName)) {
7078                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7079                                        + name + " already exists; skipping");
7080                            }
7081                        } else {
7082                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7083                                    + name + " that is not declared on system image; skipping");
7084                        }
7085                    }
7086                    if ((scanFlags&SCAN_BOOTING) == 0) {
7087                        // If we are not booting, we need to update any applications
7088                        // that are clients of our shared library.  If we are booting,
7089                        // this will all be done once the scan is complete.
7090                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7091                    }
7092                }
7093            }
7094        }
7095
7096        // We also need to dexopt any apps that are dependent on this library.  Note that
7097        // if these fail, we should abort the install since installing the library will
7098        // result in some apps being broken.
7099        if (clientLibPkgs != null) {
7100            if ((scanFlags & SCAN_NO_DEX) == 0) {
7101                for (int i = 0; i < clientLibPkgs.size(); i++) {
7102                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7103                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7104                            null /* instruction sets */, forceDex,
7105                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7106                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7107                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7108                                "scanPackageLI failed to dexopt clientLibPkgs");
7109                    }
7110                }
7111            }
7112        }
7113
7114        // Also need to kill any apps that are dependent on the library.
7115        if (clientLibPkgs != null) {
7116            for (int i=0; i<clientLibPkgs.size(); i++) {
7117                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7118                killApplication(clientPkg.applicationInfo.packageName,
7119                        clientPkg.applicationInfo.uid, "update lib");
7120            }
7121        }
7122
7123        // Make sure we're not adding any bogus keyset info
7124        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7125        ksms.assertScannedPackageValid(pkg);
7126
7127        // writer
7128        synchronized (mPackages) {
7129            // We don't expect installation to fail beyond this point
7130
7131            // Add the new setting to mSettings
7132            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7133            // Add the new setting to mPackages
7134            mPackages.put(pkg.applicationInfo.packageName, pkg);
7135            // Make sure we don't accidentally delete its data.
7136            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7137            while (iter.hasNext()) {
7138                PackageCleanItem item = iter.next();
7139                if (pkgName.equals(item.packageName)) {
7140                    iter.remove();
7141                }
7142            }
7143
7144            // Take care of first install / last update times.
7145            if (currentTime != 0) {
7146                if (pkgSetting.firstInstallTime == 0) {
7147                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7148                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7149                    pkgSetting.lastUpdateTime = currentTime;
7150                }
7151            } else if (pkgSetting.firstInstallTime == 0) {
7152                // We need *something*.  Take time time stamp of the file.
7153                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7154            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7155                if (scanFileTime != pkgSetting.timeStamp) {
7156                    // A package on the system image has changed; consider this
7157                    // to be an update.
7158                    pkgSetting.lastUpdateTime = scanFileTime;
7159                }
7160            }
7161
7162            // Add the package's KeySets to the global KeySetManagerService
7163            ksms.addScannedPackageLPw(pkg);
7164
7165            int N = pkg.providers.size();
7166            StringBuilder r = null;
7167            int i;
7168            for (i=0; i<N; i++) {
7169                PackageParser.Provider p = pkg.providers.get(i);
7170                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7171                        p.info.processName, pkg.applicationInfo.uid);
7172                mProviders.addProvider(p);
7173                p.syncable = p.info.isSyncable;
7174                if (p.info.authority != null) {
7175                    String names[] = p.info.authority.split(";");
7176                    p.info.authority = null;
7177                    for (int j = 0; j < names.length; j++) {
7178                        if (j == 1 && p.syncable) {
7179                            // We only want the first authority for a provider to possibly be
7180                            // syncable, so if we already added this provider using a different
7181                            // authority clear the syncable flag. We copy the provider before
7182                            // changing it because the mProviders object contains a reference
7183                            // to a provider that we don't want to change.
7184                            // Only do this for the second authority since the resulting provider
7185                            // object can be the same for all future authorities for this provider.
7186                            p = new PackageParser.Provider(p);
7187                            p.syncable = false;
7188                        }
7189                        if (!mProvidersByAuthority.containsKey(names[j])) {
7190                            mProvidersByAuthority.put(names[j], p);
7191                            if (p.info.authority == null) {
7192                                p.info.authority = names[j];
7193                            } else {
7194                                p.info.authority = p.info.authority + ";" + names[j];
7195                            }
7196                            if (DEBUG_PACKAGE_SCANNING) {
7197                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7198                                    Log.d(TAG, "Registered content provider: " + names[j]
7199                                            + ", className = " + p.info.name + ", isSyncable = "
7200                                            + p.info.isSyncable);
7201                            }
7202                        } else {
7203                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7204                            Slog.w(TAG, "Skipping provider name " + names[j] +
7205                                    " (in package " + pkg.applicationInfo.packageName +
7206                                    "): name already used by "
7207                                    + ((other != null && other.getComponentName() != null)
7208                                            ? other.getComponentName().getPackageName() : "?"));
7209                        }
7210                    }
7211                }
7212                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7213                    if (r == null) {
7214                        r = new StringBuilder(256);
7215                    } else {
7216                        r.append(' ');
7217                    }
7218                    r.append(p.info.name);
7219                }
7220            }
7221            if (r != null) {
7222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7223            }
7224
7225            N = pkg.services.size();
7226            r = null;
7227            for (i=0; i<N; i++) {
7228                PackageParser.Service s = pkg.services.get(i);
7229                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7230                        s.info.processName, pkg.applicationInfo.uid);
7231                mServices.addService(s);
7232                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7233                    if (r == null) {
7234                        r = new StringBuilder(256);
7235                    } else {
7236                        r.append(' ');
7237                    }
7238                    r.append(s.info.name);
7239                }
7240            }
7241            if (r != null) {
7242                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7243            }
7244
7245            N = pkg.receivers.size();
7246            r = null;
7247            for (i=0; i<N; i++) {
7248                PackageParser.Activity a = pkg.receivers.get(i);
7249                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7250                        a.info.processName, pkg.applicationInfo.uid);
7251                mReceivers.addActivity(a, "receiver");
7252                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7253                    if (r == null) {
7254                        r = new StringBuilder(256);
7255                    } else {
7256                        r.append(' ');
7257                    }
7258                    r.append(a.info.name);
7259                }
7260            }
7261            if (r != null) {
7262                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7263            }
7264
7265            N = pkg.activities.size();
7266            r = null;
7267            for (i=0; i<N; i++) {
7268                PackageParser.Activity a = pkg.activities.get(i);
7269                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7270                        a.info.processName, pkg.applicationInfo.uid);
7271                mActivities.addActivity(a, "activity");
7272                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7273                    if (r == null) {
7274                        r = new StringBuilder(256);
7275                    } else {
7276                        r.append(' ');
7277                    }
7278                    r.append(a.info.name);
7279                }
7280            }
7281            if (r != null) {
7282                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7283            }
7284
7285            N = pkg.permissionGroups.size();
7286            r = null;
7287            for (i=0; i<N; i++) {
7288                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7289                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7290                if (cur == null) {
7291                    mPermissionGroups.put(pg.info.name, pg);
7292                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7293                        if (r == null) {
7294                            r = new StringBuilder(256);
7295                        } else {
7296                            r.append(' ');
7297                        }
7298                        r.append(pg.info.name);
7299                    }
7300                } else {
7301                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7302                            + pg.info.packageName + " ignored: original from "
7303                            + cur.info.packageName);
7304                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7305                        if (r == null) {
7306                            r = new StringBuilder(256);
7307                        } else {
7308                            r.append(' ');
7309                        }
7310                        r.append("DUP:");
7311                        r.append(pg.info.name);
7312                    }
7313                }
7314            }
7315            if (r != null) {
7316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7317            }
7318
7319            N = pkg.permissions.size();
7320            r = null;
7321            for (i=0; i<N; i++) {
7322                PackageParser.Permission p = pkg.permissions.get(i);
7323
7324                // Assume by default that we did not install this permission into the system.
7325                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7326
7327                // Now that permission groups have a special meaning, we ignore permission
7328                // groups for legacy apps to prevent unexpected behavior. In particular,
7329                // permissions for one app being granted to someone just becuase they happen
7330                // to be in a group defined by another app (before this had no implications).
7331                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7332                    p.group = mPermissionGroups.get(p.info.group);
7333                    // Warn for a permission in an unknown group.
7334                    if (p.info.group != null && p.group == null) {
7335                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7336                                + p.info.packageName + " in an unknown group " + p.info.group);
7337                    }
7338                }
7339
7340                ArrayMap<String, BasePermission> permissionMap =
7341                        p.tree ? mSettings.mPermissionTrees
7342                                : mSettings.mPermissions;
7343                BasePermission bp = permissionMap.get(p.info.name);
7344
7345                // Allow system apps to redefine non-system permissions
7346                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7347                    final boolean currentOwnerIsSystem = (bp.perm != null
7348                            && isSystemApp(bp.perm.owner));
7349                    if (isSystemApp(p.owner)) {
7350                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7351                            // It's a built-in permission and no owner, take ownership now
7352                            bp.packageSetting = pkgSetting;
7353                            bp.perm = p;
7354                            bp.uid = pkg.applicationInfo.uid;
7355                            bp.sourcePackage = p.info.packageName;
7356                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7357                        } else if (!currentOwnerIsSystem) {
7358                            String msg = "New decl " + p.owner + " of permission  "
7359                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7360                            reportSettingsProblem(Log.WARN, msg);
7361                            bp = null;
7362                        }
7363                    }
7364                }
7365
7366                if (bp == null) {
7367                    bp = new BasePermission(p.info.name, p.info.packageName,
7368                            BasePermission.TYPE_NORMAL);
7369                    permissionMap.put(p.info.name, bp);
7370                }
7371
7372                if (bp.perm == null) {
7373                    if (bp.sourcePackage == null
7374                            || bp.sourcePackage.equals(p.info.packageName)) {
7375                        BasePermission tree = findPermissionTreeLP(p.info.name);
7376                        if (tree == null
7377                                || tree.sourcePackage.equals(p.info.packageName)) {
7378                            bp.packageSetting = pkgSetting;
7379                            bp.perm = p;
7380                            bp.uid = pkg.applicationInfo.uid;
7381                            bp.sourcePackage = p.info.packageName;
7382                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7383                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7384                                if (r == null) {
7385                                    r = new StringBuilder(256);
7386                                } else {
7387                                    r.append(' ');
7388                                }
7389                                r.append(p.info.name);
7390                            }
7391                        } else {
7392                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7393                                    + p.info.packageName + " ignored: base tree "
7394                                    + tree.name + " is from package "
7395                                    + tree.sourcePackage);
7396                        }
7397                    } else {
7398                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7399                                + p.info.packageName + " ignored: original from "
7400                                + bp.sourcePackage);
7401                    }
7402                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7403                    if (r == null) {
7404                        r = new StringBuilder(256);
7405                    } else {
7406                        r.append(' ');
7407                    }
7408                    r.append("DUP:");
7409                    r.append(p.info.name);
7410                }
7411                if (bp.perm == p) {
7412                    bp.protectionLevel = p.info.protectionLevel;
7413                }
7414            }
7415
7416            if (r != null) {
7417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7418            }
7419
7420            N = pkg.instrumentation.size();
7421            r = null;
7422            for (i=0; i<N; i++) {
7423                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7424                a.info.packageName = pkg.applicationInfo.packageName;
7425                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7426                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7427                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7428                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7429                a.info.dataDir = pkg.applicationInfo.dataDir;
7430
7431                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7432                // need other information about the application, like the ABI and what not ?
7433                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7434                mInstrumentation.put(a.getComponentName(), a);
7435                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7436                    if (r == null) {
7437                        r = new StringBuilder(256);
7438                    } else {
7439                        r.append(' ');
7440                    }
7441                    r.append(a.info.name);
7442                }
7443            }
7444            if (r != null) {
7445                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7446            }
7447
7448            if (pkg.protectedBroadcasts != null) {
7449                N = pkg.protectedBroadcasts.size();
7450                for (i=0; i<N; i++) {
7451                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7452                }
7453            }
7454
7455            pkgSetting.setTimeStamp(scanFileTime);
7456
7457            // Create idmap files for pairs of (packages, overlay packages).
7458            // Note: "android", ie framework-res.apk, is handled by native layers.
7459            if (pkg.mOverlayTarget != null) {
7460                // This is an overlay package.
7461                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7462                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7463                        mOverlays.put(pkg.mOverlayTarget,
7464                                new ArrayMap<String, PackageParser.Package>());
7465                    }
7466                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7467                    map.put(pkg.packageName, pkg);
7468                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7469                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7470                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7471                                "scanPackageLI failed to createIdmap");
7472                    }
7473                }
7474            } else if (mOverlays.containsKey(pkg.packageName) &&
7475                    !pkg.packageName.equals("android")) {
7476                // This is a regular package, with one or more known overlay packages.
7477                createIdmapsForPackageLI(pkg);
7478            }
7479        }
7480
7481        return pkg;
7482    }
7483
7484    /**
7485     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7486     * is derived purely on the basis of the contents of {@code scanFile} and
7487     * {@code cpuAbiOverride}.
7488     *
7489     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7490     */
7491    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7492                                 String cpuAbiOverride, boolean extractLibs)
7493            throws PackageManagerException {
7494        // TODO: We can probably be smarter about this stuff. For installed apps,
7495        // we can calculate this information at install time once and for all. For
7496        // system apps, we can probably assume that this information doesn't change
7497        // after the first boot scan. As things stand, we do lots of unnecessary work.
7498
7499        // Give ourselves some initial paths; we'll come back for another
7500        // pass once we've determined ABI below.
7501        setNativeLibraryPaths(pkg);
7502
7503        // We would never need to extract libs for forward-locked and external packages,
7504        // since the container service will do it for us. We shouldn't attempt to
7505        // extract libs from system app when it was not updated.
7506        if (pkg.isForwardLocked() || isExternal(pkg) ||
7507            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7508            extractLibs = false;
7509        }
7510
7511        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7512        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7513
7514        NativeLibraryHelper.Handle handle = null;
7515        try {
7516            handle = NativeLibraryHelper.Handle.create(scanFile);
7517            // TODO(multiArch): This can be null for apps that didn't go through the
7518            // usual installation process. We can calculate it again, like we
7519            // do during install time.
7520            //
7521            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7522            // unnecessary.
7523            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7524
7525            // Null out the abis so that they can be recalculated.
7526            pkg.applicationInfo.primaryCpuAbi = null;
7527            pkg.applicationInfo.secondaryCpuAbi = null;
7528            if (isMultiArch(pkg.applicationInfo)) {
7529                // Warn if we've set an abiOverride for multi-lib packages..
7530                // By definition, we need to copy both 32 and 64 bit libraries for
7531                // such packages.
7532                if (pkg.cpuAbiOverride != null
7533                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7534                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7535                }
7536
7537                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7538                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7539                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7540                    if (extractLibs) {
7541                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7542                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7543                                useIsaSpecificSubdirs);
7544                    } else {
7545                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7546                    }
7547                }
7548
7549                maybeThrowExceptionForMultiArchCopy(
7550                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7551
7552                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7553                    if (extractLibs) {
7554                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7555                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7556                                useIsaSpecificSubdirs);
7557                    } else {
7558                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7559                    }
7560                }
7561
7562                maybeThrowExceptionForMultiArchCopy(
7563                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7564
7565                if (abi64 >= 0) {
7566                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7567                }
7568
7569                if (abi32 >= 0) {
7570                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7571                    if (abi64 >= 0) {
7572                        pkg.applicationInfo.secondaryCpuAbi = abi;
7573                    } else {
7574                        pkg.applicationInfo.primaryCpuAbi = abi;
7575                    }
7576                }
7577            } else {
7578                String[] abiList = (cpuAbiOverride != null) ?
7579                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7580
7581                // Enable gross and lame hacks for apps that are built with old
7582                // SDK tools. We must scan their APKs for renderscript bitcode and
7583                // not launch them if it's present. Don't bother checking on devices
7584                // that don't have 64 bit support.
7585                boolean needsRenderScriptOverride = false;
7586                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7587                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7588                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7589                    needsRenderScriptOverride = true;
7590                }
7591
7592                final int copyRet;
7593                if (extractLibs) {
7594                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7595                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7596                } else {
7597                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7598                }
7599
7600                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7601                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7602                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7603                }
7604
7605                if (copyRet >= 0) {
7606                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7607                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7608                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7609                } else if (needsRenderScriptOverride) {
7610                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7611                }
7612            }
7613        } catch (IOException ioe) {
7614            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7615        } finally {
7616            IoUtils.closeQuietly(handle);
7617        }
7618
7619        // Now that we've calculated the ABIs and determined if it's an internal app,
7620        // we will go ahead and populate the nativeLibraryPath.
7621        setNativeLibraryPaths(pkg);
7622    }
7623
7624    /**
7625     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7626     * i.e, so that all packages can be run inside a single process if required.
7627     *
7628     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7629     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7630     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7631     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7632     * updating a package that belongs to a shared user.
7633     *
7634     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7635     * adds unnecessary complexity.
7636     */
7637    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7638            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7639        String requiredInstructionSet = null;
7640        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7641            requiredInstructionSet = VMRuntime.getInstructionSet(
7642                     scannedPackage.applicationInfo.primaryCpuAbi);
7643        }
7644
7645        PackageSetting requirer = null;
7646        for (PackageSetting ps : packagesForUser) {
7647            // If packagesForUser contains scannedPackage, we skip it. This will happen
7648            // when scannedPackage is an update of an existing package. Without this check,
7649            // we will never be able to change the ABI of any package belonging to a shared
7650            // user, even if it's compatible with other packages.
7651            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7652                if (ps.primaryCpuAbiString == null) {
7653                    continue;
7654                }
7655
7656                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7657                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7658                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7659                    // this but there's not much we can do.
7660                    String errorMessage = "Instruction set mismatch, "
7661                            + ((requirer == null) ? "[caller]" : requirer)
7662                            + " requires " + requiredInstructionSet + " whereas " + ps
7663                            + " requires " + instructionSet;
7664                    Slog.w(TAG, errorMessage);
7665                }
7666
7667                if (requiredInstructionSet == null) {
7668                    requiredInstructionSet = instructionSet;
7669                    requirer = ps;
7670                }
7671            }
7672        }
7673
7674        if (requiredInstructionSet != null) {
7675            String adjustedAbi;
7676            if (requirer != null) {
7677                // requirer != null implies that either scannedPackage was null or that scannedPackage
7678                // did not require an ABI, in which case we have to adjust scannedPackage to match
7679                // the ABI of the set (which is the same as requirer's ABI)
7680                adjustedAbi = requirer.primaryCpuAbiString;
7681                if (scannedPackage != null) {
7682                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7683                }
7684            } else {
7685                // requirer == null implies that we're updating all ABIs in the set to
7686                // match scannedPackage.
7687                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7688            }
7689
7690            for (PackageSetting ps : packagesForUser) {
7691                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7692                    if (ps.primaryCpuAbiString != null) {
7693                        continue;
7694                    }
7695
7696                    ps.primaryCpuAbiString = adjustedAbi;
7697                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7698                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7699                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7700
7701                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7702                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7703                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7704                            ps.primaryCpuAbiString = null;
7705                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7706                            return;
7707                        } else {
7708                            mInstaller.rmdex(ps.codePathString,
7709                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7710                        }
7711                    }
7712                }
7713            }
7714        }
7715    }
7716
7717    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7718        synchronized (mPackages) {
7719            mResolverReplaced = true;
7720            // Set up information for custom user intent resolution activity.
7721            mResolveActivity.applicationInfo = pkg.applicationInfo;
7722            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7723            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7724            mResolveActivity.processName = pkg.applicationInfo.packageName;
7725            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7726            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7727                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7728            mResolveActivity.theme = 0;
7729            mResolveActivity.exported = true;
7730            mResolveActivity.enabled = true;
7731            mResolveInfo.activityInfo = mResolveActivity;
7732            mResolveInfo.priority = 0;
7733            mResolveInfo.preferredOrder = 0;
7734            mResolveInfo.match = 0;
7735            mResolveComponentName = mCustomResolverComponentName;
7736            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7737                    mResolveComponentName);
7738        }
7739    }
7740
7741    private static String calculateBundledApkRoot(final String codePathString) {
7742        final File codePath = new File(codePathString);
7743        final File codeRoot;
7744        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7745            codeRoot = Environment.getRootDirectory();
7746        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7747            codeRoot = Environment.getOemDirectory();
7748        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7749            codeRoot = Environment.getVendorDirectory();
7750        } else {
7751            // Unrecognized code path; take its top real segment as the apk root:
7752            // e.g. /something/app/blah.apk => /something
7753            try {
7754                File f = codePath.getCanonicalFile();
7755                File parent = f.getParentFile();    // non-null because codePath is a file
7756                File tmp;
7757                while ((tmp = parent.getParentFile()) != null) {
7758                    f = parent;
7759                    parent = tmp;
7760                }
7761                codeRoot = f;
7762                Slog.w(TAG, "Unrecognized code path "
7763                        + codePath + " - using " + codeRoot);
7764            } catch (IOException e) {
7765                // Can't canonicalize the code path -- shenanigans?
7766                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7767                return Environment.getRootDirectory().getPath();
7768            }
7769        }
7770        return codeRoot.getPath();
7771    }
7772
7773    /**
7774     * Derive and set the location of native libraries for the given package,
7775     * which varies depending on where and how the package was installed.
7776     */
7777    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7778        final ApplicationInfo info = pkg.applicationInfo;
7779        final String codePath = pkg.codePath;
7780        final File codeFile = new File(codePath);
7781        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7782        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7783
7784        info.nativeLibraryRootDir = null;
7785        info.nativeLibraryRootRequiresIsa = false;
7786        info.nativeLibraryDir = null;
7787        info.secondaryNativeLibraryDir = null;
7788
7789        if (isApkFile(codeFile)) {
7790            // Monolithic install
7791            if (bundledApp) {
7792                // If "/system/lib64/apkname" exists, assume that is the per-package
7793                // native library directory to use; otherwise use "/system/lib/apkname".
7794                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7795                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7796                        getPrimaryInstructionSet(info));
7797
7798                // This is a bundled system app so choose the path based on the ABI.
7799                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7800                // is just the default path.
7801                final String apkName = deriveCodePathName(codePath);
7802                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7803                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7804                        apkName).getAbsolutePath();
7805
7806                if (info.secondaryCpuAbi != null) {
7807                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7808                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7809                            secondaryLibDir, apkName).getAbsolutePath();
7810                }
7811            } else if (asecApp) {
7812                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7813                        .getAbsolutePath();
7814            } else {
7815                final String apkName = deriveCodePathName(codePath);
7816                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7817                        .getAbsolutePath();
7818            }
7819
7820            info.nativeLibraryRootRequiresIsa = false;
7821            info.nativeLibraryDir = info.nativeLibraryRootDir;
7822        } else {
7823            // Cluster install
7824            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7825            info.nativeLibraryRootRequiresIsa = true;
7826
7827            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7828                    getPrimaryInstructionSet(info)).getAbsolutePath();
7829
7830            if (info.secondaryCpuAbi != null) {
7831                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7832                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7833            }
7834        }
7835    }
7836
7837    /**
7838     * Calculate the abis and roots for a bundled app. These can uniquely
7839     * be determined from the contents of the system partition, i.e whether
7840     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7841     * of this information, and instead assume that the system was built
7842     * sensibly.
7843     */
7844    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7845                                           PackageSetting pkgSetting) {
7846        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7847
7848        // If "/system/lib64/apkname" exists, assume that is the per-package
7849        // native library directory to use; otherwise use "/system/lib/apkname".
7850        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7851        setBundledAppAbi(pkg, apkRoot, apkName);
7852        // pkgSetting might be null during rescan following uninstall of updates
7853        // to a bundled app, so accommodate that possibility.  The settings in
7854        // that case will be established later from the parsed package.
7855        //
7856        // If the settings aren't null, sync them up with what we've just derived.
7857        // note that apkRoot isn't stored in the package settings.
7858        if (pkgSetting != null) {
7859            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7860            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7861        }
7862    }
7863
7864    /**
7865     * Deduces the ABI of a bundled app and sets the relevant fields on the
7866     * parsed pkg object.
7867     *
7868     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7869     *        under which system libraries are installed.
7870     * @param apkName the name of the installed package.
7871     */
7872    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7873        final File codeFile = new File(pkg.codePath);
7874
7875        final boolean has64BitLibs;
7876        final boolean has32BitLibs;
7877        if (isApkFile(codeFile)) {
7878            // Monolithic install
7879            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7880            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7881        } else {
7882            // Cluster install
7883            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7884            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7885                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7886                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7887                has64BitLibs = (new File(rootDir, isa)).exists();
7888            } else {
7889                has64BitLibs = false;
7890            }
7891            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7892                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7893                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7894                has32BitLibs = (new File(rootDir, isa)).exists();
7895            } else {
7896                has32BitLibs = false;
7897            }
7898        }
7899
7900        if (has64BitLibs && !has32BitLibs) {
7901            // The package has 64 bit libs, but not 32 bit libs. Its primary
7902            // ABI should be 64 bit. We can safely assume here that the bundled
7903            // native libraries correspond to the most preferred ABI in the list.
7904
7905            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7906            pkg.applicationInfo.secondaryCpuAbi = null;
7907        } else if (has32BitLibs && !has64BitLibs) {
7908            // The package has 32 bit libs but not 64 bit libs. Its primary
7909            // ABI should be 32 bit.
7910
7911            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7912            pkg.applicationInfo.secondaryCpuAbi = null;
7913        } else if (has32BitLibs && has64BitLibs) {
7914            // The application has both 64 and 32 bit bundled libraries. We check
7915            // here that the app declares multiArch support, and warn if it doesn't.
7916            //
7917            // We will be lenient here and record both ABIs. The primary will be the
7918            // ABI that's higher on the list, i.e, a device that's configured to prefer
7919            // 64 bit apps will see a 64 bit primary ABI,
7920
7921            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7922                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7923            }
7924
7925            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7926                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7927                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7928            } else {
7929                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7930                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7931            }
7932        } else {
7933            pkg.applicationInfo.primaryCpuAbi = null;
7934            pkg.applicationInfo.secondaryCpuAbi = null;
7935        }
7936    }
7937
7938    private void killApplication(String pkgName, int appId, String reason) {
7939        // Request the ActivityManager to kill the process(only for existing packages)
7940        // so that we do not end up in a confused state while the user is still using the older
7941        // version of the application while the new one gets installed.
7942        IActivityManager am = ActivityManagerNative.getDefault();
7943        if (am != null) {
7944            try {
7945                am.killApplicationWithAppId(pkgName, appId, reason);
7946            } catch (RemoteException e) {
7947            }
7948        }
7949    }
7950
7951    void removePackageLI(PackageSetting ps, boolean chatty) {
7952        if (DEBUG_INSTALL) {
7953            if (chatty)
7954                Log.d(TAG, "Removing package " + ps.name);
7955        }
7956
7957        // writer
7958        synchronized (mPackages) {
7959            mPackages.remove(ps.name);
7960            final PackageParser.Package pkg = ps.pkg;
7961            if (pkg != null) {
7962                cleanPackageDataStructuresLILPw(pkg, chatty);
7963            }
7964        }
7965    }
7966
7967    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7968        if (DEBUG_INSTALL) {
7969            if (chatty)
7970                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7971        }
7972
7973        // writer
7974        synchronized (mPackages) {
7975            mPackages.remove(pkg.applicationInfo.packageName);
7976            cleanPackageDataStructuresLILPw(pkg, chatty);
7977        }
7978    }
7979
7980    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7981        int N = pkg.providers.size();
7982        StringBuilder r = null;
7983        int i;
7984        for (i=0; i<N; i++) {
7985            PackageParser.Provider p = pkg.providers.get(i);
7986            mProviders.removeProvider(p);
7987            if (p.info.authority == null) {
7988
7989                /* There was another ContentProvider with this authority when
7990                 * this app was installed so this authority is null,
7991                 * Ignore it as we don't have to unregister the provider.
7992                 */
7993                continue;
7994            }
7995            String names[] = p.info.authority.split(";");
7996            for (int j = 0; j < names.length; j++) {
7997                if (mProvidersByAuthority.get(names[j]) == p) {
7998                    mProvidersByAuthority.remove(names[j]);
7999                    if (DEBUG_REMOVE) {
8000                        if (chatty)
8001                            Log.d(TAG, "Unregistered content provider: " + names[j]
8002                                    + ", className = " + p.info.name + ", isSyncable = "
8003                                    + p.info.isSyncable);
8004                    }
8005                }
8006            }
8007            if (DEBUG_REMOVE && chatty) {
8008                if (r == null) {
8009                    r = new StringBuilder(256);
8010                } else {
8011                    r.append(' ');
8012                }
8013                r.append(p.info.name);
8014            }
8015        }
8016        if (r != null) {
8017            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8018        }
8019
8020        N = pkg.services.size();
8021        r = null;
8022        for (i=0; i<N; i++) {
8023            PackageParser.Service s = pkg.services.get(i);
8024            mServices.removeService(s);
8025            if (chatty) {
8026                if (r == null) {
8027                    r = new StringBuilder(256);
8028                } else {
8029                    r.append(' ');
8030                }
8031                r.append(s.info.name);
8032            }
8033        }
8034        if (r != null) {
8035            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8036        }
8037
8038        N = pkg.receivers.size();
8039        r = null;
8040        for (i=0; i<N; i++) {
8041            PackageParser.Activity a = pkg.receivers.get(i);
8042            mReceivers.removeActivity(a, "receiver");
8043            if (DEBUG_REMOVE && chatty) {
8044                if (r == null) {
8045                    r = new StringBuilder(256);
8046                } else {
8047                    r.append(' ');
8048                }
8049                r.append(a.info.name);
8050            }
8051        }
8052        if (r != null) {
8053            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8054        }
8055
8056        N = pkg.activities.size();
8057        r = null;
8058        for (i=0; i<N; i++) {
8059            PackageParser.Activity a = pkg.activities.get(i);
8060            mActivities.removeActivity(a, "activity");
8061            if (DEBUG_REMOVE && chatty) {
8062                if (r == null) {
8063                    r = new StringBuilder(256);
8064                } else {
8065                    r.append(' ');
8066                }
8067                r.append(a.info.name);
8068            }
8069        }
8070        if (r != null) {
8071            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8072        }
8073
8074        N = pkg.permissions.size();
8075        r = null;
8076        for (i=0; i<N; i++) {
8077            PackageParser.Permission p = pkg.permissions.get(i);
8078            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8079            if (bp == null) {
8080                bp = mSettings.mPermissionTrees.get(p.info.name);
8081            }
8082            if (bp != null && bp.perm == p) {
8083                bp.perm = null;
8084                if (DEBUG_REMOVE && chatty) {
8085                    if (r == null) {
8086                        r = new StringBuilder(256);
8087                    } else {
8088                        r.append(' ');
8089                    }
8090                    r.append(p.info.name);
8091                }
8092            }
8093            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8094                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8095                if (appOpPerms != null) {
8096                    appOpPerms.remove(pkg.packageName);
8097                }
8098            }
8099        }
8100        if (r != null) {
8101            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8102        }
8103
8104        N = pkg.requestedPermissions.size();
8105        r = null;
8106        for (i=0; i<N; i++) {
8107            String perm = pkg.requestedPermissions.get(i);
8108            BasePermission bp = mSettings.mPermissions.get(perm);
8109            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8110                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8111                if (appOpPerms != null) {
8112                    appOpPerms.remove(pkg.packageName);
8113                    if (appOpPerms.isEmpty()) {
8114                        mAppOpPermissionPackages.remove(perm);
8115                    }
8116                }
8117            }
8118        }
8119        if (r != null) {
8120            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8121        }
8122
8123        N = pkg.instrumentation.size();
8124        r = null;
8125        for (i=0; i<N; i++) {
8126            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8127            mInstrumentation.remove(a.getComponentName());
8128            if (DEBUG_REMOVE && chatty) {
8129                if (r == null) {
8130                    r = new StringBuilder(256);
8131                } else {
8132                    r.append(' ');
8133                }
8134                r.append(a.info.name);
8135            }
8136        }
8137        if (r != null) {
8138            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8139        }
8140
8141        r = null;
8142        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8143            // Only system apps can hold shared libraries.
8144            if (pkg.libraryNames != null) {
8145                for (i=0; i<pkg.libraryNames.size(); i++) {
8146                    String name = pkg.libraryNames.get(i);
8147                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8148                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8149                        mSharedLibraries.remove(name);
8150                        if (DEBUG_REMOVE && chatty) {
8151                            if (r == null) {
8152                                r = new StringBuilder(256);
8153                            } else {
8154                                r.append(' ');
8155                            }
8156                            r.append(name);
8157                        }
8158                    }
8159                }
8160            }
8161        }
8162        if (r != null) {
8163            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8164        }
8165    }
8166
8167    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8168        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8169            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8170                return true;
8171            }
8172        }
8173        return false;
8174    }
8175
8176    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8177    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8178    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8179
8180    private void updatePermissionsLPw(String changingPkg,
8181            PackageParser.Package pkgInfo, int flags) {
8182        // Make sure there are no dangling permission trees.
8183        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8184        while (it.hasNext()) {
8185            final BasePermission bp = it.next();
8186            if (bp.packageSetting == null) {
8187                // We may not yet have parsed the package, so just see if
8188                // we still know about its settings.
8189                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8190            }
8191            if (bp.packageSetting == null) {
8192                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8193                        + " from package " + bp.sourcePackage);
8194                it.remove();
8195            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8196                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8197                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8198                            + " from package " + bp.sourcePackage);
8199                    flags |= UPDATE_PERMISSIONS_ALL;
8200                    it.remove();
8201                }
8202            }
8203        }
8204
8205        // Make sure all dynamic permissions have been assigned to a package,
8206        // and make sure there are no dangling permissions.
8207        it = mSettings.mPermissions.values().iterator();
8208        while (it.hasNext()) {
8209            final BasePermission bp = it.next();
8210            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8211                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8212                        + bp.name + " pkg=" + bp.sourcePackage
8213                        + " info=" + bp.pendingInfo);
8214                if (bp.packageSetting == null && bp.pendingInfo != null) {
8215                    final BasePermission tree = findPermissionTreeLP(bp.name);
8216                    if (tree != null && tree.perm != null) {
8217                        bp.packageSetting = tree.packageSetting;
8218                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8219                                new PermissionInfo(bp.pendingInfo));
8220                        bp.perm.info.packageName = tree.perm.info.packageName;
8221                        bp.perm.info.name = bp.name;
8222                        bp.uid = tree.uid;
8223                    }
8224                }
8225            }
8226            if (bp.packageSetting == null) {
8227                // We may not yet have parsed the package, so just see if
8228                // we still know about its settings.
8229                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8230            }
8231            if (bp.packageSetting == null) {
8232                Slog.w(TAG, "Removing dangling permission: " + bp.name
8233                        + " from package " + bp.sourcePackage);
8234                it.remove();
8235            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8236                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8237                    Slog.i(TAG, "Removing old permission: " + bp.name
8238                            + " from package " + bp.sourcePackage);
8239                    flags |= UPDATE_PERMISSIONS_ALL;
8240                    it.remove();
8241                }
8242            }
8243        }
8244
8245        // Now update the permissions for all packages, in particular
8246        // replace the granted permissions of the system packages.
8247        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8248            for (PackageParser.Package pkg : mPackages.values()) {
8249                if (pkg != pkgInfo) {
8250                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8251                            changingPkg);
8252                }
8253            }
8254        }
8255
8256        if (pkgInfo != null) {
8257            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8258        }
8259    }
8260
8261    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8262            String packageOfInterest) {
8263        // IMPORTANT: There are two types of permissions: install and runtime.
8264        // Install time permissions are granted when the app is installed to
8265        // all device users and users added in the future. Runtime permissions
8266        // are granted at runtime explicitly to specific users. Normal and signature
8267        // protected permissions are install time permissions. Dangerous permissions
8268        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8269        // otherwise they are runtime permissions. This function does not manage
8270        // runtime permissions except for the case an app targeting Lollipop MR1
8271        // being upgraded to target a newer SDK, in which case dangerous permissions
8272        // are transformed from install time to runtime ones.
8273
8274        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8275        if (ps == null) {
8276            return;
8277        }
8278
8279        PermissionsState permissionsState = ps.getPermissionsState();
8280        PermissionsState origPermissions = permissionsState;
8281
8282        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8283
8284        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8285
8286        boolean changedInstallPermission = false;
8287
8288        if (replace) {
8289            ps.installPermissionsFixed = false;
8290            if (!ps.isSharedUser()) {
8291                origPermissions = new PermissionsState(permissionsState);
8292                permissionsState.reset();
8293            }
8294        }
8295
8296        permissionsState.setGlobalGids(mGlobalGids);
8297
8298        final int N = pkg.requestedPermissions.size();
8299        for (int i=0; i<N; i++) {
8300            final String name = pkg.requestedPermissions.get(i);
8301            final BasePermission bp = mSettings.mPermissions.get(name);
8302
8303            if (DEBUG_INSTALL) {
8304                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8305            }
8306
8307            if (bp == null || bp.packageSetting == null) {
8308                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8309                    Slog.w(TAG, "Unknown permission " + name
8310                            + " in package " + pkg.packageName);
8311                }
8312                continue;
8313            }
8314
8315            final String perm = bp.name;
8316            boolean allowedSig = false;
8317            int grant = GRANT_DENIED;
8318
8319            // Keep track of app op permissions.
8320            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8321                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8322                if (pkgs == null) {
8323                    pkgs = new ArraySet<>();
8324                    mAppOpPermissionPackages.put(bp.name, pkgs);
8325                }
8326                pkgs.add(pkg.packageName);
8327            }
8328
8329            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8330            switch (level) {
8331                case PermissionInfo.PROTECTION_NORMAL: {
8332                    // For all apps normal permissions are install time ones.
8333                    grant = GRANT_INSTALL;
8334                } break;
8335
8336                case PermissionInfo.PROTECTION_DANGEROUS: {
8337                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8338                        // For legacy apps dangerous permissions are install time ones.
8339                        grant = GRANT_INSTALL_LEGACY;
8340                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8341                        // For legacy apps that became modern, install becomes runtime.
8342                        grant = GRANT_UPGRADE;
8343                    } else {
8344                        // For modern apps keep runtime permissions unchanged.
8345                        grant = GRANT_RUNTIME;
8346                    }
8347                } break;
8348
8349                case PermissionInfo.PROTECTION_SIGNATURE: {
8350                    // For all apps signature permissions are install time ones.
8351                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8352                    if (allowedSig) {
8353                        grant = GRANT_INSTALL;
8354                    }
8355                } break;
8356            }
8357
8358            if (DEBUG_INSTALL) {
8359                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8360            }
8361
8362            if (grant != GRANT_DENIED) {
8363                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8364                    // If this is an existing, non-system package, then
8365                    // we can't add any new permissions to it.
8366                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8367                        // Except...  if this is a permission that was added
8368                        // to the platform (note: need to only do this when
8369                        // updating the platform).
8370                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8371                            grant = GRANT_DENIED;
8372                        }
8373                    }
8374                }
8375
8376                switch (grant) {
8377                    case GRANT_INSTALL: {
8378                        // Revoke this as runtime permission to handle the case of
8379                        // a runtime permission being downgraded to an install one.
8380                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8381                            if (origPermissions.getRuntimePermissionState(
8382                                    bp.name, userId) != null) {
8383                                // Revoke the runtime permission and clear the flags.
8384                                origPermissions.revokeRuntimePermission(bp, userId);
8385                                origPermissions.updatePermissionFlags(bp, userId,
8386                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8387                                // If we revoked a permission permission, we have to write.
8388                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8389                                        changedRuntimePermissionUserIds, userId);
8390                            }
8391                        }
8392                        // Grant an install permission.
8393                        if (permissionsState.grantInstallPermission(bp) !=
8394                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8395                            changedInstallPermission = true;
8396                        }
8397                    } break;
8398
8399                    case GRANT_INSTALL_LEGACY: {
8400                        // Grant an install permission.
8401                        if (permissionsState.grantInstallPermission(bp) !=
8402                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8403                            changedInstallPermission = true;
8404                        }
8405                    } break;
8406
8407                    case GRANT_RUNTIME: {
8408                        // Grant previously granted runtime permissions.
8409                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8410                            PermissionState permissionState = origPermissions
8411                                    .getRuntimePermissionState(bp.name, userId);
8412                            final int flags = permissionState != null
8413                                    ? permissionState.getFlags() : 0;
8414                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8415                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8416                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8417                                    // If we cannot put the permission as it was, we have to write.
8418                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8419                                            changedRuntimePermissionUserIds, userId);
8420                                }
8421                            }
8422                            // Propagate the permission flags.
8423                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8424                        }
8425                    } break;
8426
8427                    case GRANT_UPGRADE: {
8428                        // Grant runtime permissions for a previously held install permission.
8429                        PermissionState permissionState = origPermissions
8430                                .getInstallPermissionState(bp.name);
8431                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8432
8433                        if (origPermissions.revokeInstallPermission(bp)
8434                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8435                            // We will be transferring the permission flags, so clear them.
8436                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8437                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8438                            changedInstallPermission = true;
8439                        }
8440
8441                        // If the permission is not to be promoted to runtime we ignore it and
8442                        // also its other flags as they are not applicable to install permissions.
8443                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8444                            for (int userId : currentUserIds) {
8445                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8446                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8447                                    // Transfer the permission flags.
8448                                    permissionsState.updatePermissionFlags(bp, userId,
8449                                            flags, flags);
8450                                    // If we granted the permission, we have to write.
8451                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8452                                            changedRuntimePermissionUserIds, userId);
8453                                }
8454                            }
8455                        }
8456                    } break;
8457
8458                    default: {
8459                        if (packageOfInterest == null
8460                                || packageOfInterest.equals(pkg.packageName)) {
8461                            Slog.w(TAG, "Not granting permission " + perm
8462                                    + " to package " + pkg.packageName
8463                                    + " because it was previously installed without");
8464                        }
8465                    } break;
8466                }
8467            } else {
8468                if (permissionsState.revokeInstallPermission(bp) !=
8469                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8470                    // Also drop the permission flags.
8471                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8472                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8473                    changedInstallPermission = true;
8474                    Slog.i(TAG, "Un-granting permission " + perm
8475                            + " from package " + pkg.packageName
8476                            + " (protectionLevel=" + bp.protectionLevel
8477                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8478                            + ")");
8479                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8480                    // Don't print warning for app op permissions, since it is fine for them
8481                    // not to be granted, there is a UI for the user to decide.
8482                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8483                        Slog.w(TAG, "Not granting permission " + perm
8484                                + " to package " + pkg.packageName
8485                                + " (protectionLevel=" + bp.protectionLevel
8486                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8487                                + ")");
8488                    }
8489                }
8490            }
8491        }
8492
8493        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8494                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8495            // This is the first that we have heard about this package, so the
8496            // permissions we have now selected are fixed until explicitly
8497            // changed.
8498            ps.installPermissionsFixed = true;
8499        }
8500
8501        // Persist the runtime permissions state for users with changes.
8502        for (int userId : changedRuntimePermissionUserIds) {
8503            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8504        }
8505    }
8506
8507    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8508        boolean allowed = false;
8509        final int NP = PackageParser.NEW_PERMISSIONS.length;
8510        for (int ip=0; ip<NP; ip++) {
8511            final PackageParser.NewPermissionInfo npi
8512                    = PackageParser.NEW_PERMISSIONS[ip];
8513            if (npi.name.equals(perm)
8514                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8515                allowed = true;
8516                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8517                        + pkg.packageName);
8518                break;
8519            }
8520        }
8521        return allowed;
8522    }
8523
8524    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8525            BasePermission bp, PermissionsState origPermissions) {
8526        boolean allowed;
8527        allowed = (compareSignatures(
8528                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8529                        == PackageManager.SIGNATURE_MATCH)
8530                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8531                        == PackageManager.SIGNATURE_MATCH);
8532        if (!allowed && (bp.protectionLevel
8533                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8534            if (isSystemApp(pkg)) {
8535                // For updated system applications, a system permission
8536                // is granted only if it had been defined by the original application.
8537                if (pkg.isUpdatedSystemApp()) {
8538                    final PackageSetting sysPs = mSettings
8539                            .getDisabledSystemPkgLPr(pkg.packageName);
8540                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8541                        // If the original was granted this permission, we take
8542                        // that grant decision as read and propagate it to the
8543                        // update.
8544                        if (sysPs.isPrivileged()) {
8545                            allowed = true;
8546                        }
8547                    } else {
8548                        // The system apk may have been updated with an older
8549                        // version of the one on the data partition, but which
8550                        // granted a new system permission that it didn't have
8551                        // before.  In this case we do want to allow the app to
8552                        // now get the new permission if the ancestral apk is
8553                        // privileged to get it.
8554                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8555                            for (int j=0;
8556                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8557                                if (perm.equals(
8558                                        sysPs.pkg.requestedPermissions.get(j))) {
8559                                    allowed = true;
8560                                    break;
8561                                }
8562                            }
8563                        }
8564                    }
8565                } else {
8566                    allowed = isPrivilegedApp(pkg);
8567                }
8568            }
8569        }
8570        if (!allowed) {
8571            if (!allowed && (bp.protectionLevel
8572                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8573                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8574                // If this was a previously normal/dangerous permission that got moved
8575                // to a system permission as part of the runtime permission redesign, then
8576                // we still want to blindly grant it to old apps.
8577                allowed = true;
8578            }
8579            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8580                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8581                // If this permission is to be granted to the system installer and
8582                // this app is an installer, then it gets the permission.
8583                allowed = true;
8584            }
8585            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8586                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8587                // If this permission is to be granted to the system verifier and
8588                // this app is a verifier, then it gets the permission.
8589                allowed = true;
8590            }
8591            if (!allowed && (bp.protectionLevel
8592                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8593                    && isSystemApp(pkg)) {
8594                // Any pre-installed system app is allowed to get this permission.
8595                allowed = true;
8596            }
8597            if (!allowed && (bp.protectionLevel
8598                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8599                // For development permissions, a development permission
8600                // is granted only if it was already granted.
8601                allowed = origPermissions.hasInstallPermission(perm);
8602            }
8603        }
8604        return allowed;
8605    }
8606
8607    final class ActivityIntentResolver
8608            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8609        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8610                boolean defaultOnly, int userId) {
8611            if (!sUserManager.exists(userId)) return null;
8612            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8613            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8614        }
8615
8616        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8617                int userId) {
8618            if (!sUserManager.exists(userId)) return null;
8619            mFlags = flags;
8620            return super.queryIntent(intent, resolvedType,
8621                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8622        }
8623
8624        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8625                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8626            if (!sUserManager.exists(userId)) return null;
8627            if (packageActivities == null) {
8628                return null;
8629            }
8630            mFlags = flags;
8631            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8632            final int N = packageActivities.size();
8633            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8634                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8635
8636            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8637            for (int i = 0; i < N; ++i) {
8638                intentFilters = packageActivities.get(i).intents;
8639                if (intentFilters != null && intentFilters.size() > 0) {
8640                    PackageParser.ActivityIntentInfo[] array =
8641                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8642                    intentFilters.toArray(array);
8643                    listCut.add(array);
8644                }
8645            }
8646            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8647        }
8648
8649        public final void addActivity(PackageParser.Activity a, String type) {
8650            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8651            mActivities.put(a.getComponentName(), a);
8652            if (DEBUG_SHOW_INFO)
8653                Log.v(
8654                TAG, "  " + type + " " +
8655                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8656            if (DEBUG_SHOW_INFO)
8657                Log.v(TAG, "    Class=" + a.info.name);
8658            final int NI = a.intents.size();
8659            for (int j=0; j<NI; j++) {
8660                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8661                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8662                    intent.setPriority(0);
8663                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8664                            + a.className + " with priority > 0, forcing to 0");
8665                }
8666                if (DEBUG_SHOW_INFO) {
8667                    Log.v(TAG, "    IntentFilter:");
8668                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8669                }
8670                if (!intent.debugCheck()) {
8671                    Log.w(TAG, "==> For Activity " + a.info.name);
8672                }
8673                addFilter(intent);
8674            }
8675        }
8676
8677        public final void removeActivity(PackageParser.Activity a, String type) {
8678            mActivities.remove(a.getComponentName());
8679            if (DEBUG_SHOW_INFO) {
8680                Log.v(TAG, "  " + type + " "
8681                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8682                                : a.info.name) + ":");
8683                Log.v(TAG, "    Class=" + a.info.name);
8684            }
8685            final int NI = a.intents.size();
8686            for (int j=0; j<NI; j++) {
8687                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8688                if (DEBUG_SHOW_INFO) {
8689                    Log.v(TAG, "    IntentFilter:");
8690                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8691                }
8692                removeFilter(intent);
8693            }
8694        }
8695
8696        @Override
8697        protected boolean allowFilterResult(
8698                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8699            ActivityInfo filterAi = filter.activity.info;
8700            for (int i=dest.size()-1; i>=0; i--) {
8701                ActivityInfo destAi = dest.get(i).activityInfo;
8702                if (destAi.name == filterAi.name
8703                        && destAi.packageName == filterAi.packageName) {
8704                    return false;
8705                }
8706            }
8707            return true;
8708        }
8709
8710        @Override
8711        protected ActivityIntentInfo[] newArray(int size) {
8712            return new ActivityIntentInfo[size];
8713        }
8714
8715        @Override
8716        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8717            if (!sUserManager.exists(userId)) return true;
8718            PackageParser.Package p = filter.activity.owner;
8719            if (p != null) {
8720                PackageSetting ps = (PackageSetting)p.mExtras;
8721                if (ps != null) {
8722                    // System apps are never considered stopped for purposes of
8723                    // filtering, because there may be no way for the user to
8724                    // actually re-launch them.
8725                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8726                            && ps.getStopped(userId);
8727                }
8728            }
8729            return false;
8730        }
8731
8732        @Override
8733        protected boolean isPackageForFilter(String packageName,
8734                PackageParser.ActivityIntentInfo info) {
8735            return packageName.equals(info.activity.owner.packageName);
8736        }
8737
8738        @Override
8739        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8740                int match, int userId) {
8741            if (!sUserManager.exists(userId)) return null;
8742            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8743                return null;
8744            }
8745            final PackageParser.Activity activity = info.activity;
8746            if (mSafeMode && (activity.info.applicationInfo.flags
8747                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8748                return null;
8749            }
8750            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8751            if (ps == null) {
8752                return null;
8753            }
8754            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8755                    ps.readUserState(userId), userId);
8756            if (ai == null) {
8757                return null;
8758            }
8759            final ResolveInfo res = new ResolveInfo();
8760            res.activityInfo = ai;
8761            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8762                res.filter = info;
8763            }
8764            if (info != null) {
8765                res.handleAllWebDataURI = info.handleAllWebDataURI();
8766            }
8767            res.priority = info.getPriority();
8768            res.preferredOrder = activity.owner.mPreferredOrder;
8769            //System.out.println("Result: " + res.activityInfo.className +
8770            //                   " = " + res.priority);
8771            res.match = match;
8772            res.isDefault = info.hasDefault;
8773            res.labelRes = info.labelRes;
8774            res.nonLocalizedLabel = info.nonLocalizedLabel;
8775            if (userNeedsBadging(userId)) {
8776                res.noResourceId = true;
8777            } else {
8778                res.icon = info.icon;
8779            }
8780            res.iconResourceId = info.icon;
8781            res.system = res.activityInfo.applicationInfo.isSystemApp();
8782            return res;
8783        }
8784
8785        @Override
8786        protected void sortResults(List<ResolveInfo> results) {
8787            Collections.sort(results, mResolvePrioritySorter);
8788        }
8789
8790        @Override
8791        protected void dumpFilter(PrintWriter out, String prefix,
8792                PackageParser.ActivityIntentInfo filter) {
8793            out.print(prefix); out.print(
8794                    Integer.toHexString(System.identityHashCode(filter.activity)));
8795                    out.print(' ');
8796                    filter.activity.printComponentShortName(out);
8797                    out.print(" filter ");
8798                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8799        }
8800
8801        @Override
8802        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8803            return filter.activity;
8804        }
8805
8806        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8807            PackageParser.Activity activity = (PackageParser.Activity)label;
8808            out.print(prefix); out.print(
8809                    Integer.toHexString(System.identityHashCode(activity)));
8810                    out.print(' ');
8811                    activity.printComponentShortName(out);
8812            if (count > 1) {
8813                out.print(" ("); out.print(count); out.print(" filters)");
8814            }
8815            out.println();
8816        }
8817
8818//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8819//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8820//            final List<ResolveInfo> retList = Lists.newArrayList();
8821//            while (i.hasNext()) {
8822//                final ResolveInfo resolveInfo = i.next();
8823//                if (isEnabledLP(resolveInfo.activityInfo)) {
8824//                    retList.add(resolveInfo);
8825//                }
8826//            }
8827//            return retList;
8828//        }
8829
8830        // Keys are String (activity class name), values are Activity.
8831        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8832                = new ArrayMap<ComponentName, PackageParser.Activity>();
8833        private int mFlags;
8834    }
8835
8836    private final class ServiceIntentResolver
8837            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8838        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8839                boolean defaultOnly, int userId) {
8840            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8841            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8842        }
8843
8844        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8845                int userId) {
8846            if (!sUserManager.exists(userId)) return null;
8847            mFlags = flags;
8848            return super.queryIntent(intent, resolvedType,
8849                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8850        }
8851
8852        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8853                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8854            if (!sUserManager.exists(userId)) return null;
8855            if (packageServices == null) {
8856                return null;
8857            }
8858            mFlags = flags;
8859            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8860            final int N = packageServices.size();
8861            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8862                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8863
8864            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8865            for (int i = 0; i < N; ++i) {
8866                intentFilters = packageServices.get(i).intents;
8867                if (intentFilters != null && intentFilters.size() > 0) {
8868                    PackageParser.ServiceIntentInfo[] array =
8869                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8870                    intentFilters.toArray(array);
8871                    listCut.add(array);
8872                }
8873            }
8874            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8875        }
8876
8877        public final void addService(PackageParser.Service s) {
8878            mServices.put(s.getComponentName(), s);
8879            if (DEBUG_SHOW_INFO) {
8880                Log.v(TAG, "  "
8881                        + (s.info.nonLocalizedLabel != null
8882                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8883                Log.v(TAG, "    Class=" + s.info.name);
8884            }
8885            final int NI = s.intents.size();
8886            int j;
8887            for (j=0; j<NI; j++) {
8888                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8889                if (DEBUG_SHOW_INFO) {
8890                    Log.v(TAG, "    IntentFilter:");
8891                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8892                }
8893                if (!intent.debugCheck()) {
8894                    Log.w(TAG, "==> For Service " + s.info.name);
8895                }
8896                addFilter(intent);
8897            }
8898        }
8899
8900        public final void removeService(PackageParser.Service s) {
8901            mServices.remove(s.getComponentName());
8902            if (DEBUG_SHOW_INFO) {
8903                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8904                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8905                Log.v(TAG, "    Class=" + s.info.name);
8906            }
8907            final int NI = s.intents.size();
8908            int j;
8909            for (j=0; j<NI; j++) {
8910                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8911                if (DEBUG_SHOW_INFO) {
8912                    Log.v(TAG, "    IntentFilter:");
8913                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8914                }
8915                removeFilter(intent);
8916            }
8917        }
8918
8919        @Override
8920        protected boolean allowFilterResult(
8921                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8922            ServiceInfo filterSi = filter.service.info;
8923            for (int i=dest.size()-1; i>=0; i--) {
8924                ServiceInfo destAi = dest.get(i).serviceInfo;
8925                if (destAi.name == filterSi.name
8926                        && destAi.packageName == filterSi.packageName) {
8927                    return false;
8928                }
8929            }
8930            return true;
8931        }
8932
8933        @Override
8934        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8935            return new PackageParser.ServiceIntentInfo[size];
8936        }
8937
8938        @Override
8939        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8940            if (!sUserManager.exists(userId)) return true;
8941            PackageParser.Package p = filter.service.owner;
8942            if (p != null) {
8943                PackageSetting ps = (PackageSetting)p.mExtras;
8944                if (ps != null) {
8945                    // System apps are never considered stopped for purposes of
8946                    // filtering, because there may be no way for the user to
8947                    // actually re-launch them.
8948                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8949                            && ps.getStopped(userId);
8950                }
8951            }
8952            return false;
8953        }
8954
8955        @Override
8956        protected boolean isPackageForFilter(String packageName,
8957                PackageParser.ServiceIntentInfo info) {
8958            return packageName.equals(info.service.owner.packageName);
8959        }
8960
8961        @Override
8962        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8963                int match, int userId) {
8964            if (!sUserManager.exists(userId)) return null;
8965            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8966            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8967                return null;
8968            }
8969            final PackageParser.Service service = info.service;
8970            if (mSafeMode && (service.info.applicationInfo.flags
8971                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8972                return null;
8973            }
8974            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8975            if (ps == null) {
8976                return null;
8977            }
8978            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8979                    ps.readUserState(userId), userId);
8980            if (si == null) {
8981                return null;
8982            }
8983            final ResolveInfo res = new ResolveInfo();
8984            res.serviceInfo = si;
8985            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8986                res.filter = filter;
8987            }
8988            res.priority = info.getPriority();
8989            res.preferredOrder = service.owner.mPreferredOrder;
8990            res.match = match;
8991            res.isDefault = info.hasDefault;
8992            res.labelRes = info.labelRes;
8993            res.nonLocalizedLabel = info.nonLocalizedLabel;
8994            res.icon = info.icon;
8995            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8996            return res;
8997        }
8998
8999        @Override
9000        protected void sortResults(List<ResolveInfo> results) {
9001            Collections.sort(results, mResolvePrioritySorter);
9002        }
9003
9004        @Override
9005        protected void dumpFilter(PrintWriter out, String prefix,
9006                PackageParser.ServiceIntentInfo filter) {
9007            out.print(prefix); out.print(
9008                    Integer.toHexString(System.identityHashCode(filter.service)));
9009                    out.print(' ');
9010                    filter.service.printComponentShortName(out);
9011                    out.print(" filter ");
9012                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9013        }
9014
9015        @Override
9016        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9017            return filter.service;
9018        }
9019
9020        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9021            PackageParser.Service service = (PackageParser.Service)label;
9022            out.print(prefix); out.print(
9023                    Integer.toHexString(System.identityHashCode(service)));
9024                    out.print(' ');
9025                    service.printComponentShortName(out);
9026            if (count > 1) {
9027                out.print(" ("); out.print(count); out.print(" filters)");
9028            }
9029            out.println();
9030        }
9031
9032//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9033//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9034//            final List<ResolveInfo> retList = Lists.newArrayList();
9035//            while (i.hasNext()) {
9036//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9037//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9038//                    retList.add(resolveInfo);
9039//                }
9040//            }
9041//            return retList;
9042//        }
9043
9044        // Keys are String (activity class name), values are Activity.
9045        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9046                = new ArrayMap<ComponentName, PackageParser.Service>();
9047        private int mFlags;
9048    };
9049
9050    private final class ProviderIntentResolver
9051            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9052        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9053                boolean defaultOnly, int userId) {
9054            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9055            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9056        }
9057
9058        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9059                int userId) {
9060            if (!sUserManager.exists(userId))
9061                return null;
9062            mFlags = flags;
9063            return super.queryIntent(intent, resolvedType,
9064                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9065        }
9066
9067        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9068                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9069            if (!sUserManager.exists(userId))
9070                return null;
9071            if (packageProviders == null) {
9072                return null;
9073            }
9074            mFlags = flags;
9075            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9076            final int N = packageProviders.size();
9077            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9078                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9079
9080            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9081            for (int i = 0; i < N; ++i) {
9082                intentFilters = packageProviders.get(i).intents;
9083                if (intentFilters != null && intentFilters.size() > 0) {
9084                    PackageParser.ProviderIntentInfo[] array =
9085                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9086                    intentFilters.toArray(array);
9087                    listCut.add(array);
9088                }
9089            }
9090            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9091        }
9092
9093        public final void addProvider(PackageParser.Provider p) {
9094            if (mProviders.containsKey(p.getComponentName())) {
9095                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9096                return;
9097            }
9098
9099            mProviders.put(p.getComponentName(), p);
9100            if (DEBUG_SHOW_INFO) {
9101                Log.v(TAG, "  "
9102                        + (p.info.nonLocalizedLabel != null
9103                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9104                Log.v(TAG, "    Class=" + p.info.name);
9105            }
9106            final int NI = p.intents.size();
9107            int j;
9108            for (j = 0; j < NI; j++) {
9109                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9110                if (DEBUG_SHOW_INFO) {
9111                    Log.v(TAG, "    IntentFilter:");
9112                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9113                }
9114                if (!intent.debugCheck()) {
9115                    Log.w(TAG, "==> For Provider " + p.info.name);
9116                }
9117                addFilter(intent);
9118            }
9119        }
9120
9121        public final void removeProvider(PackageParser.Provider p) {
9122            mProviders.remove(p.getComponentName());
9123            if (DEBUG_SHOW_INFO) {
9124                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9125                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9126                Log.v(TAG, "    Class=" + p.info.name);
9127            }
9128            final int NI = p.intents.size();
9129            int j;
9130            for (j = 0; j < NI; j++) {
9131                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9132                if (DEBUG_SHOW_INFO) {
9133                    Log.v(TAG, "    IntentFilter:");
9134                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9135                }
9136                removeFilter(intent);
9137            }
9138        }
9139
9140        @Override
9141        protected boolean allowFilterResult(
9142                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9143            ProviderInfo filterPi = filter.provider.info;
9144            for (int i = dest.size() - 1; i >= 0; i--) {
9145                ProviderInfo destPi = dest.get(i).providerInfo;
9146                if (destPi.name == filterPi.name
9147                        && destPi.packageName == filterPi.packageName) {
9148                    return false;
9149                }
9150            }
9151            return true;
9152        }
9153
9154        @Override
9155        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9156            return new PackageParser.ProviderIntentInfo[size];
9157        }
9158
9159        @Override
9160        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9161            if (!sUserManager.exists(userId))
9162                return true;
9163            PackageParser.Package p = filter.provider.owner;
9164            if (p != null) {
9165                PackageSetting ps = (PackageSetting) p.mExtras;
9166                if (ps != null) {
9167                    // System apps are never considered stopped for purposes of
9168                    // filtering, because there may be no way for the user to
9169                    // actually re-launch them.
9170                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9171                            && ps.getStopped(userId);
9172                }
9173            }
9174            return false;
9175        }
9176
9177        @Override
9178        protected boolean isPackageForFilter(String packageName,
9179                PackageParser.ProviderIntentInfo info) {
9180            return packageName.equals(info.provider.owner.packageName);
9181        }
9182
9183        @Override
9184        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9185                int match, int userId) {
9186            if (!sUserManager.exists(userId))
9187                return null;
9188            final PackageParser.ProviderIntentInfo info = filter;
9189            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9190                return null;
9191            }
9192            final PackageParser.Provider provider = info.provider;
9193            if (mSafeMode && (provider.info.applicationInfo.flags
9194                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9195                return null;
9196            }
9197            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9198            if (ps == null) {
9199                return null;
9200            }
9201            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9202                    ps.readUserState(userId), userId);
9203            if (pi == null) {
9204                return null;
9205            }
9206            final ResolveInfo res = new ResolveInfo();
9207            res.providerInfo = pi;
9208            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9209                res.filter = filter;
9210            }
9211            res.priority = info.getPriority();
9212            res.preferredOrder = provider.owner.mPreferredOrder;
9213            res.match = match;
9214            res.isDefault = info.hasDefault;
9215            res.labelRes = info.labelRes;
9216            res.nonLocalizedLabel = info.nonLocalizedLabel;
9217            res.icon = info.icon;
9218            res.system = res.providerInfo.applicationInfo.isSystemApp();
9219            return res;
9220        }
9221
9222        @Override
9223        protected void sortResults(List<ResolveInfo> results) {
9224            Collections.sort(results, mResolvePrioritySorter);
9225        }
9226
9227        @Override
9228        protected void dumpFilter(PrintWriter out, String prefix,
9229                PackageParser.ProviderIntentInfo filter) {
9230            out.print(prefix);
9231            out.print(
9232                    Integer.toHexString(System.identityHashCode(filter.provider)));
9233            out.print(' ');
9234            filter.provider.printComponentShortName(out);
9235            out.print(" filter ");
9236            out.println(Integer.toHexString(System.identityHashCode(filter)));
9237        }
9238
9239        @Override
9240        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9241            return filter.provider;
9242        }
9243
9244        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9245            PackageParser.Provider provider = (PackageParser.Provider)label;
9246            out.print(prefix); out.print(
9247                    Integer.toHexString(System.identityHashCode(provider)));
9248                    out.print(' ');
9249                    provider.printComponentShortName(out);
9250            if (count > 1) {
9251                out.print(" ("); out.print(count); out.print(" filters)");
9252            }
9253            out.println();
9254        }
9255
9256        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9257                = new ArrayMap<ComponentName, PackageParser.Provider>();
9258        private int mFlags;
9259    };
9260
9261    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9262            new Comparator<ResolveInfo>() {
9263        public int compare(ResolveInfo r1, ResolveInfo r2) {
9264            int v1 = r1.priority;
9265            int v2 = r2.priority;
9266            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9267            if (v1 != v2) {
9268                return (v1 > v2) ? -1 : 1;
9269            }
9270            v1 = r1.preferredOrder;
9271            v2 = r2.preferredOrder;
9272            if (v1 != v2) {
9273                return (v1 > v2) ? -1 : 1;
9274            }
9275            if (r1.isDefault != r2.isDefault) {
9276                return r1.isDefault ? -1 : 1;
9277            }
9278            v1 = r1.match;
9279            v2 = r2.match;
9280            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9281            if (v1 != v2) {
9282                return (v1 > v2) ? -1 : 1;
9283            }
9284            if (r1.system != r2.system) {
9285                return r1.system ? -1 : 1;
9286            }
9287            return 0;
9288        }
9289    };
9290
9291    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9292            new Comparator<ProviderInfo>() {
9293        public int compare(ProviderInfo p1, ProviderInfo p2) {
9294            final int v1 = p1.initOrder;
9295            final int v2 = p2.initOrder;
9296            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9297        }
9298    };
9299
9300    final void sendPackageBroadcast(final String action, final String pkg,
9301            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9302            final int[] userIds) {
9303        mHandler.post(new Runnable() {
9304            @Override
9305            public void run() {
9306                try {
9307                    final IActivityManager am = ActivityManagerNative.getDefault();
9308                    if (am == null) return;
9309                    final int[] resolvedUserIds;
9310                    if (userIds == null) {
9311                        resolvedUserIds = am.getRunningUserIds();
9312                    } else {
9313                        resolvedUserIds = userIds;
9314                    }
9315                    for (int id : resolvedUserIds) {
9316                        final Intent intent = new Intent(action,
9317                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9318                        if (extras != null) {
9319                            intent.putExtras(extras);
9320                        }
9321                        if (targetPkg != null) {
9322                            intent.setPackage(targetPkg);
9323                        }
9324                        // Modify the UID when posting to other users
9325                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9326                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9327                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9328                            intent.putExtra(Intent.EXTRA_UID, uid);
9329                        }
9330                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9331                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9332                        if (DEBUG_BROADCASTS) {
9333                            RuntimeException here = new RuntimeException("here");
9334                            here.fillInStackTrace();
9335                            Slog.d(TAG, "Sending to user " + id + ": "
9336                                    + intent.toShortString(false, true, false, false)
9337                                    + " " + intent.getExtras(), here);
9338                        }
9339                        am.broadcastIntent(null, intent, null, finishedReceiver,
9340                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9341                                null, finishedReceiver != null, false, id);
9342                    }
9343                } catch (RemoteException ex) {
9344                }
9345            }
9346        });
9347    }
9348
9349    /**
9350     * Check if the external storage media is available. This is true if there
9351     * is a mounted external storage medium or if the external storage is
9352     * emulated.
9353     */
9354    private boolean isExternalMediaAvailable() {
9355        return mMediaMounted || Environment.isExternalStorageEmulated();
9356    }
9357
9358    @Override
9359    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9360        // writer
9361        synchronized (mPackages) {
9362            if (!isExternalMediaAvailable()) {
9363                // If the external storage is no longer mounted at this point,
9364                // the caller may not have been able to delete all of this
9365                // packages files and can not delete any more.  Bail.
9366                return null;
9367            }
9368            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9369            if (lastPackage != null) {
9370                pkgs.remove(lastPackage);
9371            }
9372            if (pkgs.size() > 0) {
9373                return pkgs.get(0);
9374            }
9375        }
9376        return null;
9377    }
9378
9379    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9380        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9381                userId, andCode ? 1 : 0, packageName);
9382        if (mSystemReady) {
9383            msg.sendToTarget();
9384        } else {
9385            if (mPostSystemReadyMessages == null) {
9386                mPostSystemReadyMessages = new ArrayList<>();
9387            }
9388            mPostSystemReadyMessages.add(msg);
9389        }
9390    }
9391
9392    void startCleaningPackages() {
9393        // reader
9394        synchronized (mPackages) {
9395            if (!isExternalMediaAvailable()) {
9396                return;
9397            }
9398            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9399                return;
9400            }
9401        }
9402        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9403        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9404        IActivityManager am = ActivityManagerNative.getDefault();
9405        if (am != null) {
9406            try {
9407                am.startService(null, intent, null, mContext.getOpPackageName(),
9408                        UserHandle.USER_OWNER);
9409            } catch (RemoteException e) {
9410            }
9411        }
9412    }
9413
9414    @Override
9415    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9416            int installFlags, String installerPackageName, VerificationParams verificationParams,
9417            String packageAbiOverride) {
9418        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9419                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9420    }
9421
9422    @Override
9423    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9424            int installFlags, String installerPackageName, VerificationParams verificationParams,
9425            String packageAbiOverride, int userId) {
9426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9427
9428        final int callingUid = Binder.getCallingUid();
9429        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9430
9431        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9432            try {
9433                if (observer != null) {
9434                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9435                }
9436            } catch (RemoteException re) {
9437            }
9438            return;
9439        }
9440
9441        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9442            installFlags |= PackageManager.INSTALL_FROM_ADB;
9443
9444        } else {
9445            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9446            // about installerPackageName.
9447
9448            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9449            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9450        }
9451
9452        UserHandle user;
9453        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9454            user = UserHandle.ALL;
9455        } else {
9456            user = new UserHandle(userId);
9457        }
9458
9459        // Only system components can circumvent runtime permissions when installing.
9460        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9461                && mContext.checkCallingOrSelfPermission(Manifest.permission
9462                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9463            throw new SecurityException("You need the "
9464                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9465                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9466        }
9467
9468        verificationParams.setInstallerUid(callingUid);
9469
9470        final File originFile = new File(originPath);
9471        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9472
9473        final Message msg = mHandler.obtainMessage(INIT_COPY);
9474        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9475                null, verificationParams, user, packageAbiOverride, null);
9476        mHandler.sendMessage(msg);
9477    }
9478
9479    void installStage(String packageName, File stagedDir, String stagedCid,
9480            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9481            String installerPackageName, int installerUid, UserHandle user) {
9482        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9483                params.referrerUri, installerUid, null);
9484        verifParams.setInstallerUid(installerUid);
9485
9486        final OriginInfo origin;
9487        if (stagedDir != null) {
9488            origin = OriginInfo.fromStagedFile(stagedDir);
9489        } else {
9490            origin = OriginInfo.fromStagedContainer(stagedCid);
9491        }
9492
9493        final Message msg = mHandler.obtainMessage(INIT_COPY);
9494        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9495                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9496                params.grantedRuntimePermissions);
9497        mHandler.sendMessage(msg);
9498    }
9499
9500    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9501        Bundle extras = new Bundle(1);
9502        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9503
9504        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9505                packageName, extras, null, null, new int[] {userId});
9506        try {
9507            IActivityManager am = ActivityManagerNative.getDefault();
9508            final boolean isSystem =
9509                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9510            if (isSystem && am.isUserRunning(userId, false)) {
9511                // The just-installed/enabled app is bundled on the system, so presumed
9512                // to be able to run automatically without needing an explicit launch.
9513                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9514                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9515                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9516                        .setPackage(packageName);
9517                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9518                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9519            }
9520        } catch (RemoteException e) {
9521            // shouldn't happen
9522            Slog.w(TAG, "Unable to bootstrap installed package", e);
9523        }
9524    }
9525
9526    @Override
9527    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9528            int userId) {
9529        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9530        PackageSetting pkgSetting;
9531        final int uid = Binder.getCallingUid();
9532        enforceCrossUserPermission(uid, userId, true, true,
9533                "setApplicationHiddenSetting for user " + userId);
9534
9535        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9536            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9537            return false;
9538        }
9539
9540        long callingId = Binder.clearCallingIdentity();
9541        try {
9542            boolean sendAdded = false;
9543            boolean sendRemoved = false;
9544            // writer
9545            synchronized (mPackages) {
9546                pkgSetting = mSettings.mPackages.get(packageName);
9547                if (pkgSetting == null) {
9548                    return false;
9549                }
9550                if (pkgSetting.getHidden(userId) != hidden) {
9551                    pkgSetting.setHidden(hidden, userId);
9552                    mSettings.writePackageRestrictionsLPr(userId);
9553                    if (hidden) {
9554                        sendRemoved = true;
9555                    } else {
9556                        sendAdded = true;
9557                    }
9558                }
9559            }
9560            if (sendAdded) {
9561                sendPackageAddedForUser(packageName, pkgSetting, userId);
9562                return true;
9563            }
9564            if (sendRemoved) {
9565                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9566                        "hiding pkg");
9567                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9568            }
9569        } finally {
9570            Binder.restoreCallingIdentity(callingId);
9571        }
9572        return false;
9573    }
9574
9575    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9576            int userId) {
9577        final PackageRemovedInfo info = new PackageRemovedInfo();
9578        info.removedPackage = packageName;
9579        info.removedUsers = new int[] {userId};
9580        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9581        info.sendBroadcast(false, false, false);
9582    }
9583
9584    /**
9585     * Returns true if application is not found or there was an error. Otherwise it returns
9586     * the hidden state of the package for the given user.
9587     */
9588    @Override
9589    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9590        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9591        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9592                false, "getApplicationHidden for user " + userId);
9593        PackageSetting pkgSetting;
9594        long callingId = Binder.clearCallingIdentity();
9595        try {
9596            // writer
9597            synchronized (mPackages) {
9598                pkgSetting = mSettings.mPackages.get(packageName);
9599                if (pkgSetting == null) {
9600                    return true;
9601                }
9602                return pkgSetting.getHidden(userId);
9603            }
9604        } finally {
9605            Binder.restoreCallingIdentity(callingId);
9606        }
9607    }
9608
9609    /**
9610     * @hide
9611     */
9612    @Override
9613    public int installExistingPackageAsUser(String packageName, int userId) {
9614        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9615                null);
9616        PackageSetting pkgSetting;
9617        final int uid = Binder.getCallingUid();
9618        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9619                + userId);
9620        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9621            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9622        }
9623
9624        long callingId = Binder.clearCallingIdentity();
9625        try {
9626            boolean sendAdded = false;
9627
9628            // writer
9629            synchronized (mPackages) {
9630                pkgSetting = mSettings.mPackages.get(packageName);
9631                if (pkgSetting == null) {
9632                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9633                }
9634                if (!pkgSetting.getInstalled(userId)) {
9635                    pkgSetting.setInstalled(true, userId);
9636                    pkgSetting.setHidden(false, userId);
9637                    mSettings.writePackageRestrictionsLPr(userId);
9638                    sendAdded = true;
9639                }
9640            }
9641
9642            if (sendAdded) {
9643                sendPackageAddedForUser(packageName, pkgSetting, userId);
9644            }
9645        } finally {
9646            Binder.restoreCallingIdentity(callingId);
9647        }
9648
9649        return PackageManager.INSTALL_SUCCEEDED;
9650    }
9651
9652    boolean isUserRestricted(int userId, String restrictionKey) {
9653        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9654        if (restrictions.getBoolean(restrictionKey, false)) {
9655            Log.w(TAG, "User is restricted: " + restrictionKey);
9656            return true;
9657        }
9658        return false;
9659    }
9660
9661    @Override
9662    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9663        mContext.enforceCallingOrSelfPermission(
9664                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9665                "Only package verification agents can verify applications");
9666
9667        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9668        final PackageVerificationResponse response = new PackageVerificationResponse(
9669                verificationCode, Binder.getCallingUid());
9670        msg.arg1 = id;
9671        msg.obj = response;
9672        mHandler.sendMessage(msg);
9673    }
9674
9675    @Override
9676    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9677            long millisecondsToDelay) {
9678        mContext.enforceCallingOrSelfPermission(
9679                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9680                "Only package verification agents can extend verification timeouts");
9681
9682        final PackageVerificationState state = mPendingVerification.get(id);
9683        final PackageVerificationResponse response = new PackageVerificationResponse(
9684                verificationCodeAtTimeout, Binder.getCallingUid());
9685
9686        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9687            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9688        }
9689        if (millisecondsToDelay < 0) {
9690            millisecondsToDelay = 0;
9691        }
9692        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9693                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9694            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9695        }
9696
9697        if ((state != null) && !state.timeoutExtended()) {
9698            state.extendTimeout();
9699
9700            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9701            msg.arg1 = id;
9702            msg.obj = response;
9703            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9704        }
9705    }
9706
9707    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9708            int verificationCode, UserHandle user) {
9709        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9710        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9711        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9712        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9713        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9714
9715        mContext.sendBroadcastAsUser(intent, user,
9716                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9717    }
9718
9719    private ComponentName matchComponentForVerifier(String packageName,
9720            List<ResolveInfo> receivers) {
9721        ActivityInfo targetReceiver = null;
9722
9723        final int NR = receivers.size();
9724        for (int i = 0; i < NR; i++) {
9725            final ResolveInfo info = receivers.get(i);
9726            if (info.activityInfo == null) {
9727                continue;
9728            }
9729
9730            if (packageName.equals(info.activityInfo.packageName)) {
9731                targetReceiver = info.activityInfo;
9732                break;
9733            }
9734        }
9735
9736        if (targetReceiver == null) {
9737            return null;
9738        }
9739
9740        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9741    }
9742
9743    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9744            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9745        if (pkgInfo.verifiers.length == 0) {
9746            return null;
9747        }
9748
9749        final int N = pkgInfo.verifiers.length;
9750        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9751        for (int i = 0; i < N; i++) {
9752            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9753
9754            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9755                    receivers);
9756            if (comp == null) {
9757                continue;
9758            }
9759
9760            final int verifierUid = getUidForVerifier(verifierInfo);
9761            if (verifierUid == -1) {
9762                continue;
9763            }
9764
9765            if (DEBUG_VERIFY) {
9766                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9767                        + " with the correct signature");
9768            }
9769            sufficientVerifiers.add(comp);
9770            verificationState.addSufficientVerifier(verifierUid);
9771        }
9772
9773        return sufficientVerifiers;
9774    }
9775
9776    private int getUidForVerifier(VerifierInfo verifierInfo) {
9777        synchronized (mPackages) {
9778            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9779            if (pkg == null) {
9780                return -1;
9781            } else if (pkg.mSignatures.length != 1) {
9782                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9783                        + " has more than one signature; ignoring");
9784                return -1;
9785            }
9786
9787            /*
9788             * If the public key of the package's signature does not match
9789             * our expected public key, then this is a different package and
9790             * we should skip.
9791             */
9792
9793            final byte[] expectedPublicKey;
9794            try {
9795                final Signature verifierSig = pkg.mSignatures[0];
9796                final PublicKey publicKey = verifierSig.getPublicKey();
9797                expectedPublicKey = publicKey.getEncoded();
9798            } catch (CertificateException e) {
9799                return -1;
9800            }
9801
9802            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9803
9804            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9805                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9806                        + " does not have the expected public key; ignoring");
9807                return -1;
9808            }
9809
9810            return pkg.applicationInfo.uid;
9811        }
9812    }
9813
9814    @Override
9815    public void finishPackageInstall(int token) {
9816        enforceSystemOrRoot("Only the system is allowed to finish installs");
9817
9818        if (DEBUG_INSTALL) {
9819            Slog.v(TAG, "BM finishing package install for " + token);
9820        }
9821
9822        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9823        mHandler.sendMessage(msg);
9824    }
9825
9826    /**
9827     * Get the verification agent timeout.
9828     *
9829     * @return verification timeout in milliseconds
9830     */
9831    private long getVerificationTimeout() {
9832        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9833                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9834                DEFAULT_VERIFICATION_TIMEOUT);
9835    }
9836
9837    /**
9838     * Get the default verification agent response code.
9839     *
9840     * @return default verification response code
9841     */
9842    private int getDefaultVerificationResponse() {
9843        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9844                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9845                DEFAULT_VERIFICATION_RESPONSE);
9846    }
9847
9848    /**
9849     * Check whether or not package verification has been enabled.
9850     *
9851     * @return true if verification should be performed
9852     */
9853    private boolean isVerificationEnabled(int userId, int installFlags) {
9854        if (!DEFAULT_VERIFY_ENABLE) {
9855            return false;
9856        }
9857
9858        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9859
9860        // Check if installing from ADB
9861        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9862            // Do not run verification in a test harness environment
9863            if (ActivityManager.isRunningInTestHarness()) {
9864                return false;
9865            }
9866            if (ensureVerifyAppsEnabled) {
9867                return true;
9868            }
9869            // Check if the developer does not want package verification for ADB installs
9870            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9871                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9872                return false;
9873            }
9874        }
9875
9876        if (ensureVerifyAppsEnabled) {
9877            return true;
9878        }
9879
9880        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9881                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9882    }
9883
9884    @Override
9885    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9886            throws RemoteException {
9887        mContext.enforceCallingOrSelfPermission(
9888                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9889                "Only intentfilter verification agents can verify applications");
9890
9891        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9892        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9893                Binder.getCallingUid(), verificationCode, failedDomains);
9894        msg.arg1 = id;
9895        msg.obj = response;
9896        mHandler.sendMessage(msg);
9897    }
9898
9899    @Override
9900    public int getIntentVerificationStatus(String packageName, int userId) {
9901        synchronized (mPackages) {
9902            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9903        }
9904    }
9905
9906    @Override
9907    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9908        mContext.enforceCallingOrSelfPermission(
9909                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9910
9911        boolean result = false;
9912        synchronized (mPackages) {
9913            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9914        }
9915        if (result) {
9916            scheduleWritePackageRestrictionsLocked(userId);
9917        }
9918        return result;
9919    }
9920
9921    @Override
9922    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9923        synchronized (mPackages) {
9924            return mSettings.getIntentFilterVerificationsLPr(packageName);
9925        }
9926    }
9927
9928    @Override
9929    public List<IntentFilter> getAllIntentFilters(String packageName) {
9930        if (TextUtils.isEmpty(packageName)) {
9931            return Collections.<IntentFilter>emptyList();
9932        }
9933        synchronized (mPackages) {
9934            PackageParser.Package pkg = mPackages.get(packageName);
9935            if (pkg == null || pkg.activities == null) {
9936                return Collections.<IntentFilter>emptyList();
9937            }
9938            final int count = pkg.activities.size();
9939            ArrayList<IntentFilter> result = new ArrayList<>();
9940            for (int n=0; n<count; n++) {
9941                PackageParser.Activity activity = pkg.activities.get(n);
9942                if (activity.intents != null || activity.intents.size() > 0) {
9943                    result.addAll(activity.intents);
9944                }
9945            }
9946            return result;
9947        }
9948    }
9949
9950    @Override
9951    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9952        mContext.enforceCallingOrSelfPermission(
9953                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9954
9955        synchronized (mPackages) {
9956            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9957            if (packageName != null) {
9958                result |= updateIntentVerificationStatus(packageName,
9959                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9960                        userId);
9961                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9962                        packageName, userId);
9963            }
9964            return result;
9965        }
9966    }
9967
9968    @Override
9969    public String getDefaultBrowserPackageName(int userId) {
9970        synchronized (mPackages) {
9971            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9972        }
9973    }
9974
9975    /**
9976     * Get the "allow unknown sources" setting.
9977     *
9978     * @return the current "allow unknown sources" setting
9979     */
9980    private int getUnknownSourcesSettings() {
9981        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9982                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9983                -1);
9984    }
9985
9986    @Override
9987    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9988        final int uid = Binder.getCallingUid();
9989        // writer
9990        synchronized (mPackages) {
9991            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9992            if (targetPackageSetting == null) {
9993                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9994            }
9995
9996            PackageSetting installerPackageSetting;
9997            if (installerPackageName != null) {
9998                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9999                if (installerPackageSetting == null) {
10000                    throw new IllegalArgumentException("Unknown installer package: "
10001                            + installerPackageName);
10002                }
10003            } else {
10004                installerPackageSetting = null;
10005            }
10006
10007            Signature[] callerSignature;
10008            Object obj = mSettings.getUserIdLPr(uid);
10009            if (obj != null) {
10010                if (obj instanceof SharedUserSetting) {
10011                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10012                } else if (obj instanceof PackageSetting) {
10013                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10014                } else {
10015                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10016                }
10017            } else {
10018                throw new SecurityException("Unknown calling uid " + uid);
10019            }
10020
10021            // Verify: can't set installerPackageName to a package that is
10022            // not signed with the same cert as the caller.
10023            if (installerPackageSetting != null) {
10024                if (compareSignatures(callerSignature,
10025                        installerPackageSetting.signatures.mSignatures)
10026                        != PackageManager.SIGNATURE_MATCH) {
10027                    throw new SecurityException(
10028                            "Caller does not have same cert as new installer package "
10029                            + installerPackageName);
10030                }
10031            }
10032
10033            // Verify: if target already has an installer package, it must
10034            // be signed with the same cert as the caller.
10035            if (targetPackageSetting.installerPackageName != null) {
10036                PackageSetting setting = mSettings.mPackages.get(
10037                        targetPackageSetting.installerPackageName);
10038                // If the currently set package isn't valid, then it's always
10039                // okay to change it.
10040                if (setting != null) {
10041                    if (compareSignatures(callerSignature,
10042                            setting.signatures.mSignatures)
10043                            != PackageManager.SIGNATURE_MATCH) {
10044                        throw new SecurityException(
10045                                "Caller does not have same cert as old installer package "
10046                                + targetPackageSetting.installerPackageName);
10047                    }
10048                }
10049            }
10050
10051            // Okay!
10052            targetPackageSetting.installerPackageName = installerPackageName;
10053            scheduleWriteSettingsLocked();
10054        }
10055    }
10056
10057    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10058        // Queue up an async operation since the package installation may take a little while.
10059        mHandler.post(new Runnable() {
10060            public void run() {
10061                mHandler.removeCallbacks(this);
10062                 // Result object to be returned
10063                PackageInstalledInfo res = new PackageInstalledInfo();
10064                res.returnCode = currentStatus;
10065                res.uid = -1;
10066                res.pkg = null;
10067                res.removedInfo = new PackageRemovedInfo();
10068                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10069                    args.doPreInstall(res.returnCode);
10070                    synchronized (mInstallLock) {
10071                        installPackageLI(args, res);
10072                    }
10073                    args.doPostInstall(res.returnCode, res.uid);
10074                }
10075
10076                // A restore should be performed at this point if (a) the install
10077                // succeeded, (b) the operation is not an update, and (c) the new
10078                // package has not opted out of backup participation.
10079                final boolean update = res.removedInfo.removedPackage != null;
10080                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10081                boolean doRestore = !update
10082                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10083
10084                // Set up the post-install work request bookkeeping.  This will be used
10085                // and cleaned up by the post-install event handling regardless of whether
10086                // there's a restore pass performed.  Token values are >= 1.
10087                int token;
10088                if (mNextInstallToken < 0) mNextInstallToken = 1;
10089                token = mNextInstallToken++;
10090
10091                PostInstallData data = new PostInstallData(args, res);
10092                mRunningInstalls.put(token, data);
10093                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10094
10095                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10096                    // Pass responsibility to the Backup Manager.  It will perform a
10097                    // restore if appropriate, then pass responsibility back to the
10098                    // Package Manager to run the post-install observer callbacks
10099                    // and broadcasts.
10100                    IBackupManager bm = IBackupManager.Stub.asInterface(
10101                            ServiceManager.getService(Context.BACKUP_SERVICE));
10102                    if (bm != null) {
10103                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10104                                + " to BM for possible restore");
10105                        try {
10106                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10107                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10108                            } else {
10109                                doRestore = false;
10110                            }
10111                        } catch (RemoteException e) {
10112                            // can't happen; the backup manager is local
10113                        } catch (Exception e) {
10114                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10115                            doRestore = false;
10116                        }
10117                    } else {
10118                        Slog.e(TAG, "Backup Manager not found!");
10119                        doRestore = false;
10120                    }
10121                }
10122
10123                if (!doRestore) {
10124                    // No restore possible, or the Backup Manager was mysteriously not
10125                    // available -- just fire the post-install work request directly.
10126                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10127                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10128                    mHandler.sendMessage(msg);
10129                }
10130            }
10131        });
10132    }
10133
10134    private abstract class HandlerParams {
10135        private static final int MAX_RETRIES = 4;
10136
10137        /**
10138         * Number of times startCopy() has been attempted and had a non-fatal
10139         * error.
10140         */
10141        private int mRetries = 0;
10142
10143        /** User handle for the user requesting the information or installation. */
10144        private final UserHandle mUser;
10145
10146        HandlerParams(UserHandle user) {
10147            mUser = user;
10148        }
10149
10150        UserHandle getUser() {
10151            return mUser;
10152        }
10153
10154        final boolean startCopy() {
10155            boolean res;
10156            try {
10157                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10158
10159                if (++mRetries > MAX_RETRIES) {
10160                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10161                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10162                    handleServiceError();
10163                    return false;
10164                } else {
10165                    handleStartCopy();
10166                    res = true;
10167                }
10168            } catch (RemoteException e) {
10169                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10170                mHandler.sendEmptyMessage(MCS_RECONNECT);
10171                res = false;
10172            }
10173            handleReturnCode();
10174            return res;
10175        }
10176
10177        final void serviceError() {
10178            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10179            handleServiceError();
10180            handleReturnCode();
10181        }
10182
10183        abstract void handleStartCopy() throws RemoteException;
10184        abstract void handleServiceError();
10185        abstract void handleReturnCode();
10186    }
10187
10188    class MeasureParams extends HandlerParams {
10189        private final PackageStats mStats;
10190        private boolean mSuccess;
10191
10192        private final IPackageStatsObserver mObserver;
10193
10194        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10195            super(new UserHandle(stats.userHandle));
10196            mObserver = observer;
10197            mStats = stats;
10198        }
10199
10200        @Override
10201        public String toString() {
10202            return "MeasureParams{"
10203                + Integer.toHexString(System.identityHashCode(this))
10204                + " " + mStats.packageName + "}";
10205        }
10206
10207        @Override
10208        void handleStartCopy() throws RemoteException {
10209            synchronized (mInstallLock) {
10210                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10211            }
10212
10213            if (mSuccess) {
10214                final boolean mounted;
10215                if (Environment.isExternalStorageEmulated()) {
10216                    mounted = true;
10217                } else {
10218                    final String status = Environment.getExternalStorageState();
10219                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10220                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10221                }
10222
10223                if (mounted) {
10224                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10225
10226                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10227                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10228
10229                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10230                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10231
10232                    // Always subtract cache size, since it's a subdirectory
10233                    mStats.externalDataSize -= mStats.externalCacheSize;
10234
10235                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10236                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10237
10238                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10239                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10240                }
10241            }
10242        }
10243
10244        @Override
10245        void handleReturnCode() {
10246            if (mObserver != null) {
10247                try {
10248                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10249                } catch (RemoteException e) {
10250                    Slog.i(TAG, "Observer no longer exists.");
10251                }
10252            }
10253        }
10254
10255        @Override
10256        void handleServiceError() {
10257            Slog.e(TAG, "Could not measure application " + mStats.packageName
10258                            + " external storage");
10259        }
10260    }
10261
10262    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10263            throws RemoteException {
10264        long result = 0;
10265        for (File path : paths) {
10266            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10267        }
10268        return result;
10269    }
10270
10271    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10272        for (File path : paths) {
10273            try {
10274                mcs.clearDirectory(path.getAbsolutePath());
10275            } catch (RemoteException e) {
10276            }
10277        }
10278    }
10279
10280    static class OriginInfo {
10281        /**
10282         * Location where install is coming from, before it has been
10283         * copied/renamed into place. This could be a single monolithic APK
10284         * file, or a cluster directory. This location may be untrusted.
10285         */
10286        final File file;
10287        final String cid;
10288
10289        /**
10290         * Flag indicating that {@link #file} or {@link #cid} has already been
10291         * staged, meaning downstream users don't need to defensively copy the
10292         * contents.
10293         */
10294        final boolean staged;
10295
10296        /**
10297         * Flag indicating that {@link #file} or {@link #cid} is an already
10298         * installed app that is being moved.
10299         */
10300        final boolean existing;
10301
10302        final String resolvedPath;
10303        final File resolvedFile;
10304
10305        static OriginInfo fromNothing() {
10306            return new OriginInfo(null, null, false, false);
10307        }
10308
10309        static OriginInfo fromUntrustedFile(File file) {
10310            return new OriginInfo(file, null, false, false);
10311        }
10312
10313        static OriginInfo fromExistingFile(File file) {
10314            return new OriginInfo(file, null, false, true);
10315        }
10316
10317        static OriginInfo fromStagedFile(File file) {
10318            return new OriginInfo(file, null, true, false);
10319        }
10320
10321        static OriginInfo fromStagedContainer(String cid) {
10322            return new OriginInfo(null, cid, true, false);
10323        }
10324
10325        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10326            this.file = file;
10327            this.cid = cid;
10328            this.staged = staged;
10329            this.existing = existing;
10330
10331            if (cid != null) {
10332                resolvedPath = PackageHelper.getSdDir(cid);
10333                resolvedFile = new File(resolvedPath);
10334            } else if (file != null) {
10335                resolvedPath = file.getAbsolutePath();
10336                resolvedFile = file;
10337            } else {
10338                resolvedPath = null;
10339                resolvedFile = null;
10340            }
10341        }
10342    }
10343
10344    class MoveInfo {
10345        final int moveId;
10346        final String fromUuid;
10347        final String toUuid;
10348        final String packageName;
10349        final String dataAppName;
10350        final int appId;
10351        final String seinfo;
10352
10353        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10354                String dataAppName, int appId, String seinfo) {
10355            this.moveId = moveId;
10356            this.fromUuid = fromUuid;
10357            this.toUuid = toUuid;
10358            this.packageName = packageName;
10359            this.dataAppName = dataAppName;
10360            this.appId = appId;
10361            this.seinfo = seinfo;
10362        }
10363    }
10364
10365    class InstallParams extends HandlerParams {
10366        final OriginInfo origin;
10367        final MoveInfo move;
10368        final IPackageInstallObserver2 observer;
10369        int installFlags;
10370        final String installerPackageName;
10371        final String volumeUuid;
10372        final VerificationParams verificationParams;
10373        private InstallArgs mArgs;
10374        private int mRet;
10375        final String packageAbiOverride;
10376        final String[] grantedRuntimePermissions;
10377
10378
10379        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10380                int installFlags, String installerPackageName, String volumeUuid,
10381                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10382                String[] grantedPermissions) {
10383            super(user);
10384            this.origin = origin;
10385            this.move = move;
10386            this.observer = observer;
10387            this.installFlags = installFlags;
10388            this.installerPackageName = installerPackageName;
10389            this.volumeUuid = volumeUuid;
10390            this.verificationParams = verificationParams;
10391            this.packageAbiOverride = packageAbiOverride;
10392            this.grantedRuntimePermissions = grantedPermissions;
10393        }
10394
10395        @Override
10396        public String toString() {
10397            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10398                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10399        }
10400
10401        public ManifestDigest getManifestDigest() {
10402            if (verificationParams == null) {
10403                return null;
10404            }
10405            return verificationParams.getManifestDigest();
10406        }
10407
10408        private int installLocationPolicy(PackageInfoLite pkgLite) {
10409            String packageName = pkgLite.packageName;
10410            int installLocation = pkgLite.installLocation;
10411            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10412            // reader
10413            synchronized (mPackages) {
10414                PackageParser.Package pkg = mPackages.get(packageName);
10415                if (pkg != null) {
10416                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10417                        // Check for downgrading.
10418                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10419                            try {
10420                                checkDowngrade(pkg, pkgLite);
10421                            } catch (PackageManagerException e) {
10422                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10423                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10424                            }
10425                        }
10426                        // Check for updated system application.
10427                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10428                            if (onSd) {
10429                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10430                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10431                            }
10432                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10433                        } else {
10434                            if (onSd) {
10435                                // Install flag overrides everything.
10436                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10437                            }
10438                            // If current upgrade specifies particular preference
10439                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10440                                // Application explicitly specified internal.
10441                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10442                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10443                                // App explictly prefers external. Let policy decide
10444                            } else {
10445                                // Prefer previous location
10446                                if (isExternal(pkg)) {
10447                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10448                                }
10449                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10450                            }
10451                        }
10452                    } else {
10453                        // Invalid install. Return error code
10454                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10455                    }
10456                }
10457            }
10458            // All the special cases have been taken care of.
10459            // Return result based on recommended install location.
10460            if (onSd) {
10461                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10462            }
10463            return pkgLite.recommendedInstallLocation;
10464        }
10465
10466        /*
10467         * Invoke remote method to get package information and install
10468         * location values. Override install location based on default
10469         * policy if needed and then create install arguments based
10470         * on the install location.
10471         */
10472        public void handleStartCopy() throws RemoteException {
10473            int ret = PackageManager.INSTALL_SUCCEEDED;
10474
10475            // If we're already staged, we've firmly committed to an install location
10476            if (origin.staged) {
10477                if (origin.file != null) {
10478                    installFlags |= PackageManager.INSTALL_INTERNAL;
10479                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10480                } else if (origin.cid != null) {
10481                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10482                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10483                } else {
10484                    throw new IllegalStateException("Invalid stage location");
10485                }
10486            }
10487
10488            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10489            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10490
10491            PackageInfoLite pkgLite = null;
10492
10493            if (onInt && onSd) {
10494                // Check if both bits are set.
10495                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10496                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10497            } else {
10498                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10499                        packageAbiOverride);
10500
10501                /*
10502                 * If we have too little free space, try to free cache
10503                 * before giving up.
10504                 */
10505                if (!origin.staged && pkgLite.recommendedInstallLocation
10506                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10507                    // TODO: focus freeing disk space on the target device
10508                    final StorageManager storage = StorageManager.from(mContext);
10509                    final long lowThreshold = storage.getStorageLowBytes(
10510                            Environment.getDataDirectory());
10511
10512                    final long sizeBytes = mContainerService.calculateInstalledSize(
10513                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10514
10515                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10516                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10517                                installFlags, packageAbiOverride);
10518                    }
10519
10520                    /*
10521                     * The cache free must have deleted the file we
10522                     * downloaded to install.
10523                     *
10524                     * TODO: fix the "freeCache" call to not delete
10525                     *       the file we care about.
10526                     */
10527                    if (pkgLite.recommendedInstallLocation
10528                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10529                        pkgLite.recommendedInstallLocation
10530                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10531                    }
10532                }
10533            }
10534
10535            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10536                int loc = pkgLite.recommendedInstallLocation;
10537                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10538                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10539                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10540                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10541                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10542                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10543                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10544                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10545                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10546                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10547                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10548                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10549                } else {
10550                    // Override with defaults if needed.
10551                    loc = installLocationPolicy(pkgLite);
10552                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10553                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10554                    } else if (!onSd && !onInt) {
10555                        // Override install location with flags
10556                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10557                            // Set the flag to install on external media.
10558                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10559                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10560                        } else {
10561                            // Make sure the flag for installing on external
10562                            // media is unset
10563                            installFlags |= PackageManager.INSTALL_INTERNAL;
10564                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10565                        }
10566                    }
10567                }
10568            }
10569
10570            final InstallArgs args = createInstallArgs(this);
10571            mArgs = args;
10572
10573            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10574                 /*
10575                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10576                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10577                 */
10578                int userIdentifier = getUser().getIdentifier();
10579                if (userIdentifier == UserHandle.USER_ALL
10580                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10581                    userIdentifier = UserHandle.USER_OWNER;
10582                }
10583
10584                /*
10585                 * Determine if we have any installed package verifiers. If we
10586                 * do, then we'll defer to them to verify the packages.
10587                 */
10588                final int requiredUid = mRequiredVerifierPackage == null ? -1
10589                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10590                if (!origin.existing && requiredUid != -1
10591                        && isVerificationEnabled(userIdentifier, installFlags)) {
10592                    final Intent verification = new Intent(
10593                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10594                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10595                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10596                            PACKAGE_MIME_TYPE);
10597                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10598
10599                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10600                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10601                            0 /* TODO: Which userId? */);
10602
10603                    if (DEBUG_VERIFY) {
10604                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10605                                + verification.toString() + " with " + pkgLite.verifiers.length
10606                                + " optional verifiers");
10607                    }
10608
10609                    final int verificationId = mPendingVerificationToken++;
10610
10611                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10612
10613                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10614                            installerPackageName);
10615
10616                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10617                            installFlags);
10618
10619                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10620                            pkgLite.packageName);
10621
10622                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10623                            pkgLite.versionCode);
10624
10625                    if (verificationParams != null) {
10626                        if (verificationParams.getVerificationURI() != null) {
10627                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10628                                 verificationParams.getVerificationURI());
10629                        }
10630                        if (verificationParams.getOriginatingURI() != null) {
10631                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10632                                  verificationParams.getOriginatingURI());
10633                        }
10634                        if (verificationParams.getReferrer() != null) {
10635                            verification.putExtra(Intent.EXTRA_REFERRER,
10636                                  verificationParams.getReferrer());
10637                        }
10638                        if (verificationParams.getOriginatingUid() >= 0) {
10639                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10640                                  verificationParams.getOriginatingUid());
10641                        }
10642                        if (verificationParams.getInstallerUid() >= 0) {
10643                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10644                                  verificationParams.getInstallerUid());
10645                        }
10646                    }
10647
10648                    final PackageVerificationState verificationState = new PackageVerificationState(
10649                            requiredUid, args);
10650
10651                    mPendingVerification.append(verificationId, verificationState);
10652
10653                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10654                            receivers, verificationState);
10655
10656                    // Apps installed for "all" users use the device owner to verify the app
10657                    UserHandle verifierUser = getUser();
10658                    if (verifierUser == UserHandle.ALL) {
10659                        verifierUser = UserHandle.OWNER;
10660                    }
10661
10662                    /*
10663                     * If any sufficient verifiers were listed in the package
10664                     * manifest, attempt to ask them.
10665                     */
10666                    if (sufficientVerifiers != null) {
10667                        final int N = sufficientVerifiers.size();
10668                        if (N == 0) {
10669                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10670                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10671                        } else {
10672                            for (int i = 0; i < N; i++) {
10673                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10674
10675                                final Intent sufficientIntent = new Intent(verification);
10676                                sufficientIntent.setComponent(verifierComponent);
10677                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10678                            }
10679                        }
10680                    }
10681
10682                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10683                            mRequiredVerifierPackage, receivers);
10684                    if (ret == PackageManager.INSTALL_SUCCEEDED
10685                            && mRequiredVerifierPackage != null) {
10686                        /*
10687                         * Send the intent to the required verification agent,
10688                         * but only start the verification timeout after the
10689                         * target BroadcastReceivers have run.
10690                         */
10691                        verification.setComponent(requiredVerifierComponent);
10692                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10693                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10694                                new BroadcastReceiver() {
10695                                    @Override
10696                                    public void onReceive(Context context, Intent intent) {
10697                                        final Message msg = mHandler
10698                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10699                                        msg.arg1 = verificationId;
10700                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10701                                    }
10702                                }, null, 0, null, null);
10703
10704                        /*
10705                         * We don't want the copy to proceed until verification
10706                         * succeeds, so null out this field.
10707                         */
10708                        mArgs = null;
10709                    }
10710                } else {
10711                    /*
10712                     * No package verification is enabled, so immediately start
10713                     * the remote call to initiate copy using temporary file.
10714                     */
10715                    ret = args.copyApk(mContainerService, true);
10716                }
10717            }
10718
10719            mRet = ret;
10720        }
10721
10722        @Override
10723        void handleReturnCode() {
10724            // If mArgs is null, then MCS couldn't be reached. When it
10725            // reconnects, it will try again to install. At that point, this
10726            // will succeed.
10727            if (mArgs != null) {
10728                processPendingInstall(mArgs, mRet);
10729            }
10730        }
10731
10732        @Override
10733        void handleServiceError() {
10734            mArgs = createInstallArgs(this);
10735            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10736        }
10737
10738        public boolean isForwardLocked() {
10739            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10740        }
10741    }
10742
10743    /**
10744     * Used during creation of InstallArgs
10745     *
10746     * @param installFlags package installation flags
10747     * @return true if should be installed on external storage
10748     */
10749    private static boolean installOnExternalAsec(int installFlags) {
10750        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10751            return false;
10752        }
10753        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10754            return true;
10755        }
10756        return false;
10757    }
10758
10759    /**
10760     * Used during creation of InstallArgs
10761     *
10762     * @param installFlags package installation flags
10763     * @return true if should be installed as forward locked
10764     */
10765    private static boolean installForwardLocked(int installFlags) {
10766        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10767    }
10768
10769    private InstallArgs createInstallArgs(InstallParams params) {
10770        if (params.move != null) {
10771            return new MoveInstallArgs(params);
10772        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10773            return new AsecInstallArgs(params);
10774        } else {
10775            return new FileInstallArgs(params);
10776        }
10777    }
10778
10779    /**
10780     * Create args that describe an existing installed package. Typically used
10781     * when cleaning up old installs, or used as a move source.
10782     */
10783    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10784            String resourcePath, String[] instructionSets) {
10785        final boolean isInAsec;
10786        if (installOnExternalAsec(installFlags)) {
10787            /* Apps on SD card are always in ASEC containers. */
10788            isInAsec = true;
10789        } else if (installForwardLocked(installFlags)
10790                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10791            /*
10792             * Forward-locked apps are only in ASEC containers if they're the
10793             * new style
10794             */
10795            isInAsec = true;
10796        } else {
10797            isInAsec = false;
10798        }
10799
10800        if (isInAsec) {
10801            return new AsecInstallArgs(codePath, instructionSets,
10802                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10803        } else {
10804            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10805        }
10806    }
10807
10808    static abstract class InstallArgs {
10809        /** @see InstallParams#origin */
10810        final OriginInfo origin;
10811        /** @see InstallParams#move */
10812        final MoveInfo move;
10813
10814        final IPackageInstallObserver2 observer;
10815        // Always refers to PackageManager flags only
10816        final int installFlags;
10817        final String installerPackageName;
10818        final String volumeUuid;
10819        final ManifestDigest manifestDigest;
10820        final UserHandle user;
10821        final String abiOverride;
10822        final String[] installGrantPermissions;
10823
10824        // The list of instruction sets supported by this app. This is currently
10825        // only used during the rmdex() phase to clean up resources. We can get rid of this
10826        // if we move dex files under the common app path.
10827        /* nullable */ String[] instructionSets;
10828
10829        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10830                int installFlags, String installerPackageName, String volumeUuid,
10831                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10832                String abiOverride, String[] installGrantPermissions) {
10833            this.origin = origin;
10834            this.move = move;
10835            this.installFlags = installFlags;
10836            this.observer = observer;
10837            this.installerPackageName = installerPackageName;
10838            this.volumeUuid = volumeUuid;
10839            this.manifestDigest = manifestDigest;
10840            this.user = user;
10841            this.instructionSets = instructionSets;
10842            this.abiOverride = abiOverride;
10843            this.installGrantPermissions = installGrantPermissions;
10844        }
10845
10846        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10847        abstract int doPreInstall(int status);
10848
10849        /**
10850         * Rename package into final resting place. All paths on the given
10851         * scanned package should be updated to reflect the rename.
10852         */
10853        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10854        abstract int doPostInstall(int status, int uid);
10855
10856        /** @see PackageSettingBase#codePathString */
10857        abstract String getCodePath();
10858        /** @see PackageSettingBase#resourcePathString */
10859        abstract String getResourcePath();
10860
10861        // Need installer lock especially for dex file removal.
10862        abstract void cleanUpResourcesLI();
10863        abstract boolean doPostDeleteLI(boolean delete);
10864
10865        /**
10866         * Called before the source arguments are copied. This is used mostly
10867         * for MoveParams when it needs to read the source file to put it in the
10868         * destination.
10869         */
10870        int doPreCopy() {
10871            return PackageManager.INSTALL_SUCCEEDED;
10872        }
10873
10874        /**
10875         * Called after the source arguments are copied. This is used mostly for
10876         * MoveParams when it needs to read the source file to put it in the
10877         * destination.
10878         *
10879         * @return
10880         */
10881        int doPostCopy(int uid) {
10882            return PackageManager.INSTALL_SUCCEEDED;
10883        }
10884
10885        protected boolean isFwdLocked() {
10886            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10887        }
10888
10889        protected boolean isExternalAsec() {
10890            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10891        }
10892
10893        UserHandle getUser() {
10894            return user;
10895        }
10896    }
10897
10898    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10899        if (!allCodePaths.isEmpty()) {
10900            if (instructionSets == null) {
10901                throw new IllegalStateException("instructionSet == null");
10902            }
10903            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10904            for (String codePath : allCodePaths) {
10905                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10906                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10907                    if (retCode < 0) {
10908                        Slog.w(TAG, "Couldn't remove dex file for package: "
10909                                + " at location " + codePath + ", retcode=" + retCode);
10910                        // we don't consider this to be a failure of the core package deletion
10911                    }
10912                }
10913            }
10914        }
10915    }
10916
10917    /**
10918     * Logic to handle installation of non-ASEC applications, including copying
10919     * and renaming logic.
10920     */
10921    class FileInstallArgs extends InstallArgs {
10922        private File codeFile;
10923        private File resourceFile;
10924
10925        // Example topology:
10926        // /data/app/com.example/base.apk
10927        // /data/app/com.example/split_foo.apk
10928        // /data/app/com.example/lib/arm/libfoo.so
10929        // /data/app/com.example/lib/arm64/libfoo.so
10930        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10931
10932        /** New install */
10933        FileInstallArgs(InstallParams params) {
10934            super(params.origin, params.move, params.observer, params.installFlags,
10935                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10936                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10937                    params.grantedRuntimePermissions);
10938            if (isFwdLocked()) {
10939                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10940            }
10941        }
10942
10943        /** Existing install */
10944        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10945            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10946                    null, null);
10947            this.codeFile = (codePath != null) ? new File(codePath) : null;
10948            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10949        }
10950
10951        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10952            if (origin.staged) {
10953                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10954                codeFile = origin.file;
10955                resourceFile = origin.file;
10956                return PackageManager.INSTALL_SUCCEEDED;
10957            }
10958
10959            try {
10960                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10961                codeFile = tempDir;
10962                resourceFile = tempDir;
10963            } catch (IOException e) {
10964                Slog.w(TAG, "Failed to create copy file: " + e);
10965                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10966            }
10967
10968            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10969                @Override
10970                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10971                    if (!FileUtils.isValidExtFilename(name)) {
10972                        throw new IllegalArgumentException("Invalid filename: " + name);
10973                    }
10974                    try {
10975                        final File file = new File(codeFile, name);
10976                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10977                                O_RDWR | O_CREAT, 0644);
10978                        Os.chmod(file.getAbsolutePath(), 0644);
10979                        return new ParcelFileDescriptor(fd);
10980                    } catch (ErrnoException e) {
10981                        throw new RemoteException("Failed to open: " + e.getMessage());
10982                    }
10983                }
10984            };
10985
10986            int ret = PackageManager.INSTALL_SUCCEEDED;
10987            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10988            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10989                Slog.e(TAG, "Failed to copy package");
10990                return ret;
10991            }
10992
10993            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10994            NativeLibraryHelper.Handle handle = null;
10995            try {
10996                handle = NativeLibraryHelper.Handle.create(codeFile);
10997                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10998                        abiOverride);
10999            } catch (IOException e) {
11000                Slog.e(TAG, "Copying native libraries failed", e);
11001                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11002            } finally {
11003                IoUtils.closeQuietly(handle);
11004            }
11005
11006            return ret;
11007        }
11008
11009        int doPreInstall(int status) {
11010            if (status != PackageManager.INSTALL_SUCCEEDED) {
11011                cleanUp();
11012            }
11013            return status;
11014        }
11015
11016        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11017            if (status != PackageManager.INSTALL_SUCCEEDED) {
11018                cleanUp();
11019                return false;
11020            }
11021
11022            final File targetDir = codeFile.getParentFile();
11023            final File beforeCodeFile = codeFile;
11024            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11025
11026            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11027            try {
11028                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11029            } catch (ErrnoException e) {
11030                Slog.w(TAG, "Failed to rename", e);
11031                return false;
11032            }
11033
11034            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11035                Slog.w(TAG, "Failed to restorecon");
11036                return false;
11037            }
11038
11039            // Reflect the rename internally
11040            codeFile = afterCodeFile;
11041            resourceFile = afterCodeFile;
11042
11043            // Reflect the rename in scanned details
11044            pkg.codePath = afterCodeFile.getAbsolutePath();
11045            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11046                    pkg.baseCodePath);
11047            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11048                    pkg.splitCodePaths);
11049
11050            // Reflect the rename in app info
11051            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11052            pkg.applicationInfo.setCodePath(pkg.codePath);
11053            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11054            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11055            pkg.applicationInfo.setResourcePath(pkg.codePath);
11056            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11057            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11058
11059            return true;
11060        }
11061
11062        int doPostInstall(int status, int uid) {
11063            if (status != PackageManager.INSTALL_SUCCEEDED) {
11064                cleanUp();
11065            }
11066            return status;
11067        }
11068
11069        @Override
11070        String getCodePath() {
11071            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11072        }
11073
11074        @Override
11075        String getResourcePath() {
11076            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11077        }
11078
11079        private boolean cleanUp() {
11080            if (codeFile == null || !codeFile.exists()) {
11081                return false;
11082            }
11083
11084            if (codeFile.isDirectory()) {
11085                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11086            } else {
11087                codeFile.delete();
11088            }
11089
11090            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11091                resourceFile.delete();
11092            }
11093
11094            return true;
11095        }
11096
11097        void cleanUpResourcesLI() {
11098            // Try enumerating all code paths before deleting
11099            List<String> allCodePaths = Collections.EMPTY_LIST;
11100            if (codeFile != null && codeFile.exists()) {
11101                try {
11102                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11103                    allCodePaths = pkg.getAllCodePaths();
11104                } catch (PackageParserException e) {
11105                    // Ignored; we tried our best
11106                }
11107            }
11108
11109            cleanUp();
11110            removeDexFiles(allCodePaths, instructionSets);
11111        }
11112
11113        boolean doPostDeleteLI(boolean delete) {
11114            // XXX err, shouldn't we respect the delete flag?
11115            cleanUpResourcesLI();
11116            return true;
11117        }
11118    }
11119
11120    private boolean isAsecExternal(String cid) {
11121        final String asecPath = PackageHelper.getSdFilesystem(cid);
11122        return !asecPath.startsWith(mAsecInternalPath);
11123    }
11124
11125    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11126            PackageManagerException {
11127        if (copyRet < 0) {
11128            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11129                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11130                throw new PackageManagerException(copyRet, message);
11131            }
11132        }
11133    }
11134
11135    /**
11136     * Extract the MountService "container ID" from the full code path of an
11137     * .apk.
11138     */
11139    static String cidFromCodePath(String fullCodePath) {
11140        int eidx = fullCodePath.lastIndexOf("/");
11141        String subStr1 = fullCodePath.substring(0, eidx);
11142        int sidx = subStr1.lastIndexOf("/");
11143        return subStr1.substring(sidx+1, eidx);
11144    }
11145
11146    /**
11147     * Logic to handle installation of ASEC applications, including copying and
11148     * renaming logic.
11149     */
11150    class AsecInstallArgs extends InstallArgs {
11151        static final String RES_FILE_NAME = "pkg.apk";
11152        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11153
11154        String cid;
11155        String packagePath;
11156        String resourcePath;
11157
11158        /** New install */
11159        AsecInstallArgs(InstallParams params) {
11160            super(params.origin, params.move, params.observer, params.installFlags,
11161                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11162                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11163                    params.grantedRuntimePermissions);
11164        }
11165
11166        /** Existing install */
11167        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11168                        boolean isExternal, boolean isForwardLocked) {
11169            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11170                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11171                    instructionSets, null, null);
11172            // Hackily pretend we're still looking at a full code path
11173            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11174                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11175            }
11176
11177            // Extract cid from fullCodePath
11178            int eidx = fullCodePath.lastIndexOf("/");
11179            String subStr1 = fullCodePath.substring(0, eidx);
11180            int sidx = subStr1.lastIndexOf("/");
11181            cid = subStr1.substring(sidx+1, eidx);
11182            setMountPath(subStr1);
11183        }
11184
11185        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11186            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11187                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11188                    instructionSets, null, null);
11189            this.cid = cid;
11190            setMountPath(PackageHelper.getSdDir(cid));
11191        }
11192
11193        void createCopyFile() {
11194            cid = mInstallerService.allocateExternalStageCidLegacy();
11195        }
11196
11197        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11198            if (origin.staged) {
11199                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11200                cid = origin.cid;
11201                setMountPath(PackageHelper.getSdDir(cid));
11202                return PackageManager.INSTALL_SUCCEEDED;
11203            }
11204
11205            if (temp) {
11206                createCopyFile();
11207            } else {
11208                /*
11209                 * Pre-emptively destroy the container since it's destroyed if
11210                 * copying fails due to it existing anyway.
11211                 */
11212                PackageHelper.destroySdDir(cid);
11213            }
11214
11215            final String newMountPath = imcs.copyPackageToContainer(
11216                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11217                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11218
11219            if (newMountPath != null) {
11220                setMountPath(newMountPath);
11221                return PackageManager.INSTALL_SUCCEEDED;
11222            } else {
11223                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11224            }
11225        }
11226
11227        @Override
11228        String getCodePath() {
11229            return packagePath;
11230        }
11231
11232        @Override
11233        String getResourcePath() {
11234            return resourcePath;
11235        }
11236
11237        int doPreInstall(int status) {
11238            if (status != PackageManager.INSTALL_SUCCEEDED) {
11239                // Destroy container
11240                PackageHelper.destroySdDir(cid);
11241            } else {
11242                boolean mounted = PackageHelper.isContainerMounted(cid);
11243                if (!mounted) {
11244                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11245                            Process.SYSTEM_UID);
11246                    if (newMountPath != null) {
11247                        setMountPath(newMountPath);
11248                    } else {
11249                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11250                    }
11251                }
11252            }
11253            return status;
11254        }
11255
11256        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11257            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11258            String newMountPath = null;
11259            if (PackageHelper.isContainerMounted(cid)) {
11260                // Unmount the container
11261                if (!PackageHelper.unMountSdDir(cid)) {
11262                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11263                    return false;
11264                }
11265            }
11266            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11267                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11268                        " which might be stale. Will try to clean up.");
11269                // Clean up the stale container and proceed to recreate.
11270                if (!PackageHelper.destroySdDir(newCacheId)) {
11271                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11272                    return false;
11273                }
11274                // Successfully cleaned up stale container. Try to rename again.
11275                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11276                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11277                            + " inspite of cleaning it up.");
11278                    return false;
11279                }
11280            }
11281            if (!PackageHelper.isContainerMounted(newCacheId)) {
11282                Slog.w(TAG, "Mounting container " + newCacheId);
11283                newMountPath = PackageHelper.mountSdDir(newCacheId,
11284                        getEncryptKey(), Process.SYSTEM_UID);
11285            } else {
11286                newMountPath = PackageHelper.getSdDir(newCacheId);
11287            }
11288            if (newMountPath == null) {
11289                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11290                return false;
11291            }
11292            Log.i(TAG, "Succesfully renamed " + cid +
11293                    " to " + newCacheId +
11294                    " at new path: " + newMountPath);
11295            cid = newCacheId;
11296
11297            final File beforeCodeFile = new File(packagePath);
11298            setMountPath(newMountPath);
11299            final File afterCodeFile = new File(packagePath);
11300
11301            // Reflect the rename in scanned details
11302            pkg.codePath = afterCodeFile.getAbsolutePath();
11303            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11304                    pkg.baseCodePath);
11305            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11306                    pkg.splitCodePaths);
11307
11308            // Reflect the rename in app info
11309            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11310            pkg.applicationInfo.setCodePath(pkg.codePath);
11311            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11312            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11313            pkg.applicationInfo.setResourcePath(pkg.codePath);
11314            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11315            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11316
11317            return true;
11318        }
11319
11320        private void setMountPath(String mountPath) {
11321            final File mountFile = new File(mountPath);
11322
11323            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11324            if (monolithicFile.exists()) {
11325                packagePath = monolithicFile.getAbsolutePath();
11326                if (isFwdLocked()) {
11327                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11328                } else {
11329                    resourcePath = packagePath;
11330                }
11331            } else {
11332                packagePath = mountFile.getAbsolutePath();
11333                resourcePath = packagePath;
11334            }
11335        }
11336
11337        int doPostInstall(int status, int uid) {
11338            if (status != PackageManager.INSTALL_SUCCEEDED) {
11339                cleanUp();
11340            } else {
11341                final int groupOwner;
11342                final String protectedFile;
11343                if (isFwdLocked()) {
11344                    groupOwner = UserHandle.getSharedAppGid(uid);
11345                    protectedFile = RES_FILE_NAME;
11346                } else {
11347                    groupOwner = -1;
11348                    protectedFile = null;
11349                }
11350
11351                if (uid < Process.FIRST_APPLICATION_UID
11352                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11353                    Slog.e(TAG, "Failed to finalize " + cid);
11354                    PackageHelper.destroySdDir(cid);
11355                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11356                }
11357
11358                boolean mounted = PackageHelper.isContainerMounted(cid);
11359                if (!mounted) {
11360                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11361                }
11362            }
11363            return status;
11364        }
11365
11366        private void cleanUp() {
11367            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11368
11369            // Destroy secure container
11370            PackageHelper.destroySdDir(cid);
11371        }
11372
11373        private List<String> getAllCodePaths() {
11374            final File codeFile = new File(getCodePath());
11375            if (codeFile != null && codeFile.exists()) {
11376                try {
11377                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11378                    return pkg.getAllCodePaths();
11379                } catch (PackageParserException e) {
11380                    // Ignored; we tried our best
11381                }
11382            }
11383            return Collections.EMPTY_LIST;
11384        }
11385
11386        void cleanUpResourcesLI() {
11387            // Enumerate all code paths before deleting
11388            cleanUpResourcesLI(getAllCodePaths());
11389        }
11390
11391        private void cleanUpResourcesLI(List<String> allCodePaths) {
11392            cleanUp();
11393            removeDexFiles(allCodePaths, instructionSets);
11394        }
11395
11396        String getPackageName() {
11397            return getAsecPackageName(cid);
11398        }
11399
11400        boolean doPostDeleteLI(boolean delete) {
11401            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11402            final List<String> allCodePaths = getAllCodePaths();
11403            boolean mounted = PackageHelper.isContainerMounted(cid);
11404            if (mounted) {
11405                // Unmount first
11406                if (PackageHelper.unMountSdDir(cid)) {
11407                    mounted = false;
11408                }
11409            }
11410            if (!mounted && delete) {
11411                cleanUpResourcesLI(allCodePaths);
11412            }
11413            return !mounted;
11414        }
11415
11416        @Override
11417        int doPreCopy() {
11418            if (isFwdLocked()) {
11419                if (!PackageHelper.fixSdPermissions(cid,
11420                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11421                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11422                }
11423            }
11424
11425            return PackageManager.INSTALL_SUCCEEDED;
11426        }
11427
11428        @Override
11429        int doPostCopy(int uid) {
11430            if (isFwdLocked()) {
11431                if (uid < Process.FIRST_APPLICATION_UID
11432                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11433                                RES_FILE_NAME)) {
11434                    Slog.e(TAG, "Failed to finalize " + cid);
11435                    PackageHelper.destroySdDir(cid);
11436                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11437                }
11438            }
11439
11440            return PackageManager.INSTALL_SUCCEEDED;
11441        }
11442    }
11443
11444    /**
11445     * Logic to handle movement of existing installed applications.
11446     */
11447    class MoveInstallArgs extends InstallArgs {
11448        private File codeFile;
11449        private File resourceFile;
11450
11451        /** New install */
11452        MoveInstallArgs(InstallParams params) {
11453            super(params.origin, params.move, params.observer, params.installFlags,
11454                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11455                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11456                    params.grantedRuntimePermissions);
11457        }
11458
11459        int copyApk(IMediaContainerService imcs, boolean temp) {
11460            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11461                    + move.fromUuid + " to " + move.toUuid);
11462            synchronized (mInstaller) {
11463                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11464                        move.dataAppName, move.appId, move.seinfo) != 0) {
11465                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11466                }
11467            }
11468
11469            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11470            resourceFile = codeFile;
11471            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11472
11473            return PackageManager.INSTALL_SUCCEEDED;
11474        }
11475
11476        int doPreInstall(int status) {
11477            if (status != PackageManager.INSTALL_SUCCEEDED) {
11478                cleanUp(move.toUuid);
11479            }
11480            return status;
11481        }
11482
11483        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11484            if (status != PackageManager.INSTALL_SUCCEEDED) {
11485                cleanUp(move.toUuid);
11486                return false;
11487            }
11488
11489            // Reflect the move in app info
11490            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11491            pkg.applicationInfo.setCodePath(pkg.codePath);
11492            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11493            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11494            pkg.applicationInfo.setResourcePath(pkg.codePath);
11495            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11496            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11497
11498            return true;
11499        }
11500
11501        int doPostInstall(int status, int uid) {
11502            if (status == PackageManager.INSTALL_SUCCEEDED) {
11503                cleanUp(move.fromUuid);
11504            } else {
11505                cleanUp(move.toUuid);
11506            }
11507            return status;
11508        }
11509
11510        @Override
11511        String getCodePath() {
11512            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11513        }
11514
11515        @Override
11516        String getResourcePath() {
11517            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11518        }
11519
11520        private boolean cleanUp(String volumeUuid) {
11521            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11522                    move.dataAppName);
11523            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11524            synchronized (mInstallLock) {
11525                // Clean up both app data and code
11526                removeDataDirsLI(volumeUuid, move.packageName);
11527                if (codeFile.isDirectory()) {
11528                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11529                } else {
11530                    codeFile.delete();
11531                }
11532            }
11533            return true;
11534        }
11535
11536        void cleanUpResourcesLI() {
11537            throw new UnsupportedOperationException();
11538        }
11539
11540        boolean doPostDeleteLI(boolean delete) {
11541            throw new UnsupportedOperationException();
11542        }
11543    }
11544
11545    static String getAsecPackageName(String packageCid) {
11546        int idx = packageCid.lastIndexOf("-");
11547        if (idx == -1) {
11548            return packageCid;
11549        }
11550        return packageCid.substring(0, idx);
11551    }
11552
11553    // Utility method used to create code paths based on package name and available index.
11554    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11555        String idxStr = "";
11556        int idx = 1;
11557        // Fall back to default value of idx=1 if prefix is not
11558        // part of oldCodePath
11559        if (oldCodePath != null) {
11560            String subStr = oldCodePath;
11561            // Drop the suffix right away
11562            if (suffix != null && subStr.endsWith(suffix)) {
11563                subStr = subStr.substring(0, subStr.length() - suffix.length());
11564            }
11565            // If oldCodePath already contains prefix find out the
11566            // ending index to either increment or decrement.
11567            int sidx = subStr.lastIndexOf(prefix);
11568            if (sidx != -1) {
11569                subStr = subStr.substring(sidx + prefix.length());
11570                if (subStr != null) {
11571                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11572                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11573                    }
11574                    try {
11575                        idx = Integer.parseInt(subStr);
11576                        if (idx <= 1) {
11577                            idx++;
11578                        } else {
11579                            idx--;
11580                        }
11581                    } catch(NumberFormatException e) {
11582                    }
11583                }
11584            }
11585        }
11586        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11587        return prefix + idxStr;
11588    }
11589
11590    private File getNextCodePath(File targetDir, String packageName) {
11591        int suffix = 1;
11592        File result;
11593        do {
11594            result = new File(targetDir, packageName + "-" + suffix);
11595            suffix++;
11596        } while (result.exists());
11597        return result;
11598    }
11599
11600    // Utility method that returns the relative package path with respect
11601    // to the installation directory. Like say for /data/data/com.test-1.apk
11602    // string com.test-1 is returned.
11603    static String deriveCodePathName(String codePath) {
11604        if (codePath == null) {
11605            return null;
11606        }
11607        final File codeFile = new File(codePath);
11608        final String name = codeFile.getName();
11609        if (codeFile.isDirectory()) {
11610            return name;
11611        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11612            final int lastDot = name.lastIndexOf('.');
11613            return name.substring(0, lastDot);
11614        } else {
11615            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11616            return null;
11617        }
11618    }
11619
11620    class PackageInstalledInfo {
11621        String name;
11622        int uid;
11623        // The set of users that originally had this package installed.
11624        int[] origUsers;
11625        // The set of users that now have this package installed.
11626        int[] newUsers;
11627        PackageParser.Package pkg;
11628        int returnCode;
11629        String returnMsg;
11630        PackageRemovedInfo removedInfo;
11631
11632        public void setError(int code, String msg) {
11633            returnCode = code;
11634            returnMsg = msg;
11635            Slog.w(TAG, msg);
11636        }
11637
11638        public void setError(String msg, PackageParserException e) {
11639            returnCode = e.error;
11640            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11641            Slog.w(TAG, msg, e);
11642        }
11643
11644        public void setError(String msg, PackageManagerException e) {
11645            returnCode = e.error;
11646            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11647            Slog.w(TAG, msg, e);
11648        }
11649
11650        // In some error cases we want to convey more info back to the observer
11651        String origPackage;
11652        String origPermission;
11653    }
11654
11655    /*
11656     * Install a non-existing package.
11657     */
11658    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11659            UserHandle user, String installerPackageName, String volumeUuid,
11660            PackageInstalledInfo res) {
11661        // Remember this for later, in case we need to rollback this install
11662        String pkgName = pkg.packageName;
11663
11664        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11665        final boolean dataDirExists = Environment
11666                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11667        synchronized(mPackages) {
11668            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11669                // A package with the same name is already installed, though
11670                // it has been renamed to an older name.  The package we
11671                // are trying to install should be installed as an update to
11672                // the existing one, but that has not been requested, so bail.
11673                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11674                        + " without first uninstalling package running as "
11675                        + mSettings.mRenamedPackages.get(pkgName));
11676                return;
11677            }
11678            if (mPackages.containsKey(pkgName)) {
11679                // Don't allow installation over an existing package with the same name.
11680                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11681                        + " without first uninstalling.");
11682                return;
11683            }
11684        }
11685
11686        try {
11687            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11688                    System.currentTimeMillis(), user);
11689
11690            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11691            // delete the partially installed application. the data directory will have to be
11692            // restored if it was already existing
11693            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11694                // remove package from internal structures.  Note that we want deletePackageX to
11695                // delete the package data and cache directories that it created in
11696                // scanPackageLocked, unless those directories existed before we even tried to
11697                // install.
11698                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11699                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11700                                res.removedInfo, true);
11701            }
11702
11703        } catch (PackageManagerException e) {
11704            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11705        }
11706    }
11707
11708    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11709        // Can't rotate keys during boot or if sharedUser.
11710        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11711                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11712            return false;
11713        }
11714        // app is using upgradeKeySets; make sure all are valid
11715        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11716        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11717        for (int i = 0; i < upgradeKeySets.length; i++) {
11718            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11719                Slog.wtf(TAG, "Package "
11720                         + (oldPs.name != null ? oldPs.name : "<null>")
11721                         + " contains upgrade-key-set reference to unknown key-set: "
11722                         + upgradeKeySets[i]
11723                         + " reverting to signatures check.");
11724                return false;
11725            }
11726        }
11727        return true;
11728    }
11729
11730    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11731        // Upgrade keysets are being used.  Determine if new package has a superset of the
11732        // required keys.
11733        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11734        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11735        for (int i = 0; i < upgradeKeySets.length; i++) {
11736            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11737            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11738                return true;
11739            }
11740        }
11741        return false;
11742    }
11743
11744    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11745            UserHandle user, String installerPackageName, String volumeUuid,
11746            PackageInstalledInfo res) {
11747        final PackageParser.Package oldPackage;
11748        final String pkgName = pkg.packageName;
11749        final int[] allUsers;
11750        final boolean[] perUserInstalled;
11751        final boolean weFroze;
11752
11753        // First find the old package info and check signatures
11754        synchronized(mPackages) {
11755            oldPackage = mPackages.get(pkgName);
11756            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11757            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11758            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11759                if(!checkUpgradeKeySetLP(ps, pkg)) {
11760                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11761                            "New package not signed by keys specified by upgrade-keysets: "
11762                            + pkgName);
11763                    return;
11764                }
11765            } else {
11766                // default to original signature matching
11767                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11768                    != PackageManager.SIGNATURE_MATCH) {
11769                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11770                            "New package has a different signature: " + pkgName);
11771                    return;
11772                }
11773            }
11774
11775            // In case of rollback, remember per-user/profile install state
11776            allUsers = sUserManager.getUserIds();
11777            perUserInstalled = new boolean[allUsers.length];
11778            for (int i = 0; i < allUsers.length; i++) {
11779                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11780            }
11781
11782            // Mark the app as frozen to prevent launching during the upgrade
11783            // process, and then kill all running instances
11784            if (!ps.frozen) {
11785                ps.frozen = true;
11786                weFroze = true;
11787            } else {
11788                weFroze = false;
11789            }
11790        }
11791
11792        // Now that we're guarded by frozen state, kill app during upgrade
11793        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11794
11795        try {
11796            boolean sysPkg = (isSystemApp(oldPackage));
11797            if (sysPkg) {
11798                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11799                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11800            } else {
11801                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11802                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11803            }
11804        } finally {
11805            // Regardless of success or failure of upgrade steps above, always
11806            // unfreeze the package if we froze it
11807            if (weFroze) {
11808                unfreezePackage(pkgName);
11809            }
11810        }
11811    }
11812
11813    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11814            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11815            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11816            String volumeUuid, PackageInstalledInfo res) {
11817        String pkgName = deletedPackage.packageName;
11818        boolean deletedPkg = true;
11819        boolean updatedSettings = false;
11820
11821        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11822                + deletedPackage);
11823        long origUpdateTime;
11824        if (pkg.mExtras != null) {
11825            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11826        } else {
11827            origUpdateTime = 0;
11828        }
11829
11830        // First delete the existing package while retaining the data directory
11831        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11832                res.removedInfo, true)) {
11833            // If the existing package wasn't successfully deleted
11834            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11835            deletedPkg = false;
11836        } else {
11837            // Successfully deleted the old package; proceed with replace.
11838
11839            // If deleted package lived in a container, give users a chance to
11840            // relinquish resources before killing.
11841            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11842                if (DEBUG_INSTALL) {
11843                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11844                }
11845                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11846                final ArrayList<String> pkgList = new ArrayList<String>(1);
11847                pkgList.add(deletedPackage.applicationInfo.packageName);
11848                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11849            }
11850
11851            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11852            try {
11853                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11854                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11855                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11856                        perUserInstalled, res, user);
11857                updatedSettings = true;
11858            } catch (PackageManagerException e) {
11859                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11860            }
11861        }
11862
11863        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11864            // remove package from internal structures.  Note that we want deletePackageX to
11865            // delete the package data and cache directories that it created in
11866            // scanPackageLocked, unless those directories existed before we even tried to
11867            // install.
11868            if(updatedSettings) {
11869                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11870                deletePackageLI(
11871                        pkgName, null, true, allUsers, perUserInstalled,
11872                        PackageManager.DELETE_KEEP_DATA,
11873                                res.removedInfo, true);
11874            }
11875            // Since we failed to install the new package we need to restore the old
11876            // package that we deleted.
11877            if (deletedPkg) {
11878                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11879                File restoreFile = new File(deletedPackage.codePath);
11880                // Parse old package
11881                boolean oldExternal = isExternal(deletedPackage);
11882                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11883                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11884                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11885                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11886                try {
11887                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11888                } catch (PackageManagerException e) {
11889                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11890                            + e.getMessage());
11891                    return;
11892                }
11893                // Restore of old package succeeded. Update permissions.
11894                // writer
11895                synchronized (mPackages) {
11896                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11897                            UPDATE_PERMISSIONS_ALL);
11898                    // can downgrade to reader
11899                    mSettings.writeLPr();
11900                }
11901                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11902            }
11903        }
11904    }
11905
11906    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11907            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11908            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11909            String volumeUuid, PackageInstalledInfo res) {
11910        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11911                + ", old=" + deletedPackage);
11912        boolean disabledSystem = false;
11913        boolean updatedSettings = false;
11914        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11915        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11916                != 0) {
11917            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11918        }
11919        String packageName = deletedPackage.packageName;
11920        if (packageName == null) {
11921            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11922                    "Attempt to delete null packageName.");
11923            return;
11924        }
11925        PackageParser.Package oldPkg;
11926        PackageSetting oldPkgSetting;
11927        // reader
11928        synchronized (mPackages) {
11929            oldPkg = mPackages.get(packageName);
11930            oldPkgSetting = mSettings.mPackages.get(packageName);
11931            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11932                    (oldPkgSetting == null)) {
11933                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11934                        "Couldn't find package:" + packageName + " information");
11935                return;
11936            }
11937        }
11938
11939        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11940        res.removedInfo.removedPackage = packageName;
11941        // Remove existing system package
11942        removePackageLI(oldPkgSetting, true);
11943        // writer
11944        synchronized (mPackages) {
11945            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11946            if (!disabledSystem && deletedPackage != null) {
11947                // We didn't need to disable the .apk as a current system package,
11948                // which means we are replacing another update that is already
11949                // installed.  We need to make sure to delete the older one's .apk.
11950                res.removedInfo.args = createInstallArgsForExisting(0,
11951                        deletedPackage.applicationInfo.getCodePath(),
11952                        deletedPackage.applicationInfo.getResourcePath(),
11953                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11954            } else {
11955                res.removedInfo.args = null;
11956            }
11957        }
11958
11959        // Successfully disabled the old package. Now proceed with re-installation
11960        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11961
11962        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11963        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11964
11965        PackageParser.Package newPackage = null;
11966        try {
11967            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11968            if (newPackage.mExtras != null) {
11969                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11970                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11971                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11972
11973                // is the update attempting to change shared user? that isn't going to work...
11974                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11975                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11976                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11977                            + " to " + newPkgSetting.sharedUser);
11978                    updatedSettings = true;
11979                }
11980            }
11981
11982            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11983                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11984                        perUserInstalled, res, user);
11985                updatedSettings = true;
11986            }
11987
11988        } catch (PackageManagerException e) {
11989            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11990        }
11991
11992        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11993            // Re installation failed. Restore old information
11994            // Remove new pkg information
11995            if (newPackage != null) {
11996                removeInstalledPackageLI(newPackage, true);
11997            }
11998            // Add back the old system package
11999            try {
12000                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12001            } catch (PackageManagerException e) {
12002                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12003            }
12004            // Restore the old system information in Settings
12005            synchronized (mPackages) {
12006                if (disabledSystem) {
12007                    mSettings.enableSystemPackageLPw(packageName);
12008                }
12009                if (updatedSettings) {
12010                    mSettings.setInstallerPackageName(packageName,
12011                            oldPkgSetting.installerPackageName);
12012                }
12013                mSettings.writeLPr();
12014            }
12015        }
12016    }
12017
12018    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12019            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12020            UserHandle user) {
12021        String pkgName = newPackage.packageName;
12022        synchronized (mPackages) {
12023            //write settings. the installStatus will be incomplete at this stage.
12024            //note that the new package setting would have already been
12025            //added to mPackages. It hasn't been persisted yet.
12026            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12027            mSettings.writeLPr();
12028        }
12029
12030        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12031
12032        synchronized (mPackages) {
12033            updatePermissionsLPw(newPackage.packageName, newPackage,
12034                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12035                            ? UPDATE_PERMISSIONS_ALL : 0));
12036            // For system-bundled packages, we assume that installing an upgraded version
12037            // of the package implies that the user actually wants to run that new code,
12038            // so we enable the package.
12039            PackageSetting ps = mSettings.mPackages.get(pkgName);
12040            if (ps != null) {
12041                if (isSystemApp(newPackage)) {
12042                    // NB: implicit assumption that system package upgrades apply to all users
12043                    if (DEBUG_INSTALL) {
12044                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12045                    }
12046                    if (res.origUsers != null) {
12047                        for (int userHandle : res.origUsers) {
12048                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12049                                    userHandle, installerPackageName);
12050                        }
12051                    }
12052                    // Also convey the prior install/uninstall state
12053                    if (allUsers != null && perUserInstalled != null) {
12054                        for (int i = 0; i < allUsers.length; i++) {
12055                            if (DEBUG_INSTALL) {
12056                                Slog.d(TAG, "    user " + allUsers[i]
12057                                        + " => " + perUserInstalled[i]);
12058                            }
12059                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12060                        }
12061                        // these install state changes will be persisted in the
12062                        // upcoming call to mSettings.writeLPr().
12063                    }
12064                }
12065                // It's implied that when a user requests installation, they want the app to be
12066                // installed and enabled.
12067                int userId = user.getIdentifier();
12068                if (userId != UserHandle.USER_ALL) {
12069                    ps.setInstalled(true, userId);
12070                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12071                }
12072            }
12073            res.name = pkgName;
12074            res.uid = newPackage.applicationInfo.uid;
12075            res.pkg = newPackage;
12076            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12077            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12078            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12079            //to update install status
12080            mSettings.writeLPr();
12081        }
12082    }
12083
12084    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12085        final int installFlags = args.installFlags;
12086        final String installerPackageName = args.installerPackageName;
12087        final String volumeUuid = args.volumeUuid;
12088        final File tmpPackageFile = new File(args.getCodePath());
12089        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12090        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12091                || (args.volumeUuid != null));
12092        boolean replace = false;
12093        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12094        if (args.move != null) {
12095            // moving a complete application; perfom an initial scan on the new install location
12096            scanFlags |= SCAN_INITIAL;
12097        }
12098        // Result object to be returned
12099        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12100
12101        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12102        // Retrieve PackageSettings and parse package
12103        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12104                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12105                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12106        PackageParser pp = new PackageParser();
12107        pp.setSeparateProcesses(mSeparateProcesses);
12108        pp.setDisplayMetrics(mMetrics);
12109
12110        final PackageParser.Package pkg;
12111        try {
12112            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12113        } catch (PackageParserException e) {
12114            res.setError("Failed parse during installPackageLI", e);
12115            return;
12116        }
12117
12118        // Mark that we have an install time CPU ABI override.
12119        pkg.cpuAbiOverride = args.abiOverride;
12120
12121        String pkgName = res.name = pkg.packageName;
12122        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12123            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12124                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12125                return;
12126            }
12127        }
12128
12129        try {
12130            pp.collectCertificates(pkg, parseFlags);
12131            pp.collectManifestDigest(pkg);
12132        } catch (PackageParserException e) {
12133            res.setError("Failed collect during installPackageLI", e);
12134            return;
12135        }
12136
12137        /* If the installer passed in a manifest digest, compare it now. */
12138        if (args.manifestDigest != null) {
12139            if (DEBUG_INSTALL) {
12140                final String parsedManifest = pkg.manifestDigest == null ? "null"
12141                        : pkg.manifestDigest.toString();
12142                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12143                        + parsedManifest);
12144            }
12145
12146            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12147                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12148                return;
12149            }
12150        } else if (DEBUG_INSTALL) {
12151            final String parsedManifest = pkg.manifestDigest == null
12152                    ? "null" : pkg.manifestDigest.toString();
12153            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12154        }
12155
12156        // Get rid of all references to package scan path via parser.
12157        pp = null;
12158        String oldCodePath = null;
12159        boolean systemApp = false;
12160        synchronized (mPackages) {
12161            // Check if installing already existing package
12162            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12163                String oldName = mSettings.mRenamedPackages.get(pkgName);
12164                if (pkg.mOriginalPackages != null
12165                        && pkg.mOriginalPackages.contains(oldName)
12166                        && mPackages.containsKey(oldName)) {
12167                    // This package is derived from an original package,
12168                    // and this device has been updating from that original
12169                    // name.  We must continue using the original name, so
12170                    // rename the new package here.
12171                    pkg.setPackageName(oldName);
12172                    pkgName = pkg.packageName;
12173                    replace = true;
12174                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12175                            + oldName + " pkgName=" + pkgName);
12176                } else if (mPackages.containsKey(pkgName)) {
12177                    // This package, under its official name, already exists
12178                    // on the device; we should replace it.
12179                    replace = true;
12180                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12181                }
12182
12183                // Prevent apps opting out from runtime permissions
12184                if (replace) {
12185                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12186                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12187                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12188                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12189                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12190                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12191                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12192                                        + " doesn't support runtime permissions but the old"
12193                                        + " target SDK " + oldTargetSdk + " does.");
12194                        return;
12195                    }
12196                }
12197            }
12198
12199            PackageSetting ps = mSettings.mPackages.get(pkgName);
12200            if (ps != null) {
12201                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12202
12203                // Quick sanity check that we're signed correctly if updating;
12204                // we'll check this again later when scanning, but we want to
12205                // bail early here before tripping over redefined permissions.
12206                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12207                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12208                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12209                                + pkg.packageName + " upgrade keys do not match the "
12210                                + "previously installed version");
12211                        return;
12212                    }
12213                } else {
12214                    try {
12215                        verifySignaturesLP(ps, pkg);
12216                    } catch (PackageManagerException e) {
12217                        res.setError(e.error, e.getMessage());
12218                        return;
12219                    }
12220                }
12221
12222                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12223                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12224                    systemApp = (ps.pkg.applicationInfo.flags &
12225                            ApplicationInfo.FLAG_SYSTEM) != 0;
12226                }
12227                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12228            }
12229
12230            // Check whether the newly-scanned package wants to define an already-defined perm
12231            int N = pkg.permissions.size();
12232            for (int i = N-1; i >= 0; i--) {
12233                PackageParser.Permission perm = pkg.permissions.get(i);
12234                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12235                if (bp != null) {
12236                    // If the defining package is signed with our cert, it's okay.  This
12237                    // also includes the "updating the same package" case, of course.
12238                    // "updating same package" could also involve key-rotation.
12239                    final boolean sigsOk;
12240                    if (bp.sourcePackage.equals(pkg.packageName)
12241                            && (bp.packageSetting instanceof PackageSetting)
12242                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12243                                    scanFlags))) {
12244                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12245                    } else {
12246                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12247                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12248                    }
12249                    if (!sigsOk) {
12250                        // If the owning package is the system itself, we log but allow
12251                        // install to proceed; we fail the install on all other permission
12252                        // redefinitions.
12253                        if (!bp.sourcePackage.equals("android")) {
12254                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12255                                    + pkg.packageName + " attempting to redeclare permission "
12256                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12257                            res.origPermission = perm.info.name;
12258                            res.origPackage = bp.sourcePackage;
12259                            return;
12260                        } else {
12261                            Slog.w(TAG, "Package " + pkg.packageName
12262                                    + " attempting to redeclare system permission "
12263                                    + perm.info.name + "; ignoring new declaration");
12264                            pkg.permissions.remove(i);
12265                        }
12266                    }
12267                }
12268            }
12269
12270        }
12271
12272        if (systemApp && onExternal) {
12273            // Disable updates to system apps on sdcard
12274            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12275                    "Cannot install updates to system apps on sdcard");
12276            return;
12277        }
12278
12279        if (args.move != null) {
12280            // We did an in-place move, so dex is ready to roll
12281            scanFlags |= SCAN_NO_DEX;
12282            scanFlags |= SCAN_MOVE;
12283
12284            synchronized (mPackages) {
12285                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12286                if (ps == null) {
12287                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12288                            "Missing settings for moved package " + pkgName);
12289                }
12290
12291                // We moved the entire application as-is, so bring over the
12292                // previously derived ABI information.
12293                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12294                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12295            }
12296
12297        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12298            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12299            scanFlags |= SCAN_NO_DEX;
12300
12301            try {
12302                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12303                        true /* extract libs */);
12304            } catch (PackageManagerException pme) {
12305                Slog.e(TAG, "Error deriving application ABI", pme);
12306                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12307                return;
12308            }
12309
12310            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12311            int result = mPackageDexOptimizer
12312                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12313                            false /* defer */, false /* inclDependencies */);
12314            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12315                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12316                return;
12317            }
12318        }
12319
12320        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12321            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12322            return;
12323        }
12324
12325        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12326
12327        if (replace) {
12328            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12329                    installerPackageName, volumeUuid, res);
12330        } else {
12331            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12332                    args.user, installerPackageName, volumeUuid, res);
12333        }
12334        synchronized (mPackages) {
12335            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12336            if (ps != null) {
12337                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12338            }
12339        }
12340    }
12341
12342    private void startIntentFilterVerifications(int userId, boolean replacing,
12343            PackageParser.Package pkg) {
12344        if (mIntentFilterVerifierComponent == null) {
12345            Slog.w(TAG, "No IntentFilter verification will not be done as "
12346                    + "there is no IntentFilterVerifier available!");
12347            return;
12348        }
12349
12350        final int verifierUid = getPackageUid(
12351                mIntentFilterVerifierComponent.getPackageName(),
12352                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12353
12354        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12355        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12356        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12357        mHandler.sendMessage(msg);
12358    }
12359
12360    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12361            PackageParser.Package pkg) {
12362        int size = pkg.activities.size();
12363        if (size == 0) {
12364            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12365                    "No activity, so no need to verify any IntentFilter!");
12366            return;
12367        }
12368
12369        final boolean hasDomainURLs = hasDomainURLs(pkg);
12370        if (!hasDomainURLs) {
12371            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12372                    "No domain URLs, so no need to verify any IntentFilter!");
12373            return;
12374        }
12375
12376        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12377                + " if any IntentFilter from the " + size
12378                + " Activities needs verification ...");
12379
12380        int count = 0;
12381        final String packageName = pkg.packageName;
12382
12383        synchronized (mPackages) {
12384            // If this is a new install and we see that we've already run verification for this
12385            // package, we have nothing to do: it means the state was restored from backup.
12386            if (!replacing) {
12387                IntentFilterVerificationInfo ivi =
12388                        mSettings.getIntentFilterVerificationLPr(packageName);
12389                if (ivi != null) {
12390                    if (DEBUG_DOMAIN_VERIFICATION) {
12391                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12392                                + ivi.getStatusString());
12393                    }
12394                    return;
12395                }
12396            }
12397
12398            // If any filters need to be verified, then all need to be.
12399            boolean needToVerify = false;
12400            for (PackageParser.Activity a : pkg.activities) {
12401                for (ActivityIntentInfo filter : a.intents) {
12402                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12403                        if (DEBUG_DOMAIN_VERIFICATION) {
12404                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12405                        }
12406                        needToVerify = true;
12407                        break;
12408                    }
12409                }
12410            }
12411
12412            if (needToVerify) {
12413                final int verificationId = mIntentFilterVerificationToken++;
12414                for (PackageParser.Activity a : pkg.activities) {
12415                    for (ActivityIntentInfo filter : a.intents) {
12416                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12417                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12418                                    "Verification needed for IntentFilter:" + filter.toString());
12419                            mIntentFilterVerifier.addOneIntentFilterVerification(
12420                                    verifierUid, userId, verificationId, filter, packageName);
12421                            count++;
12422                        }
12423                    }
12424                }
12425            }
12426        }
12427
12428        if (count > 0) {
12429            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12430                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12431                    +  " for userId:" + userId);
12432            mIntentFilterVerifier.startVerifications(userId);
12433        } else {
12434            if (DEBUG_DOMAIN_VERIFICATION) {
12435                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12436            }
12437        }
12438    }
12439
12440    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12441        final ComponentName cn  = filter.activity.getComponentName();
12442        final String packageName = cn.getPackageName();
12443
12444        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12445                packageName);
12446        if (ivi == null) {
12447            return true;
12448        }
12449        int status = ivi.getStatus();
12450        switch (status) {
12451            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12452            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12453                return true;
12454
12455            default:
12456                // Nothing to do
12457                return false;
12458        }
12459    }
12460
12461    private static boolean isMultiArch(PackageSetting ps) {
12462        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12463    }
12464
12465    private static boolean isMultiArch(ApplicationInfo info) {
12466        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12467    }
12468
12469    private static boolean isExternal(PackageParser.Package pkg) {
12470        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12471    }
12472
12473    private static boolean isExternal(PackageSetting ps) {
12474        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12475    }
12476
12477    private static boolean isExternal(ApplicationInfo info) {
12478        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12479    }
12480
12481    private static boolean isSystemApp(PackageParser.Package pkg) {
12482        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12483    }
12484
12485    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12486        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12487    }
12488
12489    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12490        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12491    }
12492
12493    private static boolean isSystemApp(PackageSetting ps) {
12494        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12495    }
12496
12497    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12498        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12499    }
12500
12501    private int packageFlagsToInstallFlags(PackageSetting ps) {
12502        int installFlags = 0;
12503        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12504            // This existing package was an external ASEC install when we have
12505            // the external flag without a UUID
12506            installFlags |= PackageManager.INSTALL_EXTERNAL;
12507        }
12508        if (ps.isForwardLocked()) {
12509            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12510        }
12511        return installFlags;
12512    }
12513
12514    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12515        if (isExternal(pkg)) {
12516            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12517                return mSettings.getExternalVersion();
12518            } else {
12519                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12520            }
12521        } else {
12522            return mSettings.getInternalVersion();
12523        }
12524    }
12525
12526    private void deleteTempPackageFiles() {
12527        final FilenameFilter filter = new FilenameFilter() {
12528            public boolean accept(File dir, String name) {
12529                return name.startsWith("vmdl") && name.endsWith(".tmp");
12530            }
12531        };
12532        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12533            file.delete();
12534        }
12535    }
12536
12537    @Override
12538    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12539            int flags) {
12540        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12541                flags);
12542    }
12543
12544    @Override
12545    public void deletePackage(final String packageName,
12546            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12547        mContext.enforceCallingOrSelfPermission(
12548                android.Manifest.permission.DELETE_PACKAGES, null);
12549        Preconditions.checkNotNull(packageName);
12550        Preconditions.checkNotNull(observer);
12551        final int uid = Binder.getCallingUid();
12552        if (UserHandle.getUserId(uid) != userId) {
12553            mContext.enforceCallingPermission(
12554                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12555                    "deletePackage for user " + userId);
12556        }
12557        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12558            try {
12559                observer.onPackageDeleted(packageName,
12560                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12561            } catch (RemoteException re) {
12562            }
12563            return;
12564        }
12565
12566        boolean uninstallBlocked = false;
12567        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12568            int[] users = sUserManager.getUserIds();
12569            for (int i = 0; i < users.length; ++i) {
12570                if (getBlockUninstallForUser(packageName, users[i])) {
12571                    uninstallBlocked = true;
12572                    break;
12573                }
12574            }
12575        } else {
12576            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12577        }
12578        if (uninstallBlocked) {
12579            try {
12580                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12581                        null);
12582            } catch (RemoteException re) {
12583            }
12584            return;
12585        }
12586
12587        if (DEBUG_REMOVE) {
12588            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12589        }
12590        // Queue up an async operation since the package deletion may take a little while.
12591        mHandler.post(new Runnable() {
12592            public void run() {
12593                mHandler.removeCallbacks(this);
12594                final int returnCode = deletePackageX(packageName, userId, flags);
12595                if (observer != null) {
12596                    try {
12597                        observer.onPackageDeleted(packageName, returnCode, null);
12598                    } catch (RemoteException e) {
12599                        Log.i(TAG, "Observer no longer exists.");
12600                    } //end catch
12601                } //end if
12602            } //end run
12603        });
12604    }
12605
12606    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12607        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12608                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12609        try {
12610            if (dpm != null) {
12611                if (dpm.isDeviceOwner(packageName)) {
12612                    return true;
12613                }
12614                int[] users;
12615                if (userId == UserHandle.USER_ALL) {
12616                    users = sUserManager.getUserIds();
12617                } else {
12618                    users = new int[]{userId};
12619                }
12620                for (int i = 0; i < users.length; ++i) {
12621                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12622                        return true;
12623                    }
12624                }
12625            }
12626        } catch (RemoteException e) {
12627        }
12628        return false;
12629    }
12630
12631    /**
12632     *  This method is an internal method that could be get invoked either
12633     *  to delete an installed package or to clean up a failed installation.
12634     *  After deleting an installed package, a broadcast is sent to notify any
12635     *  listeners that the package has been installed. For cleaning up a failed
12636     *  installation, the broadcast is not necessary since the package's
12637     *  installation wouldn't have sent the initial broadcast either
12638     *  The key steps in deleting a package are
12639     *  deleting the package information in internal structures like mPackages,
12640     *  deleting the packages base directories through installd
12641     *  updating mSettings to reflect current status
12642     *  persisting settings for later use
12643     *  sending a broadcast if necessary
12644     */
12645    private int deletePackageX(String packageName, int userId, int flags) {
12646        final PackageRemovedInfo info = new PackageRemovedInfo();
12647        final boolean res;
12648
12649        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12650                ? UserHandle.ALL : new UserHandle(userId);
12651
12652        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12653            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12654            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12655        }
12656
12657        boolean removedForAllUsers = false;
12658        boolean systemUpdate = false;
12659
12660        // for the uninstall-updates case and restricted profiles, remember the per-
12661        // userhandle installed state
12662        int[] allUsers;
12663        boolean[] perUserInstalled;
12664        synchronized (mPackages) {
12665            PackageSetting ps = mSettings.mPackages.get(packageName);
12666            allUsers = sUserManager.getUserIds();
12667            perUserInstalled = new boolean[allUsers.length];
12668            for (int i = 0; i < allUsers.length; i++) {
12669                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12670            }
12671        }
12672
12673        synchronized (mInstallLock) {
12674            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12675            res = deletePackageLI(packageName, removeForUser,
12676                    true, allUsers, perUserInstalled,
12677                    flags | REMOVE_CHATTY, info, true);
12678            systemUpdate = info.isRemovedPackageSystemUpdate;
12679            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12680                removedForAllUsers = true;
12681            }
12682            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12683                    + " removedForAllUsers=" + removedForAllUsers);
12684        }
12685
12686        if (res) {
12687            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12688
12689            // If the removed package was a system update, the old system package
12690            // was re-enabled; we need to broadcast this information
12691            if (systemUpdate) {
12692                Bundle extras = new Bundle(1);
12693                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12694                        ? info.removedAppId : info.uid);
12695                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12696
12697                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12698                        extras, null, null, null);
12699                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12700                        extras, null, null, null);
12701                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12702                        null, packageName, null, null);
12703            }
12704        }
12705        // Force a gc here.
12706        Runtime.getRuntime().gc();
12707        // Delete the resources here after sending the broadcast to let
12708        // other processes clean up before deleting resources.
12709        if (info.args != null) {
12710            synchronized (mInstallLock) {
12711                info.args.doPostDeleteLI(true);
12712            }
12713        }
12714
12715        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12716    }
12717
12718    class PackageRemovedInfo {
12719        String removedPackage;
12720        int uid = -1;
12721        int removedAppId = -1;
12722        int[] removedUsers = null;
12723        boolean isRemovedPackageSystemUpdate = false;
12724        // Clean up resources deleted packages.
12725        InstallArgs args = null;
12726
12727        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12728            Bundle extras = new Bundle(1);
12729            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12730            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12731            if (replacing) {
12732                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12733            }
12734            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12735            if (removedPackage != null) {
12736                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12737                        extras, null, null, removedUsers);
12738                if (fullRemove && !replacing) {
12739                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12740                            extras, null, null, removedUsers);
12741                }
12742            }
12743            if (removedAppId >= 0) {
12744                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12745                        removedUsers);
12746            }
12747        }
12748    }
12749
12750    /*
12751     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12752     * flag is not set, the data directory is removed as well.
12753     * make sure this flag is set for partially installed apps. If not its meaningless to
12754     * delete a partially installed application.
12755     */
12756    private void removePackageDataLI(PackageSetting ps,
12757            int[] allUserHandles, boolean[] perUserInstalled,
12758            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12759        String packageName = ps.name;
12760        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12761        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12762        // Retrieve object to delete permissions for shared user later on
12763        final PackageSetting deletedPs;
12764        // reader
12765        synchronized (mPackages) {
12766            deletedPs = mSettings.mPackages.get(packageName);
12767            if (outInfo != null) {
12768                outInfo.removedPackage = packageName;
12769                outInfo.removedUsers = deletedPs != null
12770                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12771                        : null;
12772            }
12773        }
12774        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12775            removeDataDirsLI(ps.volumeUuid, packageName);
12776            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12777        }
12778        // writer
12779        synchronized (mPackages) {
12780            if (deletedPs != null) {
12781                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12782                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12783                    clearDefaultBrowserIfNeeded(packageName);
12784                    if (outInfo != null) {
12785                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12786                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12787                    }
12788                    updatePermissionsLPw(deletedPs.name, null, 0);
12789                    if (deletedPs.sharedUser != null) {
12790                        // Remove permissions associated with package. Since runtime
12791                        // permissions are per user we have to kill the removed package
12792                        // or packages running under the shared user of the removed
12793                        // package if revoking the permissions requested only by the removed
12794                        // package is successful and this causes a change in gids.
12795                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12796                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12797                                    userId);
12798                            if (userIdToKill == UserHandle.USER_ALL
12799                                    || userIdToKill >= UserHandle.USER_OWNER) {
12800                                // If gids changed for this user, kill all affected packages.
12801                                mHandler.post(new Runnable() {
12802                                    @Override
12803                                    public void run() {
12804                                        // This has to happen with no lock held.
12805                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12806                                                KILL_APP_REASON_GIDS_CHANGED);
12807                                    }
12808                                });
12809                                break;
12810                            }
12811                        }
12812                    }
12813                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12814                }
12815                // make sure to preserve per-user disabled state if this removal was just
12816                // a downgrade of a system app to the factory package
12817                if (allUserHandles != null && perUserInstalled != null) {
12818                    if (DEBUG_REMOVE) {
12819                        Slog.d(TAG, "Propagating install state across downgrade");
12820                    }
12821                    for (int i = 0; i < allUserHandles.length; i++) {
12822                        if (DEBUG_REMOVE) {
12823                            Slog.d(TAG, "    user " + allUserHandles[i]
12824                                    + " => " + perUserInstalled[i]);
12825                        }
12826                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12827                    }
12828                }
12829            }
12830            // can downgrade to reader
12831            if (writeSettings) {
12832                // Save settings now
12833                mSettings.writeLPr();
12834            }
12835        }
12836        if (outInfo != null) {
12837            // A user ID was deleted here. Go through all users and remove it
12838            // from KeyStore.
12839            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12840        }
12841    }
12842
12843    static boolean locationIsPrivileged(File path) {
12844        try {
12845            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12846                    .getCanonicalPath();
12847            return path.getCanonicalPath().startsWith(privilegedAppDir);
12848        } catch (IOException e) {
12849            Slog.e(TAG, "Unable to access code path " + path);
12850        }
12851        return false;
12852    }
12853
12854    /*
12855     * Tries to delete system package.
12856     */
12857    private boolean deleteSystemPackageLI(PackageSetting newPs,
12858            int[] allUserHandles, boolean[] perUserInstalled,
12859            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12860        final boolean applyUserRestrictions
12861                = (allUserHandles != null) && (perUserInstalled != null);
12862        PackageSetting disabledPs = null;
12863        // Confirm if the system package has been updated
12864        // An updated system app can be deleted. This will also have to restore
12865        // the system pkg from system partition
12866        // reader
12867        synchronized (mPackages) {
12868            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12869        }
12870        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12871                + " disabledPs=" + disabledPs);
12872        if (disabledPs == null) {
12873            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12874            return false;
12875        } else if (DEBUG_REMOVE) {
12876            Slog.d(TAG, "Deleting system pkg from data partition");
12877        }
12878        if (DEBUG_REMOVE) {
12879            if (applyUserRestrictions) {
12880                Slog.d(TAG, "Remembering install states:");
12881                for (int i = 0; i < allUserHandles.length; i++) {
12882                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12883                }
12884            }
12885        }
12886        // Delete the updated package
12887        outInfo.isRemovedPackageSystemUpdate = true;
12888        if (disabledPs.versionCode < newPs.versionCode) {
12889            // Delete data for downgrades
12890            flags &= ~PackageManager.DELETE_KEEP_DATA;
12891        } else {
12892            // Preserve data by setting flag
12893            flags |= PackageManager.DELETE_KEEP_DATA;
12894        }
12895        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12896                allUserHandles, perUserInstalled, outInfo, writeSettings);
12897        if (!ret) {
12898            return false;
12899        }
12900        // writer
12901        synchronized (mPackages) {
12902            // Reinstate the old system package
12903            mSettings.enableSystemPackageLPw(newPs.name);
12904            // Remove any native libraries from the upgraded package.
12905            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12906        }
12907        // Install the system package
12908        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12909        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12910        if (locationIsPrivileged(disabledPs.codePath)) {
12911            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12912        }
12913
12914        final PackageParser.Package newPkg;
12915        try {
12916            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12917        } catch (PackageManagerException e) {
12918            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12919            return false;
12920        }
12921
12922        // writer
12923        synchronized (mPackages) {
12924            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12925
12926            // Propagate the permissions state as we do want to drop on the floor
12927            // runtime permissions. The update permissions method below will take
12928            // care of removing obsolete permissions and grant install permissions.
12929            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12930            updatePermissionsLPw(newPkg.packageName, newPkg,
12931                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12932
12933            if (applyUserRestrictions) {
12934                if (DEBUG_REMOVE) {
12935                    Slog.d(TAG, "Propagating install state across reinstall");
12936                }
12937                for (int i = 0; i < allUserHandles.length; i++) {
12938                    if (DEBUG_REMOVE) {
12939                        Slog.d(TAG, "    user " + allUserHandles[i]
12940                                + " => " + perUserInstalled[i]);
12941                    }
12942                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12943                }
12944                // Regardless of writeSettings we need to ensure that this restriction
12945                // state propagation is persisted
12946                mSettings.writeAllUsersPackageRestrictionsLPr();
12947            }
12948            // can downgrade to reader here
12949            if (writeSettings) {
12950                mSettings.writeLPr();
12951            }
12952        }
12953        return true;
12954    }
12955
12956    private boolean deleteInstalledPackageLI(PackageSetting ps,
12957            boolean deleteCodeAndResources, int flags,
12958            int[] allUserHandles, boolean[] perUserInstalled,
12959            PackageRemovedInfo outInfo, boolean writeSettings) {
12960        if (outInfo != null) {
12961            outInfo.uid = ps.appId;
12962        }
12963
12964        // Delete package data from internal structures and also remove data if flag is set
12965        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12966
12967        // Delete application code and resources
12968        if (deleteCodeAndResources && (outInfo != null)) {
12969            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12970                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12971            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12972        }
12973        return true;
12974    }
12975
12976    @Override
12977    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12978            int userId) {
12979        mContext.enforceCallingOrSelfPermission(
12980                android.Manifest.permission.DELETE_PACKAGES, null);
12981        synchronized (mPackages) {
12982            PackageSetting ps = mSettings.mPackages.get(packageName);
12983            if (ps == null) {
12984                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12985                return false;
12986            }
12987            if (!ps.getInstalled(userId)) {
12988                // Can't block uninstall for an app that is not installed or enabled.
12989                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12990                return false;
12991            }
12992            ps.setBlockUninstall(blockUninstall, userId);
12993            mSettings.writePackageRestrictionsLPr(userId);
12994        }
12995        return true;
12996    }
12997
12998    @Override
12999    public boolean getBlockUninstallForUser(String packageName, int userId) {
13000        synchronized (mPackages) {
13001            PackageSetting ps = mSettings.mPackages.get(packageName);
13002            if (ps == null) {
13003                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13004                return false;
13005            }
13006            return ps.getBlockUninstall(userId);
13007        }
13008    }
13009
13010    /*
13011     * This method handles package deletion in general
13012     */
13013    private boolean deletePackageLI(String packageName, UserHandle user,
13014            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13015            int flags, PackageRemovedInfo outInfo,
13016            boolean writeSettings) {
13017        if (packageName == null) {
13018            Slog.w(TAG, "Attempt to delete null packageName.");
13019            return false;
13020        }
13021        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13022        PackageSetting ps;
13023        boolean dataOnly = false;
13024        int removeUser = -1;
13025        int appId = -1;
13026        synchronized (mPackages) {
13027            ps = mSettings.mPackages.get(packageName);
13028            if (ps == null) {
13029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13030                return false;
13031            }
13032            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13033                    && user.getIdentifier() != UserHandle.USER_ALL) {
13034                // The caller is asking that the package only be deleted for a single
13035                // user.  To do this, we just mark its uninstalled state and delete
13036                // its data.  If this is a system app, we only allow this to happen if
13037                // they have set the special DELETE_SYSTEM_APP which requests different
13038                // semantics than normal for uninstalling system apps.
13039                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13040                ps.setUserState(user.getIdentifier(),
13041                        COMPONENT_ENABLED_STATE_DEFAULT,
13042                        false, //installed
13043                        true,  //stopped
13044                        true,  //notLaunched
13045                        false, //hidden
13046                        null, null, null,
13047                        false, // blockUninstall
13048                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13049                if (!isSystemApp(ps)) {
13050                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13051                        // Other user still have this package installed, so all
13052                        // we need to do is clear this user's data and save that
13053                        // it is uninstalled.
13054                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13055                        removeUser = user.getIdentifier();
13056                        appId = ps.appId;
13057                        scheduleWritePackageRestrictionsLocked(removeUser);
13058                    } else {
13059                        // We need to set it back to 'installed' so the uninstall
13060                        // broadcasts will be sent correctly.
13061                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13062                        ps.setInstalled(true, user.getIdentifier());
13063                    }
13064                } else {
13065                    // This is a system app, so we assume that the
13066                    // other users still have this package installed, so all
13067                    // we need to do is clear this user's data and save that
13068                    // it is uninstalled.
13069                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13070                    removeUser = user.getIdentifier();
13071                    appId = ps.appId;
13072                    scheduleWritePackageRestrictionsLocked(removeUser);
13073                }
13074            }
13075        }
13076
13077        if (removeUser >= 0) {
13078            // From above, we determined that we are deleting this only
13079            // for a single user.  Continue the work here.
13080            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13081            if (outInfo != null) {
13082                outInfo.removedPackage = packageName;
13083                outInfo.removedAppId = appId;
13084                outInfo.removedUsers = new int[] {removeUser};
13085            }
13086            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13087            removeKeystoreDataIfNeeded(removeUser, appId);
13088            schedulePackageCleaning(packageName, removeUser, false);
13089            synchronized (mPackages) {
13090                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13091                    scheduleWritePackageRestrictionsLocked(removeUser);
13092                }
13093                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13094            }
13095            return true;
13096        }
13097
13098        if (dataOnly) {
13099            // Delete application data first
13100            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13101            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13102            return true;
13103        }
13104
13105        boolean ret = false;
13106        if (isSystemApp(ps)) {
13107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13108            // When an updated system application is deleted we delete the existing resources as well and
13109            // fall back to existing code in system partition
13110            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13111                    flags, outInfo, writeSettings);
13112        } else {
13113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13114            // Kill application pre-emptively especially for apps on sd.
13115            killApplication(packageName, ps.appId, "uninstall pkg");
13116            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13117                    allUserHandles, perUserInstalled,
13118                    outInfo, writeSettings);
13119        }
13120
13121        return ret;
13122    }
13123
13124    private final class ClearStorageConnection implements ServiceConnection {
13125        IMediaContainerService mContainerService;
13126
13127        @Override
13128        public void onServiceConnected(ComponentName name, IBinder service) {
13129            synchronized (this) {
13130                mContainerService = IMediaContainerService.Stub.asInterface(service);
13131                notifyAll();
13132            }
13133        }
13134
13135        @Override
13136        public void onServiceDisconnected(ComponentName name) {
13137        }
13138    }
13139
13140    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13141        final boolean mounted;
13142        if (Environment.isExternalStorageEmulated()) {
13143            mounted = true;
13144        } else {
13145            final String status = Environment.getExternalStorageState();
13146
13147            mounted = status.equals(Environment.MEDIA_MOUNTED)
13148                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13149        }
13150
13151        if (!mounted) {
13152            return;
13153        }
13154
13155        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13156        int[] users;
13157        if (userId == UserHandle.USER_ALL) {
13158            users = sUserManager.getUserIds();
13159        } else {
13160            users = new int[] { userId };
13161        }
13162        final ClearStorageConnection conn = new ClearStorageConnection();
13163        if (mContext.bindServiceAsUser(
13164                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13165            try {
13166                for (int curUser : users) {
13167                    long timeout = SystemClock.uptimeMillis() + 5000;
13168                    synchronized (conn) {
13169                        long now = SystemClock.uptimeMillis();
13170                        while (conn.mContainerService == null && now < timeout) {
13171                            try {
13172                                conn.wait(timeout - now);
13173                            } catch (InterruptedException e) {
13174                            }
13175                        }
13176                    }
13177                    if (conn.mContainerService == null) {
13178                        return;
13179                    }
13180
13181                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13182                    clearDirectory(conn.mContainerService,
13183                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13184                    if (allData) {
13185                        clearDirectory(conn.mContainerService,
13186                                userEnv.buildExternalStorageAppDataDirs(packageName));
13187                        clearDirectory(conn.mContainerService,
13188                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13189                    }
13190                }
13191            } finally {
13192                mContext.unbindService(conn);
13193            }
13194        }
13195    }
13196
13197    @Override
13198    public void clearApplicationUserData(final String packageName,
13199            final IPackageDataObserver observer, final int userId) {
13200        mContext.enforceCallingOrSelfPermission(
13201                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13202        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13203        // Queue up an async operation since the package deletion may take a little while.
13204        mHandler.post(new Runnable() {
13205            public void run() {
13206                mHandler.removeCallbacks(this);
13207                final boolean succeeded;
13208                synchronized (mInstallLock) {
13209                    succeeded = clearApplicationUserDataLI(packageName, userId);
13210                }
13211                clearExternalStorageDataSync(packageName, userId, true);
13212                if (succeeded) {
13213                    // invoke DeviceStorageMonitor's update method to clear any notifications
13214                    DeviceStorageMonitorInternal
13215                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13216                    if (dsm != null) {
13217                        dsm.checkMemory();
13218                    }
13219                }
13220                if(observer != null) {
13221                    try {
13222                        observer.onRemoveCompleted(packageName, succeeded);
13223                    } catch (RemoteException e) {
13224                        Log.i(TAG, "Observer no longer exists.");
13225                    }
13226                } //end if observer
13227            } //end run
13228        });
13229    }
13230
13231    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13232        if (packageName == null) {
13233            Slog.w(TAG, "Attempt to delete null packageName.");
13234            return false;
13235        }
13236
13237        // Try finding details about the requested package
13238        PackageParser.Package pkg;
13239        synchronized (mPackages) {
13240            pkg = mPackages.get(packageName);
13241            if (pkg == null) {
13242                final PackageSetting ps = mSettings.mPackages.get(packageName);
13243                if (ps != null) {
13244                    pkg = ps.pkg;
13245                }
13246            }
13247
13248            if (pkg == null) {
13249                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13250                return false;
13251            }
13252
13253            PackageSetting ps = (PackageSetting) pkg.mExtras;
13254            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13255        }
13256
13257        // Always delete data directories for package, even if we found no other
13258        // record of app. This helps users recover from UID mismatches without
13259        // resorting to a full data wipe.
13260        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13261        if (retCode < 0) {
13262            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13263            return false;
13264        }
13265
13266        final int appId = pkg.applicationInfo.uid;
13267        removeKeystoreDataIfNeeded(userId, appId);
13268
13269        // Create a native library symlink only if we have native libraries
13270        // and if the native libraries are 32 bit libraries. We do not provide
13271        // this symlink for 64 bit libraries.
13272        if (pkg.applicationInfo.primaryCpuAbi != null &&
13273                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13274            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13275            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13276                    nativeLibPath, userId) < 0) {
13277                Slog.w(TAG, "Failed linking native library dir");
13278                return false;
13279            }
13280        }
13281
13282        return true;
13283    }
13284
13285    /**
13286     * Reverts user permission state changes (permissions and flags).
13287     *
13288     * @param ps The package for which to reset.
13289     * @param userId The device user for which to do a reset.
13290     */
13291    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13292            final PackageSetting ps, final int userId) {
13293        if (ps.pkg == null) {
13294            return;
13295        }
13296
13297        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13298                | FLAG_PERMISSION_USER_FIXED
13299                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13300
13301        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13302                | FLAG_PERMISSION_POLICY_FIXED;
13303
13304        boolean writeInstallPermissions = false;
13305        boolean writeRuntimePermissions = false;
13306
13307        final int permissionCount = ps.pkg.requestedPermissions.size();
13308        for (int i = 0; i < permissionCount; i++) {
13309            String permission = ps.pkg.requestedPermissions.get(i);
13310
13311            BasePermission bp = mSettings.mPermissions.get(permission);
13312            if (bp == null) {
13313                continue;
13314            }
13315
13316            // If shared user we just reset the state to which only this app contributed.
13317            if (ps.sharedUser != null) {
13318                boolean used = false;
13319                final int packageCount = ps.sharedUser.packages.size();
13320                for (int j = 0; j < packageCount; j++) {
13321                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13322                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13323                            && pkg.pkg.requestedPermissions.contains(permission)) {
13324                        used = true;
13325                        break;
13326                    }
13327                }
13328                if (used) {
13329                    continue;
13330                }
13331            }
13332
13333            PermissionsState permissionsState = ps.getPermissionsState();
13334
13335            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13336
13337            // Always clear the user settable flags.
13338            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13339                    bp.name) != null;
13340            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13341                if (hasInstallState) {
13342                    writeInstallPermissions = true;
13343                } else {
13344                    writeRuntimePermissions = true;
13345                }
13346            }
13347
13348            // Below is only runtime permission handling.
13349            if (!bp.isRuntime()) {
13350                continue;
13351            }
13352
13353            // Never clobber system or policy.
13354            if ((oldFlags & policyOrSystemFlags) != 0) {
13355                continue;
13356            }
13357
13358            // If this permission was granted by default, make sure it is.
13359            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13360                if (permissionsState.grantRuntimePermission(bp, userId)
13361                        != PERMISSION_OPERATION_FAILURE) {
13362                    writeRuntimePermissions = true;
13363                }
13364            } else {
13365                // Otherwise, reset the permission.
13366                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13367                switch (revokeResult) {
13368                    case PERMISSION_OPERATION_SUCCESS: {
13369                        writeRuntimePermissions = true;
13370                    } break;
13371
13372                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13373                        writeRuntimePermissions = true;
13374                        // If gids changed for this user, kill all affected packages.
13375                        mHandler.post(new Runnable() {
13376                            @Override
13377                            public void run() {
13378                                // This has to happen with no lock held.
13379                                killSettingPackagesForUser(ps, userId,
13380                                        KILL_APP_REASON_GIDS_CHANGED);
13381                            }
13382                        });
13383                    } break;
13384                }
13385            }
13386        }
13387
13388        // Synchronously write as we are taking permissions away.
13389        if (writeRuntimePermissions) {
13390            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13391        }
13392
13393        // Synchronously write as we are taking permissions away.
13394        if (writeInstallPermissions) {
13395            mSettings.writeLPr();
13396        }
13397    }
13398
13399    /**
13400     * Remove entries from the keystore daemon. Will only remove it if the
13401     * {@code appId} is valid.
13402     */
13403    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13404        if (appId < 0) {
13405            return;
13406        }
13407
13408        final KeyStore keyStore = KeyStore.getInstance();
13409        if (keyStore != null) {
13410            if (userId == UserHandle.USER_ALL) {
13411                for (final int individual : sUserManager.getUserIds()) {
13412                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13413                }
13414            } else {
13415                keyStore.clearUid(UserHandle.getUid(userId, appId));
13416            }
13417        } else {
13418            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13419        }
13420    }
13421
13422    @Override
13423    public void deleteApplicationCacheFiles(final String packageName,
13424            final IPackageDataObserver observer) {
13425        mContext.enforceCallingOrSelfPermission(
13426                android.Manifest.permission.DELETE_CACHE_FILES, null);
13427        // Queue up an async operation since the package deletion may take a little while.
13428        final int userId = UserHandle.getCallingUserId();
13429        mHandler.post(new Runnable() {
13430            public void run() {
13431                mHandler.removeCallbacks(this);
13432                final boolean succeded;
13433                synchronized (mInstallLock) {
13434                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13435                }
13436                clearExternalStorageDataSync(packageName, userId, false);
13437                if (observer != null) {
13438                    try {
13439                        observer.onRemoveCompleted(packageName, succeded);
13440                    } catch (RemoteException e) {
13441                        Log.i(TAG, "Observer no longer exists.");
13442                    }
13443                } //end if observer
13444            } //end run
13445        });
13446    }
13447
13448    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13449        if (packageName == null) {
13450            Slog.w(TAG, "Attempt to delete null packageName.");
13451            return false;
13452        }
13453        PackageParser.Package p;
13454        synchronized (mPackages) {
13455            p = mPackages.get(packageName);
13456        }
13457        if (p == null) {
13458            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13459            return false;
13460        }
13461        final ApplicationInfo applicationInfo = p.applicationInfo;
13462        if (applicationInfo == null) {
13463            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13464            return false;
13465        }
13466        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13467        if (retCode < 0) {
13468            Slog.w(TAG, "Couldn't remove cache files for package: "
13469                       + packageName + " u" + userId);
13470            return false;
13471        }
13472        return true;
13473    }
13474
13475    @Override
13476    public void getPackageSizeInfo(final String packageName, int userHandle,
13477            final IPackageStatsObserver observer) {
13478        mContext.enforceCallingOrSelfPermission(
13479                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13480        if (packageName == null) {
13481            throw new IllegalArgumentException("Attempt to get size of null packageName");
13482        }
13483
13484        PackageStats stats = new PackageStats(packageName, userHandle);
13485
13486        /*
13487         * Queue up an async operation since the package measurement may take a
13488         * little while.
13489         */
13490        Message msg = mHandler.obtainMessage(INIT_COPY);
13491        msg.obj = new MeasureParams(stats, observer);
13492        mHandler.sendMessage(msg);
13493    }
13494
13495    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13496            PackageStats pStats) {
13497        if (packageName == null) {
13498            Slog.w(TAG, "Attempt to get size of null packageName.");
13499            return false;
13500        }
13501        PackageParser.Package p;
13502        boolean dataOnly = false;
13503        String libDirRoot = null;
13504        String asecPath = null;
13505        PackageSetting ps = null;
13506        synchronized (mPackages) {
13507            p = mPackages.get(packageName);
13508            ps = mSettings.mPackages.get(packageName);
13509            if(p == null) {
13510                dataOnly = true;
13511                if((ps == null) || (ps.pkg == null)) {
13512                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13513                    return false;
13514                }
13515                p = ps.pkg;
13516            }
13517            if (ps != null) {
13518                libDirRoot = ps.legacyNativeLibraryPathString;
13519            }
13520            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13521                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13522                if (secureContainerId != null) {
13523                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13524                }
13525            }
13526        }
13527        String publicSrcDir = null;
13528        if(!dataOnly) {
13529            final ApplicationInfo applicationInfo = p.applicationInfo;
13530            if (applicationInfo == null) {
13531                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13532                return false;
13533            }
13534            if (p.isForwardLocked()) {
13535                publicSrcDir = applicationInfo.getBaseResourcePath();
13536            }
13537        }
13538        // TODO: extend to measure size of split APKs
13539        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13540        // not just the first level.
13541        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13542        // just the primary.
13543        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13544        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13545                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13546        if (res < 0) {
13547            return false;
13548        }
13549
13550        // Fix-up for forward-locked applications in ASEC containers.
13551        if (!isExternal(p)) {
13552            pStats.codeSize += pStats.externalCodeSize;
13553            pStats.externalCodeSize = 0L;
13554        }
13555
13556        return true;
13557    }
13558
13559
13560    @Override
13561    public void addPackageToPreferred(String packageName) {
13562        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13563    }
13564
13565    @Override
13566    public void removePackageFromPreferred(String packageName) {
13567        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13568    }
13569
13570    @Override
13571    public List<PackageInfo> getPreferredPackages(int flags) {
13572        return new ArrayList<PackageInfo>();
13573    }
13574
13575    private int getUidTargetSdkVersionLockedLPr(int uid) {
13576        Object obj = mSettings.getUserIdLPr(uid);
13577        if (obj instanceof SharedUserSetting) {
13578            final SharedUserSetting sus = (SharedUserSetting) obj;
13579            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13580            final Iterator<PackageSetting> it = sus.packages.iterator();
13581            while (it.hasNext()) {
13582                final PackageSetting ps = it.next();
13583                if (ps.pkg != null) {
13584                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13585                    if (v < vers) vers = v;
13586                }
13587            }
13588            return vers;
13589        } else if (obj instanceof PackageSetting) {
13590            final PackageSetting ps = (PackageSetting) obj;
13591            if (ps.pkg != null) {
13592                return ps.pkg.applicationInfo.targetSdkVersion;
13593            }
13594        }
13595        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13596    }
13597
13598    @Override
13599    public void addPreferredActivity(IntentFilter filter, int match,
13600            ComponentName[] set, ComponentName activity, int userId) {
13601        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13602                "Adding preferred");
13603    }
13604
13605    private void addPreferredActivityInternal(IntentFilter filter, int match,
13606            ComponentName[] set, ComponentName activity, boolean always, int userId,
13607            String opname) {
13608        // writer
13609        int callingUid = Binder.getCallingUid();
13610        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13611        if (filter.countActions() == 0) {
13612            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13613            return;
13614        }
13615        synchronized (mPackages) {
13616            if (mContext.checkCallingOrSelfPermission(
13617                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13618                    != PackageManager.PERMISSION_GRANTED) {
13619                if (getUidTargetSdkVersionLockedLPr(callingUid)
13620                        < Build.VERSION_CODES.FROYO) {
13621                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13622                            + callingUid);
13623                    return;
13624                }
13625                mContext.enforceCallingOrSelfPermission(
13626                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13627            }
13628
13629            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13630            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13631                    + userId + ":");
13632            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13633            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13634            scheduleWritePackageRestrictionsLocked(userId);
13635        }
13636    }
13637
13638    @Override
13639    public void replacePreferredActivity(IntentFilter filter, int match,
13640            ComponentName[] set, ComponentName activity, int userId) {
13641        if (filter.countActions() != 1) {
13642            throw new IllegalArgumentException(
13643                    "replacePreferredActivity expects filter to have only 1 action.");
13644        }
13645        if (filter.countDataAuthorities() != 0
13646                || filter.countDataPaths() != 0
13647                || filter.countDataSchemes() > 1
13648                || filter.countDataTypes() != 0) {
13649            throw new IllegalArgumentException(
13650                    "replacePreferredActivity expects filter to have no data authorities, " +
13651                    "paths, or types; and at most one scheme.");
13652        }
13653
13654        final int callingUid = Binder.getCallingUid();
13655        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13656        synchronized (mPackages) {
13657            if (mContext.checkCallingOrSelfPermission(
13658                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13659                    != PackageManager.PERMISSION_GRANTED) {
13660                if (getUidTargetSdkVersionLockedLPr(callingUid)
13661                        < Build.VERSION_CODES.FROYO) {
13662                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13663                            + Binder.getCallingUid());
13664                    return;
13665                }
13666                mContext.enforceCallingOrSelfPermission(
13667                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13668            }
13669
13670            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13671            if (pir != null) {
13672                // Get all of the existing entries that exactly match this filter.
13673                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13674                if (existing != null && existing.size() == 1) {
13675                    PreferredActivity cur = existing.get(0);
13676                    if (DEBUG_PREFERRED) {
13677                        Slog.i(TAG, "Checking replace of preferred:");
13678                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13679                        if (!cur.mPref.mAlways) {
13680                            Slog.i(TAG, "  -- CUR; not mAlways!");
13681                        } else {
13682                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13683                            Slog.i(TAG, "  -- CUR: mSet="
13684                                    + Arrays.toString(cur.mPref.mSetComponents));
13685                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13686                            Slog.i(TAG, "  -- NEW: mMatch="
13687                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13688                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13689                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13690                        }
13691                    }
13692                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13693                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13694                            && cur.mPref.sameSet(set)) {
13695                        // Setting the preferred activity to what it happens to be already
13696                        if (DEBUG_PREFERRED) {
13697                            Slog.i(TAG, "Replacing with same preferred activity "
13698                                    + cur.mPref.mShortComponent + " for user "
13699                                    + userId + ":");
13700                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13701                        }
13702                        return;
13703                    }
13704                }
13705
13706                if (existing != null) {
13707                    if (DEBUG_PREFERRED) {
13708                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13709                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13710                    }
13711                    for (int i = 0; i < existing.size(); i++) {
13712                        PreferredActivity pa = existing.get(i);
13713                        if (DEBUG_PREFERRED) {
13714                            Slog.i(TAG, "Removing existing preferred activity "
13715                                    + pa.mPref.mComponent + ":");
13716                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13717                        }
13718                        pir.removeFilter(pa);
13719                    }
13720                }
13721            }
13722            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13723                    "Replacing preferred");
13724        }
13725    }
13726
13727    @Override
13728    public void clearPackagePreferredActivities(String packageName) {
13729        final int uid = Binder.getCallingUid();
13730        // writer
13731        synchronized (mPackages) {
13732            PackageParser.Package pkg = mPackages.get(packageName);
13733            if (pkg == null || pkg.applicationInfo.uid != uid) {
13734                if (mContext.checkCallingOrSelfPermission(
13735                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13736                        != PackageManager.PERMISSION_GRANTED) {
13737                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13738                            < Build.VERSION_CODES.FROYO) {
13739                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13740                                + Binder.getCallingUid());
13741                        return;
13742                    }
13743                    mContext.enforceCallingOrSelfPermission(
13744                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13745                }
13746            }
13747
13748            int user = UserHandle.getCallingUserId();
13749            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13750                scheduleWritePackageRestrictionsLocked(user);
13751            }
13752        }
13753    }
13754
13755    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13756    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13757        ArrayList<PreferredActivity> removed = null;
13758        boolean changed = false;
13759        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13760            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13761            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13762            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13763                continue;
13764            }
13765            Iterator<PreferredActivity> it = pir.filterIterator();
13766            while (it.hasNext()) {
13767                PreferredActivity pa = it.next();
13768                // Mark entry for removal only if it matches the package name
13769                // and the entry is of type "always".
13770                if (packageName == null ||
13771                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13772                                && pa.mPref.mAlways)) {
13773                    if (removed == null) {
13774                        removed = new ArrayList<PreferredActivity>();
13775                    }
13776                    removed.add(pa);
13777                }
13778            }
13779            if (removed != null) {
13780                for (int j=0; j<removed.size(); j++) {
13781                    PreferredActivity pa = removed.get(j);
13782                    pir.removeFilter(pa);
13783                }
13784                changed = true;
13785            }
13786        }
13787        return changed;
13788    }
13789
13790    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13791    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13792        if (userId == UserHandle.USER_ALL) {
13793            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13794                    sUserManager.getUserIds())) {
13795                for (int oneUserId : sUserManager.getUserIds()) {
13796                    scheduleWritePackageRestrictionsLocked(oneUserId);
13797                }
13798            }
13799        } else {
13800            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13801                scheduleWritePackageRestrictionsLocked(userId);
13802            }
13803        }
13804    }
13805
13806
13807    void clearDefaultBrowserIfNeeded(String packageName) {
13808        for (int oneUserId : sUserManager.getUserIds()) {
13809            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13810            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13811            if (packageName.equals(defaultBrowserPackageName)) {
13812                setDefaultBrowserPackageName(null, oneUserId);
13813            }
13814        }
13815    }
13816
13817    @Override
13818    public void resetPreferredActivities(int userId) {
13819        mContext.enforceCallingOrSelfPermission(
13820                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13821        // writer
13822        synchronized (mPackages) {
13823            clearPackagePreferredActivitiesLPw(null, userId);
13824            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13825            applyFactoryDefaultBrowserLPw(userId);
13826            primeDomainVerificationsLPw(userId);
13827
13828            scheduleWritePackageRestrictionsLocked(userId);
13829        }
13830    }
13831
13832    @Override
13833    public int getPreferredActivities(List<IntentFilter> outFilters,
13834            List<ComponentName> outActivities, String packageName) {
13835
13836        int num = 0;
13837        final int userId = UserHandle.getCallingUserId();
13838        // reader
13839        synchronized (mPackages) {
13840            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13841            if (pir != null) {
13842                final Iterator<PreferredActivity> it = pir.filterIterator();
13843                while (it.hasNext()) {
13844                    final PreferredActivity pa = it.next();
13845                    if (packageName == null
13846                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13847                                    && pa.mPref.mAlways)) {
13848                        if (outFilters != null) {
13849                            outFilters.add(new IntentFilter(pa));
13850                        }
13851                        if (outActivities != null) {
13852                            outActivities.add(pa.mPref.mComponent);
13853                        }
13854                    }
13855                }
13856            }
13857        }
13858
13859        return num;
13860    }
13861
13862    @Override
13863    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13864            int userId) {
13865        int callingUid = Binder.getCallingUid();
13866        if (callingUid != Process.SYSTEM_UID) {
13867            throw new SecurityException(
13868                    "addPersistentPreferredActivity can only be run by the system");
13869        }
13870        if (filter.countActions() == 0) {
13871            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13872            return;
13873        }
13874        synchronized (mPackages) {
13875            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13876                    " :");
13877            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13878            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13879                    new PersistentPreferredActivity(filter, activity));
13880            scheduleWritePackageRestrictionsLocked(userId);
13881        }
13882    }
13883
13884    @Override
13885    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13886        int callingUid = Binder.getCallingUid();
13887        if (callingUid != Process.SYSTEM_UID) {
13888            throw new SecurityException(
13889                    "clearPackagePersistentPreferredActivities can only be run by the system");
13890        }
13891        ArrayList<PersistentPreferredActivity> removed = null;
13892        boolean changed = false;
13893        synchronized (mPackages) {
13894            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13895                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13896                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13897                        .valueAt(i);
13898                if (userId != thisUserId) {
13899                    continue;
13900                }
13901                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13902                while (it.hasNext()) {
13903                    PersistentPreferredActivity ppa = it.next();
13904                    // Mark entry for removal only if it matches the package name.
13905                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13906                        if (removed == null) {
13907                            removed = new ArrayList<PersistentPreferredActivity>();
13908                        }
13909                        removed.add(ppa);
13910                    }
13911                }
13912                if (removed != null) {
13913                    for (int j=0; j<removed.size(); j++) {
13914                        PersistentPreferredActivity ppa = removed.get(j);
13915                        ppir.removeFilter(ppa);
13916                    }
13917                    changed = true;
13918                }
13919            }
13920
13921            if (changed) {
13922                scheduleWritePackageRestrictionsLocked(userId);
13923            }
13924        }
13925    }
13926
13927    /**
13928     * Common machinery for picking apart a restored XML blob and passing
13929     * it to a caller-supplied functor to be applied to the running system.
13930     */
13931    private void restoreFromXml(XmlPullParser parser, int userId,
13932            String expectedStartTag, BlobXmlRestorer functor)
13933            throws IOException, XmlPullParserException {
13934        int type;
13935        while ((type = parser.next()) != XmlPullParser.START_TAG
13936                && type != XmlPullParser.END_DOCUMENT) {
13937        }
13938        if (type != XmlPullParser.START_TAG) {
13939            // oops didn't find a start tag?!
13940            if (DEBUG_BACKUP) {
13941                Slog.e(TAG, "Didn't find start tag during restore");
13942            }
13943            return;
13944        }
13945
13946        // this is supposed to be TAG_PREFERRED_BACKUP
13947        if (!expectedStartTag.equals(parser.getName())) {
13948            if (DEBUG_BACKUP) {
13949                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13950            }
13951            return;
13952        }
13953
13954        // skip interfering stuff, then we're aligned with the backing implementation
13955        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13956        functor.apply(parser, userId);
13957    }
13958
13959    private interface BlobXmlRestorer {
13960        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13961    }
13962
13963    /**
13964     * Non-Binder method, support for the backup/restore mechanism: write the
13965     * full set of preferred activities in its canonical XML format.  Returns the
13966     * XML output as a byte array, or null if there is none.
13967     */
13968    @Override
13969    public byte[] getPreferredActivityBackup(int userId) {
13970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13971            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13972        }
13973
13974        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13975        try {
13976            final XmlSerializer serializer = new FastXmlSerializer();
13977            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13978            serializer.startDocument(null, true);
13979            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13980
13981            synchronized (mPackages) {
13982                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13983            }
13984
13985            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13986            serializer.endDocument();
13987            serializer.flush();
13988        } catch (Exception e) {
13989            if (DEBUG_BACKUP) {
13990                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13991            }
13992            return null;
13993        }
13994
13995        return dataStream.toByteArray();
13996    }
13997
13998    @Override
13999    public void restorePreferredActivities(byte[] backup, int userId) {
14000        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14001            throw new SecurityException("Only the system may call restorePreferredActivities()");
14002        }
14003
14004        try {
14005            final XmlPullParser parser = Xml.newPullParser();
14006            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14007            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14008                    new BlobXmlRestorer() {
14009                        @Override
14010                        public void apply(XmlPullParser parser, int userId)
14011                                throws XmlPullParserException, IOException {
14012                            synchronized (mPackages) {
14013                                mSettings.readPreferredActivitiesLPw(parser, userId);
14014                            }
14015                        }
14016                    } );
14017        } catch (Exception e) {
14018            if (DEBUG_BACKUP) {
14019                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14020            }
14021        }
14022    }
14023
14024    /**
14025     * Non-Binder method, support for the backup/restore mechanism: write the
14026     * default browser (etc) settings in its canonical XML format.  Returns the default
14027     * browser XML representation as a byte array, or null if there is none.
14028     */
14029    @Override
14030    public byte[] getDefaultAppsBackup(int userId) {
14031        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14032            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14033        }
14034
14035        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14036        try {
14037            final XmlSerializer serializer = new FastXmlSerializer();
14038            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14039            serializer.startDocument(null, true);
14040            serializer.startTag(null, TAG_DEFAULT_APPS);
14041
14042            synchronized (mPackages) {
14043                mSettings.writeDefaultAppsLPr(serializer, userId);
14044            }
14045
14046            serializer.endTag(null, TAG_DEFAULT_APPS);
14047            serializer.endDocument();
14048            serializer.flush();
14049        } catch (Exception e) {
14050            if (DEBUG_BACKUP) {
14051                Slog.e(TAG, "Unable to write default apps for backup", e);
14052            }
14053            return null;
14054        }
14055
14056        return dataStream.toByteArray();
14057    }
14058
14059    @Override
14060    public void restoreDefaultApps(byte[] backup, int userId) {
14061        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14062            throw new SecurityException("Only the system may call restoreDefaultApps()");
14063        }
14064
14065        try {
14066            final XmlPullParser parser = Xml.newPullParser();
14067            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14068            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14069                    new BlobXmlRestorer() {
14070                        @Override
14071                        public void apply(XmlPullParser parser, int userId)
14072                                throws XmlPullParserException, IOException {
14073                            synchronized (mPackages) {
14074                                mSettings.readDefaultAppsLPw(parser, userId);
14075                            }
14076                        }
14077                    } );
14078        } catch (Exception e) {
14079            if (DEBUG_BACKUP) {
14080                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14081            }
14082        }
14083    }
14084
14085    @Override
14086    public byte[] getIntentFilterVerificationBackup(int userId) {
14087        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14088            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14089        }
14090
14091        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14092        try {
14093            final XmlSerializer serializer = new FastXmlSerializer();
14094            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14095            serializer.startDocument(null, true);
14096            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14097
14098            synchronized (mPackages) {
14099                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14100            }
14101
14102            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14103            serializer.endDocument();
14104            serializer.flush();
14105        } catch (Exception e) {
14106            if (DEBUG_BACKUP) {
14107                Slog.e(TAG, "Unable to write default apps for backup", e);
14108            }
14109            return null;
14110        }
14111
14112        return dataStream.toByteArray();
14113    }
14114
14115    @Override
14116    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14117        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14118            throw new SecurityException("Only the system may call restorePreferredActivities()");
14119        }
14120
14121        try {
14122            final XmlPullParser parser = Xml.newPullParser();
14123            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14124            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14125                    new BlobXmlRestorer() {
14126                        @Override
14127                        public void apply(XmlPullParser parser, int userId)
14128                                throws XmlPullParserException, IOException {
14129                            synchronized (mPackages) {
14130                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14131                                mSettings.writeLPr();
14132                            }
14133                        }
14134                    } );
14135        } catch (Exception e) {
14136            if (DEBUG_BACKUP) {
14137                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14138            }
14139        }
14140    }
14141
14142    @Override
14143    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14144            int sourceUserId, int targetUserId, int flags) {
14145        mContext.enforceCallingOrSelfPermission(
14146                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14147        int callingUid = Binder.getCallingUid();
14148        enforceOwnerRights(ownerPackage, callingUid);
14149        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14150        if (intentFilter.countActions() == 0) {
14151            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14152            return;
14153        }
14154        synchronized (mPackages) {
14155            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14156                    ownerPackage, targetUserId, flags);
14157            CrossProfileIntentResolver resolver =
14158                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14159            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14160            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14161            if (existing != null) {
14162                int size = existing.size();
14163                for (int i = 0; i < size; i++) {
14164                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14165                        return;
14166                    }
14167                }
14168            }
14169            resolver.addFilter(newFilter);
14170            scheduleWritePackageRestrictionsLocked(sourceUserId);
14171        }
14172    }
14173
14174    @Override
14175    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14176        mContext.enforceCallingOrSelfPermission(
14177                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14178        int callingUid = Binder.getCallingUid();
14179        enforceOwnerRights(ownerPackage, callingUid);
14180        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14181        synchronized (mPackages) {
14182            CrossProfileIntentResolver resolver =
14183                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14184            ArraySet<CrossProfileIntentFilter> set =
14185                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14186            for (CrossProfileIntentFilter filter : set) {
14187                if (filter.getOwnerPackage().equals(ownerPackage)) {
14188                    resolver.removeFilter(filter);
14189                }
14190            }
14191            scheduleWritePackageRestrictionsLocked(sourceUserId);
14192        }
14193    }
14194
14195    // Enforcing that callingUid is owning pkg on userId
14196    private void enforceOwnerRights(String pkg, int callingUid) {
14197        // The system owns everything.
14198        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14199            return;
14200        }
14201        int callingUserId = UserHandle.getUserId(callingUid);
14202        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14203        if (pi == null) {
14204            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14205                    + callingUserId);
14206        }
14207        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14208            throw new SecurityException("Calling uid " + callingUid
14209                    + " does not own package " + pkg);
14210        }
14211    }
14212
14213    @Override
14214    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14215        Intent intent = new Intent(Intent.ACTION_MAIN);
14216        intent.addCategory(Intent.CATEGORY_HOME);
14217
14218        final int callingUserId = UserHandle.getCallingUserId();
14219        List<ResolveInfo> list = queryIntentActivities(intent, null,
14220                PackageManager.GET_META_DATA, callingUserId);
14221        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14222                true, false, false, callingUserId);
14223
14224        allHomeCandidates.clear();
14225        if (list != null) {
14226            for (ResolveInfo ri : list) {
14227                allHomeCandidates.add(ri);
14228            }
14229        }
14230        return (preferred == null || preferred.activityInfo == null)
14231                ? null
14232                : new ComponentName(preferred.activityInfo.packageName,
14233                        preferred.activityInfo.name);
14234    }
14235
14236    @Override
14237    public void setApplicationEnabledSetting(String appPackageName,
14238            int newState, int flags, int userId, String callingPackage) {
14239        if (!sUserManager.exists(userId)) return;
14240        if (callingPackage == null) {
14241            callingPackage = Integer.toString(Binder.getCallingUid());
14242        }
14243        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14244    }
14245
14246    @Override
14247    public void setComponentEnabledSetting(ComponentName componentName,
14248            int newState, int flags, int userId) {
14249        if (!sUserManager.exists(userId)) return;
14250        setEnabledSetting(componentName.getPackageName(),
14251                componentName.getClassName(), newState, flags, userId, null);
14252    }
14253
14254    private void setEnabledSetting(final String packageName, String className, int newState,
14255            final int flags, int userId, String callingPackage) {
14256        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14257              || newState == COMPONENT_ENABLED_STATE_ENABLED
14258              || newState == COMPONENT_ENABLED_STATE_DISABLED
14259              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14260              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14261            throw new IllegalArgumentException("Invalid new component state: "
14262                    + newState);
14263        }
14264        PackageSetting pkgSetting;
14265        final int uid = Binder.getCallingUid();
14266        final int permission = mContext.checkCallingOrSelfPermission(
14267                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14268        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14269        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14270        boolean sendNow = false;
14271        boolean isApp = (className == null);
14272        String componentName = isApp ? packageName : className;
14273        int packageUid = -1;
14274        ArrayList<String> components;
14275
14276        // writer
14277        synchronized (mPackages) {
14278            pkgSetting = mSettings.mPackages.get(packageName);
14279            if (pkgSetting == null) {
14280                if (className == null) {
14281                    throw new IllegalArgumentException(
14282                            "Unknown package: " + packageName);
14283                }
14284                throw new IllegalArgumentException(
14285                        "Unknown component: " + packageName
14286                        + "/" + className);
14287            }
14288            // Allow root and verify that userId is not being specified by a different user
14289            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14290                throw new SecurityException(
14291                        "Permission Denial: attempt to change component state from pid="
14292                        + Binder.getCallingPid()
14293                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14294            }
14295            if (className == null) {
14296                // We're dealing with an application/package level state change
14297                if (pkgSetting.getEnabled(userId) == newState) {
14298                    // Nothing to do
14299                    return;
14300                }
14301                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14302                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14303                    // Don't care about who enables an app.
14304                    callingPackage = null;
14305                }
14306                pkgSetting.setEnabled(newState, userId, callingPackage);
14307                // pkgSetting.pkg.mSetEnabled = newState;
14308            } else {
14309                // We're dealing with a component level state change
14310                // First, verify that this is a valid class name.
14311                PackageParser.Package pkg = pkgSetting.pkg;
14312                if (pkg == null || !pkg.hasComponentClassName(className)) {
14313                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14314                        throw new IllegalArgumentException("Component class " + className
14315                                + " does not exist in " + packageName);
14316                    } else {
14317                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14318                                + className + " does not exist in " + packageName);
14319                    }
14320                }
14321                switch (newState) {
14322                case COMPONENT_ENABLED_STATE_ENABLED:
14323                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14324                        return;
14325                    }
14326                    break;
14327                case COMPONENT_ENABLED_STATE_DISABLED:
14328                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14329                        return;
14330                    }
14331                    break;
14332                case COMPONENT_ENABLED_STATE_DEFAULT:
14333                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14334                        return;
14335                    }
14336                    break;
14337                default:
14338                    Slog.e(TAG, "Invalid new component state: " + newState);
14339                    return;
14340                }
14341            }
14342            scheduleWritePackageRestrictionsLocked(userId);
14343            components = mPendingBroadcasts.get(userId, packageName);
14344            final boolean newPackage = components == null;
14345            if (newPackage) {
14346                components = new ArrayList<String>();
14347            }
14348            if (!components.contains(componentName)) {
14349                components.add(componentName);
14350            }
14351            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14352                sendNow = true;
14353                // Purge entry from pending broadcast list if another one exists already
14354                // since we are sending one right away.
14355                mPendingBroadcasts.remove(userId, packageName);
14356            } else {
14357                if (newPackage) {
14358                    mPendingBroadcasts.put(userId, packageName, components);
14359                }
14360                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14361                    // Schedule a message
14362                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14363                }
14364            }
14365        }
14366
14367        long callingId = Binder.clearCallingIdentity();
14368        try {
14369            if (sendNow) {
14370                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14371                sendPackageChangedBroadcast(packageName,
14372                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14373            }
14374        } finally {
14375            Binder.restoreCallingIdentity(callingId);
14376        }
14377    }
14378
14379    private void sendPackageChangedBroadcast(String packageName,
14380            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14381        if (DEBUG_INSTALL)
14382            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14383                    + componentNames);
14384        Bundle extras = new Bundle(4);
14385        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14386        String nameList[] = new String[componentNames.size()];
14387        componentNames.toArray(nameList);
14388        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14389        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14390        extras.putInt(Intent.EXTRA_UID, packageUid);
14391        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14392                new int[] {UserHandle.getUserId(packageUid)});
14393    }
14394
14395    @Override
14396    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14397        if (!sUserManager.exists(userId)) return;
14398        final int uid = Binder.getCallingUid();
14399        final int permission = mContext.checkCallingOrSelfPermission(
14400                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14401        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14402        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14403        // writer
14404        synchronized (mPackages) {
14405            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14406                    allowedByPermission, uid, userId)) {
14407                scheduleWritePackageRestrictionsLocked(userId);
14408            }
14409        }
14410    }
14411
14412    @Override
14413    public String getInstallerPackageName(String packageName) {
14414        // reader
14415        synchronized (mPackages) {
14416            return mSettings.getInstallerPackageNameLPr(packageName);
14417        }
14418    }
14419
14420    @Override
14421    public int getApplicationEnabledSetting(String packageName, int userId) {
14422        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14423        int uid = Binder.getCallingUid();
14424        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14425        // reader
14426        synchronized (mPackages) {
14427            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14428        }
14429    }
14430
14431    @Override
14432    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14433        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14434        int uid = Binder.getCallingUid();
14435        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14436        // reader
14437        synchronized (mPackages) {
14438            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14439        }
14440    }
14441
14442    @Override
14443    public void enterSafeMode() {
14444        enforceSystemOrRoot("Only the system can request entering safe mode");
14445
14446        if (!mSystemReady) {
14447            mSafeMode = true;
14448        }
14449    }
14450
14451    @Override
14452    public void systemReady() {
14453        mSystemReady = true;
14454
14455        // Read the compatibilty setting when the system is ready.
14456        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14457                mContext.getContentResolver(),
14458                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14459        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14460        if (DEBUG_SETTINGS) {
14461            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14462        }
14463
14464        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14465
14466        synchronized (mPackages) {
14467            // Verify that all of the preferred activity components actually
14468            // exist.  It is possible for applications to be updated and at
14469            // that point remove a previously declared activity component that
14470            // had been set as a preferred activity.  We try to clean this up
14471            // the next time we encounter that preferred activity, but it is
14472            // possible for the user flow to never be able to return to that
14473            // situation so here we do a sanity check to make sure we haven't
14474            // left any junk around.
14475            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14476            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14477                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14478                removed.clear();
14479                for (PreferredActivity pa : pir.filterSet()) {
14480                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14481                        removed.add(pa);
14482                    }
14483                }
14484                if (removed.size() > 0) {
14485                    for (int r=0; r<removed.size(); r++) {
14486                        PreferredActivity pa = removed.get(r);
14487                        Slog.w(TAG, "Removing dangling preferred activity: "
14488                                + pa.mPref.mComponent);
14489                        pir.removeFilter(pa);
14490                    }
14491                    mSettings.writePackageRestrictionsLPr(
14492                            mSettings.mPreferredActivities.keyAt(i));
14493                }
14494            }
14495
14496            for (int userId : UserManagerService.getInstance().getUserIds()) {
14497                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14498                    grantPermissionsUserIds = ArrayUtils.appendInt(
14499                            grantPermissionsUserIds, userId);
14500                }
14501            }
14502        }
14503        sUserManager.systemReady();
14504
14505        // If we upgraded grant all default permissions before kicking off.
14506        for (int userId : grantPermissionsUserIds) {
14507            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14508        }
14509
14510        // Kick off any messages waiting for system ready
14511        if (mPostSystemReadyMessages != null) {
14512            for (Message msg : mPostSystemReadyMessages) {
14513                msg.sendToTarget();
14514            }
14515            mPostSystemReadyMessages = null;
14516        }
14517
14518        // Watch for external volumes that come and go over time
14519        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14520        storage.registerListener(mStorageListener);
14521
14522        mInstallerService.systemReady();
14523        mPackageDexOptimizer.systemReady();
14524
14525        MountServiceInternal mountServiceInternal = LocalServices.getService(
14526                MountServiceInternal.class);
14527        mountServiceInternal.addExternalStoragePolicy(
14528                new MountServiceInternal.ExternalStorageMountPolicy() {
14529            @Override
14530            public int getMountMode(int uid, String packageName) {
14531                if (Process.isIsolated(uid)) {
14532                    return Zygote.MOUNT_EXTERNAL_NONE;
14533                }
14534                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14535                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14536                }
14537                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14538                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14539                }
14540                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14541                    return Zygote.MOUNT_EXTERNAL_READ;
14542                }
14543                return Zygote.MOUNT_EXTERNAL_WRITE;
14544            }
14545
14546            @Override
14547            public boolean hasExternalStorage(int uid, String packageName) {
14548                return true;
14549            }
14550        });
14551    }
14552
14553    @Override
14554    public boolean isSafeMode() {
14555        return mSafeMode;
14556    }
14557
14558    @Override
14559    public boolean hasSystemUidErrors() {
14560        return mHasSystemUidErrors;
14561    }
14562
14563    static String arrayToString(int[] array) {
14564        StringBuffer buf = new StringBuffer(128);
14565        buf.append('[');
14566        if (array != null) {
14567            for (int i=0; i<array.length; i++) {
14568                if (i > 0) buf.append(", ");
14569                buf.append(array[i]);
14570            }
14571        }
14572        buf.append(']');
14573        return buf.toString();
14574    }
14575
14576    static class DumpState {
14577        public static final int DUMP_LIBS = 1 << 0;
14578        public static final int DUMP_FEATURES = 1 << 1;
14579        public static final int DUMP_RESOLVERS = 1 << 2;
14580        public static final int DUMP_PERMISSIONS = 1 << 3;
14581        public static final int DUMP_PACKAGES = 1 << 4;
14582        public static final int DUMP_SHARED_USERS = 1 << 5;
14583        public static final int DUMP_MESSAGES = 1 << 6;
14584        public static final int DUMP_PROVIDERS = 1 << 7;
14585        public static final int DUMP_VERIFIERS = 1 << 8;
14586        public static final int DUMP_PREFERRED = 1 << 9;
14587        public static final int DUMP_PREFERRED_XML = 1 << 10;
14588        public static final int DUMP_KEYSETS = 1 << 11;
14589        public static final int DUMP_VERSION = 1 << 12;
14590        public static final int DUMP_INSTALLS = 1 << 13;
14591        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14592        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14593
14594        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14595
14596        private int mTypes;
14597
14598        private int mOptions;
14599
14600        private boolean mTitlePrinted;
14601
14602        private SharedUserSetting mSharedUser;
14603
14604        public boolean isDumping(int type) {
14605            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14606                return true;
14607            }
14608
14609            return (mTypes & type) != 0;
14610        }
14611
14612        public void setDump(int type) {
14613            mTypes |= type;
14614        }
14615
14616        public boolean isOptionEnabled(int option) {
14617            return (mOptions & option) != 0;
14618        }
14619
14620        public void setOptionEnabled(int option) {
14621            mOptions |= option;
14622        }
14623
14624        public boolean onTitlePrinted() {
14625            final boolean printed = mTitlePrinted;
14626            mTitlePrinted = true;
14627            return printed;
14628        }
14629
14630        public boolean getTitlePrinted() {
14631            return mTitlePrinted;
14632        }
14633
14634        public void setTitlePrinted(boolean enabled) {
14635            mTitlePrinted = enabled;
14636        }
14637
14638        public SharedUserSetting getSharedUser() {
14639            return mSharedUser;
14640        }
14641
14642        public void setSharedUser(SharedUserSetting user) {
14643            mSharedUser = user;
14644        }
14645    }
14646
14647    @Override
14648    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14649        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14650                != PackageManager.PERMISSION_GRANTED) {
14651            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14652                    + Binder.getCallingPid()
14653                    + ", uid=" + Binder.getCallingUid()
14654                    + " without permission "
14655                    + android.Manifest.permission.DUMP);
14656            return;
14657        }
14658
14659        DumpState dumpState = new DumpState();
14660        boolean fullPreferred = false;
14661        boolean checkin = false;
14662
14663        String packageName = null;
14664        ArraySet<String> permissionNames = null;
14665
14666        int opti = 0;
14667        while (opti < args.length) {
14668            String opt = args[opti];
14669            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14670                break;
14671            }
14672            opti++;
14673
14674            if ("-a".equals(opt)) {
14675                // Right now we only know how to print all.
14676            } else if ("-h".equals(opt)) {
14677                pw.println("Package manager dump options:");
14678                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14679                pw.println("    --checkin: dump for a checkin");
14680                pw.println("    -f: print details of intent filters");
14681                pw.println("    -h: print this help");
14682                pw.println("  cmd may be one of:");
14683                pw.println("    l[ibraries]: list known shared libraries");
14684                pw.println("    f[ibraries]: list device features");
14685                pw.println("    k[eysets]: print known keysets");
14686                pw.println("    r[esolvers]: dump intent resolvers");
14687                pw.println("    perm[issions]: dump permissions");
14688                pw.println("    permission [name ...]: dump declaration and use of given permission");
14689                pw.println("    pref[erred]: print preferred package settings");
14690                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14691                pw.println("    prov[iders]: dump content providers");
14692                pw.println("    p[ackages]: dump installed packages");
14693                pw.println("    s[hared-users]: dump shared user IDs");
14694                pw.println("    m[essages]: print collected runtime messages");
14695                pw.println("    v[erifiers]: print package verifier info");
14696                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14697                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14698                pw.println("    version: print database version info");
14699                pw.println("    write: write current settings now");
14700                pw.println("    installs: details about install sessions");
14701                pw.println("    <package.name>: info about given package");
14702                return;
14703            } else if ("--checkin".equals(opt)) {
14704                checkin = true;
14705            } else if ("-f".equals(opt)) {
14706                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14707            } else {
14708                pw.println("Unknown argument: " + opt + "; use -h for help");
14709            }
14710        }
14711
14712        // Is the caller requesting to dump a particular piece of data?
14713        if (opti < args.length) {
14714            String cmd = args[opti];
14715            opti++;
14716            // Is this a package name?
14717            if ("android".equals(cmd) || cmd.contains(".")) {
14718                packageName = cmd;
14719                // When dumping a single package, we always dump all of its
14720                // filter information since the amount of data will be reasonable.
14721                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14722            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14723                dumpState.setDump(DumpState.DUMP_LIBS);
14724            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14725                dumpState.setDump(DumpState.DUMP_FEATURES);
14726            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14727                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14728            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14729                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14730            } else if ("permission".equals(cmd)) {
14731                if (opti >= args.length) {
14732                    pw.println("Error: permission requires permission name");
14733                    return;
14734                }
14735                permissionNames = new ArraySet<>();
14736                while (opti < args.length) {
14737                    permissionNames.add(args[opti]);
14738                    opti++;
14739                }
14740                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14741                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14742            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14743                dumpState.setDump(DumpState.DUMP_PREFERRED);
14744            } else if ("preferred-xml".equals(cmd)) {
14745                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14746                if (opti < args.length && "--full".equals(args[opti])) {
14747                    fullPreferred = true;
14748                    opti++;
14749                }
14750            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14751                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14752            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14753                dumpState.setDump(DumpState.DUMP_PACKAGES);
14754            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14755                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14756            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14757                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14758            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14759                dumpState.setDump(DumpState.DUMP_MESSAGES);
14760            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14761                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14762            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14763                    || "intent-filter-verifiers".equals(cmd)) {
14764                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14765            } else if ("version".equals(cmd)) {
14766                dumpState.setDump(DumpState.DUMP_VERSION);
14767            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14768                dumpState.setDump(DumpState.DUMP_KEYSETS);
14769            } else if ("installs".equals(cmd)) {
14770                dumpState.setDump(DumpState.DUMP_INSTALLS);
14771            } else if ("write".equals(cmd)) {
14772                synchronized (mPackages) {
14773                    mSettings.writeLPr();
14774                    pw.println("Settings written.");
14775                    return;
14776                }
14777            }
14778        }
14779
14780        if (checkin) {
14781            pw.println("vers,1");
14782        }
14783
14784        // reader
14785        synchronized (mPackages) {
14786            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14787                if (!checkin) {
14788                    if (dumpState.onTitlePrinted())
14789                        pw.println();
14790                    pw.println("Database versions:");
14791                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14792                }
14793            }
14794
14795            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14796                if (!checkin) {
14797                    if (dumpState.onTitlePrinted())
14798                        pw.println();
14799                    pw.println("Verifiers:");
14800                    pw.print("  Required: ");
14801                    pw.print(mRequiredVerifierPackage);
14802                    pw.print(" (uid=");
14803                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14804                    pw.println(")");
14805                } else if (mRequiredVerifierPackage != null) {
14806                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14807                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14808                }
14809            }
14810
14811            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14812                    packageName == null) {
14813                if (mIntentFilterVerifierComponent != null) {
14814                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14815                    if (!checkin) {
14816                        if (dumpState.onTitlePrinted())
14817                            pw.println();
14818                        pw.println("Intent Filter Verifier:");
14819                        pw.print("  Using: ");
14820                        pw.print(verifierPackageName);
14821                        pw.print(" (uid=");
14822                        pw.print(getPackageUid(verifierPackageName, 0));
14823                        pw.println(")");
14824                    } else if (verifierPackageName != null) {
14825                        pw.print("ifv,"); pw.print(verifierPackageName);
14826                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14827                    }
14828                } else {
14829                    pw.println();
14830                    pw.println("No Intent Filter Verifier available!");
14831                }
14832            }
14833
14834            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14835                boolean printedHeader = false;
14836                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14837                while (it.hasNext()) {
14838                    String name = it.next();
14839                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14840                    if (!checkin) {
14841                        if (!printedHeader) {
14842                            if (dumpState.onTitlePrinted())
14843                                pw.println();
14844                            pw.println("Libraries:");
14845                            printedHeader = true;
14846                        }
14847                        pw.print("  ");
14848                    } else {
14849                        pw.print("lib,");
14850                    }
14851                    pw.print(name);
14852                    if (!checkin) {
14853                        pw.print(" -> ");
14854                    }
14855                    if (ent.path != null) {
14856                        if (!checkin) {
14857                            pw.print("(jar) ");
14858                            pw.print(ent.path);
14859                        } else {
14860                            pw.print(",jar,");
14861                            pw.print(ent.path);
14862                        }
14863                    } else {
14864                        if (!checkin) {
14865                            pw.print("(apk) ");
14866                            pw.print(ent.apk);
14867                        } else {
14868                            pw.print(",apk,");
14869                            pw.print(ent.apk);
14870                        }
14871                    }
14872                    pw.println();
14873                }
14874            }
14875
14876            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14877                if (dumpState.onTitlePrinted())
14878                    pw.println();
14879                if (!checkin) {
14880                    pw.println("Features:");
14881                }
14882                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14883                while (it.hasNext()) {
14884                    String name = it.next();
14885                    if (!checkin) {
14886                        pw.print("  ");
14887                    } else {
14888                        pw.print("feat,");
14889                    }
14890                    pw.println(name);
14891                }
14892            }
14893
14894            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14895                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14896                        : "Activity Resolver Table:", "  ", packageName,
14897                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14898                    dumpState.setTitlePrinted(true);
14899                }
14900                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14901                        : "Receiver Resolver Table:", "  ", packageName,
14902                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14903                    dumpState.setTitlePrinted(true);
14904                }
14905                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14906                        : "Service Resolver Table:", "  ", packageName,
14907                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14908                    dumpState.setTitlePrinted(true);
14909                }
14910                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14911                        : "Provider Resolver Table:", "  ", packageName,
14912                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14913                    dumpState.setTitlePrinted(true);
14914                }
14915            }
14916
14917            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14918                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14919                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14920                    int user = mSettings.mPreferredActivities.keyAt(i);
14921                    if (pir.dump(pw,
14922                            dumpState.getTitlePrinted()
14923                                ? "\nPreferred Activities User " + user + ":"
14924                                : "Preferred Activities User " + user + ":", "  ",
14925                            packageName, true, false)) {
14926                        dumpState.setTitlePrinted(true);
14927                    }
14928                }
14929            }
14930
14931            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14932                pw.flush();
14933                FileOutputStream fout = new FileOutputStream(fd);
14934                BufferedOutputStream str = new BufferedOutputStream(fout);
14935                XmlSerializer serializer = new FastXmlSerializer();
14936                try {
14937                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14938                    serializer.startDocument(null, true);
14939                    serializer.setFeature(
14940                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14941                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14942                    serializer.endDocument();
14943                    serializer.flush();
14944                } catch (IllegalArgumentException e) {
14945                    pw.println("Failed writing: " + e);
14946                } catch (IllegalStateException e) {
14947                    pw.println("Failed writing: " + e);
14948                } catch (IOException e) {
14949                    pw.println("Failed writing: " + e);
14950                }
14951            }
14952
14953            if (!checkin
14954                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14955                    && packageName == null) {
14956                pw.println();
14957                int count = mSettings.mPackages.size();
14958                if (count == 0) {
14959                    pw.println("No applications!");
14960                    pw.println();
14961                } else {
14962                    final String prefix = "  ";
14963                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14964                    if (allPackageSettings.size() == 0) {
14965                        pw.println("No domain preferred apps!");
14966                        pw.println();
14967                    } else {
14968                        pw.println("App verification status:");
14969                        pw.println();
14970                        count = 0;
14971                        for (PackageSetting ps : allPackageSettings) {
14972                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14973                            if (ivi == null || ivi.getPackageName() == null) continue;
14974                            pw.println(prefix + "Package: " + ivi.getPackageName());
14975                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14976                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14977                            pw.println();
14978                            count++;
14979                        }
14980                        if (count == 0) {
14981                            pw.println(prefix + "No app verification established.");
14982                            pw.println();
14983                        }
14984                        for (int userId : sUserManager.getUserIds()) {
14985                            pw.println("App linkages for user " + userId + ":");
14986                            pw.println();
14987                            count = 0;
14988                            for (PackageSetting ps : allPackageSettings) {
14989                                final long status = ps.getDomainVerificationStatusForUser(userId);
14990                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14991                                    continue;
14992                                }
14993                                pw.println(prefix + "Package: " + ps.name);
14994                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14995                                String statusStr = IntentFilterVerificationInfo.
14996                                        getStatusStringFromValue(status);
14997                                pw.println(prefix + "Status:  " + statusStr);
14998                                pw.println();
14999                                count++;
15000                            }
15001                            if (count == 0) {
15002                                pw.println(prefix + "No configured app linkages.");
15003                                pw.println();
15004                            }
15005                        }
15006                    }
15007                }
15008            }
15009
15010            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15011                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15012                if (packageName == null && permissionNames == null) {
15013                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15014                        if (iperm == 0) {
15015                            if (dumpState.onTitlePrinted())
15016                                pw.println();
15017                            pw.println("AppOp Permissions:");
15018                        }
15019                        pw.print("  AppOp Permission ");
15020                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15021                        pw.println(":");
15022                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15023                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15024                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15025                        }
15026                    }
15027                }
15028            }
15029
15030            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15031                boolean printedSomething = false;
15032                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15033                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15034                        continue;
15035                    }
15036                    if (!printedSomething) {
15037                        if (dumpState.onTitlePrinted())
15038                            pw.println();
15039                        pw.println("Registered ContentProviders:");
15040                        printedSomething = true;
15041                    }
15042                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15043                    pw.print("    "); pw.println(p.toString());
15044                }
15045                printedSomething = false;
15046                for (Map.Entry<String, PackageParser.Provider> entry :
15047                        mProvidersByAuthority.entrySet()) {
15048                    PackageParser.Provider p = entry.getValue();
15049                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15050                        continue;
15051                    }
15052                    if (!printedSomething) {
15053                        if (dumpState.onTitlePrinted())
15054                            pw.println();
15055                        pw.println("ContentProvider Authorities:");
15056                        printedSomething = true;
15057                    }
15058                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15059                    pw.print("    "); pw.println(p.toString());
15060                    if (p.info != null && p.info.applicationInfo != null) {
15061                        final String appInfo = p.info.applicationInfo.toString();
15062                        pw.print("      applicationInfo="); pw.println(appInfo);
15063                    }
15064                }
15065            }
15066
15067            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15068                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15069            }
15070
15071            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15072                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15073            }
15074
15075            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15076                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15077            }
15078
15079            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15080                // XXX should handle packageName != null by dumping only install data that
15081                // the given package is involved with.
15082                if (dumpState.onTitlePrinted()) pw.println();
15083                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15084            }
15085
15086            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15087                if (dumpState.onTitlePrinted()) pw.println();
15088                mSettings.dumpReadMessagesLPr(pw, dumpState);
15089
15090                pw.println();
15091                pw.println("Package warning messages:");
15092                BufferedReader in = null;
15093                String line = null;
15094                try {
15095                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15096                    while ((line = in.readLine()) != null) {
15097                        if (line.contains("ignored: updated version")) continue;
15098                        pw.println(line);
15099                    }
15100                } catch (IOException ignored) {
15101                } finally {
15102                    IoUtils.closeQuietly(in);
15103                }
15104            }
15105
15106            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15107                BufferedReader in = null;
15108                String line = null;
15109                try {
15110                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15111                    while ((line = in.readLine()) != null) {
15112                        if (line.contains("ignored: updated version")) continue;
15113                        pw.print("msg,");
15114                        pw.println(line);
15115                    }
15116                } catch (IOException ignored) {
15117                } finally {
15118                    IoUtils.closeQuietly(in);
15119                }
15120            }
15121        }
15122    }
15123
15124    private String dumpDomainString(String packageName) {
15125        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15126        List<IntentFilter> filters = getAllIntentFilters(packageName);
15127
15128        ArraySet<String> result = new ArraySet<>();
15129        if (iviList.size() > 0) {
15130            for (IntentFilterVerificationInfo ivi : iviList) {
15131                for (String host : ivi.getDomains()) {
15132                    result.add(host);
15133                }
15134            }
15135        }
15136        if (filters != null && filters.size() > 0) {
15137            for (IntentFilter filter : filters) {
15138                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15139                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15140                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15141                    result.addAll(filter.getHostsList());
15142                }
15143            }
15144        }
15145
15146        StringBuilder sb = new StringBuilder(result.size() * 16);
15147        for (String domain : result) {
15148            if (sb.length() > 0) sb.append(" ");
15149            sb.append(domain);
15150        }
15151        return sb.toString();
15152    }
15153
15154    // ------- apps on sdcard specific code -------
15155    static final boolean DEBUG_SD_INSTALL = false;
15156
15157    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15158
15159    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15160
15161    private boolean mMediaMounted = false;
15162
15163    static String getEncryptKey() {
15164        try {
15165            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15166                    SD_ENCRYPTION_KEYSTORE_NAME);
15167            if (sdEncKey == null) {
15168                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15169                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15170                if (sdEncKey == null) {
15171                    Slog.e(TAG, "Failed to create encryption keys");
15172                    return null;
15173                }
15174            }
15175            return sdEncKey;
15176        } catch (NoSuchAlgorithmException nsae) {
15177            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15178            return null;
15179        } catch (IOException ioe) {
15180            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15181            return null;
15182        }
15183    }
15184
15185    /*
15186     * Update media status on PackageManager.
15187     */
15188    @Override
15189    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15190        int callingUid = Binder.getCallingUid();
15191        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15192            throw new SecurityException("Media status can only be updated by the system");
15193        }
15194        // reader; this apparently protects mMediaMounted, but should probably
15195        // be a different lock in that case.
15196        synchronized (mPackages) {
15197            Log.i(TAG, "Updating external media status from "
15198                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15199                    + (mediaStatus ? "mounted" : "unmounted"));
15200            if (DEBUG_SD_INSTALL)
15201                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15202                        + ", mMediaMounted=" + mMediaMounted);
15203            if (mediaStatus == mMediaMounted) {
15204                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15205                        : 0, -1);
15206                mHandler.sendMessage(msg);
15207                return;
15208            }
15209            mMediaMounted = mediaStatus;
15210        }
15211        // Queue up an async operation since the package installation may take a
15212        // little while.
15213        mHandler.post(new Runnable() {
15214            public void run() {
15215                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15216            }
15217        });
15218    }
15219
15220    /**
15221     * Called by MountService when the initial ASECs to scan are available.
15222     * Should block until all the ASEC containers are finished being scanned.
15223     */
15224    public void scanAvailableAsecs() {
15225        updateExternalMediaStatusInner(true, false, false);
15226        if (mShouldRestoreconData) {
15227            SELinuxMMAC.setRestoreconDone();
15228            mShouldRestoreconData = false;
15229        }
15230    }
15231
15232    /*
15233     * Collect information of applications on external media, map them against
15234     * existing containers and update information based on current mount status.
15235     * Please note that we always have to report status if reportStatus has been
15236     * set to true especially when unloading packages.
15237     */
15238    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15239            boolean externalStorage) {
15240        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15241        int[] uidArr = EmptyArray.INT;
15242
15243        final String[] list = PackageHelper.getSecureContainerList();
15244        if (ArrayUtils.isEmpty(list)) {
15245            Log.i(TAG, "No secure containers found");
15246        } else {
15247            // Process list of secure containers and categorize them
15248            // as active or stale based on their package internal state.
15249
15250            // reader
15251            synchronized (mPackages) {
15252                for (String cid : list) {
15253                    // Leave stages untouched for now; installer service owns them
15254                    if (PackageInstallerService.isStageName(cid)) continue;
15255
15256                    if (DEBUG_SD_INSTALL)
15257                        Log.i(TAG, "Processing container " + cid);
15258                    String pkgName = getAsecPackageName(cid);
15259                    if (pkgName == null) {
15260                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15261                        continue;
15262                    }
15263                    if (DEBUG_SD_INSTALL)
15264                        Log.i(TAG, "Looking for pkg : " + pkgName);
15265
15266                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15267                    if (ps == null) {
15268                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15269                        continue;
15270                    }
15271
15272                    /*
15273                     * Skip packages that are not external if we're unmounting
15274                     * external storage.
15275                     */
15276                    if (externalStorage && !isMounted && !isExternal(ps)) {
15277                        continue;
15278                    }
15279
15280                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15281                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15282                    // The package status is changed only if the code path
15283                    // matches between settings and the container id.
15284                    if (ps.codePathString != null
15285                            && ps.codePathString.startsWith(args.getCodePath())) {
15286                        if (DEBUG_SD_INSTALL) {
15287                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15288                                    + " at code path: " + ps.codePathString);
15289                        }
15290
15291                        // We do have a valid package installed on sdcard
15292                        processCids.put(args, ps.codePathString);
15293                        final int uid = ps.appId;
15294                        if (uid != -1) {
15295                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15296                        }
15297                    } else {
15298                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15299                                + ps.codePathString);
15300                    }
15301                }
15302            }
15303
15304            Arrays.sort(uidArr);
15305        }
15306
15307        // Process packages with valid entries.
15308        if (isMounted) {
15309            if (DEBUG_SD_INSTALL)
15310                Log.i(TAG, "Loading packages");
15311            loadMediaPackages(processCids, uidArr);
15312            startCleaningPackages();
15313            mInstallerService.onSecureContainersAvailable();
15314        } else {
15315            if (DEBUG_SD_INSTALL)
15316                Log.i(TAG, "Unloading packages");
15317            unloadMediaPackages(processCids, uidArr, reportStatus);
15318        }
15319    }
15320
15321    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15322            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15323        final int size = infos.size();
15324        final String[] packageNames = new String[size];
15325        final int[] packageUids = new int[size];
15326        for (int i = 0; i < size; i++) {
15327            final ApplicationInfo info = infos.get(i);
15328            packageNames[i] = info.packageName;
15329            packageUids[i] = info.uid;
15330        }
15331        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15332                finishedReceiver);
15333    }
15334
15335    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15336            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15337        sendResourcesChangedBroadcast(mediaStatus, replacing,
15338                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15339    }
15340
15341    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15342            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15343        int size = pkgList.length;
15344        if (size > 0) {
15345            // Send broadcasts here
15346            Bundle extras = new Bundle();
15347            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15348            if (uidArr != null) {
15349                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15350            }
15351            if (replacing) {
15352                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15353            }
15354            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15355                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15356            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15357        }
15358    }
15359
15360   /*
15361     * Look at potentially valid container ids from processCids If package
15362     * information doesn't match the one on record or package scanning fails,
15363     * the cid is added to list of removeCids. We currently don't delete stale
15364     * containers.
15365     */
15366    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15367        ArrayList<String> pkgList = new ArrayList<String>();
15368        Set<AsecInstallArgs> keys = processCids.keySet();
15369
15370        for (AsecInstallArgs args : keys) {
15371            String codePath = processCids.get(args);
15372            if (DEBUG_SD_INSTALL)
15373                Log.i(TAG, "Loading container : " + args.cid);
15374            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15375            try {
15376                // Make sure there are no container errors first.
15377                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15378                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15379                            + " when installing from sdcard");
15380                    continue;
15381                }
15382                // Check code path here.
15383                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15384                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15385                            + " does not match one in settings " + codePath);
15386                    continue;
15387                }
15388                // Parse package
15389                int parseFlags = mDefParseFlags;
15390                if (args.isExternalAsec()) {
15391                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15392                }
15393                if (args.isFwdLocked()) {
15394                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15395                }
15396
15397                synchronized (mInstallLock) {
15398                    PackageParser.Package pkg = null;
15399                    try {
15400                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15401                    } catch (PackageManagerException e) {
15402                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15403                    }
15404                    // Scan the package
15405                    if (pkg != null) {
15406                        /*
15407                         * TODO why is the lock being held? doPostInstall is
15408                         * called in other places without the lock. This needs
15409                         * to be straightened out.
15410                         */
15411                        // writer
15412                        synchronized (mPackages) {
15413                            retCode = PackageManager.INSTALL_SUCCEEDED;
15414                            pkgList.add(pkg.packageName);
15415                            // Post process args
15416                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15417                                    pkg.applicationInfo.uid);
15418                        }
15419                    } else {
15420                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15421                    }
15422                }
15423
15424            } finally {
15425                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15426                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15427                }
15428            }
15429        }
15430        // writer
15431        synchronized (mPackages) {
15432            // If the platform SDK has changed since the last time we booted,
15433            // we need to re-grant app permission to catch any new ones that
15434            // appear. This is really a hack, and means that apps can in some
15435            // cases get permissions that the user didn't initially explicitly
15436            // allow... it would be nice to have some better way to handle
15437            // this situation.
15438            final VersionInfo ver = mSettings.getExternalVersion();
15439
15440            int updateFlags = UPDATE_PERMISSIONS_ALL;
15441            if (ver.sdkVersion != mSdkVersion) {
15442                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15443                        + mSdkVersion + "; regranting permissions for external");
15444                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15445            }
15446            updatePermissionsLPw(null, null, updateFlags);
15447
15448            // Yay, everything is now upgraded
15449            ver.forceCurrent();
15450
15451            // can downgrade to reader
15452            // Persist settings
15453            mSettings.writeLPr();
15454        }
15455        // Send a broadcast to let everyone know we are done processing
15456        if (pkgList.size() > 0) {
15457            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15458        }
15459    }
15460
15461   /*
15462     * Utility method to unload a list of specified containers
15463     */
15464    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15465        // Just unmount all valid containers.
15466        for (AsecInstallArgs arg : cidArgs) {
15467            synchronized (mInstallLock) {
15468                arg.doPostDeleteLI(false);
15469           }
15470       }
15471   }
15472
15473    /*
15474     * Unload packages mounted on external media. This involves deleting package
15475     * data from internal structures, sending broadcasts about diabled packages,
15476     * gc'ing to free up references, unmounting all secure containers
15477     * corresponding to packages on external media, and posting a
15478     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15479     * that we always have to post this message if status has been requested no
15480     * matter what.
15481     */
15482    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15483            final boolean reportStatus) {
15484        if (DEBUG_SD_INSTALL)
15485            Log.i(TAG, "unloading media packages");
15486        ArrayList<String> pkgList = new ArrayList<String>();
15487        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15488        final Set<AsecInstallArgs> keys = processCids.keySet();
15489        for (AsecInstallArgs args : keys) {
15490            String pkgName = args.getPackageName();
15491            if (DEBUG_SD_INSTALL)
15492                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15493            // Delete package internally
15494            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15495            synchronized (mInstallLock) {
15496                boolean res = deletePackageLI(pkgName, null, false, null, null,
15497                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15498                if (res) {
15499                    pkgList.add(pkgName);
15500                } else {
15501                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15502                    failedList.add(args);
15503                }
15504            }
15505        }
15506
15507        // reader
15508        synchronized (mPackages) {
15509            // We didn't update the settings after removing each package;
15510            // write them now for all packages.
15511            mSettings.writeLPr();
15512        }
15513
15514        // We have to absolutely send UPDATED_MEDIA_STATUS only
15515        // after confirming that all the receivers processed the ordered
15516        // broadcast when packages get disabled, force a gc to clean things up.
15517        // and unload all the containers.
15518        if (pkgList.size() > 0) {
15519            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15520                    new IIntentReceiver.Stub() {
15521                public void performReceive(Intent intent, int resultCode, String data,
15522                        Bundle extras, boolean ordered, boolean sticky,
15523                        int sendingUser) throws RemoteException {
15524                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15525                            reportStatus ? 1 : 0, 1, keys);
15526                    mHandler.sendMessage(msg);
15527                }
15528            });
15529        } else {
15530            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15531                    keys);
15532            mHandler.sendMessage(msg);
15533        }
15534    }
15535
15536    private void loadPrivatePackages(VolumeInfo vol) {
15537        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15538        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15539        synchronized (mInstallLock) {
15540        synchronized (mPackages) {
15541            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15542            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15543            for (PackageSetting ps : packages) {
15544                final PackageParser.Package pkg;
15545                try {
15546                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15547                    loaded.add(pkg.applicationInfo);
15548                } catch (PackageManagerException e) {
15549                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15550                }
15551
15552                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15553                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15554                }
15555            }
15556
15557            int updateFlags = UPDATE_PERMISSIONS_ALL;
15558            if (ver.sdkVersion != mSdkVersion) {
15559                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15560                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15561                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15562            }
15563            updatePermissionsLPw(null, null, updateFlags);
15564
15565            // Yay, everything is now upgraded
15566            ver.forceCurrent();
15567
15568            mSettings.writeLPr();
15569        }
15570        }
15571
15572        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15573        sendResourcesChangedBroadcast(true, false, loaded, null);
15574    }
15575
15576    private void unloadPrivatePackages(VolumeInfo vol) {
15577        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15578        synchronized (mInstallLock) {
15579        synchronized (mPackages) {
15580            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15581            for (PackageSetting ps : packages) {
15582                if (ps.pkg == null) continue;
15583
15584                final ApplicationInfo info = ps.pkg.applicationInfo;
15585                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15586                if (deletePackageLI(ps.name, null, false, null, null,
15587                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15588                    unloaded.add(info);
15589                } else {
15590                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15591                }
15592            }
15593
15594            mSettings.writeLPr();
15595        }
15596        }
15597
15598        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15599        sendResourcesChangedBroadcast(false, false, unloaded, null);
15600    }
15601
15602    /**
15603     * Examine all users present on given mounted volume, and destroy data
15604     * belonging to users that are no longer valid, or whose user ID has been
15605     * recycled.
15606     */
15607    private void reconcileUsers(String volumeUuid) {
15608        final File[] files = FileUtils
15609                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15610        for (File file : files) {
15611            if (!file.isDirectory()) continue;
15612
15613            final int userId;
15614            final UserInfo info;
15615            try {
15616                userId = Integer.parseInt(file.getName());
15617                info = sUserManager.getUserInfo(userId);
15618            } catch (NumberFormatException e) {
15619                Slog.w(TAG, "Invalid user directory " + file);
15620                continue;
15621            }
15622
15623            boolean destroyUser = false;
15624            if (info == null) {
15625                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15626                        + " because no matching user was found");
15627                destroyUser = true;
15628            } else {
15629                try {
15630                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15631                } catch (IOException e) {
15632                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15633                            + " because we failed to enforce serial number: " + e);
15634                    destroyUser = true;
15635                }
15636            }
15637
15638            if (destroyUser) {
15639                synchronized (mInstallLock) {
15640                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15641                }
15642            }
15643        }
15644
15645        final UserManager um = mContext.getSystemService(UserManager.class);
15646        for (UserInfo user : um.getUsers()) {
15647            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15648            if (userDir.exists()) continue;
15649
15650            try {
15651                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15652                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15653            } catch (IOException e) {
15654                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15655            }
15656        }
15657    }
15658
15659    /**
15660     * Examine all apps present on given mounted volume, and destroy apps that
15661     * aren't expected, either due to uninstallation or reinstallation on
15662     * another volume.
15663     */
15664    private void reconcileApps(String volumeUuid) {
15665        final File[] files = FileUtils
15666                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15667        for (File file : files) {
15668            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15669                    && !PackageInstallerService.isStageName(file.getName());
15670            if (!isPackage) {
15671                // Ignore entries which are not packages
15672                continue;
15673            }
15674
15675            boolean destroyApp = false;
15676            String packageName = null;
15677            try {
15678                final PackageLite pkg = PackageParser.parsePackageLite(file,
15679                        PackageParser.PARSE_MUST_BE_APK);
15680                packageName = pkg.packageName;
15681
15682                synchronized (mPackages) {
15683                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15684                    if (ps == null) {
15685                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15686                                + volumeUuid + " because we found no install record");
15687                        destroyApp = true;
15688                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15689                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15690                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15691                        destroyApp = true;
15692                    }
15693                }
15694
15695            } catch (PackageParserException e) {
15696                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15697                destroyApp = true;
15698            }
15699
15700            if (destroyApp) {
15701                synchronized (mInstallLock) {
15702                    if (packageName != null) {
15703                        removeDataDirsLI(volumeUuid, packageName);
15704                    }
15705                    if (file.isDirectory()) {
15706                        mInstaller.rmPackageDir(file.getAbsolutePath());
15707                    } else {
15708                        file.delete();
15709                    }
15710                }
15711            }
15712        }
15713    }
15714
15715    private void unfreezePackage(String packageName) {
15716        synchronized (mPackages) {
15717            final PackageSetting ps = mSettings.mPackages.get(packageName);
15718            if (ps != null) {
15719                ps.frozen = false;
15720            }
15721        }
15722    }
15723
15724    @Override
15725    public int movePackage(final String packageName, final String volumeUuid) {
15726        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15727
15728        final int moveId = mNextMoveId.getAndIncrement();
15729        try {
15730            movePackageInternal(packageName, volumeUuid, moveId);
15731        } catch (PackageManagerException e) {
15732            Slog.w(TAG, "Failed to move " + packageName, e);
15733            mMoveCallbacks.notifyStatusChanged(moveId,
15734                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15735        }
15736        return moveId;
15737    }
15738
15739    private void movePackageInternal(final String packageName, final String volumeUuid,
15740            final int moveId) throws PackageManagerException {
15741        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15742        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15743        final PackageManager pm = mContext.getPackageManager();
15744
15745        final boolean currentAsec;
15746        final String currentVolumeUuid;
15747        final File codeFile;
15748        final String installerPackageName;
15749        final String packageAbiOverride;
15750        final int appId;
15751        final String seinfo;
15752        final String label;
15753
15754        // reader
15755        synchronized (mPackages) {
15756            final PackageParser.Package pkg = mPackages.get(packageName);
15757            final PackageSetting ps = mSettings.mPackages.get(packageName);
15758            if (pkg == null || ps == null) {
15759                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15760            }
15761
15762            if (pkg.applicationInfo.isSystemApp()) {
15763                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15764                        "Cannot move system application");
15765            }
15766
15767            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15768                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15769                        "Package already moved to " + volumeUuid);
15770            }
15771
15772            final File probe = new File(pkg.codePath);
15773            final File probeOat = new File(probe, "oat");
15774            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15775                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15776                        "Move only supported for modern cluster style installs");
15777            }
15778
15779            if (ps.frozen) {
15780                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15781                        "Failed to move already frozen package");
15782            }
15783            ps.frozen = true;
15784
15785            currentAsec = pkg.applicationInfo.isForwardLocked()
15786                    || pkg.applicationInfo.isExternalAsec();
15787            currentVolumeUuid = ps.volumeUuid;
15788            codeFile = new File(pkg.codePath);
15789            installerPackageName = ps.installerPackageName;
15790            packageAbiOverride = ps.cpuAbiOverrideString;
15791            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15792            seinfo = pkg.applicationInfo.seinfo;
15793            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15794        }
15795
15796        // Now that we're guarded by frozen state, kill app during move
15797        final long token = Binder.clearCallingIdentity();
15798        try {
15799            killApplication(packageName, appId, "move pkg");
15800        } finally {
15801            Binder.restoreCallingIdentity(token);
15802        }
15803
15804        final Bundle extras = new Bundle();
15805        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15806        extras.putString(Intent.EXTRA_TITLE, label);
15807        mMoveCallbacks.notifyCreated(moveId, extras);
15808
15809        int installFlags;
15810        final boolean moveCompleteApp;
15811        final File measurePath;
15812
15813        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15814            installFlags = INSTALL_INTERNAL;
15815            moveCompleteApp = !currentAsec;
15816            measurePath = Environment.getDataAppDirectory(volumeUuid);
15817        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15818            installFlags = INSTALL_EXTERNAL;
15819            moveCompleteApp = false;
15820            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15821        } else {
15822            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15823            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15824                    || !volume.isMountedWritable()) {
15825                unfreezePackage(packageName);
15826                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15827                        "Move location not mounted private volume");
15828            }
15829
15830            Preconditions.checkState(!currentAsec);
15831
15832            installFlags = INSTALL_INTERNAL;
15833            moveCompleteApp = true;
15834            measurePath = Environment.getDataAppDirectory(volumeUuid);
15835        }
15836
15837        final PackageStats stats = new PackageStats(null, -1);
15838        synchronized (mInstaller) {
15839            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15840                unfreezePackage(packageName);
15841                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15842                        "Failed to measure package size");
15843            }
15844        }
15845
15846        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15847                + stats.dataSize);
15848
15849        final long startFreeBytes = measurePath.getFreeSpace();
15850        final long sizeBytes;
15851        if (moveCompleteApp) {
15852            sizeBytes = stats.codeSize + stats.dataSize;
15853        } else {
15854            sizeBytes = stats.codeSize;
15855        }
15856
15857        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15858            unfreezePackage(packageName);
15859            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15860                    "Not enough free space to move");
15861        }
15862
15863        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15864
15865        final CountDownLatch installedLatch = new CountDownLatch(1);
15866        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15867            @Override
15868            public void onUserActionRequired(Intent intent) throws RemoteException {
15869                throw new IllegalStateException();
15870            }
15871
15872            @Override
15873            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15874                    Bundle extras) throws RemoteException {
15875                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15876                        + PackageManager.installStatusToString(returnCode, msg));
15877
15878                installedLatch.countDown();
15879
15880                // Regardless of success or failure of the move operation,
15881                // always unfreeze the package
15882                unfreezePackage(packageName);
15883
15884                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15885                switch (status) {
15886                    case PackageInstaller.STATUS_SUCCESS:
15887                        mMoveCallbacks.notifyStatusChanged(moveId,
15888                                PackageManager.MOVE_SUCCEEDED);
15889                        break;
15890                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15891                        mMoveCallbacks.notifyStatusChanged(moveId,
15892                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15893                        break;
15894                    default:
15895                        mMoveCallbacks.notifyStatusChanged(moveId,
15896                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15897                        break;
15898                }
15899            }
15900        };
15901
15902        final MoveInfo move;
15903        if (moveCompleteApp) {
15904            // Kick off a thread to report progress estimates
15905            new Thread() {
15906                @Override
15907                public void run() {
15908                    while (true) {
15909                        try {
15910                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15911                                break;
15912                            }
15913                        } catch (InterruptedException ignored) {
15914                        }
15915
15916                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15917                        final int progress = 10 + (int) MathUtils.constrain(
15918                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15919                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15920                    }
15921                }
15922            }.start();
15923
15924            final String dataAppName = codeFile.getName();
15925            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15926                    dataAppName, appId, seinfo);
15927        } else {
15928            move = null;
15929        }
15930
15931        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15932
15933        final Message msg = mHandler.obtainMessage(INIT_COPY);
15934        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15935        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15936                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15937        mHandler.sendMessage(msg);
15938    }
15939
15940    @Override
15941    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15942        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15943
15944        final int realMoveId = mNextMoveId.getAndIncrement();
15945        final Bundle extras = new Bundle();
15946        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15947        mMoveCallbacks.notifyCreated(realMoveId, extras);
15948
15949        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15950            @Override
15951            public void onCreated(int moveId, Bundle extras) {
15952                // Ignored
15953            }
15954
15955            @Override
15956            public void onStatusChanged(int moveId, int status, long estMillis) {
15957                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15958            }
15959        };
15960
15961        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15962        storage.setPrimaryStorageUuid(volumeUuid, callback);
15963        return realMoveId;
15964    }
15965
15966    @Override
15967    public int getMoveStatus(int moveId) {
15968        mContext.enforceCallingOrSelfPermission(
15969                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15970        return mMoveCallbacks.mLastStatus.get(moveId);
15971    }
15972
15973    @Override
15974    public void registerMoveCallback(IPackageMoveObserver callback) {
15975        mContext.enforceCallingOrSelfPermission(
15976                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15977        mMoveCallbacks.register(callback);
15978    }
15979
15980    @Override
15981    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15982        mContext.enforceCallingOrSelfPermission(
15983                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15984        mMoveCallbacks.unregister(callback);
15985    }
15986
15987    @Override
15988    public boolean setInstallLocation(int loc) {
15989        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15990                null);
15991        if (getInstallLocation() == loc) {
15992            return true;
15993        }
15994        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15995                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15996            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15997                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15998            return true;
15999        }
16000        return false;
16001   }
16002
16003    @Override
16004    public int getInstallLocation() {
16005        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16006                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16007                PackageHelper.APP_INSTALL_AUTO);
16008    }
16009
16010    /** Called by UserManagerService */
16011    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16012        mDirtyUsers.remove(userHandle);
16013        mSettings.removeUserLPw(userHandle);
16014        mPendingBroadcasts.remove(userHandle);
16015        if (mInstaller != null) {
16016            // Technically, we shouldn't be doing this with the package lock
16017            // held.  However, this is very rare, and there is already so much
16018            // other disk I/O going on, that we'll let it slide for now.
16019            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16020            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16021                final String volumeUuid = vol.getFsUuid();
16022                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16023                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16024            }
16025        }
16026        mUserNeedsBadging.delete(userHandle);
16027        removeUnusedPackagesLILPw(userManager, userHandle);
16028    }
16029
16030    /**
16031     * We're removing userHandle and would like to remove any downloaded packages
16032     * that are no longer in use by any other user.
16033     * @param userHandle the user being removed
16034     */
16035    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16036        final boolean DEBUG_CLEAN_APKS = false;
16037        int [] users = userManager.getUserIdsLPr();
16038        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16039        while (psit.hasNext()) {
16040            PackageSetting ps = psit.next();
16041            if (ps.pkg == null) {
16042                continue;
16043            }
16044            final String packageName = ps.pkg.packageName;
16045            // Skip over if system app
16046            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16047                continue;
16048            }
16049            if (DEBUG_CLEAN_APKS) {
16050                Slog.i(TAG, "Checking package " + packageName);
16051            }
16052            boolean keep = false;
16053            for (int i = 0; i < users.length; i++) {
16054                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16055                    keep = true;
16056                    if (DEBUG_CLEAN_APKS) {
16057                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16058                                + users[i]);
16059                    }
16060                    break;
16061                }
16062            }
16063            if (!keep) {
16064                if (DEBUG_CLEAN_APKS) {
16065                    Slog.i(TAG, "  Removing package " + packageName);
16066                }
16067                mHandler.post(new Runnable() {
16068                    public void run() {
16069                        deletePackageX(packageName, userHandle, 0);
16070                    } //end run
16071                });
16072            }
16073        }
16074    }
16075
16076    /** Called by UserManagerService */
16077    void createNewUserLILPw(int userHandle) {
16078        if (mInstaller != null) {
16079            mInstaller.createUserConfig(userHandle);
16080            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16081            applyFactoryDefaultBrowserLPw(userHandle);
16082            primeDomainVerificationsLPw(userHandle);
16083        }
16084    }
16085
16086    void newUserCreated(final int userHandle) {
16087        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16088    }
16089
16090    @Override
16091    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16092        mContext.enforceCallingOrSelfPermission(
16093                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16094                "Only package verification agents can read the verifier device identity");
16095
16096        synchronized (mPackages) {
16097            return mSettings.getVerifierDeviceIdentityLPw();
16098        }
16099    }
16100
16101    @Override
16102    public void setPermissionEnforced(String permission, boolean enforced) {
16103        // TODO: Now that we no longer change GID for storage, this should to away.
16104        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16105                "setPermissionEnforced");
16106        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16107            synchronized (mPackages) {
16108                if (mSettings.mReadExternalStorageEnforced == null
16109                        || mSettings.mReadExternalStorageEnforced != enforced) {
16110                    mSettings.mReadExternalStorageEnforced = enforced;
16111                    mSettings.writeLPr();
16112                }
16113            }
16114            // kill any non-foreground processes so we restart them and
16115            // grant/revoke the GID.
16116            final IActivityManager am = ActivityManagerNative.getDefault();
16117            if (am != null) {
16118                final long token = Binder.clearCallingIdentity();
16119                try {
16120                    am.killProcessesBelowForeground("setPermissionEnforcement");
16121                } catch (RemoteException e) {
16122                } finally {
16123                    Binder.restoreCallingIdentity(token);
16124                }
16125            }
16126        } else {
16127            throw new IllegalArgumentException("No selective enforcement for " + permission);
16128        }
16129    }
16130
16131    @Override
16132    @Deprecated
16133    public boolean isPermissionEnforced(String permission) {
16134        return true;
16135    }
16136
16137    @Override
16138    public boolean isStorageLow() {
16139        final long token = Binder.clearCallingIdentity();
16140        try {
16141            final DeviceStorageMonitorInternal
16142                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16143            if (dsm != null) {
16144                return dsm.isMemoryLow();
16145            } else {
16146                return false;
16147            }
16148        } finally {
16149            Binder.restoreCallingIdentity(token);
16150        }
16151    }
16152
16153    @Override
16154    public IPackageInstaller getPackageInstaller() {
16155        return mInstallerService;
16156    }
16157
16158    private boolean userNeedsBadging(int userId) {
16159        int index = mUserNeedsBadging.indexOfKey(userId);
16160        if (index < 0) {
16161            final UserInfo userInfo;
16162            final long token = Binder.clearCallingIdentity();
16163            try {
16164                userInfo = sUserManager.getUserInfo(userId);
16165            } finally {
16166                Binder.restoreCallingIdentity(token);
16167            }
16168            final boolean b;
16169            if (userInfo != null && userInfo.isManagedProfile()) {
16170                b = true;
16171            } else {
16172                b = false;
16173            }
16174            mUserNeedsBadging.put(userId, b);
16175            return b;
16176        }
16177        return mUserNeedsBadging.valueAt(index);
16178    }
16179
16180    @Override
16181    public KeySet getKeySetByAlias(String packageName, String alias) {
16182        if (packageName == null || alias == null) {
16183            return null;
16184        }
16185        synchronized(mPackages) {
16186            final PackageParser.Package pkg = mPackages.get(packageName);
16187            if (pkg == null) {
16188                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16189                throw new IllegalArgumentException("Unknown package: " + packageName);
16190            }
16191            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16192            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16193        }
16194    }
16195
16196    @Override
16197    public KeySet getSigningKeySet(String packageName) {
16198        if (packageName == null) {
16199            return null;
16200        }
16201        synchronized(mPackages) {
16202            final PackageParser.Package pkg = mPackages.get(packageName);
16203            if (pkg == null) {
16204                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16205                throw new IllegalArgumentException("Unknown package: " + packageName);
16206            }
16207            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16208                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16209                throw new SecurityException("May not access signing KeySet of other apps.");
16210            }
16211            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16212            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16213        }
16214    }
16215
16216    @Override
16217    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16218        if (packageName == null || ks == null) {
16219            return false;
16220        }
16221        synchronized(mPackages) {
16222            final PackageParser.Package pkg = mPackages.get(packageName);
16223            if (pkg == null) {
16224                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16225                throw new IllegalArgumentException("Unknown package: " + packageName);
16226            }
16227            IBinder ksh = ks.getToken();
16228            if (ksh instanceof KeySetHandle) {
16229                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16230                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16231            }
16232            return false;
16233        }
16234    }
16235
16236    @Override
16237    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16238        if (packageName == null || ks == null) {
16239            return false;
16240        }
16241        synchronized(mPackages) {
16242            final PackageParser.Package pkg = mPackages.get(packageName);
16243            if (pkg == null) {
16244                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16245                throw new IllegalArgumentException("Unknown package: " + packageName);
16246            }
16247            IBinder ksh = ks.getToken();
16248            if (ksh instanceof KeySetHandle) {
16249                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16250                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16251            }
16252            return false;
16253        }
16254    }
16255
16256    public void getUsageStatsIfNoPackageUsageInfo() {
16257        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16258            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16259            if (usm == null) {
16260                throw new IllegalStateException("UsageStatsManager must be initialized");
16261            }
16262            long now = System.currentTimeMillis();
16263            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16264            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16265                String packageName = entry.getKey();
16266                PackageParser.Package pkg = mPackages.get(packageName);
16267                if (pkg == null) {
16268                    continue;
16269                }
16270                UsageStats usage = entry.getValue();
16271                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16272                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16273            }
16274        }
16275    }
16276
16277    /**
16278     * Check and throw if the given before/after packages would be considered a
16279     * downgrade.
16280     */
16281    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16282            throws PackageManagerException {
16283        if (after.versionCode < before.mVersionCode) {
16284            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16285                    "Update version code " + after.versionCode + " is older than current "
16286                    + before.mVersionCode);
16287        } else if (after.versionCode == before.mVersionCode) {
16288            if (after.baseRevisionCode < before.baseRevisionCode) {
16289                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16290                        "Update base revision code " + after.baseRevisionCode
16291                        + " is older than current " + before.baseRevisionCode);
16292            }
16293
16294            if (!ArrayUtils.isEmpty(after.splitNames)) {
16295                for (int i = 0; i < after.splitNames.length; i++) {
16296                    final String splitName = after.splitNames[i];
16297                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16298                    if (j != -1) {
16299                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16300                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16301                                    "Update split " + splitName + " revision code "
16302                                    + after.splitRevisionCodes[i] + " is older than current "
16303                                    + before.splitRevisionCodes[j]);
16304                        }
16305                    }
16306                }
16307            }
16308        }
16309    }
16310
16311    private static class MoveCallbacks extends Handler {
16312        private static final int MSG_CREATED = 1;
16313        private static final int MSG_STATUS_CHANGED = 2;
16314
16315        private final RemoteCallbackList<IPackageMoveObserver>
16316                mCallbacks = new RemoteCallbackList<>();
16317
16318        private final SparseIntArray mLastStatus = new SparseIntArray();
16319
16320        public MoveCallbacks(Looper looper) {
16321            super(looper);
16322        }
16323
16324        public void register(IPackageMoveObserver callback) {
16325            mCallbacks.register(callback);
16326        }
16327
16328        public void unregister(IPackageMoveObserver callback) {
16329            mCallbacks.unregister(callback);
16330        }
16331
16332        @Override
16333        public void handleMessage(Message msg) {
16334            final SomeArgs args = (SomeArgs) msg.obj;
16335            final int n = mCallbacks.beginBroadcast();
16336            for (int i = 0; i < n; i++) {
16337                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16338                try {
16339                    invokeCallback(callback, msg.what, args);
16340                } catch (RemoteException ignored) {
16341                }
16342            }
16343            mCallbacks.finishBroadcast();
16344            args.recycle();
16345        }
16346
16347        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16348                throws RemoteException {
16349            switch (what) {
16350                case MSG_CREATED: {
16351                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16352                    break;
16353                }
16354                case MSG_STATUS_CHANGED: {
16355                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16356                    break;
16357                }
16358            }
16359        }
16360
16361        private void notifyCreated(int moveId, Bundle extras) {
16362            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16363
16364            final SomeArgs args = SomeArgs.obtain();
16365            args.argi1 = moveId;
16366            args.arg2 = extras;
16367            obtainMessage(MSG_CREATED, args).sendToTarget();
16368        }
16369
16370        private void notifyStatusChanged(int moveId, int status) {
16371            notifyStatusChanged(moveId, status, -1);
16372        }
16373
16374        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16375            Slog.v(TAG, "Move " + moveId + " status " + status);
16376
16377            final SomeArgs args = SomeArgs.obtain();
16378            args.argi1 = moveId;
16379            args.argi2 = status;
16380            args.arg3 = estMillis;
16381            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16382
16383            synchronized (mLastStatus) {
16384                mLastStatus.put(moveId, status);
16385            }
16386        }
16387    }
16388
16389    private final class OnPermissionChangeListeners extends Handler {
16390        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16391
16392        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16393                new RemoteCallbackList<>();
16394
16395        public OnPermissionChangeListeners(Looper looper) {
16396            super(looper);
16397        }
16398
16399        @Override
16400        public void handleMessage(Message msg) {
16401            switch (msg.what) {
16402                case MSG_ON_PERMISSIONS_CHANGED: {
16403                    final int uid = msg.arg1;
16404                    handleOnPermissionsChanged(uid);
16405                } break;
16406            }
16407        }
16408
16409        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16410            mPermissionListeners.register(listener);
16411
16412        }
16413
16414        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16415            mPermissionListeners.unregister(listener);
16416        }
16417
16418        public void onPermissionsChanged(int uid) {
16419            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16420                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16421            }
16422        }
16423
16424        private void handleOnPermissionsChanged(int uid) {
16425            final int count = mPermissionListeners.beginBroadcast();
16426            try {
16427                for (int i = 0; i < count; i++) {
16428                    IOnPermissionsChangeListener callback = mPermissionListeners
16429                            .getBroadcastItem(i);
16430                    try {
16431                        callback.onPermissionsChanged(uid);
16432                    } catch (RemoteException e) {
16433                        Log.e(TAG, "Permission listener is dead", e);
16434                    }
16435                }
16436            } finally {
16437                mPermissionListeners.finishBroadcast();
16438            }
16439        }
16440    }
16441
16442    private class PackageManagerInternalImpl extends PackageManagerInternal {
16443        @Override
16444        public void setLocationPackagesProvider(PackagesProvider provider) {
16445            synchronized (mPackages) {
16446                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16447            }
16448        }
16449
16450        @Override
16451        public void setImePackagesProvider(PackagesProvider provider) {
16452            synchronized (mPackages) {
16453                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16454            }
16455        }
16456
16457        @Override
16458        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16459            synchronized (mPackages) {
16460                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16461            }
16462        }
16463
16464        @Override
16465        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16466            synchronized (mPackages) {
16467                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16468            }
16469        }
16470
16471        @Override
16472        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16473            synchronized (mPackages) {
16474                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16475            }
16476        }
16477
16478        @Override
16479        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16480            synchronized (mPackages) {
16481                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16482            }
16483        }
16484
16485        @Override
16486        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16487            synchronized (mPackages) {
16488                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16489                        packageName, userId);
16490            }
16491        }
16492
16493        @Override
16494        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16495            synchronized (mPackages) {
16496                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16497                        packageName, userId);
16498            }
16499        }
16500    }
16501
16502    @Override
16503    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16504        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16505        synchronized (mPackages) {
16506            final long identity = Binder.clearCallingIdentity();
16507            try {
16508                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16509                        packageNames, userId);
16510            } finally {
16511                Binder.restoreCallingIdentity(identity);
16512            }
16513        }
16514    }
16515
16516    private static void enforceSystemOrPhoneCaller(String tag) {
16517        int callingUid = Binder.getCallingUid();
16518        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16519            throw new SecurityException(
16520                    "Cannot call " + tag + " from UID " + callingUid);
16521        }
16522    }
16523}
16524