PackageManagerService.java revision 28762e61e2e45a7e30af02c6fa840a065a645b68
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                    resetUserChangesToRuntimePermissionsAndFlagsLPw(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 these flags and nothing else.
3609        if (getCallingUid() != Process.SYSTEM_UID) {
3610            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3612            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3613            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3614            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3615            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3616        }
3617
3618        synchronized (mPackages) {
3619            final PackageParser.Package pkg = mPackages.get(packageName);
3620            if (pkg == null) {
3621                throw new IllegalArgumentException("Unknown package: " + packageName);
3622            }
3623
3624            final BasePermission bp = mSettings.mPermissions.get(name);
3625            if (bp == null) {
3626                throw new IllegalArgumentException("Unknown permission: " + name);
3627            }
3628
3629            SettingBase sb = (SettingBase) pkg.mExtras;
3630            if (sb == null) {
3631                throw new IllegalArgumentException("Unknown package: " + packageName);
3632            }
3633
3634            PermissionsState permissionsState = sb.getPermissionsState();
3635
3636            // Only the package manager can change flags for system component permissions.
3637            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3638            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3639                return;
3640            }
3641
3642            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3643
3644            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3645                // Install and runtime permissions are stored in different places,
3646                // so figure out what permission changed and persist the change.
3647                if (permissionsState.getInstallPermissionState(name) != null) {
3648                    scheduleWriteSettingsLocked();
3649                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3650                        || hadState) {
3651                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3652                }
3653            }
3654        }
3655    }
3656
3657    /**
3658     * Update the permission flags for all packages and runtime permissions of a user in order
3659     * to allow device or profile owner to remove POLICY_FIXED.
3660     */
3661    @Override
3662    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3663        if (!sUserManager.exists(userId)) {
3664            return;
3665        }
3666
3667        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3668
3669        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3670                "updatePermissionFlagsForAllApps");
3671
3672        // Only the system can change system fixed flags.
3673        if (getCallingUid() != Process.SYSTEM_UID) {
3674            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3675            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3676        }
3677
3678        synchronized (mPackages) {
3679            boolean changed = false;
3680            final int packageCount = mPackages.size();
3681            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3682                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3683                SettingBase sb = (SettingBase) pkg.mExtras;
3684                if (sb == null) {
3685                    continue;
3686                }
3687                PermissionsState permissionsState = sb.getPermissionsState();
3688                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3689                        userId, flagMask, flagValues);
3690            }
3691            if (changed) {
3692                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3693            }
3694        }
3695    }
3696
3697    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3698        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3699                != PackageManager.PERMISSION_GRANTED
3700            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3701                != PackageManager.PERMISSION_GRANTED) {
3702            throw new SecurityException(message + " requires "
3703                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3704                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3705        }
3706    }
3707
3708    @Override
3709    public boolean shouldShowRequestPermissionRationale(String permissionName,
3710            String packageName, int userId) {
3711        if (UserHandle.getCallingUserId() != userId) {
3712            mContext.enforceCallingPermission(
3713                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3714                    "canShowRequestPermissionRationale for user " + userId);
3715        }
3716
3717        final int uid = getPackageUid(packageName, userId);
3718        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3719            return false;
3720        }
3721
3722        if (checkPermission(permissionName, packageName, userId)
3723                == PackageManager.PERMISSION_GRANTED) {
3724            return false;
3725        }
3726
3727        final int flags;
3728
3729        final long identity = Binder.clearCallingIdentity();
3730        try {
3731            flags = getPermissionFlags(permissionName,
3732                    packageName, userId);
3733        } finally {
3734            Binder.restoreCallingIdentity(identity);
3735        }
3736
3737        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3738                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3739                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3740
3741        if ((flags & fixedFlags) != 0) {
3742            return false;
3743        }
3744
3745        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3746    }
3747
3748    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3749        BasePermission bp = mSettings.mPermissions.get(permission);
3750        if (bp == null) {
3751            throw new SecurityException("Missing " + permission + " permission");
3752        }
3753
3754        SettingBase sb = (SettingBase) pkg.mExtras;
3755        PermissionsState permissionsState = sb.getPermissionsState();
3756
3757        if (permissionsState.grantInstallPermission(bp) !=
3758                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3759            scheduleWriteSettingsLocked();
3760        }
3761    }
3762
3763    @Override
3764    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3765        mContext.enforceCallingOrSelfPermission(
3766                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3767                "addOnPermissionsChangeListener");
3768
3769        synchronized (mPackages) {
3770            mOnPermissionChangeListeners.addListenerLocked(listener);
3771        }
3772    }
3773
3774    @Override
3775    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3776        synchronized (mPackages) {
3777            mOnPermissionChangeListeners.removeListenerLocked(listener);
3778        }
3779    }
3780
3781    @Override
3782    public boolean isProtectedBroadcast(String actionName) {
3783        synchronized (mPackages) {
3784            return mProtectedBroadcasts.contains(actionName);
3785        }
3786    }
3787
3788    @Override
3789    public int checkSignatures(String pkg1, String pkg2) {
3790        synchronized (mPackages) {
3791            final PackageParser.Package p1 = mPackages.get(pkg1);
3792            final PackageParser.Package p2 = mPackages.get(pkg2);
3793            if (p1 == null || p1.mExtras == null
3794                    || p2 == null || p2.mExtras == null) {
3795                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3796            }
3797            return compareSignatures(p1.mSignatures, p2.mSignatures);
3798        }
3799    }
3800
3801    @Override
3802    public int checkUidSignatures(int uid1, int uid2) {
3803        // Map to base uids.
3804        uid1 = UserHandle.getAppId(uid1);
3805        uid2 = UserHandle.getAppId(uid2);
3806        // reader
3807        synchronized (mPackages) {
3808            Signature[] s1;
3809            Signature[] s2;
3810            Object obj = mSettings.getUserIdLPr(uid1);
3811            if (obj != null) {
3812                if (obj instanceof SharedUserSetting) {
3813                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3814                } else if (obj instanceof PackageSetting) {
3815                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3816                } else {
3817                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3818                }
3819            } else {
3820                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3821            }
3822            obj = mSettings.getUserIdLPr(uid2);
3823            if (obj != null) {
3824                if (obj instanceof SharedUserSetting) {
3825                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3826                } else if (obj instanceof PackageSetting) {
3827                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3828                } else {
3829                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3830                }
3831            } else {
3832                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3833            }
3834            return compareSignatures(s1, s2);
3835        }
3836    }
3837
3838    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3839        final long identity = Binder.clearCallingIdentity();
3840        try {
3841            if (sb instanceof SharedUserSetting) {
3842                SharedUserSetting sus = (SharedUserSetting) sb;
3843                final int packageCount = sus.packages.size();
3844                for (int i = 0; i < packageCount; i++) {
3845                    PackageSetting susPs = sus.packages.valueAt(i);
3846                    if (userId == UserHandle.USER_ALL) {
3847                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3848                    } else {
3849                        final int uid = UserHandle.getUid(userId, susPs.appId);
3850                        killUid(uid, reason);
3851                    }
3852                }
3853            } else if (sb instanceof PackageSetting) {
3854                PackageSetting ps = (PackageSetting) sb;
3855                if (userId == UserHandle.USER_ALL) {
3856                    killApplication(ps.pkg.packageName, ps.appId, reason);
3857                } else {
3858                    final int uid = UserHandle.getUid(userId, ps.appId);
3859                    killUid(uid, reason);
3860                }
3861            }
3862        } finally {
3863            Binder.restoreCallingIdentity(identity);
3864        }
3865    }
3866
3867    private static void killUid(int uid, String reason) {
3868        IActivityManager am = ActivityManagerNative.getDefault();
3869        if (am != null) {
3870            try {
3871                am.killUid(uid, reason);
3872            } catch (RemoteException e) {
3873                /* ignore - same process */
3874            }
3875        }
3876    }
3877
3878    /**
3879     * Compares two sets of signatures. Returns:
3880     * <br />
3881     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3882     * <br />
3883     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3884     * <br />
3885     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3886     * <br />
3887     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3888     * <br />
3889     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3890     */
3891    static int compareSignatures(Signature[] s1, Signature[] s2) {
3892        if (s1 == null) {
3893            return s2 == null
3894                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3895                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3896        }
3897
3898        if (s2 == null) {
3899            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3900        }
3901
3902        if (s1.length != s2.length) {
3903            return PackageManager.SIGNATURE_NO_MATCH;
3904        }
3905
3906        // Since both signature sets are of size 1, we can compare without HashSets.
3907        if (s1.length == 1) {
3908            return s1[0].equals(s2[0]) ?
3909                    PackageManager.SIGNATURE_MATCH :
3910                    PackageManager.SIGNATURE_NO_MATCH;
3911        }
3912
3913        ArraySet<Signature> set1 = new ArraySet<Signature>();
3914        for (Signature sig : s1) {
3915            set1.add(sig);
3916        }
3917        ArraySet<Signature> set2 = new ArraySet<Signature>();
3918        for (Signature sig : s2) {
3919            set2.add(sig);
3920        }
3921        // Make sure s2 contains all signatures in s1.
3922        if (set1.equals(set2)) {
3923            return PackageManager.SIGNATURE_MATCH;
3924        }
3925        return PackageManager.SIGNATURE_NO_MATCH;
3926    }
3927
3928    /**
3929     * If the database version for this type of package (internal storage or
3930     * external storage) is less than the version where package signatures
3931     * were updated, return true.
3932     */
3933    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3934        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3935        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3936    }
3937
3938    /**
3939     * Used for backward compatibility to make sure any packages with
3940     * certificate chains get upgraded to the new style. {@code existingSigs}
3941     * will be in the old format (since they were stored on disk from before the
3942     * system upgrade) and {@code scannedSigs} will be in the newer format.
3943     */
3944    private int compareSignaturesCompat(PackageSignatures existingSigs,
3945            PackageParser.Package scannedPkg) {
3946        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3947            return PackageManager.SIGNATURE_NO_MATCH;
3948        }
3949
3950        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3951        for (Signature sig : existingSigs.mSignatures) {
3952            existingSet.add(sig);
3953        }
3954        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3955        for (Signature sig : scannedPkg.mSignatures) {
3956            try {
3957                Signature[] chainSignatures = sig.getChainSignatures();
3958                for (Signature chainSig : chainSignatures) {
3959                    scannedCompatSet.add(chainSig);
3960                }
3961            } catch (CertificateEncodingException e) {
3962                scannedCompatSet.add(sig);
3963            }
3964        }
3965        /*
3966         * Make sure the expanded scanned set contains all signatures in the
3967         * existing one.
3968         */
3969        if (scannedCompatSet.equals(existingSet)) {
3970            // Migrate the old signatures to the new scheme.
3971            existingSigs.assignSignatures(scannedPkg.mSignatures);
3972            // The new KeySets will be re-added later in the scanning process.
3973            synchronized (mPackages) {
3974                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3975            }
3976            return PackageManager.SIGNATURE_MATCH;
3977        }
3978        return PackageManager.SIGNATURE_NO_MATCH;
3979    }
3980
3981    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3982        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3983        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3984    }
3985
3986    private int compareSignaturesRecover(PackageSignatures existingSigs,
3987            PackageParser.Package scannedPkg) {
3988        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3989            return PackageManager.SIGNATURE_NO_MATCH;
3990        }
3991
3992        String msg = null;
3993        try {
3994            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3995                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3996                        + scannedPkg.packageName);
3997                return PackageManager.SIGNATURE_MATCH;
3998            }
3999        } catch (CertificateException e) {
4000            msg = e.getMessage();
4001        }
4002
4003        logCriticalInfo(Log.INFO,
4004                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4005        return PackageManager.SIGNATURE_NO_MATCH;
4006    }
4007
4008    @Override
4009    public String[] getPackagesForUid(int uid) {
4010        uid = UserHandle.getAppId(uid);
4011        // reader
4012        synchronized (mPackages) {
4013            Object obj = mSettings.getUserIdLPr(uid);
4014            if (obj instanceof SharedUserSetting) {
4015                final SharedUserSetting sus = (SharedUserSetting) obj;
4016                final int N = sus.packages.size();
4017                final String[] res = new String[N];
4018                final Iterator<PackageSetting> it = sus.packages.iterator();
4019                int i = 0;
4020                while (it.hasNext()) {
4021                    res[i++] = it.next().name;
4022                }
4023                return res;
4024            } else if (obj instanceof PackageSetting) {
4025                final PackageSetting ps = (PackageSetting) obj;
4026                return new String[] { ps.name };
4027            }
4028        }
4029        return null;
4030    }
4031
4032    @Override
4033    public String getNameForUid(int uid) {
4034        // reader
4035        synchronized (mPackages) {
4036            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4037            if (obj instanceof SharedUserSetting) {
4038                final SharedUserSetting sus = (SharedUserSetting) obj;
4039                return sus.name + ":" + sus.userId;
4040            } else if (obj instanceof PackageSetting) {
4041                final PackageSetting ps = (PackageSetting) obj;
4042                return ps.name;
4043            }
4044        }
4045        return null;
4046    }
4047
4048    @Override
4049    public int getUidForSharedUser(String sharedUserName) {
4050        if(sharedUserName == null) {
4051            return -1;
4052        }
4053        // reader
4054        synchronized (mPackages) {
4055            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4056            if (suid == null) {
4057                return -1;
4058            }
4059            return suid.userId;
4060        }
4061    }
4062
4063    @Override
4064    public int getFlagsForUid(int uid) {
4065        synchronized (mPackages) {
4066            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4067            if (obj instanceof SharedUserSetting) {
4068                final SharedUserSetting sus = (SharedUserSetting) obj;
4069                return sus.pkgFlags;
4070            } else if (obj instanceof PackageSetting) {
4071                final PackageSetting ps = (PackageSetting) obj;
4072                return ps.pkgFlags;
4073            }
4074        }
4075        return 0;
4076    }
4077
4078    @Override
4079    public int getPrivateFlagsForUid(int uid) {
4080        synchronized (mPackages) {
4081            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4082            if (obj instanceof SharedUserSetting) {
4083                final SharedUserSetting sus = (SharedUserSetting) obj;
4084                return sus.pkgPrivateFlags;
4085            } else if (obj instanceof PackageSetting) {
4086                final PackageSetting ps = (PackageSetting) obj;
4087                return ps.pkgPrivateFlags;
4088            }
4089        }
4090        return 0;
4091    }
4092
4093    @Override
4094    public boolean isUidPrivileged(int uid) {
4095        uid = UserHandle.getAppId(uid);
4096        // reader
4097        synchronized (mPackages) {
4098            Object obj = mSettings.getUserIdLPr(uid);
4099            if (obj instanceof SharedUserSetting) {
4100                final SharedUserSetting sus = (SharedUserSetting) obj;
4101                final Iterator<PackageSetting> it = sus.packages.iterator();
4102                while (it.hasNext()) {
4103                    if (it.next().isPrivileged()) {
4104                        return true;
4105                    }
4106                }
4107            } else if (obj instanceof PackageSetting) {
4108                final PackageSetting ps = (PackageSetting) obj;
4109                return ps.isPrivileged();
4110            }
4111        }
4112        return false;
4113    }
4114
4115    @Override
4116    public String[] getAppOpPermissionPackages(String permissionName) {
4117        synchronized (mPackages) {
4118            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4119            if (pkgs == null) {
4120                return null;
4121            }
4122            return pkgs.toArray(new String[pkgs.size()]);
4123        }
4124    }
4125
4126    @Override
4127    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4128            int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4131        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4132        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4133    }
4134
4135    @Override
4136    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4137            IntentFilter filter, int match, ComponentName activity) {
4138        final int userId = UserHandle.getCallingUserId();
4139        if (DEBUG_PREFERRED) {
4140            Log.v(TAG, "setLastChosenActivity intent=" + intent
4141                + " resolvedType=" + resolvedType
4142                + " flags=" + flags
4143                + " filter=" + filter
4144                + " match=" + match
4145                + " activity=" + activity);
4146            filter.dump(new PrintStreamPrinter(System.out), "    ");
4147        }
4148        intent.setComponent(null);
4149        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4150        // Find any earlier preferred or last chosen entries and nuke them
4151        findPreferredActivity(intent, resolvedType,
4152                flags, query, 0, false, true, false, userId);
4153        // Add the new activity as the last chosen for this filter
4154        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4155                "Setting last chosen");
4156    }
4157
4158    @Override
4159    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4160        final int userId = UserHandle.getCallingUserId();
4161        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4162        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4163        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4164                false, false, false, userId);
4165    }
4166
4167    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4168            int flags, List<ResolveInfo> query, int userId) {
4169        if (query != null) {
4170            final int N = query.size();
4171            if (N == 1) {
4172                return query.get(0);
4173            } else if (N > 1) {
4174                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4175                // If there is more than one activity with the same priority,
4176                // then let the user decide between them.
4177                ResolveInfo r0 = query.get(0);
4178                ResolveInfo r1 = query.get(1);
4179                if (DEBUG_INTENT_MATCHING || debug) {
4180                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4181                            + r1.activityInfo.name + "=" + r1.priority);
4182                }
4183                // If the first activity has a higher priority, or a different
4184                // default, then it is always desireable to pick it.
4185                if (r0.priority != r1.priority
4186                        || r0.preferredOrder != r1.preferredOrder
4187                        || r0.isDefault != r1.isDefault) {
4188                    return query.get(0);
4189                }
4190                // If we have saved a preference for a preferred activity for
4191                // this Intent, use that.
4192                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4193                        flags, query, r0.priority, true, false, debug, userId);
4194                if (ri != null) {
4195                    return ri;
4196                }
4197                if (userId != 0) {
4198                    ri = new ResolveInfo(mResolveInfo);
4199                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4200                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4201                            ri.activityInfo.applicationInfo);
4202                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4203                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4204                    return ri;
4205                }
4206                return mResolveInfo;
4207            }
4208        }
4209        return null;
4210    }
4211
4212    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4213            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4214        final int N = query.size();
4215        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4216                .get(userId);
4217        // Get the list of persistent preferred activities that handle the intent
4218        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4219        List<PersistentPreferredActivity> pprefs = ppir != null
4220                ? ppir.queryIntent(intent, resolvedType,
4221                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4222                : null;
4223        if (pprefs != null && pprefs.size() > 0) {
4224            final int M = pprefs.size();
4225            for (int i=0; i<M; i++) {
4226                final PersistentPreferredActivity ppa = pprefs.get(i);
4227                if (DEBUG_PREFERRED || debug) {
4228                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4229                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4230                            + "\n  component=" + ppa.mComponent);
4231                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4232                }
4233                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4234                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4235                if (DEBUG_PREFERRED || debug) {
4236                    Slog.v(TAG, "Found persistent preferred activity:");
4237                    if (ai != null) {
4238                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4239                    } else {
4240                        Slog.v(TAG, "  null");
4241                    }
4242                }
4243                if (ai == null) {
4244                    // This previously registered persistent preferred activity
4245                    // component is no longer known. Ignore it and do NOT remove it.
4246                    continue;
4247                }
4248                for (int j=0; j<N; j++) {
4249                    final ResolveInfo ri = query.get(j);
4250                    if (!ri.activityInfo.applicationInfo.packageName
4251                            .equals(ai.applicationInfo.packageName)) {
4252                        continue;
4253                    }
4254                    if (!ri.activityInfo.name.equals(ai.name)) {
4255                        continue;
4256                    }
4257                    //  Found a persistent preference that can handle the intent.
4258                    if (DEBUG_PREFERRED || debug) {
4259                        Slog.v(TAG, "Returning persistent preferred activity: " +
4260                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4261                    }
4262                    return ri;
4263                }
4264            }
4265        }
4266        return null;
4267    }
4268
4269    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4270            List<ResolveInfo> query, int priority, boolean always,
4271            boolean removeMatches, boolean debug, int userId) {
4272        if (!sUserManager.exists(userId)) return null;
4273        // writer
4274        synchronized (mPackages) {
4275            if (intent.getSelector() != null) {
4276                intent = intent.getSelector();
4277            }
4278            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4279
4280            // Try to find a matching persistent preferred activity.
4281            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4282                    debug, userId);
4283
4284            // If a persistent preferred activity matched, use it.
4285            if (pri != null) {
4286                return pri;
4287            }
4288
4289            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4290            // Get the list of preferred activities that handle the intent
4291            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4292            List<PreferredActivity> prefs = pir != null
4293                    ? pir.queryIntent(intent, resolvedType,
4294                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4295                    : null;
4296            if (prefs != null && prefs.size() > 0) {
4297                boolean changed = false;
4298                try {
4299                    // First figure out how good the original match set is.
4300                    // We will only allow preferred activities that came
4301                    // from the same match quality.
4302                    int match = 0;
4303
4304                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4305
4306                    final int N = query.size();
4307                    for (int j=0; j<N; j++) {
4308                        final ResolveInfo ri = query.get(j);
4309                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4310                                + ": 0x" + Integer.toHexString(match));
4311                        if (ri.match > match) {
4312                            match = ri.match;
4313                        }
4314                    }
4315
4316                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4317                            + Integer.toHexString(match));
4318
4319                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4320                    final int M = prefs.size();
4321                    for (int i=0; i<M; i++) {
4322                        final PreferredActivity pa = prefs.get(i);
4323                        if (DEBUG_PREFERRED || debug) {
4324                            Slog.v(TAG, "Checking PreferredActivity ds="
4325                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4326                                    + "\n  component=" + pa.mPref.mComponent);
4327                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4328                        }
4329                        if (pa.mPref.mMatch != match) {
4330                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4331                                    + Integer.toHexString(pa.mPref.mMatch));
4332                            continue;
4333                        }
4334                        // If it's not an "always" type preferred activity and that's what we're
4335                        // looking for, skip it.
4336                        if (always && !pa.mPref.mAlways) {
4337                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4338                            continue;
4339                        }
4340                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4341                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4342                        if (DEBUG_PREFERRED || debug) {
4343                            Slog.v(TAG, "Found preferred activity:");
4344                            if (ai != null) {
4345                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4346                            } else {
4347                                Slog.v(TAG, "  null");
4348                            }
4349                        }
4350                        if (ai == null) {
4351                            // This previously registered preferred activity
4352                            // component is no longer known.  Most likely an update
4353                            // to the app was installed and in the new version this
4354                            // component no longer exists.  Clean it up by removing
4355                            // it from the preferred activities list, and skip it.
4356                            Slog.w(TAG, "Removing dangling preferred activity: "
4357                                    + pa.mPref.mComponent);
4358                            pir.removeFilter(pa);
4359                            changed = true;
4360                            continue;
4361                        }
4362                        for (int j=0; j<N; j++) {
4363                            final ResolveInfo ri = query.get(j);
4364                            if (!ri.activityInfo.applicationInfo.packageName
4365                                    .equals(ai.applicationInfo.packageName)) {
4366                                continue;
4367                            }
4368                            if (!ri.activityInfo.name.equals(ai.name)) {
4369                                continue;
4370                            }
4371
4372                            if (removeMatches) {
4373                                pir.removeFilter(pa);
4374                                changed = true;
4375                                if (DEBUG_PREFERRED) {
4376                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4377                                }
4378                                break;
4379                            }
4380
4381                            // Okay we found a previously set preferred or last chosen app.
4382                            // If the result set is different from when this
4383                            // was created, we need to clear it and re-ask the
4384                            // user their preference, if we're looking for an "always" type entry.
4385                            if (always && !pa.mPref.sameSet(query)) {
4386                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4387                                        + intent + " type " + resolvedType);
4388                                if (DEBUG_PREFERRED) {
4389                                    Slog.v(TAG, "Removing preferred activity since set changed "
4390                                            + pa.mPref.mComponent);
4391                                }
4392                                pir.removeFilter(pa);
4393                                // Re-add the filter as a "last chosen" entry (!always)
4394                                PreferredActivity lastChosen = new PreferredActivity(
4395                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4396                                pir.addFilter(lastChosen);
4397                                changed = true;
4398                                return null;
4399                            }
4400
4401                            // Yay! Either the set matched or we're looking for the last chosen
4402                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4403                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4404                            return ri;
4405                        }
4406                    }
4407                } finally {
4408                    if (changed) {
4409                        if (DEBUG_PREFERRED) {
4410                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4411                        }
4412                        scheduleWritePackageRestrictionsLocked(userId);
4413                    }
4414                }
4415            }
4416        }
4417        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4418        return null;
4419    }
4420
4421    /*
4422     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4423     */
4424    @Override
4425    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4426            int targetUserId) {
4427        mContext.enforceCallingOrSelfPermission(
4428                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4429        List<CrossProfileIntentFilter> matches =
4430                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4431        if (matches != null) {
4432            int size = matches.size();
4433            for (int i = 0; i < size; i++) {
4434                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4435            }
4436        }
4437        if (hasWebURI(intent)) {
4438            // cross-profile app linking works only towards the parent.
4439            final UserInfo parent = getProfileParent(sourceUserId);
4440            synchronized(mPackages) {
4441                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4442                        intent, resolvedType, 0, sourceUserId, parent.id);
4443                return xpDomainInfo != null;
4444            }
4445        }
4446        return false;
4447    }
4448
4449    private UserInfo getProfileParent(int userId) {
4450        final long identity = Binder.clearCallingIdentity();
4451        try {
4452            return sUserManager.getProfileParent(userId);
4453        } finally {
4454            Binder.restoreCallingIdentity(identity);
4455        }
4456    }
4457
4458    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4459            String resolvedType, int userId) {
4460        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4461        if (resolver != null) {
4462            return resolver.queryIntent(intent, resolvedType, false, userId);
4463        }
4464        return null;
4465    }
4466
4467    @Override
4468    public List<ResolveInfo> queryIntentActivities(Intent intent,
4469            String resolvedType, int flags, int userId) {
4470        if (!sUserManager.exists(userId)) return Collections.emptyList();
4471        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4472        ComponentName comp = intent.getComponent();
4473        if (comp == null) {
4474            if (intent.getSelector() != null) {
4475                intent = intent.getSelector();
4476                comp = intent.getComponent();
4477            }
4478        }
4479
4480        if (comp != null) {
4481            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4482            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4483            if (ai != null) {
4484                final ResolveInfo ri = new ResolveInfo();
4485                ri.activityInfo = ai;
4486                list.add(ri);
4487            }
4488            return list;
4489        }
4490
4491        // reader
4492        synchronized (mPackages) {
4493            final String pkgName = intent.getPackage();
4494            if (pkgName == null) {
4495                List<CrossProfileIntentFilter> matchingFilters =
4496                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4497                // Check for results that need to skip the current profile.
4498                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4499                        resolvedType, flags, userId);
4500                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4501                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4502                    result.add(xpResolveInfo);
4503                    return filterIfNotPrimaryUser(result, userId);
4504                }
4505
4506                // Check for results in the current profile.
4507                List<ResolveInfo> result = mActivities.queryIntent(
4508                        intent, resolvedType, flags, userId);
4509
4510                // Check for cross profile results.
4511                xpResolveInfo = queryCrossProfileIntents(
4512                        matchingFilters, intent, resolvedType, flags, userId);
4513                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4514                    result.add(xpResolveInfo);
4515                    Collections.sort(result, mResolvePrioritySorter);
4516                }
4517                result = filterIfNotPrimaryUser(result, userId);
4518                if (hasWebURI(intent)) {
4519                    CrossProfileDomainInfo xpDomainInfo = null;
4520                    final UserInfo parent = getProfileParent(userId);
4521                    if (parent != null) {
4522                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4523                                flags, userId, parent.id);
4524                    }
4525                    if (xpDomainInfo != null) {
4526                        if (xpResolveInfo != null) {
4527                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4528                            // in the result.
4529                            result.remove(xpResolveInfo);
4530                        }
4531                        if (result.size() == 0) {
4532                            result.add(xpDomainInfo.resolveInfo);
4533                            return result;
4534                        }
4535                    } else if (result.size() <= 1) {
4536                        return result;
4537                    }
4538                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4539                            xpDomainInfo, userId);
4540                    Collections.sort(result, mResolvePrioritySorter);
4541                }
4542                return result;
4543            }
4544            final PackageParser.Package pkg = mPackages.get(pkgName);
4545            if (pkg != null) {
4546                return filterIfNotPrimaryUser(
4547                        mActivities.queryIntentForPackage(
4548                                intent, resolvedType, flags, pkg.activities, userId),
4549                        userId);
4550            }
4551            return new ArrayList<ResolveInfo>();
4552        }
4553    }
4554
4555    private static class CrossProfileDomainInfo {
4556        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4557        ResolveInfo resolveInfo;
4558        /* Best domain verification status of the activities found in the other profile */
4559        int bestDomainVerificationStatus;
4560    }
4561
4562    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4563            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4564        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4565                sourceUserId)) {
4566            return null;
4567        }
4568        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4569                resolvedType, flags, parentUserId);
4570
4571        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4572            return null;
4573        }
4574        CrossProfileDomainInfo result = null;
4575        int size = resultTargetUser.size();
4576        for (int i = 0; i < size; i++) {
4577            ResolveInfo riTargetUser = resultTargetUser.get(i);
4578            // Intent filter verification is only for filters that specify a host. So don't return
4579            // those that handle all web uris.
4580            if (riTargetUser.handleAllWebDataURI) {
4581                continue;
4582            }
4583            String packageName = riTargetUser.activityInfo.packageName;
4584            PackageSetting ps = mSettings.mPackages.get(packageName);
4585            if (ps == null) {
4586                continue;
4587            }
4588            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4589            int status = (int)(verificationState >> 32);
4590            if (result == null) {
4591                result = new CrossProfileDomainInfo();
4592                result.resolveInfo =
4593                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4594                result.bestDomainVerificationStatus = status;
4595            } else {
4596                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4597                        result.bestDomainVerificationStatus);
4598            }
4599        }
4600        // Don't consider matches with status NEVER across profiles.
4601        if (result != null && result.bestDomainVerificationStatus
4602                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4603            return null;
4604        }
4605        return result;
4606    }
4607
4608    /**
4609     * Verification statuses are ordered from the worse to the best, except for
4610     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4611     */
4612    private int bestDomainVerificationStatus(int status1, int status2) {
4613        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4614            return status2;
4615        }
4616        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4617            return status1;
4618        }
4619        return (int) MathUtils.max(status1, status2);
4620    }
4621
4622    private boolean isUserEnabled(int userId) {
4623        long callingId = Binder.clearCallingIdentity();
4624        try {
4625            UserInfo userInfo = sUserManager.getUserInfo(userId);
4626            return userInfo != null && userInfo.isEnabled();
4627        } finally {
4628            Binder.restoreCallingIdentity(callingId);
4629        }
4630    }
4631
4632    /**
4633     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4634     *
4635     * @return filtered list
4636     */
4637    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4638        if (userId == UserHandle.USER_OWNER) {
4639            return resolveInfos;
4640        }
4641        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4642            ResolveInfo info = resolveInfos.get(i);
4643            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4644                resolveInfos.remove(i);
4645            }
4646        }
4647        return resolveInfos;
4648    }
4649
4650    private static boolean hasWebURI(Intent intent) {
4651        if (intent.getData() == null) {
4652            return false;
4653        }
4654        final String scheme = intent.getScheme();
4655        if (TextUtils.isEmpty(scheme)) {
4656            return false;
4657        }
4658        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4659    }
4660
4661    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4662            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4663            int userId) {
4664        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4665
4666        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4667            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4668                    candidates.size());
4669        }
4670
4671        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4672        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4673        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4674        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4675        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4676
4677        synchronized (mPackages) {
4678            final int count = candidates.size();
4679            // First, try to use linked apps. Partition the candidates into four lists:
4680            // one for the final results, one for the "do not use ever", one for "undefined status"
4681            // and finally one for "browser app type".
4682            for (int n=0; n<count; n++) {
4683                ResolveInfo info = candidates.get(n);
4684                String packageName = info.activityInfo.packageName;
4685                PackageSetting ps = mSettings.mPackages.get(packageName);
4686                if (ps != null) {
4687                    // Add to the special match all list (Browser use case)
4688                    if (info.handleAllWebDataURI) {
4689                        matchAllList.add(info);
4690                        continue;
4691                    }
4692                    // Try to get the status from User settings first
4693                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4694                    int status = (int)(packedStatus >> 32);
4695                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4696                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4697                        if (DEBUG_DOMAIN_VERIFICATION) {
4698                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4699                                    + " : linkgen=" + linkGeneration);
4700                        }
4701                        // Use link-enabled generation as preferredOrder, i.e.
4702                        // prefer newly-enabled over earlier-enabled.
4703                        info.preferredOrder = linkGeneration;
4704                        alwaysList.add(info);
4705                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4706                        if (DEBUG_DOMAIN_VERIFICATION) {
4707                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4708                        }
4709                        neverList.add(info);
4710                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4711                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4712                        if (DEBUG_DOMAIN_VERIFICATION) {
4713                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4714                        }
4715                        undefinedList.add(info);
4716                    }
4717                }
4718            }
4719            // First try to add the "always" resolution(s) for the current user, if any
4720            if (alwaysList.size() > 0) {
4721                result.addAll(alwaysList);
4722            // if there is an "always" for the parent user, add it.
4723            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4724                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4725                result.add(xpDomainInfo.resolveInfo);
4726            } else {
4727                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4728                result.addAll(undefinedList);
4729                if (xpDomainInfo != null && (
4730                        xpDomainInfo.bestDomainVerificationStatus
4731                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4732                        || xpDomainInfo.bestDomainVerificationStatus
4733                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4734                    result.add(xpDomainInfo.resolveInfo);
4735                }
4736                // Also add Browsers (all of them or only the default one)
4737                if ((matchFlags & MATCH_ALL) != 0) {
4738                    result.addAll(matchAllList);
4739                } else {
4740                    // Browser/generic handling case.  If there's a default browser, go straight
4741                    // to that (but only if there is no other higher-priority match).
4742                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4743                    int maxMatchPrio = 0;
4744                    ResolveInfo defaultBrowserMatch = null;
4745                    final int numCandidates = matchAllList.size();
4746                    for (int n = 0; n < numCandidates; n++) {
4747                        ResolveInfo info = matchAllList.get(n);
4748                        // track the highest overall match priority...
4749                        if (info.priority > maxMatchPrio) {
4750                            maxMatchPrio = info.priority;
4751                        }
4752                        // ...and the highest-priority default browser match
4753                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4754                            if (defaultBrowserMatch == null
4755                                    || (defaultBrowserMatch.priority < info.priority)) {
4756                                if (debug) {
4757                                    Slog.v(TAG, "Considering default browser match " + info);
4758                                }
4759                                defaultBrowserMatch = info;
4760                            }
4761                        }
4762                    }
4763                    if (defaultBrowserMatch != null
4764                            && defaultBrowserMatch.priority >= maxMatchPrio
4765                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4766                    {
4767                        if (debug) {
4768                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4769                        }
4770                        result.add(defaultBrowserMatch);
4771                    } else {
4772                        result.addAll(matchAllList);
4773                    }
4774                }
4775
4776                // If there is nothing selected, add all candidates and remove the ones that the user
4777                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4778                if (result.size() == 0) {
4779                    result.addAll(candidates);
4780                    result.removeAll(neverList);
4781                }
4782            }
4783        }
4784        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4785            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4786                    result.size());
4787            for (ResolveInfo info : result) {
4788                Slog.v(TAG, "  + " + info.activityInfo);
4789            }
4790        }
4791        return result;
4792    }
4793
4794    // Returns a packed value as a long:
4795    //
4796    // high 'int'-sized word: link status: undefined/ask/never/always.
4797    // low 'int'-sized word: relative priority among 'always' results.
4798    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4799        long result = ps.getDomainVerificationStatusForUser(userId);
4800        // if none available, get the master status
4801        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4802            if (ps.getIntentFilterVerificationInfo() != null) {
4803                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4804            }
4805        }
4806        return result;
4807    }
4808
4809    private ResolveInfo querySkipCurrentProfileIntents(
4810            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4811            int flags, int sourceUserId) {
4812        if (matchingFilters != null) {
4813            int size = matchingFilters.size();
4814            for (int i = 0; i < size; i ++) {
4815                CrossProfileIntentFilter filter = matchingFilters.get(i);
4816                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4817                    // Checking if there are activities in the target user that can handle the
4818                    // intent.
4819                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4820                            flags, sourceUserId);
4821                    if (resolveInfo != null) {
4822                        return resolveInfo;
4823                    }
4824                }
4825            }
4826        }
4827        return null;
4828    }
4829
4830    // Return matching ResolveInfo if any for skip current profile intent filters.
4831    private ResolveInfo queryCrossProfileIntents(
4832            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4833            int flags, int sourceUserId) {
4834        if (matchingFilters != null) {
4835            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4836            // match the same intent. For performance reasons, it is better not to
4837            // run queryIntent twice for the same userId
4838            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4839            int size = matchingFilters.size();
4840            for (int i = 0; i < size; i++) {
4841                CrossProfileIntentFilter filter = matchingFilters.get(i);
4842                int targetUserId = filter.getTargetUserId();
4843                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4844                        && !alreadyTriedUserIds.get(targetUserId)) {
4845                    // Checking if there are activities in the target user that can handle the
4846                    // intent.
4847                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4848                            flags, sourceUserId);
4849                    if (resolveInfo != null) return resolveInfo;
4850                    alreadyTriedUserIds.put(targetUserId, true);
4851                }
4852            }
4853        }
4854        return null;
4855    }
4856
4857    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4858            String resolvedType, int flags, int sourceUserId) {
4859        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4860                resolvedType, flags, filter.getTargetUserId());
4861        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4862            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4863        }
4864        return null;
4865    }
4866
4867    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4868            int sourceUserId, int targetUserId) {
4869        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4870        String className;
4871        if (targetUserId == UserHandle.USER_OWNER) {
4872            className = FORWARD_INTENT_TO_USER_OWNER;
4873        } else {
4874            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4875        }
4876        ComponentName forwardingActivityComponentName = new ComponentName(
4877                mAndroidApplication.packageName, className);
4878        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4879                sourceUserId);
4880        if (targetUserId == UserHandle.USER_OWNER) {
4881            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4882            forwardingResolveInfo.noResourceId = true;
4883        }
4884        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4885        forwardingResolveInfo.priority = 0;
4886        forwardingResolveInfo.preferredOrder = 0;
4887        forwardingResolveInfo.match = 0;
4888        forwardingResolveInfo.isDefault = true;
4889        forwardingResolveInfo.filter = filter;
4890        forwardingResolveInfo.targetUserId = targetUserId;
4891        return forwardingResolveInfo;
4892    }
4893
4894    @Override
4895    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4896            Intent[] specifics, String[] specificTypes, Intent intent,
4897            String resolvedType, int flags, int userId) {
4898        if (!sUserManager.exists(userId)) return Collections.emptyList();
4899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4900                false, "query intent activity options");
4901        final String resultsAction = intent.getAction();
4902
4903        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4904                | PackageManager.GET_RESOLVED_FILTER, userId);
4905
4906        if (DEBUG_INTENT_MATCHING) {
4907            Log.v(TAG, "Query " + intent + ": " + results);
4908        }
4909
4910        int specificsPos = 0;
4911        int N;
4912
4913        // todo: note that the algorithm used here is O(N^2).  This
4914        // isn't a problem in our current environment, but if we start running
4915        // into situations where we have more than 5 or 10 matches then this
4916        // should probably be changed to something smarter...
4917
4918        // First we go through and resolve each of the specific items
4919        // that were supplied, taking care of removing any corresponding
4920        // duplicate items in the generic resolve list.
4921        if (specifics != null) {
4922            for (int i=0; i<specifics.length; i++) {
4923                final Intent sintent = specifics[i];
4924                if (sintent == null) {
4925                    continue;
4926                }
4927
4928                if (DEBUG_INTENT_MATCHING) {
4929                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4930                }
4931
4932                String action = sintent.getAction();
4933                if (resultsAction != null && resultsAction.equals(action)) {
4934                    // If this action was explicitly requested, then don't
4935                    // remove things that have it.
4936                    action = null;
4937                }
4938
4939                ResolveInfo ri = null;
4940                ActivityInfo ai = null;
4941
4942                ComponentName comp = sintent.getComponent();
4943                if (comp == null) {
4944                    ri = resolveIntent(
4945                        sintent,
4946                        specificTypes != null ? specificTypes[i] : null,
4947                            flags, userId);
4948                    if (ri == null) {
4949                        continue;
4950                    }
4951                    if (ri == mResolveInfo) {
4952                        // ACK!  Must do something better with this.
4953                    }
4954                    ai = ri.activityInfo;
4955                    comp = new ComponentName(ai.applicationInfo.packageName,
4956                            ai.name);
4957                } else {
4958                    ai = getActivityInfo(comp, flags, userId);
4959                    if (ai == null) {
4960                        continue;
4961                    }
4962                }
4963
4964                // Look for any generic query activities that are duplicates
4965                // of this specific one, and remove them from the results.
4966                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4967                N = results.size();
4968                int j;
4969                for (j=specificsPos; j<N; j++) {
4970                    ResolveInfo sri = results.get(j);
4971                    if ((sri.activityInfo.name.equals(comp.getClassName())
4972                            && sri.activityInfo.applicationInfo.packageName.equals(
4973                                    comp.getPackageName()))
4974                        || (action != null && sri.filter.matchAction(action))) {
4975                        results.remove(j);
4976                        if (DEBUG_INTENT_MATCHING) Log.v(
4977                            TAG, "Removing duplicate item from " + j
4978                            + " due to specific " + specificsPos);
4979                        if (ri == null) {
4980                            ri = sri;
4981                        }
4982                        j--;
4983                        N--;
4984                    }
4985                }
4986
4987                // Add this specific item to its proper place.
4988                if (ri == null) {
4989                    ri = new ResolveInfo();
4990                    ri.activityInfo = ai;
4991                }
4992                results.add(specificsPos, ri);
4993                ri.specificIndex = i;
4994                specificsPos++;
4995            }
4996        }
4997
4998        // Now we go through the remaining generic results and remove any
4999        // duplicate actions that are found here.
5000        N = results.size();
5001        for (int i=specificsPos; i<N-1; i++) {
5002            final ResolveInfo rii = results.get(i);
5003            if (rii.filter == null) {
5004                continue;
5005            }
5006
5007            // Iterate over all of the actions of this result's intent
5008            // filter...  typically this should be just one.
5009            final Iterator<String> it = rii.filter.actionsIterator();
5010            if (it == null) {
5011                continue;
5012            }
5013            while (it.hasNext()) {
5014                final String action = it.next();
5015                if (resultsAction != null && resultsAction.equals(action)) {
5016                    // If this action was explicitly requested, then don't
5017                    // remove things that have it.
5018                    continue;
5019                }
5020                for (int j=i+1; j<N; j++) {
5021                    final ResolveInfo rij = results.get(j);
5022                    if (rij.filter != null && rij.filter.hasAction(action)) {
5023                        results.remove(j);
5024                        if (DEBUG_INTENT_MATCHING) Log.v(
5025                            TAG, "Removing duplicate item from " + j
5026                            + " due to action " + action + " at " + i);
5027                        j--;
5028                        N--;
5029                    }
5030                }
5031            }
5032
5033            // If the caller didn't request filter information, drop it now
5034            // so we don't have to marshall/unmarshall it.
5035            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5036                rii.filter = null;
5037            }
5038        }
5039
5040        // Filter out the caller activity if so requested.
5041        if (caller != null) {
5042            N = results.size();
5043            for (int i=0; i<N; i++) {
5044                ActivityInfo ainfo = results.get(i).activityInfo;
5045                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5046                        && caller.getClassName().equals(ainfo.name)) {
5047                    results.remove(i);
5048                    break;
5049                }
5050            }
5051        }
5052
5053        // If the caller didn't request filter information,
5054        // drop them now so we don't have to
5055        // marshall/unmarshall it.
5056        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5057            N = results.size();
5058            for (int i=0; i<N; i++) {
5059                results.get(i).filter = null;
5060            }
5061        }
5062
5063        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5064        return results;
5065    }
5066
5067    @Override
5068    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5069            int userId) {
5070        if (!sUserManager.exists(userId)) return Collections.emptyList();
5071        ComponentName comp = intent.getComponent();
5072        if (comp == null) {
5073            if (intent.getSelector() != null) {
5074                intent = intent.getSelector();
5075                comp = intent.getComponent();
5076            }
5077        }
5078        if (comp != null) {
5079            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5080            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5081            if (ai != null) {
5082                ResolveInfo ri = new ResolveInfo();
5083                ri.activityInfo = ai;
5084                list.add(ri);
5085            }
5086            return list;
5087        }
5088
5089        // reader
5090        synchronized (mPackages) {
5091            String pkgName = intent.getPackage();
5092            if (pkgName == null) {
5093                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5094            }
5095            final PackageParser.Package pkg = mPackages.get(pkgName);
5096            if (pkg != null) {
5097                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5098                        userId);
5099            }
5100            return null;
5101        }
5102    }
5103
5104    @Override
5105    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5106        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5107        if (!sUserManager.exists(userId)) return null;
5108        if (query != null) {
5109            if (query.size() >= 1) {
5110                // If there is more than one service with the same priority,
5111                // just arbitrarily pick the first one.
5112                return query.get(0);
5113            }
5114        }
5115        return null;
5116    }
5117
5118    @Override
5119    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5120            int userId) {
5121        if (!sUserManager.exists(userId)) return Collections.emptyList();
5122        ComponentName comp = intent.getComponent();
5123        if (comp == null) {
5124            if (intent.getSelector() != null) {
5125                intent = intent.getSelector();
5126                comp = intent.getComponent();
5127            }
5128        }
5129        if (comp != null) {
5130            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5131            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5132            if (si != null) {
5133                final ResolveInfo ri = new ResolveInfo();
5134                ri.serviceInfo = si;
5135                list.add(ri);
5136            }
5137            return list;
5138        }
5139
5140        // reader
5141        synchronized (mPackages) {
5142            String pkgName = intent.getPackage();
5143            if (pkgName == null) {
5144                return mServices.queryIntent(intent, resolvedType, flags, userId);
5145            }
5146            final PackageParser.Package pkg = mPackages.get(pkgName);
5147            if (pkg != null) {
5148                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5149                        userId);
5150            }
5151            return null;
5152        }
5153    }
5154
5155    @Override
5156    public List<ResolveInfo> queryIntentContentProviders(
5157            Intent intent, String resolvedType, int flags, int userId) {
5158        if (!sUserManager.exists(userId)) return Collections.emptyList();
5159        ComponentName comp = intent.getComponent();
5160        if (comp == null) {
5161            if (intent.getSelector() != null) {
5162                intent = intent.getSelector();
5163                comp = intent.getComponent();
5164            }
5165        }
5166        if (comp != null) {
5167            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5168            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5169            if (pi != null) {
5170                final ResolveInfo ri = new ResolveInfo();
5171                ri.providerInfo = pi;
5172                list.add(ri);
5173            }
5174            return list;
5175        }
5176
5177        // reader
5178        synchronized (mPackages) {
5179            String pkgName = intent.getPackage();
5180            if (pkgName == null) {
5181                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5182            }
5183            final PackageParser.Package pkg = mPackages.get(pkgName);
5184            if (pkg != null) {
5185                return mProviders.queryIntentForPackage(
5186                        intent, resolvedType, flags, pkg.providers, userId);
5187            }
5188            return null;
5189        }
5190    }
5191
5192    @Override
5193    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5194        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5195
5196        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5197
5198        // writer
5199        synchronized (mPackages) {
5200            ArrayList<PackageInfo> list;
5201            if (listUninstalled) {
5202                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5203                for (PackageSetting ps : mSettings.mPackages.values()) {
5204                    PackageInfo pi;
5205                    if (ps.pkg != null) {
5206                        pi = generatePackageInfo(ps.pkg, flags, userId);
5207                    } else {
5208                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5209                    }
5210                    if (pi != null) {
5211                        list.add(pi);
5212                    }
5213                }
5214            } else {
5215                list = new ArrayList<PackageInfo>(mPackages.size());
5216                for (PackageParser.Package p : mPackages.values()) {
5217                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5218                    if (pi != null) {
5219                        list.add(pi);
5220                    }
5221                }
5222            }
5223
5224            return new ParceledListSlice<PackageInfo>(list);
5225        }
5226    }
5227
5228    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5229            String[] permissions, boolean[] tmp, int flags, int userId) {
5230        int numMatch = 0;
5231        final PermissionsState permissionsState = ps.getPermissionsState();
5232        for (int i=0; i<permissions.length; i++) {
5233            final String permission = permissions[i];
5234            if (permissionsState.hasPermission(permission, userId)) {
5235                tmp[i] = true;
5236                numMatch++;
5237            } else {
5238                tmp[i] = false;
5239            }
5240        }
5241        if (numMatch == 0) {
5242            return;
5243        }
5244        PackageInfo pi;
5245        if (ps.pkg != null) {
5246            pi = generatePackageInfo(ps.pkg, flags, userId);
5247        } else {
5248            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5249        }
5250        // The above might return null in cases of uninstalled apps or install-state
5251        // skew across users/profiles.
5252        if (pi != null) {
5253            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5254                if (numMatch == permissions.length) {
5255                    pi.requestedPermissions = permissions;
5256                } else {
5257                    pi.requestedPermissions = new String[numMatch];
5258                    numMatch = 0;
5259                    for (int i=0; i<permissions.length; i++) {
5260                        if (tmp[i]) {
5261                            pi.requestedPermissions[numMatch] = permissions[i];
5262                            numMatch++;
5263                        }
5264                    }
5265                }
5266            }
5267            list.add(pi);
5268        }
5269    }
5270
5271    @Override
5272    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5273            String[] permissions, int flags, int userId) {
5274        if (!sUserManager.exists(userId)) return null;
5275        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5276
5277        // writer
5278        synchronized (mPackages) {
5279            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5280            boolean[] tmpBools = new boolean[permissions.length];
5281            if (listUninstalled) {
5282                for (PackageSetting ps : mSettings.mPackages.values()) {
5283                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5284                }
5285            } else {
5286                for (PackageParser.Package pkg : mPackages.values()) {
5287                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5288                    if (ps != null) {
5289                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5290                                userId);
5291                    }
5292                }
5293            }
5294
5295            return new ParceledListSlice<PackageInfo>(list);
5296        }
5297    }
5298
5299    @Override
5300    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5301        if (!sUserManager.exists(userId)) return null;
5302        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5303
5304        // writer
5305        synchronized (mPackages) {
5306            ArrayList<ApplicationInfo> list;
5307            if (listUninstalled) {
5308                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5309                for (PackageSetting ps : mSettings.mPackages.values()) {
5310                    ApplicationInfo ai;
5311                    if (ps.pkg != null) {
5312                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5313                                ps.readUserState(userId), userId);
5314                    } else {
5315                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5316                    }
5317                    if (ai != null) {
5318                        list.add(ai);
5319                    }
5320                }
5321            } else {
5322                list = new ArrayList<ApplicationInfo>(mPackages.size());
5323                for (PackageParser.Package p : mPackages.values()) {
5324                    if (p.mExtras != null) {
5325                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5326                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5327                        if (ai != null) {
5328                            list.add(ai);
5329                        }
5330                    }
5331                }
5332            }
5333
5334            return new ParceledListSlice<ApplicationInfo>(list);
5335        }
5336    }
5337
5338    public List<ApplicationInfo> getPersistentApplications(int flags) {
5339        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5340
5341        // reader
5342        synchronized (mPackages) {
5343            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5344            final int userId = UserHandle.getCallingUserId();
5345            while (i.hasNext()) {
5346                final PackageParser.Package p = i.next();
5347                if (p.applicationInfo != null
5348                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5349                        && (!mSafeMode || isSystemApp(p))) {
5350                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5351                    if (ps != null) {
5352                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5353                                ps.readUserState(userId), userId);
5354                        if (ai != null) {
5355                            finalList.add(ai);
5356                        }
5357                    }
5358                }
5359            }
5360        }
5361
5362        return finalList;
5363    }
5364
5365    @Override
5366    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5367        if (!sUserManager.exists(userId)) return null;
5368        // reader
5369        synchronized (mPackages) {
5370            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5371            PackageSetting ps = provider != null
5372                    ? mSettings.mPackages.get(provider.owner.packageName)
5373                    : null;
5374            return ps != null
5375                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5376                    && (!mSafeMode || (provider.info.applicationInfo.flags
5377                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5378                    ? PackageParser.generateProviderInfo(provider, flags,
5379                            ps.readUserState(userId), userId)
5380                    : null;
5381        }
5382    }
5383
5384    /**
5385     * @deprecated
5386     */
5387    @Deprecated
5388    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5389        // reader
5390        synchronized (mPackages) {
5391            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5392                    .entrySet().iterator();
5393            final int userId = UserHandle.getCallingUserId();
5394            while (i.hasNext()) {
5395                Map.Entry<String, PackageParser.Provider> entry = i.next();
5396                PackageParser.Provider p = entry.getValue();
5397                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5398
5399                if (ps != null && p.syncable
5400                        && (!mSafeMode || (p.info.applicationInfo.flags
5401                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5402                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5403                            ps.readUserState(userId), userId);
5404                    if (info != null) {
5405                        outNames.add(entry.getKey());
5406                        outInfo.add(info);
5407                    }
5408                }
5409            }
5410        }
5411    }
5412
5413    @Override
5414    public List<ProviderInfo> queryContentProviders(String processName,
5415            int uid, int flags) {
5416        ArrayList<ProviderInfo> finalList = null;
5417        // reader
5418        synchronized (mPackages) {
5419            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5420            final int userId = processName != null ?
5421                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5422            while (i.hasNext()) {
5423                final PackageParser.Provider p = i.next();
5424                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5425                if (ps != null && p.info.authority != null
5426                        && (processName == null
5427                                || (p.info.processName.equals(processName)
5428                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5429                        && mSettings.isEnabledLPr(p.info, flags, userId)
5430                        && (!mSafeMode
5431                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5432                    if (finalList == null) {
5433                        finalList = new ArrayList<ProviderInfo>(3);
5434                    }
5435                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5436                            ps.readUserState(userId), userId);
5437                    if (info != null) {
5438                        finalList.add(info);
5439                    }
5440                }
5441            }
5442        }
5443
5444        if (finalList != null) {
5445            Collections.sort(finalList, mProviderInitOrderSorter);
5446        }
5447
5448        return finalList;
5449    }
5450
5451    @Override
5452    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5453            int flags) {
5454        // reader
5455        synchronized (mPackages) {
5456            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5457            return PackageParser.generateInstrumentationInfo(i, flags);
5458        }
5459    }
5460
5461    @Override
5462    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5463            int flags) {
5464        ArrayList<InstrumentationInfo> finalList =
5465            new ArrayList<InstrumentationInfo>();
5466
5467        // reader
5468        synchronized (mPackages) {
5469            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5470            while (i.hasNext()) {
5471                final PackageParser.Instrumentation p = i.next();
5472                if (targetPackage == null
5473                        || targetPackage.equals(p.info.targetPackage)) {
5474                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5475                            flags);
5476                    if (ii != null) {
5477                        finalList.add(ii);
5478                    }
5479                }
5480            }
5481        }
5482
5483        return finalList;
5484    }
5485
5486    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5487        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5488        if (overlays == null) {
5489            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5490            return;
5491        }
5492        for (PackageParser.Package opkg : overlays.values()) {
5493            // Not much to do if idmap fails: we already logged the error
5494            // and we certainly don't want to abort installation of pkg simply
5495            // because an overlay didn't fit properly. For these reasons,
5496            // ignore the return value of createIdmapForPackagePairLI.
5497            createIdmapForPackagePairLI(pkg, opkg);
5498        }
5499    }
5500
5501    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5502            PackageParser.Package opkg) {
5503        if (!opkg.mTrustedOverlay) {
5504            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5505                    opkg.baseCodePath + ": overlay not trusted");
5506            return false;
5507        }
5508        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5509        if (overlaySet == null) {
5510            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5511                    opkg.baseCodePath + " but target package has no known overlays");
5512            return false;
5513        }
5514        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5515        // TODO: generate idmap for split APKs
5516        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5517            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5518                    + opkg.baseCodePath);
5519            return false;
5520        }
5521        PackageParser.Package[] overlayArray =
5522            overlaySet.values().toArray(new PackageParser.Package[0]);
5523        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5524            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5525                return p1.mOverlayPriority - p2.mOverlayPriority;
5526            }
5527        };
5528        Arrays.sort(overlayArray, cmp);
5529
5530        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5531        int i = 0;
5532        for (PackageParser.Package p : overlayArray) {
5533            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5534        }
5535        return true;
5536    }
5537
5538    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5539        final File[] files = dir.listFiles();
5540        if (ArrayUtils.isEmpty(files)) {
5541            Log.d(TAG, "No files in app dir " + dir);
5542            return;
5543        }
5544
5545        if (DEBUG_PACKAGE_SCANNING) {
5546            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5547                    + " flags=0x" + Integer.toHexString(parseFlags));
5548        }
5549
5550        for (File file : files) {
5551            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5552                    && !PackageInstallerService.isStageName(file.getName());
5553            if (!isPackage) {
5554                // Ignore entries which are not packages
5555                continue;
5556            }
5557            try {
5558                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5559                        scanFlags, currentTime, null);
5560            } catch (PackageManagerException e) {
5561                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5562
5563                // Delete invalid userdata apps
5564                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5565                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5566                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5567                    if (file.isDirectory()) {
5568                        mInstaller.rmPackageDir(file.getAbsolutePath());
5569                    } else {
5570                        file.delete();
5571                    }
5572                }
5573            }
5574        }
5575    }
5576
5577    private static File getSettingsProblemFile() {
5578        File dataDir = Environment.getDataDirectory();
5579        File systemDir = new File(dataDir, "system");
5580        File fname = new File(systemDir, "uiderrors.txt");
5581        return fname;
5582    }
5583
5584    static void reportSettingsProblem(int priority, String msg) {
5585        logCriticalInfo(priority, msg);
5586    }
5587
5588    static void logCriticalInfo(int priority, String msg) {
5589        Slog.println(priority, TAG, msg);
5590        EventLogTags.writePmCriticalInfo(msg);
5591        try {
5592            File fname = getSettingsProblemFile();
5593            FileOutputStream out = new FileOutputStream(fname, true);
5594            PrintWriter pw = new FastPrintWriter(out);
5595            SimpleDateFormat formatter = new SimpleDateFormat();
5596            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5597            pw.println(dateString + ": " + msg);
5598            pw.close();
5599            FileUtils.setPermissions(
5600                    fname.toString(),
5601                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5602                    -1, -1);
5603        } catch (java.io.IOException e) {
5604        }
5605    }
5606
5607    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5608            PackageParser.Package pkg, File srcFile, int parseFlags)
5609            throws PackageManagerException {
5610        if (ps != null
5611                && ps.codePath.equals(srcFile)
5612                && ps.timeStamp == srcFile.lastModified()
5613                && !isCompatSignatureUpdateNeeded(pkg)
5614                && !isRecoverSignatureUpdateNeeded(pkg)) {
5615            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5616            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5617            ArraySet<PublicKey> signingKs;
5618            synchronized (mPackages) {
5619                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5620            }
5621            if (ps.signatures.mSignatures != null
5622                    && ps.signatures.mSignatures.length != 0
5623                    && signingKs != null) {
5624                // Optimization: reuse the existing cached certificates
5625                // if the package appears to be unchanged.
5626                pkg.mSignatures = ps.signatures.mSignatures;
5627                pkg.mSigningKeys = signingKs;
5628                return;
5629            }
5630
5631            Slog.w(TAG, "PackageSetting for " + ps.name
5632                    + " is missing signatures.  Collecting certs again to recover them.");
5633        } else {
5634            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5635        }
5636
5637        try {
5638            pp.collectCertificates(pkg, parseFlags);
5639            pp.collectManifestDigest(pkg);
5640        } catch (PackageParserException e) {
5641            throw PackageManagerException.from(e);
5642        }
5643    }
5644
5645    /*
5646     *  Scan a package and return the newly parsed package.
5647     *  Returns null in case of errors and the error code is stored in mLastScanError
5648     */
5649    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5650            long currentTime, UserHandle user) throws PackageManagerException {
5651        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5652        parseFlags |= mDefParseFlags;
5653        PackageParser pp = new PackageParser();
5654        pp.setSeparateProcesses(mSeparateProcesses);
5655        pp.setOnlyCoreApps(mOnlyCore);
5656        pp.setDisplayMetrics(mMetrics);
5657
5658        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5659            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5660        }
5661
5662        final PackageParser.Package pkg;
5663        try {
5664            pkg = pp.parsePackage(scanFile, parseFlags);
5665        } catch (PackageParserException e) {
5666            throw PackageManagerException.from(e);
5667        }
5668
5669        PackageSetting ps = null;
5670        PackageSetting updatedPkg;
5671        // reader
5672        synchronized (mPackages) {
5673            // Look to see if we already know about this package.
5674            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5675            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5676                // This package has been renamed to its original name.  Let's
5677                // use that.
5678                ps = mSettings.peekPackageLPr(oldName);
5679            }
5680            // If there was no original package, see one for the real package name.
5681            if (ps == null) {
5682                ps = mSettings.peekPackageLPr(pkg.packageName);
5683            }
5684            // Check to see if this package could be hiding/updating a system
5685            // package.  Must look for it either under the original or real
5686            // package name depending on our state.
5687            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5688            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5689        }
5690        boolean updatedPkgBetter = false;
5691        // First check if this is a system package that may involve an update
5692        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5693            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5694            // it needs to drop FLAG_PRIVILEGED.
5695            if (locationIsPrivileged(scanFile)) {
5696                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5697            } else {
5698                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5699            }
5700
5701            if (ps != null && !ps.codePath.equals(scanFile)) {
5702                // The path has changed from what was last scanned...  check the
5703                // version of the new path against what we have stored to determine
5704                // what to do.
5705                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5706                if (pkg.mVersionCode <= ps.versionCode) {
5707                    // The system package has been updated and the code path does not match
5708                    // Ignore entry. Skip it.
5709                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5710                            + " ignored: updated version " + ps.versionCode
5711                            + " better than this " + pkg.mVersionCode);
5712                    if (!updatedPkg.codePath.equals(scanFile)) {
5713                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5714                                + ps.name + " changing from " + updatedPkg.codePathString
5715                                + " to " + scanFile);
5716                        updatedPkg.codePath = scanFile;
5717                        updatedPkg.codePathString = scanFile.toString();
5718                        updatedPkg.resourcePath = scanFile;
5719                        updatedPkg.resourcePathString = scanFile.toString();
5720                    }
5721                    updatedPkg.pkg = pkg;
5722                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5723                            "Package " + ps.name + " at " + scanFile
5724                                    + " ignored: updated version " + ps.versionCode
5725                                    + " better than this " + pkg.mVersionCode);
5726                } else {
5727                    // The current app on the system partition is better than
5728                    // what we have updated to on the data partition; switch
5729                    // back to the system partition version.
5730                    // At this point, its safely assumed that package installation for
5731                    // apps in system partition will go through. If not there won't be a working
5732                    // version of the app
5733                    // writer
5734                    synchronized (mPackages) {
5735                        // Just remove the loaded entries from package lists.
5736                        mPackages.remove(ps.name);
5737                    }
5738
5739                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5740                            + " reverting from " + ps.codePathString
5741                            + ": new version " + pkg.mVersionCode
5742                            + " better than installed " + ps.versionCode);
5743
5744                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5745                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5746                    synchronized (mInstallLock) {
5747                        args.cleanUpResourcesLI();
5748                    }
5749                    synchronized (mPackages) {
5750                        mSettings.enableSystemPackageLPw(ps.name);
5751                    }
5752                    updatedPkgBetter = true;
5753                }
5754            }
5755        }
5756
5757        if (updatedPkg != null) {
5758            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5759            // initially
5760            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5761
5762            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5763            // flag set initially
5764            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5765                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5766            }
5767        }
5768
5769        // Verify certificates against what was last scanned
5770        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5771
5772        /*
5773         * A new system app appeared, but we already had a non-system one of the
5774         * same name installed earlier.
5775         */
5776        boolean shouldHideSystemApp = false;
5777        if (updatedPkg == null && ps != null
5778                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5779            /*
5780             * Check to make sure the signatures match first. If they don't,
5781             * wipe the installed application and its data.
5782             */
5783            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5784                    != PackageManager.SIGNATURE_MATCH) {
5785                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5786                        + " signatures don't match existing userdata copy; removing");
5787                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5788                ps = null;
5789            } else {
5790                /*
5791                 * If the newly-added system app is an older version than the
5792                 * already installed version, hide it. It will be scanned later
5793                 * and re-added like an update.
5794                 */
5795                if (pkg.mVersionCode <= ps.versionCode) {
5796                    shouldHideSystemApp = true;
5797                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5798                            + " but new version " + pkg.mVersionCode + " better than installed "
5799                            + ps.versionCode + "; hiding system");
5800                } else {
5801                    /*
5802                     * The newly found system app is a newer version that the
5803                     * one previously installed. Simply remove the
5804                     * already-installed application and replace it with our own
5805                     * while keeping the application data.
5806                     */
5807                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5808                            + " reverting from " + ps.codePathString + ": new version "
5809                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5810                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5811                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5812                    synchronized (mInstallLock) {
5813                        args.cleanUpResourcesLI();
5814                    }
5815                }
5816            }
5817        }
5818
5819        // The apk is forward locked (not public) if its code and resources
5820        // are kept in different files. (except for app in either system or
5821        // vendor path).
5822        // TODO grab this value from PackageSettings
5823        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5824            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5825                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5826            }
5827        }
5828
5829        // TODO: extend to support forward-locked splits
5830        String resourcePath = null;
5831        String baseResourcePath = null;
5832        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5833            if (ps != null && ps.resourcePathString != null) {
5834                resourcePath = ps.resourcePathString;
5835                baseResourcePath = ps.resourcePathString;
5836            } else {
5837                // Should not happen at all. Just log an error.
5838                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5839            }
5840        } else {
5841            resourcePath = pkg.codePath;
5842            baseResourcePath = pkg.baseCodePath;
5843        }
5844
5845        // Set application objects path explicitly.
5846        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5847        pkg.applicationInfo.setCodePath(pkg.codePath);
5848        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5849        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5850        pkg.applicationInfo.setResourcePath(resourcePath);
5851        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5852        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5853
5854        // Note that we invoke the following method only if we are about to unpack an application
5855        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5856                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5857
5858        /*
5859         * If the system app should be overridden by a previously installed
5860         * data, hide the system app now and let the /data/app scan pick it up
5861         * again.
5862         */
5863        if (shouldHideSystemApp) {
5864            synchronized (mPackages) {
5865                /*
5866                 * We have to grant systems permissions before we hide, because
5867                 * grantPermissions will assume the package update is trying to
5868                 * expand its permissions.
5869                 */
5870                grantPermissionsLPw(pkg, true, pkg.packageName);
5871                mSettings.disableSystemPackageLPw(pkg.packageName);
5872            }
5873        }
5874
5875        return scannedPkg;
5876    }
5877
5878    private static String fixProcessName(String defProcessName,
5879            String processName, int uid) {
5880        if (processName == null) {
5881            return defProcessName;
5882        }
5883        return processName;
5884    }
5885
5886    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5887            throws PackageManagerException {
5888        if (pkgSetting.signatures.mSignatures != null) {
5889            // Already existing package. Make sure signatures match
5890            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5891                    == PackageManager.SIGNATURE_MATCH;
5892            if (!match) {
5893                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5894                        == PackageManager.SIGNATURE_MATCH;
5895            }
5896            if (!match) {
5897                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5898                        == PackageManager.SIGNATURE_MATCH;
5899            }
5900            if (!match) {
5901                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5902                        + pkg.packageName + " signatures do not match the "
5903                        + "previously installed version; ignoring!");
5904            }
5905        }
5906
5907        // Check for shared user signatures
5908        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5909            // Already existing package. Make sure signatures match
5910            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5911                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5912            if (!match) {
5913                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5914                        == PackageManager.SIGNATURE_MATCH;
5915            }
5916            if (!match) {
5917                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5918                        == PackageManager.SIGNATURE_MATCH;
5919            }
5920            if (!match) {
5921                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5922                        "Package " + pkg.packageName
5923                        + " has no signatures that match those in shared user "
5924                        + pkgSetting.sharedUser.name + "; ignoring!");
5925            }
5926        }
5927    }
5928
5929    /**
5930     * Enforces that only the system UID or root's UID can call a method exposed
5931     * via Binder.
5932     *
5933     * @param message used as message if SecurityException is thrown
5934     * @throws SecurityException if the caller is not system or root
5935     */
5936    private static final void enforceSystemOrRoot(String message) {
5937        final int uid = Binder.getCallingUid();
5938        if (uid != Process.SYSTEM_UID && uid != 0) {
5939            throw new SecurityException(message);
5940        }
5941    }
5942
5943    @Override
5944    public void performBootDexOpt() {
5945        enforceSystemOrRoot("Only the system can request dexopt be performed");
5946
5947        // Before everything else, see whether we need to fstrim.
5948        try {
5949            IMountService ms = PackageHelper.getMountService();
5950            if (ms != null) {
5951                final boolean isUpgrade = isUpgrade();
5952                boolean doTrim = isUpgrade;
5953                if (doTrim) {
5954                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5955                } else {
5956                    final long interval = android.provider.Settings.Global.getLong(
5957                            mContext.getContentResolver(),
5958                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5959                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5960                    if (interval > 0) {
5961                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5962                        if (timeSinceLast > interval) {
5963                            doTrim = true;
5964                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5965                                    + "; running immediately");
5966                        }
5967                    }
5968                }
5969                if (doTrim) {
5970                    if (!isFirstBoot()) {
5971                        try {
5972                            ActivityManagerNative.getDefault().showBootMessage(
5973                                    mContext.getResources().getString(
5974                                            R.string.android_upgrading_fstrim), true);
5975                        } catch (RemoteException e) {
5976                        }
5977                    }
5978                    ms.runMaintenance();
5979                }
5980            } else {
5981                Slog.e(TAG, "Mount service unavailable!");
5982            }
5983        } catch (RemoteException e) {
5984            // Can't happen; MountService is local
5985        }
5986
5987        final ArraySet<PackageParser.Package> pkgs;
5988        synchronized (mPackages) {
5989            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5990        }
5991
5992        if (pkgs != null) {
5993            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5994            // in case the device runs out of space.
5995            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5996            // Give priority to core apps.
5997            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5998                PackageParser.Package pkg = it.next();
5999                if (pkg.coreApp) {
6000                    if (DEBUG_DEXOPT) {
6001                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6002                    }
6003                    sortedPkgs.add(pkg);
6004                    it.remove();
6005                }
6006            }
6007            // Give priority to system apps that listen for pre boot complete.
6008            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6009            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6010            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6011                PackageParser.Package pkg = it.next();
6012                if (pkgNames.contains(pkg.packageName)) {
6013                    if (DEBUG_DEXOPT) {
6014                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6015                    }
6016                    sortedPkgs.add(pkg);
6017                    it.remove();
6018                }
6019            }
6020            // Give priority to system apps.
6021            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6022                PackageParser.Package pkg = it.next();
6023                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6024                    if (DEBUG_DEXOPT) {
6025                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6026                    }
6027                    sortedPkgs.add(pkg);
6028                    it.remove();
6029                }
6030            }
6031            // Give priority to updated system apps.
6032            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6033                PackageParser.Package pkg = it.next();
6034                if (pkg.isUpdatedSystemApp()) {
6035                    if (DEBUG_DEXOPT) {
6036                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6037                    }
6038                    sortedPkgs.add(pkg);
6039                    it.remove();
6040                }
6041            }
6042            // Give priority to apps that listen for boot complete.
6043            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6044            pkgNames = getPackageNamesForIntent(intent);
6045            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6046                PackageParser.Package pkg = it.next();
6047                if (pkgNames.contains(pkg.packageName)) {
6048                    if (DEBUG_DEXOPT) {
6049                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6050                    }
6051                    sortedPkgs.add(pkg);
6052                    it.remove();
6053                }
6054            }
6055            // Filter out packages that aren't recently used.
6056            filterRecentlyUsedApps(pkgs);
6057            // Add all remaining apps.
6058            for (PackageParser.Package pkg : pkgs) {
6059                if (DEBUG_DEXOPT) {
6060                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6061                }
6062                sortedPkgs.add(pkg);
6063            }
6064
6065            // If we want to be lazy, filter everything that wasn't recently used.
6066            if (mLazyDexOpt) {
6067                filterRecentlyUsedApps(sortedPkgs);
6068            }
6069
6070            int i = 0;
6071            int total = sortedPkgs.size();
6072            File dataDir = Environment.getDataDirectory();
6073            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6074            if (lowThreshold == 0) {
6075                throw new IllegalStateException("Invalid low memory threshold");
6076            }
6077            for (PackageParser.Package pkg : sortedPkgs) {
6078                long usableSpace = dataDir.getUsableSpace();
6079                if (usableSpace < lowThreshold) {
6080                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6081                    break;
6082                }
6083                performBootDexOpt(pkg, ++i, total);
6084            }
6085        }
6086    }
6087
6088    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6089        // Filter out packages that aren't recently used.
6090        //
6091        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6092        // should do a full dexopt.
6093        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6094            int total = pkgs.size();
6095            int skipped = 0;
6096            long now = System.currentTimeMillis();
6097            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6098                PackageParser.Package pkg = i.next();
6099                long then = pkg.mLastPackageUsageTimeInMills;
6100                if (then + mDexOptLRUThresholdInMills < now) {
6101                    if (DEBUG_DEXOPT) {
6102                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6103                              ((then == 0) ? "never" : new Date(then)));
6104                    }
6105                    i.remove();
6106                    skipped++;
6107                }
6108            }
6109            if (DEBUG_DEXOPT) {
6110                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6111            }
6112        }
6113    }
6114
6115    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6116        List<ResolveInfo> ris = null;
6117        try {
6118            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6119                    intent, null, 0, UserHandle.USER_OWNER);
6120        } catch (RemoteException e) {
6121        }
6122        ArraySet<String> pkgNames = new ArraySet<String>();
6123        if (ris != null) {
6124            for (ResolveInfo ri : ris) {
6125                pkgNames.add(ri.activityInfo.packageName);
6126            }
6127        }
6128        return pkgNames;
6129    }
6130
6131    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6132        if (DEBUG_DEXOPT) {
6133            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6134        }
6135        if (!isFirstBoot()) {
6136            try {
6137                ActivityManagerNative.getDefault().showBootMessage(
6138                        mContext.getResources().getString(R.string.android_upgrading_apk,
6139                                curr, total), true);
6140            } catch (RemoteException e) {
6141            }
6142        }
6143        PackageParser.Package p = pkg;
6144        synchronized (mInstallLock) {
6145            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6146                    false /* force dex */, false /* defer */, true /* include dependencies */);
6147        }
6148    }
6149
6150    @Override
6151    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6152        return performDexOpt(packageName, instructionSet, false);
6153    }
6154
6155    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6156        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6157        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6158        if (!dexopt && !updateUsage) {
6159            // We aren't going to dexopt or update usage, so bail early.
6160            return false;
6161        }
6162        PackageParser.Package p;
6163        final String targetInstructionSet;
6164        synchronized (mPackages) {
6165            p = mPackages.get(packageName);
6166            if (p == null) {
6167                return false;
6168            }
6169            if (updateUsage) {
6170                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6171            }
6172            mPackageUsage.write(false);
6173            if (!dexopt) {
6174                // We aren't going to dexopt, so bail early.
6175                return false;
6176            }
6177
6178            targetInstructionSet = instructionSet != null ? instructionSet :
6179                    getPrimaryInstructionSet(p.applicationInfo);
6180            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6181                return false;
6182            }
6183        }
6184        long callingId = Binder.clearCallingIdentity();
6185        try {
6186            synchronized (mInstallLock) {
6187                final String[] instructionSets = new String[] { targetInstructionSet };
6188                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6189                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6190                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6191            }
6192        } finally {
6193            Binder.restoreCallingIdentity(callingId);
6194        }
6195    }
6196
6197    public ArraySet<String> getPackagesThatNeedDexOpt() {
6198        ArraySet<String> pkgs = null;
6199        synchronized (mPackages) {
6200            for (PackageParser.Package p : mPackages.values()) {
6201                if (DEBUG_DEXOPT) {
6202                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6203                }
6204                if (!p.mDexOptPerformed.isEmpty()) {
6205                    continue;
6206                }
6207                if (pkgs == null) {
6208                    pkgs = new ArraySet<String>();
6209                }
6210                pkgs.add(p.packageName);
6211            }
6212        }
6213        return pkgs;
6214    }
6215
6216    public void shutdown() {
6217        mPackageUsage.write(true);
6218    }
6219
6220    @Override
6221    public void forceDexOpt(String packageName) {
6222        enforceSystemOrRoot("forceDexOpt");
6223
6224        PackageParser.Package pkg;
6225        synchronized (mPackages) {
6226            pkg = mPackages.get(packageName);
6227            if (pkg == null) {
6228                throw new IllegalArgumentException("Missing package: " + packageName);
6229            }
6230        }
6231
6232        synchronized (mInstallLock) {
6233            final String[] instructionSets = new String[] {
6234                    getPrimaryInstructionSet(pkg.applicationInfo) };
6235            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6236                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6237            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6238                throw new IllegalStateException("Failed to dexopt: " + res);
6239            }
6240        }
6241    }
6242
6243    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6244        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6245            Slog.w(TAG, "Unable to update from " + oldPkg.name
6246                    + " to " + newPkg.packageName
6247                    + ": old package not in system partition");
6248            return false;
6249        } else if (mPackages.get(oldPkg.name) != null) {
6250            Slog.w(TAG, "Unable to update from " + oldPkg.name
6251                    + " to " + newPkg.packageName
6252                    + ": old package still exists");
6253            return false;
6254        }
6255        return true;
6256    }
6257
6258    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6259        int[] users = sUserManager.getUserIds();
6260        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6261        if (res < 0) {
6262            return res;
6263        }
6264        for (int user : users) {
6265            if (user != 0) {
6266                res = mInstaller.createUserData(volumeUuid, packageName,
6267                        UserHandle.getUid(user, uid), user, seinfo);
6268                if (res < 0) {
6269                    return res;
6270                }
6271            }
6272        }
6273        return res;
6274    }
6275
6276    private int removeDataDirsLI(String volumeUuid, String packageName) {
6277        int[] users = sUserManager.getUserIds();
6278        int res = 0;
6279        for (int user : users) {
6280            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6281            if (resInner < 0) {
6282                res = resInner;
6283            }
6284        }
6285
6286        return res;
6287    }
6288
6289    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6290        int[] users = sUserManager.getUserIds();
6291        int res = 0;
6292        for (int user : users) {
6293            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6294            if (resInner < 0) {
6295                res = resInner;
6296            }
6297        }
6298        return res;
6299    }
6300
6301    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6302            PackageParser.Package changingLib) {
6303        if (file.path != null) {
6304            usesLibraryFiles.add(file.path);
6305            return;
6306        }
6307        PackageParser.Package p = mPackages.get(file.apk);
6308        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6309            // If we are doing this while in the middle of updating a library apk,
6310            // then we need to make sure to use that new apk for determining the
6311            // dependencies here.  (We haven't yet finished committing the new apk
6312            // to the package manager state.)
6313            if (p == null || p.packageName.equals(changingLib.packageName)) {
6314                p = changingLib;
6315            }
6316        }
6317        if (p != null) {
6318            usesLibraryFiles.addAll(p.getAllCodePaths());
6319        }
6320    }
6321
6322    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6323            PackageParser.Package changingLib) throws PackageManagerException {
6324        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6325            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6326            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6327            for (int i=0; i<N; i++) {
6328                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6329                if (file == null) {
6330                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6331                            "Package " + pkg.packageName + " requires unavailable shared library "
6332                            + pkg.usesLibraries.get(i) + "; failing!");
6333                }
6334                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6335            }
6336            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6337            for (int i=0; i<N; i++) {
6338                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6339                if (file == null) {
6340                    Slog.w(TAG, "Package " + pkg.packageName
6341                            + " desires unavailable shared library "
6342                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6343                } else {
6344                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6345                }
6346            }
6347            N = usesLibraryFiles.size();
6348            if (N > 0) {
6349                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6350            } else {
6351                pkg.usesLibraryFiles = null;
6352            }
6353        }
6354    }
6355
6356    private static boolean hasString(List<String> list, List<String> which) {
6357        if (list == null) {
6358            return false;
6359        }
6360        for (int i=list.size()-1; i>=0; i--) {
6361            for (int j=which.size()-1; j>=0; j--) {
6362                if (which.get(j).equals(list.get(i))) {
6363                    return true;
6364                }
6365            }
6366        }
6367        return false;
6368    }
6369
6370    private void updateAllSharedLibrariesLPw() {
6371        for (PackageParser.Package pkg : mPackages.values()) {
6372            try {
6373                updateSharedLibrariesLPw(pkg, null);
6374            } catch (PackageManagerException e) {
6375                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6376            }
6377        }
6378    }
6379
6380    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6381            PackageParser.Package changingPkg) {
6382        ArrayList<PackageParser.Package> res = null;
6383        for (PackageParser.Package pkg : mPackages.values()) {
6384            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6385                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6386                if (res == null) {
6387                    res = new ArrayList<PackageParser.Package>();
6388                }
6389                res.add(pkg);
6390                try {
6391                    updateSharedLibrariesLPw(pkg, changingPkg);
6392                } catch (PackageManagerException e) {
6393                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6394                }
6395            }
6396        }
6397        return res;
6398    }
6399
6400    /**
6401     * Derive the value of the {@code cpuAbiOverride} based on the provided
6402     * value and an optional stored value from the package settings.
6403     */
6404    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6405        String cpuAbiOverride = null;
6406
6407        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6408            cpuAbiOverride = null;
6409        } else if (abiOverride != null) {
6410            cpuAbiOverride = abiOverride;
6411        } else if (settings != null) {
6412            cpuAbiOverride = settings.cpuAbiOverrideString;
6413        }
6414
6415        return cpuAbiOverride;
6416    }
6417
6418    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6419            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6420        boolean success = false;
6421        try {
6422            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6423                    currentTime, user);
6424            success = true;
6425            return res;
6426        } finally {
6427            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6428                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6429            }
6430        }
6431    }
6432
6433    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6434            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6435        final File scanFile = new File(pkg.codePath);
6436        if (pkg.applicationInfo.getCodePath() == null ||
6437                pkg.applicationInfo.getResourcePath() == null) {
6438            // Bail out. The resource and code paths haven't been set.
6439            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6440                    "Code and resource paths haven't been set correctly");
6441        }
6442
6443        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6444            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6445        } else {
6446            // Only allow system apps to be flagged as core apps.
6447            pkg.coreApp = false;
6448        }
6449
6450        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6451            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6452        }
6453
6454        if (mCustomResolverComponentName != null &&
6455                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6456            setUpCustomResolverActivity(pkg);
6457        }
6458
6459        if (pkg.packageName.equals("android")) {
6460            synchronized (mPackages) {
6461                if (mAndroidApplication != null) {
6462                    Slog.w(TAG, "*************************************************");
6463                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6464                    Slog.w(TAG, " file=" + scanFile);
6465                    Slog.w(TAG, "*************************************************");
6466                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6467                            "Core android package being redefined.  Skipping.");
6468                }
6469
6470                // Set up information for our fall-back user intent resolution activity.
6471                mPlatformPackage = pkg;
6472                pkg.mVersionCode = mSdkVersion;
6473                mAndroidApplication = pkg.applicationInfo;
6474
6475                if (!mResolverReplaced) {
6476                    mResolveActivity.applicationInfo = mAndroidApplication;
6477                    mResolveActivity.name = ResolverActivity.class.getName();
6478                    mResolveActivity.packageName = mAndroidApplication.packageName;
6479                    mResolveActivity.processName = "system:ui";
6480                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6481                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6482                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6483                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6484                    mResolveActivity.exported = true;
6485                    mResolveActivity.enabled = true;
6486                    mResolveInfo.activityInfo = mResolveActivity;
6487                    mResolveInfo.priority = 0;
6488                    mResolveInfo.preferredOrder = 0;
6489                    mResolveInfo.match = 0;
6490                    mResolveComponentName = new ComponentName(
6491                            mAndroidApplication.packageName, mResolveActivity.name);
6492                }
6493            }
6494        }
6495
6496        if (DEBUG_PACKAGE_SCANNING) {
6497            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6498                Log.d(TAG, "Scanning package " + pkg.packageName);
6499        }
6500
6501        if (mPackages.containsKey(pkg.packageName)
6502                || mSharedLibraries.containsKey(pkg.packageName)) {
6503            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6504                    "Application package " + pkg.packageName
6505                    + " already installed.  Skipping duplicate.");
6506        }
6507
6508        // If we're only installing presumed-existing packages, require that the
6509        // scanned APK is both already known and at the path previously established
6510        // for it.  Previously unknown packages we pick up normally, but if we have an
6511        // a priori expectation about this package's install presence, enforce it.
6512        // With a singular exception for new system packages. When an OTA contains
6513        // a new system package, we allow the codepath to change from a system location
6514        // to the user-installed location. If we don't allow this change, any newer,
6515        // user-installed version of the application will be ignored.
6516        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6517            if (mExpectingBetter.containsKey(pkg.packageName)) {
6518                logCriticalInfo(Log.WARN,
6519                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6520            } else {
6521                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6522                if (known != null) {
6523                    if (DEBUG_PACKAGE_SCANNING) {
6524                        Log.d(TAG, "Examining " + pkg.codePath
6525                                + " and requiring known paths " + known.codePathString
6526                                + " & " + known.resourcePathString);
6527                    }
6528                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6529                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6530                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6531                                "Application package " + pkg.packageName
6532                                + " found at " + pkg.applicationInfo.getCodePath()
6533                                + " but expected at " + known.codePathString + "; ignoring.");
6534                    }
6535                }
6536            }
6537        }
6538
6539        // Initialize package source and resource directories
6540        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6541        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6542
6543        SharedUserSetting suid = null;
6544        PackageSetting pkgSetting = null;
6545
6546        if (!isSystemApp(pkg)) {
6547            // Only system apps can use these features.
6548            pkg.mOriginalPackages = null;
6549            pkg.mRealPackage = null;
6550            pkg.mAdoptPermissions = null;
6551        }
6552
6553        // writer
6554        synchronized (mPackages) {
6555            if (pkg.mSharedUserId != null) {
6556                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6557                if (suid == null) {
6558                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6559                            "Creating application package " + pkg.packageName
6560                            + " for shared user failed");
6561                }
6562                if (DEBUG_PACKAGE_SCANNING) {
6563                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6564                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6565                                + "): packages=" + suid.packages);
6566                }
6567            }
6568
6569            // Check if we are renaming from an original package name.
6570            PackageSetting origPackage = null;
6571            String realName = null;
6572            if (pkg.mOriginalPackages != null) {
6573                // This package may need to be renamed to a previously
6574                // installed name.  Let's check on that...
6575                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6576                if (pkg.mOriginalPackages.contains(renamed)) {
6577                    // This package had originally been installed as the
6578                    // original name, and we have already taken care of
6579                    // transitioning to the new one.  Just update the new
6580                    // one to continue using the old name.
6581                    realName = pkg.mRealPackage;
6582                    if (!pkg.packageName.equals(renamed)) {
6583                        // Callers into this function may have already taken
6584                        // care of renaming the package; only do it here if
6585                        // it is not already done.
6586                        pkg.setPackageName(renamed);
6587                    }
6588
6589                } else {
6590                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6591                        if ((origPackage = mSettings.peekPackageLPr(
6592                                pkg.mOriginalPackages.get(i))) != null) {
6593                            // We do have the package already installed under its
6594                            // original name...  should we use it?
6595                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6596                                // New package is not compatible with original.
6597                                origPackage = null;
6598                                continue;
6599                            } else if (origPackage.sharedUser != null) {
6600                                // Make sure uid is compatible between packages.
6601                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6602                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6603                                            + " to " + pkg.packageName + ": old uid "
6604                                            + origPackage.sharedUser.name
6605                                            + " differs from " + pkg.mSharedUserId);
6606                                    origPackage = null;
6607                                    continue;
6608                                }
6609                            } else {
6610                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6611                                        + pkg.packageName + " to old name " + origPackage.name);
6612                            }
6613                            break;
6614                        }
6615                    }
6616                }
6617            }
6618
6619            if (mTransferedPackages.contains(pkg.packageName)) {
6620                Slog.w(TAG, "Package " + pkg.packageName
6621                        + " was transferred to another, but its .apk remains");
6622            }
6623
6624            // Just create the setting, don't add it yet. For already existing packages
6625            // the PkgSetting exists already and doesn't have to be created.
6626            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6627                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6628                    pkg.applicationInfo.primaryCpuAbi,
6629                    pkg.applicationInfo.secondaryCpuAbi,
6630                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6631                    user, false);
6632            if (pkgSetting == null) {
6633                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6634                        "Creating application package " + pkg.packageName + " failed");
6635            }
6636
6637            if (pkgSetting.origPackage != null) {
6638                // If we are first transitioning from an original package,
6639                // fix up the new package's name now.  We need to do this after
6640                // looking up the package under its new name, so getPackageLP
6641                // can take care of fiddling things correctly.
6642                pkg.setPackageName(origPackage.name);
6643
6644                // File a report about this.
6645                String msg = "New package " + pkgSetting.realName
6646                        + " renamed to replace old package " + pkgSetting.name;
6647                reportSettingsProblem(Log.WARN, msg);
6648
6649                // Make a note of it.
6650                mTransferedPackages.add(origPackage.name);
6651
6652                // No longer need to retain this.
6653                pkgSetting.origPackage = null;
6654            }
6655
6656            if (realName != null) {
6657                // Make a note of it.
6658                mTransferedPackages.add(pkg.packageName);
6659            }
6660
6661            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6662                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6663            }
6664
6665            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6666                // Check all shared libraries and map to their actual file path.
6667                // We only do this here for apps not on a system dir, because those
6668                // are the only ones that can fail an install due to this.  We
6669                // will take care of the system apps by updating all of their
6670                // library paths after the scan is done.
6671                updateSharedLibrariesLPw(pkg, null);
6672            }
6673
6674            if (mFoundPolicyFile) {
6675                SELinuxMMAC.assignSeinfoValue(pkg);
6676            }
6677
6678            pkg.applicationInfo.uid = pkgSetting.appId;
6679            pkg.mExtras = pkgSetting;
6680            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6681                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6682                    // We just determined the app is signed correctly, so bring
6683                    // over the latest parsed certs.
6684                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6685                } else {
6686                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6687                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6688                                "Package " + pkg.packageName + " upgrade keys do not match the "
6689                                + "previously installed version");
6690                    } else {
6691                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6692                        String msg = "System package " + pkg.packageName
6693                            + " signature changed; retaining data.";
6694                        reportSettingsProblem(Log.WARN, msg);
6695                    }
6696                }
6697            } else {
6698                try {
6699                    verifySignaturesLP(pkgSetting, pkg);
6700                    // We just determined the app is signed correctly, so bring
6701                    // over the latest parsed certs.
6702                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6703                } catch (PackageManagerException e) {
6704                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6705                        throw e;
6706                    }
6707                    // The signature has changed, but this package is in the system
6708                    // image...  let's recover!
6709                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6710                    // However...  if this package is part of a shared user, but it
6711                    // doesn't match the signature of the shared user, let's fail.
6712                    // What this means is that you can't change the signatures
6713                    // associated with an overall shared user, which doesn't seem all
6714                    // that unreasonable.
6715                    if (pkgSetting.sharedUser != null) {
6716                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6717                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6718                            throw new PackageManagerException(
6719                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6720                                            "Signature mismatch for shared user : "
6721                                            + pkgSetting.sharedUser);
6722                        }
6723                    }
6724                    // File a report about this.
6725                    String msg = "System package " + pkg.packageName
6726                        + " signature changed; retaining data.";
6727                    reportSettingsProblem(Log.WARN, msg);
6728                }
6729            }
6730            // Verify that this new package doesn't have any content providers
6731            // that conflict with existing packages.  Only do this if the
6732            // package isn't already installed, since we don't want to break
6733            // things that are installed.
6734            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6735                final int N = pkg.providers.size();
6736                int i;
6737                for (i=0; i<N; i++) {
6738                    PackageParser.Provider p = pkg.providers.get(i);
6739                    if (p.info.authority != null) {
6740                        String names[] = p.info.authority.split(";");
6741                        for (int j = 0; j < names.length; j++) {
6742                            if (mProvidersByAuthority.containsKey(names[j])) {
6743                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6744                                final String otherPackageName =
6745                                        ((other != null && other.getComponentName() != null) ?
6746                                                other.getComponentName().getPackageName() : "?");
6747                                throw new PackageManagerException(
6748                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6749                                                "Can't install because provider name " + names[j]
6750                                                + " (in package " + pkg.applicationInfo.packageName
6751                                                + ") is already used by " + otherPackageName);
6752                            }
6753                        }
6754                    }
6755                }
6756            }
6757
6758            if (pkg.mAdoptPermissions != null) {
6759                // This package wants to adopt ownership of permissions from
6760                // another package.
6761                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6762                    final String origName = pkg.mAdoptPermissions.get(i);
6763                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6764                    if (orig != null) {
6765                        if (verifyPackageUpdateLPr(orig, pkg)) {
6766                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6767                                    + pkg.packageName);
6768                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6769                        }
6770                    }
6771                }
6772            }
6773        }
6774
6775        final String pkgName = pkg.packageName;
6776
6777        final long scanFileTime = scanFile.lastModified();
6778        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6779        pkg.applicationInfo.processName = fixProcessName(
6780                pkg.applicationInfo.packageName,
6781                pkg.applicationInfo.processName,
6782                pkg.applicationInfo.uid);
6783
6784        File dataPath;
6785        if (mPlatformPackage == pkg) {
6786            // The system package is special.
6787            dataPath = new File(Environment.getDataDirectory(), "system");
6788
6789            pkg.applicationInfo.dataDir = dataPath.getPath();
6790
6791        } else {
6792            // This is a normal package, need to make its data directory.
6793            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6794                    UserHandle.USER_OWNER, pkg.packageName);
6795
6796            boolean uidError = false;
6797            if (dataPath.exists()) {
6798                int currentUid = 0;
6799                try {
6800                    StructStat stat = Os.stat(dataPath.getPath());
6801                    currentUid = stat.st_uid;
6802                } catch (ErrnoException e) {
6803                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6804                }
6805
6806                // If we have mismatched owners for the data path, we have a problem.
6807                if (currentUid != pkg.applicationInfo.uid) {
6808                    boolean recovered = false;
6809                    if (currentUid == 0) {
6810                        // The directory somehow became owned by root.  Wow.
6811                        // This is probably because the system was stopped while
6812                        // installd was in the middle of messing with its libs
6813                        // directory.  Ask installd to fix that.
6814                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6815                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6816                        if (ret >= 0) {
6817                            recovered = true;
6818                            String msg = "Package " + pkg.packageName
6819                                    + " unexpectedly changed to uid 0; recovered to " +
6820                                    + pkg.applicationInfo.uid;
6821                            reportSettingsProblem(Log.WARN, msg);
6822                        }
6823                    }
6824                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6825                            || (scanFlags&SCAN_BOOTING) != 0)) {
6826                        // If this is a system app, we can at least delete its
6827                        // current data so the application will still work.
6828                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6829                        if (ret >= 0) {
6830                            // TODO: Kill the processes first
6831                            // Old data gone!
6832                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6833                                    ? "System package " : "Third party package ";
6834                            String msg = prefix + pkg.packageName
6835                                    + " has changed from uid: "
6836                                    + currentUid + " to "
6837                                    + pkg.applicationInfo.uid + "; old data erased";
6838                            reportSettingsProblem(Log.WARN, msg);
6839                            recovered = true;
6840
6841                            // And now re-install the app.
6842                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6843                                    pkg.applicationInfo.seinfo);
6844                            if (ret == -1) {
6845                                // Ack should not happen!
6846                                msg = prefix + pkg.packageName
6847                                        + " could not have data directory re-created after delete.";
6848                                reportSettingsProblem(Log.WARN, msg);
6849                                throw new PackageManagerException(
6850                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6851                            }
6852                        }
6853                        if (!recovered) {
6854                            mHasSystemUidErrors = true;
6855                        }
6856                    } else if (!recovered) {
6857                        // If we allow this install to proceed, we will be broken.
6858                        // Abort, abort!
6859                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6860                                "scanPackageLI");
6861                    }
6862                    if (!recovered) {
6863                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6864                            + pkg.applicationInfo.uid + "/fs_"
6865                            + currentUid;
6866                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6867                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6868                        String msg = "Package " + pkg.packageName
6869                                + " has mismatched uid: "
6870                                + currentUid + " on disk, "
6871                                + pkg.applicationInfo.uid + " in settings";
6872                        // writer
6873                        synchronized (mPackages) {
6874                            mSettings.mReadMessages.append(msg);
6875                            mSettings.mReadMessages.append('\n');
6876                            uidError = true;
6877                            if (!pkgSetting.uidError) {
6878                                reportSettingsProblem(Log.ERROR, msg);
6879                            }
6880                        }
6881                    }
6882                }
6883                pkg.applicationInfo.dataDir = dataPath.getPath();
6884                if (mShouldRestoreconData) {
6885                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6886                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6887                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6888                }
6889            } else {
6890                if (DEBUG_PACKAGE_SCANNING) {
6891                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6892                        Log.v(TAG, "Want this data dir: " + dataPath);
6893                }
6894                //invoke installer to do the actual installation
6895                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6896                        pkg.applicationInfo.seinfo);
6897                if (ret < 0) {
6898                    // Error from installer
6899                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6900                            "Unable to create data dirs [errorCode=" + ret + "]");
6901                }
6902
6903                if (dataPath.exists()) {
6904                    pkg.applicationInfo.dataDir = dataPath.getPath();
6905                } else {
6906                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6907                    pkg.applicationInfo.dataDir = null;
6908                }
6909            }
6910
6911            pkgSetting.uidError = uidError;
6912        }
6913
6914        final String path = scanFile.getPath();
6915        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6916
6917        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6918            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6919
6920            // Some system apps still use directory structure for native libraries
6921            // in which case we might end up not detecting abi solely based on apk
6922            // structure. Try to detect abi based on directory structure.
6923            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6924                    pkg.applicationInfo.primaryCpuAbi == null) {
6925                setBundledAppAbisAndRoots(pkg, pkgSetting);
6926                setNativeLibraryPaths(pkg);
6927            }
6928
6929        } else {
6930            if ((scanFlags & SCAN_MOVE) != 0) {
6931                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6932                // but we already have this packages package info in the PackageSetting. We just
6933                // use that and derive the native library path based on the new codepath.
6934                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6935                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6936            }
6937
6938            // Set native library paths again. For moves, the path will be updated based on the
6939            // ABIs we've determined above. For non-moves, the path will be updated based on the
6940            // ABIs we determined during compilation, but the path will depend on the final
6941            // package path (after the rename away from the stage path).
6942            setNativeLibraryPaths(pkg);
6943        }
6944
6945        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6946        final int[] userIds = sUserManager.getUserIds();
6947        synchronized (mInstallLock) {
6948            // Make sure all user data directories are ready to roll; we're okay
6949            // if they already exist
6950            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6951                for (int userId : userIds) {
6952                    if (userId != 0) {
6953                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6954                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6955                                pkg.applicationInfo.seinfo);
6956                    }
6957                }
6958            }
6959
6960            // Create a native library symlink only if we have native libraries
6961            // and if the native libraries are 32 bit libraries. We do not provide
6962            // this symlink for 64 bit libraries.
6963            if (pkg.applicationInfo.primaryCpuAbi != null &&
6964                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6965                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6966                for (int userId : userIds) {
6967                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6968                            nativeLibPath, userId) < 0) {
6969                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6970                                "Failed linking native library dir (user=" + userId + ")");
6971                    }
6972                }
6973            }
6974        }
6975
6976        // This is a special case for the "system" package, where the ABI is
6977        // dictated by the zygote configuration (and init.rc). We should keep track
6978        // of this ABI so that we can deal with "normal" applications that run under
6979        // the same UID correctly.
6980        if (mPlatformPackage == pkg) {
6981            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6982                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6983        }
6984
6985        // If there's a mismatch between the abi-override in the package setting
6986        // and the abiOverride specified for the install. Warn about this because we
6987        // would've already compiled the app without taking the package setting into
6988        // account.
6989        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6990            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6991                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6992                        " for package: " + pkg.packageName);
6993            }
6994        }
6995
6996        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6997        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6998        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6999
7000        // Copy the derived override back to the parsed package, so that we can
7001        // update the package settings accordingly.
7002        pkg.cpuAbiOverride = cpuAbiOverride;
7003
7004        if (DEBUG_ABI_SELECTION) {
7005            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7006                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7007                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7008        }
7009
7010        // Push the derived path down into PackageSettings so we know what to
7011        // clean up at uninstall time.
7012        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7013
7014        if (DEBUG_ABI_SELECTION) {
7015            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7016                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7017                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7018        }
7019
7020        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7021            // We don't do this here during boot because we can do it all
7022            // at once after scanning all existing packages.
7023            //
7024            // We also do this *before* we perform dexopt on this package, so that
7025            // we can avoid redundant dexopts, and also to make sure we've got the
7026            // code and package path correct.
7027            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7028                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7029        }
7030
7031        if ((scanFlags & SCAN_NO_DEX) == 0) {
7032            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7033                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7034            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7035                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7036            }
7037        }
7038        if (mFactoryTest && pkg.requestedPermissions.contains(
7039                android.Manifest.permission.FACTORY_TEST)) {
7040            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7041        }
7042
7043        ArrayList<PackageParser.Package> clientLibPkgs = null;
7044
7045        // writer
7046        synchronized (mPackages) {
7047            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7048                // Only system apps can add new shared libraries.
7049                if (pkg.libraryNames != null) {
7050                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7051                        String name = pkg.libraryNames.get(i);
7052                        boolean allowed = false;
7053                        if (pkg.isUpdatedSystemApp()) {
7054                            // New library entries can only be added through the
7055                            // system image.  This is important to get rid of a lot
7056                            // of nasty edge cases: for example if we allowed a non-
7057                            // system update of the app to add a library, then uninstalling
7058                            // the update would make the library go away, and assumptions
7059                            // we made such as through app install filtering would now
7060                            // have allowed apps on the device which aren't compatible
7061                            // with it.  Better to just have the restriction here, be
7062                            // conservative, and create many fewer cases that can negatively
7063                            // impact the user experience.
7064                            final PackageSetting sysPs = mSettings
7065                                    .getDisabledSystemPkgLPr(pkg.packageName);
7066                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7067                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7068                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7069                                        allowed = true;
7070                                        allowed = true;
7071                                        break;
7072                                    }
7073                                }
7074                            }
7075                        } else {
7076                            allowed = true;
7077                        }
7078                        if (allowed) {
7079                            if (!mSharedLibraries.containsKey(name)) {
7080                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7081                            } else if (!name.equals(pkg.packageName)) {
7082                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7083                                        + name + " already exists; skipping");
7084                            }
7085                        } else {
7086                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7087                                    + name + " that is not declared on system image; skipping");
7088                        }
7089                    }
7090                    if ((scanFlags&SCAN_BOOTING) == 0) {
7091                        // If we are not booting, we need to update any applications
7092                        // that are clients of our shared library.  If we are booting,
7093                        // this will all be done once the scan is complete.
7094                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7095                    }
7096                }
7097            }
7098        }
7099
7100        // We also need to dexopt any apps that are dependent on this library.  Note that
7101        // if these fail, we should abort the install since installing the library will
7102        // result in some apps being broken.
7103        if (clientLibPkgs != null) {
7104            if ((scanFlags & SCAN_NO_DEX) == 0) {
7105                for (int i = 0; i < clientLibPkgs.size(); i++) {
7106                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7107                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7108                            null /* instruction sets */, forceDex,
7109                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7110                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7111                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7112                                "scanPackageLI failed to dexopt clientLibPkgs");
7113                    }
7114                }
7115            }
7116        }
7117
7118        // Also need to kill any apps that are dependent on the library.
7119        if (clientLibPkgs != null) {
7120            for (int i=0; i<clientLibPkgs.size(); i++) {
7121                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7122                killApplication(clientPkg.applicationInfo.packageName,
7123                        clientPkg.applicationInfo.uid, "update lib");
7124            }
7125        }
7126
7127        // Make sure we're not adding any bogus keyset info
7128        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7129        ksms.assertScannedPackageValid(pkg);
7130
7131        // writer
7132        synchronized (mPackages) {
7133            // We don't expect installation to fail beyond this point
7134
7135            // Add the new setting to mSettings
7136            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7137            // Add the new setting to mPackages
7138            mPackages.put(pkg.applicationInfo.packageName, pkg);
7139            // Make sure we don't accidentally delete its data.
7140            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7141            while (iter.hasNext()) {
7142                PackageCleanItem item = iter.next();
7143                if (pkgName.equals(item.packageName)) {
7144                    iter.remove();
7145                }
7146            }
7147
7148            // Take care of first install / last update times.
7149            if (currentTime != 0) {
7150                if (pkgSetting.firstInstallTime == 0) {
7151                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7152                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7153                    pkgSetting.lastUpdateTime = currentTime;
7154                }
7155            } else if (pkgSetting.firstInstallTime == 0) {
7156                // We need *something*.  Take time time stamp of the file.
7157                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7158            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7159                if (scanFileTime != pkgSetting.timeStamp) {
7160                    // A package on the system image has changed; consider this
7161                    // to be an update.
7162                    pkgSetting.lastUpdateTime = scanFileTime;
7163                }
7164            }
7165
7166            // Add the package's KeySets to the global KeySetManagerService
7167            ksms.addScannedPackageLPw(pkg);
7168
7169            int N = pkg.providers.size();
7170            StringBuilder r = null;
7171            int i;
7172            for (i=0; i<N; i++) {
7173                PackageParser.Provider p = pkg.providers.get(i);
7174                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7175                        p.info.processName, pkg.applicationInfo.uid);
7176                mProviders.addProvider(p);
7177                p.syncable = p.info.isSyncable;
7178                if (p.info.authority != null) {
7179                    String names[] = p.info.authority.split(";");
7180                    p.info.authority = null;
7181                    for (int j = 0; j < names.length; j++) {
7182                        if (j == 1 && p.syncable) {
7183                            // We only want the first authority for a provider to possibly be
7184                            // syncable, so if we already added this provider using a different
7185                            // authority clear the syncable flag. We copy the provider before
7186                            // changing it because the mProviders object contains a reference
7187                            // to a provider that we don't want to change.
7188                            // Only do this for the second authority since the resulting provider
7189                            // object can be the same for all future authorities for this provider.
7190                            p = new PackageParser.Provider(p);
7191                            p.syncable = false;
7192                        }
7193                        if (!mProvidersByAuthority.containsKey(names[j])) {
7194                            mProvidersByAuthority.put(names[j], p);
7195                            if (p.info.authority == null) {
7196                                p.info.authority = names[j];
7197                            } else {
7198                                p.info.authority = p.info.authority + ";" + names[j];
7199                            }
7200                            if (DEBUG_PACKAGE_SCANNING) {
7201                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7202                                    Log.d(TAG, "Registered content provider: " + names[j]
7203                                            + ", className = " + p.info.name + ", isSyncable = "
7204                                            + p.info.isSyncable);
7205                            }
7206                        } else {
7207                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7208                            Slog.w(TAG, "Skipping provider name " + names[j] +
7209                                    " (in package " + pkg.applicationInfo.packageName +
7210                                    "): name already used by "
7211                                    + ((other != null && other.getComponentName() != null)
7212                                            ? other.getComponentName().getPackageName() : "?"));
7213                        }
7214                    }
7215                }
7216                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7217                    if (r == null) {
7218                        r = new StringBuilder(256);
7219                    } else {
7220                        r.append(' ');
7221                    }
7222                    r.append(p.info.name);
7223                }
7224            }
7225            if (r != null) {
7226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7227            }
7228
7229            N = pkg.services.size();
7230            r = null;
7231            for (i=0; i<N; i++) {
7232                PackageParser.Service s = pkg.services.get(i);
7233                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7234                        s.info.processName, pkg.applicationInfo.uid);
7235                mServices.addService(s);
7236                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7237                    if (r == null) {
7238                        r = new StringBuilder(256);
7239                    } else {
7240                        r.append(' ');
7241                    }
7242                    r.append(s.info.name);
7243                }
7244            }
7245            if (r != null) {
7246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7247            }
7248
7249            N = pkg.receivers.size();
7250            r = null;
7251            for (i=0; i<N; i++) {
7252                PackageParser.Activity a = pkg.receivers.get(i);
7253                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7254                        a.info.processName, pkg.applicationInfo.uid);
7255                mReceivers.addActivity(a, "receiver");
7256                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7257                    if (r == null) {
7258                        r = new StringBuilder(256);
7259                    } else {
7260                        r.append(' ');
7261                    }
7262                    r.append(a.info.name);
7263                }
7264            }
7265            if (r != null) {
7266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7267            }
7268
7269            N = pkg.activities.size();
7270            r = null;
7271            for (i=0; i<N; i++) {
7272                PackageParser.Activity a = pkg.activities.get(i);
7273                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7274                        a.info.processName, pkg.applicationInfo.uid);
7275                mActivities.addActivity(a, "activity");
7276                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7277                    if (r == null) {
7278                        r = new StringBuilder(256);
7279                    } else {
7280                        r.append(' ');
7281                    }
7282                    r.append(a.info.name);
7283                }
7284            }
7285            if (r != null) {
7286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7287            }
7288
7289            N = pkg.permissionGroups.size();
7290            r = null;
7291            for (i=0; i<N; i++) {
7292                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7293                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7294                if (cur == null) {
7295                    mPermissionGroups.put(pg.info.name, pg);
7296                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7297                        if (r == null) {
7298                            r = new StringBuilder(256);
7299                        } else {
7300                            r.append(' ');
7301                        }
7302                        r.append(pg.info.name);
7303                    }
7304                } else {
7305                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7306                            + pg.info.packageName + " ignored: original from "
7307                            + cur.info.packageName);
7308                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7309                        if (r == null) {
7310                            r = new StringBuilder(256);
7311                        } else {
7312                            r.append(' ');
7313                        }
7314                        r.append("DUP:");
7315                        r.append(pg.info.name);
7316                    }
7317                }
7318            }
7319            if (r != null) {
7320                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7321            }
7322
7323            N = pkg.permissions.size();
7324            r = null;
7325            for (i=0; i<N; i++) {
7326                PackageParser.Permission p = pkg.permissions.get(i);
7327
7328                // Assume by default that we did not install this permission into the system.
7329                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7330
7331                // Now that permission groups have a special meaning, we ignore permission
7332                // groups for legacy apps to prevent unexpected behavior. In particular,
7333                // permissions for one app being granted to someone just becuase they happen
7334                // to be in a group defined by another app (before this had no implications).
7335                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7336                    p.group = mPermissionGroups.get(p.info.group);
7337                    // Warn for a permission in an unknown group.
7338                    if (p.info.group != null && p.group == null) {
7339                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7340                                + p.info.packageName + " in an unknown group " + p.info.group);
7341                    }
7342                }
7343
7344                ArrayMap<String, BasePermission> permissionMap =
7345                        p.tree ? mSettings.mPermissionTrees
7346                                : mSettings.mPermissions;
7347                BasePermission bp = permissionMap.get(p.info.name);
7348
7349                // Allow system apps to redefine non-system permissions
7350                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7351                    final boolean currentOwnerIsSystem = (bp.perm != null
7352                            && isSystemApp(bp.perm.owner));
7353                    if (isSystemApp(p.owner)) {
7354                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7355                            // It's a built-in permission and no owner, take ownership now
7356                            bp.packageSetting = pkgSetting;
7357                            bp.perm = p;
7358                            bp.uid = pkg.applicationInfo.uid;
7359                            bp.sourcePackage = p.info.packageName;
7360                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7361                        } else if (!currentOwnerIsSystem) {
7362                            String msg = "New decl " + p.owner + " of permission  "
7363                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7364                            reportSettingsProblem(Log.WARN, msg);
7365                            bp = null;
7366                        }
7367                    }
7368                }
7369
7370                if (bp == null) {
7371                    bp = new BasePermission(p.info.name, p.info.packageName,
7372                            BasePermission.TYPE_NORMAL);
7373                    permissionMap.put(p.info.name, bp);
7374                }
7375
7376                if (bp.perm == null) {
7377                    if (bp.sourcePackage == null
7378                            || bp.sourcePackage.equals(p.info.packageName)) {
7379                        BasePermission tree = findPermissionTreeLP(p.info.name);
7380                        if (tree == null
7381                                || tree.sourcePackage.equals(p.info.packageName)) {
7382                            bp.packageSetting = pkgSetting;
7383                            bp.perm = p;
7384                            bp.uid = pkg.applicationInfo.uid;
7385                            bp.sourcePackage = p.info.packageName;
7386                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7387                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7388                                if (r == null) {
7389                                    r = new StringBuilder(256);
7390                                } else {
7391                                    r.append(' ');
7392                                }
7393                                r.append(p.info.name);
7394                            }
7395                        } else {
7396                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7397                                    + p.info.packageName + " ignored: base tree "
7398                                    + tree.name + " is from package "
7399                                    + tree.sourcePackage);
7400                        }
7401                    } else {
7402                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7403                                + p.info.packageName + " ignored: original from "
7404                                + bp.sourcePackage);
7405                    }
7406                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7407                    if (r == null) {
7408                        r = new StringBuilder(256);
7409                    } else {
7410                        r.append(' ');
7411                    }
7412                    r.append("DUP:");
7413                    r.append(p.info.name);
7414                }
7415                if (bp.perm == p) {
7416                    bp.protectionLevel = p.info.protectionLevel;
7417                }
7418            }
7419
7420            if (r != null) {
7421                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7422            }
7423
7424            N = pkg.instrumentation.size();
7425            r = null;
7426            for (i=0; i<N; i++) {
7427                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7428                a.info.packageName = pkg.applicationInfo.packageName;
7429                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7430                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7431                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7432                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7433                a.info.dataDir = pkg.applicationInfo.dataDir;
7434
7435                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7436                // need other information about the application, like the ABI and what not ?
7437                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7438                mInstrumentation.put(a.getComponentName(), a);
7439                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7440                    if (r == null) {
7441                        r = new StringBuilder(256);
7442                    } else {
7443                        r.append(' ');
7444                    }
7445                    r.append(a.info.name);
7446                }
7447            }
7448            if (r != null) {
7449                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7450            }
7451
7452            if (pkg.protectedBroadcasts != null) {
7453                N = pkg.protectedBroadcasts.size();
7454                for (i=0; i<N; i++) {
7455                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7456                }
7457            }
7458
7459            pkgSetting.setTimeStamp(scanFileTime);
7460
7461            // Create idmap files for pairs of (packages, overlay packages).
7462            // Note: "android", ie framework-res.apk, is handled by native layers.
7463            if (pkg.mOverlayTarget != null) {
7464                // This is an overlay package.
7465                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7466                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7467                        mOverlays.put(pkg.mOverlayTarget,
7468                                new ArrayMap<String, PackageParser.Package>());
7469                    }
7470                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7471                    map.put(pkg.packageName, pkg);
7472                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7473                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7474                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7475                                "scanPackageLI failed to createIdmap");
7476                    }
7477                }
7478            } else if (mOverlays.containsKey(pkg.packageName) &&
7479                    !pkg.packageName.equals("android")) {
7480                // This is a regular package, with one or more known overlay packages.
7481                createIdmapsForPackageLI(pkg);
7482            }
7483        }
7484
7485        return pkg;
7486    }
7487
7488    /**
7489     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7490     * is derived purely on the basis of the contents of {@code scanFile} and
7491     * {@code cpuAbiOverride}.
7492     *
7493     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7494     */
7495    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7496                                 String cpuAbiOverride, boolean extractLibs)
7497            throws PackageManagerException {
7498        // TODO: We can probably be smarter about this stuff. For installed apps,
7499        // we can calculate this information at install time once and for all. For
7500        // system apps, we can probably assume that this information doesn't change
7501        // after the first boot scan. As things stand, we do lots of unnecessary work.
7502
7503        // Give ourselves some initial paths; we'll come back for another
7504        // pass once we've determined ABI below.
7505        setNativeLibraryPaths(pkg);
7506
7507        // We would never need to extract libs for forward-locked and external packages,
7508        // since the container service will do it for us. We shouldn't attempt to
7509        // extract libs from system app when it was not updated.
7510        if (pkg.isForwardLocked() || isExternal(pkg) ||
7511            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7512            extractLibs = false;
7513        }
7514
7515        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7516        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7517
7518        NativeLibraryHelper.Handle handle = null;
7519        try {
7520            handle = NativeLibraryHelper.Handle.create(scanFile);
7521            // TODO(multiArch): This can be null for apps that didn't go through the
7522            // usual installation process. We can calculate it again, like we
7523            // do during install time.
7524            //
7525            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7526            // unnecessary.
7527            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7528
7529            // Null out the abis so that they can be recalculated.
7530            pkg.applicationInfo.primaryCpuAbi = null;
7531            pkg.applicationInfo.secondaryCpuAbi = null;
7532            if (isMultiArch(pkg.applicationInfo)) {
7533                // Warn if we've set an abiOverride for multi-lib packages..
7534                // By definition, we need to copy both 32 and 64 bit libraries for
7535                // such packages.
7536                if (pkg.cpuAbiOverride != null
7537                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7538                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7539                }
7540
7541                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7542                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7543                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7544                    if (extractLibs) {
7545                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7546                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7547                                useIsaSpecificSubdirs);
7548                    } else {
7549                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7550                    }
7551                }
7552
7553                maybeThrowExceptionForMultiArchCopy(
7554                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7555
7556                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7557                    if (extractLibs) {
7558                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7559                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7560                                useIsaSpecificSubdirs);
7561                    } else {
7562                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7563                    }
7564                }
7565
7566                maybeThrowExceptionForMultiArchCopy(
7567                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7568
7569                if (abi64 >= 0) {
7570                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7571                }
7572
7573                if (abi32 >= 0) {
7574                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7575                    if (abi64 >= 0) {
7576                        pkg.applicationInfo.secondaryCpuAbi = abi;
7577                    } else {
7578                        pkg.applicationInfo.primaryCpuAbi = abi;
7579                    }
7580                }
7581            } else {
7582                String[] abiList = (cpuAbiOverride != null) ?
7583                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7584
7585                // Enable gross and lame hacks for apps that are built with old
7586                // SDK tools. We must scan their APKs for renderscript bitcode and
7587                // not launch them if it's present. Don't bother checking on devices
7588                // that don't have 64 bit support.
7589                boolean needsRenderScriptOverride = false;
7590                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7591                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7592                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7593                    needsRenderScriptOverride = true;
7594                }
7595
7596                final int copyRet;
7597                if (extractLibs) {
7598                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7599                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7600                } else {
7601                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7602                }
7603
7604                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7605                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7606                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7607                }
7608
7609                if (copyRet >= 0) {
7610                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7611                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7612                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7613                } else if (needsRenderScriptOverride) {
7614                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7615                }
7616            }
7617        } catch (IOException ioe) {
7618            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7619        } finally {
7620            IoUtils.closeQuietly(handle);
7621        }
7622
7623        // Now that we've calculated the ABIs and determined if it's an internal app,
7624        // we will go ahead and populate the nativeLibraryPath.
7625        setNativeLibraryPaths(pkg);
7626    }
7627
7628    /**
7629     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7630     * i.e, so that all packages can be run inside a single process if required.
7631     *
7632     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7633     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7634     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7635     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7636     * updating a package that belongs to a shared user.
7637     *
7638     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7639     * adds unnecessary complexity.
7640     */
7641    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7642            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7643        String requiredInstructionSet = null;
7644        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7645            requiredInstructionSet = VMRuntime.getInstructionSet(
7646                     scannedPackage.applicationInfo.primaryCpuAbi);
7647        }
7648
7649        PackageSetting requirer = null;
7650        for (PackageSetting ps : packagesForUser) {
7651            // If packagesForUser contains scannedPackage, we skip it. This will happen
7652            // when scannedPackage is an update of an existing package. Without this check,
7653            // we will never be able to change the ABI of any package belonging to a shared
7654            // user, even if it's compatible with other packages.
7655            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7656                if (ps.primaryCpuAbiString == null) {
7657                    continue;
7658                }
7659
7660                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7661                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7662                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7663                    // this but there's not much we can do.
7664                    String errorMessage = "Instruction set mismatch, "
7665                            + ((requirer == null) ? "[caller]" : requirer)
7666                            + " requires " + requiredInstructionSet + " whereas " + ps
7667                            + " requires " + instructionSet;
7668                    Slog.w(TAG, errorMessage);
7669                }
7670
7671                if (requiredInstructionSet == null) {
7672                    requiredInstructionSet = instructionSet;
7673                    requirer = ps;
7674                }
7675            }
7676        }
7677
7678        if (requiredInstructionSet != null) {
7679            String adjustedAbi;
7680            if (requirer != null) {
7681                // requirer != null implies that either scannedPackage was null or that scannedPackage
7682                // did not require an ABI, in which case we have to adjust scannedPackage to match
7683                // the ABI of the set (which is the same as requirer's ABI)
7684                adjustedAbi = requirer.primaryCpuAbiString;
7685                if (scannedPackage != null) {
7686                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7687                }
7688            } else {
7689                // requirer == null implies that we're updating all ABIs in the set to
7690                // match scannedPackage.
7691                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7692            }
7693
7694            for (PackageSetting ps : packagesForUser) {
7695                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7696                    if (ps.primaryCpuAbiString != null) {
7697                        continue;
7698                    }
7699
7700                    ps.primaryCpuAbiString = adjustedAbi;
7701                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7702                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7703                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7704
7705                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7706                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7707                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7708                            ps.primaryCpuAbiString = null;
7709                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7710                            return;
7711                        } else {
7712                            mInstaller.rmdex(ps.codePathString,
7713                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7714                        }
7715                    }
7716                }
7717            }
7718        }
7719    }
7720
7721    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7722        synchronized (mPackages) {
7723            mResolverReplaced = true;
7724            // Set up information for custom user intent resolution activity.
7725            mResolveActivity.applicationInfo = pkg.applicationInfo;
7726            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7727            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7728            mResolveActivity.processName = pkg.applicationInfo.packageName;
7729            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7730            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7731                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7732            mResolveActivity.theme = 0;
7733            mResolveActivity.exported = true;
7734            mResolveActivity.enabled = true;
7735            mResolveInfo.activityInfo = mResolveActivity;
7736            mResolveInfo.priority = 0;
7737            mResolveInfo.preferredOrder = 0;
7738            mResolveInfo.match = 0;
7739            mResolveComponentName = mCustomResolverComponentName;
7740            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7741                    mResolveComponentName);
7742        }
7743    }
7744
7745    private static String calculateBundledApkRoot(final String codePathString) {
7746        final File codePath = new File(codePathString);
7747        final File codeRoot;
7748        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7749            codeRoot = Environment.getRootDirectory();
7750        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7751            codeRoot = Environment.getOemDirectory();
7752        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7753            codeRoot = Environment.getVendorDirectory();
7754        } else {
7755            // Unrecognized code path; take its top real segment as the apk root:
7756            // e.g. /something/app/blah.apk => /something
7757            try {
7758                File f = codePath.getCanonicalFile();
7759                File parent = f.getParentFile();    // non-null because codePath is a file
7760                File tmp;
7761                while ((tmp = parent.getParentFile()) != null) {
7762                    f = parent;
7763                    parent = tmp;
7764                }
7765                codeRoot = f;
7766                Slog.w(TAG, "Unrecognized code path "
7767                        + codePath + " - using " + codeRoot);
7768            } catch (IOException e) {
7769                // Can't canonicalize the code path -- shenanigans?
7770                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7771                return Environment.getRootDirectory().getPath();
7772            }
7773        }
7774        return codeRoot.getPath();
7775    }
7776
7777    /**
7778     * Derive and set the location of native libraries for the given package,
7779     * which varies depending on where and how the package was installed.
7780     */
7781    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7782        final ApplicationInfo info = pkg.applicationInfo;
7783        final String codePath = pkg.codePath;
7784        final File codeFile = new File(codePath);
7785        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7786        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7787
7788        info.nativeLibraryRootDir = null;
7789        info.nativeLibraryRootRequiresIsa = false;
7790        info.nativeLibraryDir = null;
7791        info.secondaryNativeLibraryDir = null;
7792
7793        if (isApkFile(codeFile)) {
7794            // Monolithic install
7795            if (bundledApp) {
7796                // If "/system/lib64/apkname" exists, assume that is the per-package
7797                // native library directory to use; otherwise use "/system/lib/apkname".
7798                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7799                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7800                        getPrimaryInstructionSet(info));
7801
7802                // This is a bundled system app so choose the path based on the ABI.
7803                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7804                // is just the default path.
7805                final String apkName = deriveCodePathName(codePath);
7806                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7807                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7808                        apkName).getAbsolutePath();
7809
7810                if (info.secondaryCpuAbi != null) {
7811                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7812                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7813                            secondaryLibDir, apkName).getAbsolutePath();
7814                }
7815            } else if (asecApp) {
7816                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7817                        .getAbsolutePath();
7818            } else {
7819                final String apkName = deriveCodePathName(codePath);
7820                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7821                        .getAbsolutePath();
7822            }
7823
7824            info.nativeLibraryRootRequiresIsa = false;
7825            info.nativeLibraryDir = info.nativeLibraryRootDir;
7826        } else {
7827            // Cluster install
7828            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7829            info.nativeLibraryRootRequiresIsa = true;
7830
7831            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7832                    getPrimaryInstructionSet(info)).getAbsolutePath();
7833
7834            if (info.secondaryCpuAbi != null) {
7835                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7836                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7837            }
7838        }
7839    }
7840
7841    /**
7842     * Calculate the abis and roots for a bundled app. These can uniquely
7843     * be determined from the contents of the system partition, i.e whether
7844     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7845     * of this information, and instead assume that the system was built
7846     * sensibly.
7847     */
7848    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7849                                           PackageSetting pkgSetting) {
7850        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7851
7852        // If "/system/lib64/apkname" exists, assume that is the per-package
7853        // native library directory to use; otherwise use "/system/lib/apkname".
7854        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7855        setBundledAppAbi(pkg, apkRoot, apkName);
7856        // pkgSetting might be null during rescan following uninstall of updates
7857        // to a bundled app, so accommodate that possibility.  The settings in
7858        // that case will be established later from the parsed package.
7859        //
7860        // If the settings aren't null, sync them up with what we've just derived.
7861        // note that apkRoot isn't stored in the package settings.
7862        if (pkgSetting != null) {
7863            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7864            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7865        }
7866    }
7867
7868    /**
7869     * Deduces the ABI of a bundled app and sets the relevant fields on the
7870     * parsed pkg object.
7871     *
7872     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7873     *        under which system libraries are installed.
7874     * @param apkName the name of the installed package.
7875     */
7876    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7877        final File codeFile = new File(pkg.codePath);
7878
7879        final boolean has64BitLibs;
7880        final boolean has32BitLibs;
7881        if (isApkFile(codeFile)) {
7882            // Monolithic install
7883            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7884            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7885        } else {
7886            // Cluster install
7887            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7888            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7889                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7890                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7891                has64BitLibs = (new File(rootDir, isa)).exists();
7892            } else {
7893                has64BitLibs = false;
7894            }
7895            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7896                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7897                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7898                has32BitLibs = (new File(rootDir, isa)).exists();
7899            } else {
7900                has32BitLibs = false;
7901            }
7902        }
7903
7904        if (has64BitLibs && !has32BitLibs) {
7905            // The package has 64 bit libs, but not 32 bit libs. Its primary
7906            // ABI should be 64 bit. We can safely assume here that the bundled
7907            // native libraries correspond to the most preferred ABI in the list.
7908
7909            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7910            pkg.applicationInfo.secondaryCpuAbi = null;
7911        } else if (has32BitLibs && !has64BitLibs) {
7912            // The package has 32 bit libs but not 64 bit libs. Its primary
7913            // ABI should be 32 bit.
7914
7915            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7916            pkg.applicationInfo.secondaryCpuAbi = null;
7917        } else if (has32BitLibs && has64BitLibs) {
7918            // The application has both 64 and 32 bit bundled libraries. We check
7919            // here that the app declares multiArch support, and warn if it doesn't.
7920            //
7921            // We will be lenient here and record both ABIs. The primary will be the
7922            // ABI that's higher on the list, i.e, a device that's configured to prefer
7923            // 64 bit apps will see a 64 bit primary ABI,
7924
7925            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7926                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7927            }
7928
7929            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7930                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7931                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7932            } else {
7933                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7934                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7935            }
7936        } else {
7937            pkg.applicationInfo.primaryCpuAbi = null;
7938            pkg.applicationInfo.secondaryCpuAbi = null;
7939        }
7940    }
7941
7942    private void killApplication(String pkgName, int appId, String reason) {
7943        // Request the ActivityManager to kill the process(only for existing packages)
7944        // so that we do not end up in a confused state while the user is still using the older
7945        // version of the application while the new one gets installed.
7946        IActivityManager am = ActivityManagerNative.getDefault();
7947        if (am != null) {
7948            try {
7949                am.killApplicationWithAppId(pkgName, appId, reason);
7950            } catch (RemoteException e) {
7951            }
7952        }
7953    }
7954
7955    void removePackageLI(PackageSetting ps, boolean chatty) {
7956        if (DEBUG_INSTALL) {
7957            if (chatty)
7958                Log.d(TAG, "Removing package " + ps.name);
7959        }
7960
7961        // writer
7962        synchronized (mPackages) {
7963            mPackages.remove(ps.name);
7964            final PackageParser.Package pkg = ps.pkg;
7965            if (pkg != null) {
7966                cleanPackageDataStructuresLILPw(pkg, chatty);
7967            }
7968        }
7969    }
7970
7971    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7972        if (DEBUG_INSTALL) {
7973            if (chatty)
7974                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7975        }
7976
7977        // writer
7978        synchronized (mPackages) {
7979            mPackages.remove(pkg.applicationInfo.packageName);
7980            cleanPackageDataStructuresLILPw(pkg, chatty);
7981        }
7982    }
7983
7984    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7985        int N = pkg.providers.size();
7986        StringBuilder r = null;
7987        int i;
7988        for (i=0; i<N; i++) {
7989            PackageParser.Provider p = pkg.providers.get(i);
7990            mProviders.removeProvider(p);
7991            if (p.info.authority == null) {
7992
7993                /* There was another ContentProvider with this authority when
7994                 * this app was installed so this authority is null,
7995                 * Ignore it as we don't have to unregister the provider.
7996                 */
7997                continue;
7998            }
7999            String names[] = p.info.authority.split(";");
8000            for (int j = 0; j < names.length; j++) {
8001                if (mProvidersByAuthority.get(names[j]) == p) {
8002                    mProvidersByAuthority.remove(names[j]);
8003                    if (DEBUG_REMOVE) {
8004                        if (chatty)
8005                            Log.d(TAG, "Unregistered content provider: " + names[j]
8006                                    + ", className = " + p.info.name + ", isSyncable = "
8007                                    + p.info.isSyncable);
8008                    }
8009                }
8010            }
8011            if (DEBUG_REMOVE && chatty) {
8012                if (r == null) {
8013                    r = new StringBuilder(256);
8014                } else {
8015                    r.append(' ');
8016                }
8017                r.append(p.info.name);
8018            }
8019        }
8020        if (r != null) {
8021            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8022        }
8023
8024        N = pkg.services.size();
8025        r = null;
8026        for (i=0; i<N; i++) {
8027            PackageParser.Service s = pkg.services.get(i);
8028            mServices.removeService(s);
8029            if (chatty) {
8030                if (r == null) {
8031                    r = new StringBuilder(256);
8032                } else {
8033                    r.append(' ');
8034                }
8035                r.append(s.info.name);
8036            }
8037        }
8038        if (r != null) {
8039            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8040        }
8041
8042        N = pkg.receivers.size();
8043        r = null;
8044        for (i=0; i<N; i++) {
8045            PackageParser.Activity a = pkg.receivers.get(i);
8046            mReceivers.removeActivity(a, "receiver");
8047            if (DEBUG_REMOVE && chatty) {
8048                if (r == null) {
8049                    r = new StringBuilder(256);
8050                } else {
8051                    r.append(' ');
8052                }
8053                r.append(a.info.name);
8054            }
8055        }
8056        if (r != null) {
8057            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8058        }
8059
8060        N = pkg.activities.size();
8061        r = null;
8062        for (i=0; i<N; i++) {
8063            PackageParser.Activity a = pkg.activities.get(i);
8064            mActivities.removeActivity(a, "activity");
8065            if (DEBUG_REMOVE && chatty) {
8066                if (r == null) {
8067                    r = new StringBuilder(256);
8068                } else {
8069                    r.append(' ');
8070                }
8071                r.append(a.info.name);
8072            }
8073        }
8074        if (r != null) {
8075            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8076        }
8077
8078        N = pkg.permissions.size();
8079        r = null;
8080        for (i=0; i<N; i++) {
8081            PackageParser.Permission p = pkg.permissions.get(i);
8082            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8083            if (bp == null) {
8084                bp = mSettings.mPermissionTrees.get(p.info.name);
8085            }
8086            if (bp != null && bp.perm == p) {
8087                bp.perm = null;
8088                if (DEBUG_REMOVE && chatty) {
8089                    if (r == null) {
8090                        r = new StringBuilder(256);
8091                    } else {
8092                        r.append(' ');
8093                    }
8094                    r.append(p.info.name);
8095                }
8096            }
8097            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8098                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8099                if (appOpPerms != null) {
8100                    appOpPerms.remove(pkg.packageName);
8101                }
8102            }
8103        }
8104        if (r != null) {
8105            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8106        }
8107
8108        N = pkg.requestedPermissions.size();
8109        r = null;
8110        for (i=0; i<N; i++) {
8111            String perm = pkg.requestedPermissions.get(i);
8112            BasePermission bp = mSettings.mPermissions.get(perm);
8113            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8114                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8115                if (appOpPerms != null) {
8116                    appOpPerms.remove(pkg.packageName);
8117                    if (appOpPerms.isEmpty()) {
8118                        mAppOpPermissionPackages.remove(perm);
8119                    }
8120                }
8121            }
8122        }
8123        if (r != null) {
8124            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8125        }
8126
8127        N = pkg.instrumentation.size();
8128        r = null;
8129        for (i=0; i<N; i++) {
8130            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8131            mInstrumentation.remove(a.getComponentName());
8132            if (DEBUG_REMOVE && chatty) {
8133                if (r == null) {
8134                    r = new StringBuilder(256);
8135                } else {
8136                    r.append(' ');
8137                }
8138                r.append(a.info.name);
8139            }
8140        }
8141        if (r != null) {
8142            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8143        }
8144
8145        r = null;
8146        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8147            // Only system apps can hold shared libraries.
8148            if (pkg.libraryNames != null) {
8149                for (i=0; i<pkg.libraryNames.size(); i++) {
8150                    String name = pkg.libraryNames.get(i);
8151                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8152                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8153                        mSharedLibraries.remove(name);
8154                        if (DEBUG_REMOVE && chatty) {
8155                            if (r == null) {
8156                                r = new StringBuilder(256);
8157                            } else {
8158                                r.append(' ');
8159                            }
8160                            r.append(name);
8161                        }
8162                    }
8163                }
8164            }
8165        }
8166        if (r != null) {
8167            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8168        }
8169    }
8170
8171    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8172        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8173            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8174                return true;
8175            }
8176        }
8177        return false;
8178    }
8179
8180    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8181    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8182    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8183
8184    private void updatePermissionsLPw(String changingPkg,
8185            PackageParser.Package pkgInfo, int flags) {
8186        // Make sure there are no dangling permission trees.
8187        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8188        while (it.hasNext()) {
8189            final BasePermission bp = it.next();
8190            if (bp.packageSetting == null) {
8191                // We may not yet have parsed the package, so just see if
8192                // we still know about its settings.
8193                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8194            }
8195            if (bp.packageSetting == null) {
8196                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8197                        + " from package " + bp.sourcePackage);
8198                it.remove();
8199            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8200                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8201                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8202                            + " from package " + bp.sourcePackage);
8203                    flags |= UPDATE_PERMISSIONS_ALL;
8204                    it.remove();
8205                }
8206            }
8207        }
8208
8209        // Make sure all dynamic permissions have been assigned to a package,
8210        // and make sure there are no dangling permissions.
8211        it = mSettings.mPermissions.values().iterator();
8212        while (it.hasNext()) {
8213            final BasePermission bp = it.next();
8214            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8215                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8216                        + bp.name + " pkg=" + bp.sourcePackage
8217                        + " info=" + bp.pendingInfo);
8218                if (bp.packageSetting == null && bp.pendingInfo != null) {
8219                    final BasePermission tree = findPermissionTreeLP(bp.name);
8220                    if (tree != null && tree.perm != null) {
8221                        bp.packageSetting = tree.packageSetting;
8222                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8223                                new PermissionInfo(bp.pendingInfo));
8224                        bp.perm.info.packageName = tree.perm.info.packageName;
8225                        bp.perm.info.name = bp.name;
8226                        bp.uid = tree.uid;
8227                    }
8228                }
8229            }
8230            if (bp.packageSetting == null) {
8231                // We may not yet have parsed the package, so just see if
8232                // we still know about its settings.
8233                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8234            }
8235            if (bp.packageSetting == null) {
8236                Slog.w(TAG, "Removing dangling permission: " + bp.name
8237                        + " from package " + bp.sourcePackage);
8238                it.remove();
8239            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8240                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8241                    Slog.i(TAG, "Removing old permission: " + bp.name
8242                            + " from package " + bp.sourcePackage);
8243                    flags |= UPDATE_PERMISSIONS_ALL;
8244                    it.remove();
8245                }
8246            }
8247        }
8248
8249        // Now update the permissions for all packages, in particular
8250        // replace the granted permissions of the system packages.
8251        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8252            for (PackageParser.Package pkg : mPackages.values()) {
8253                if (pkg != pkgInfo) {
8254                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8255                            changingPkg);
8256                }
8257            }
8258        }
8259
8260        if (pkgInfo != null) {
8261            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8262        }
8263    }
8264
8265    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8266            String packageOfInterest) {
8267        // IMPORTANT: There are two types of permissions: install and runtime.
8268        // Install time permissions are granted when the app is installed to
8269        // all device users and users added in the future. Runtime permissions
8270        // are granted at runtime explicitly to specific users. Normal and signature
8271        // protected permissions are install time permissions. Dangerous permissions
8272        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8273        // otherwise they are runtime permissions. This function does not manage
8274        // runtime permissions except for the case an app targeting Lollipop MR1
8275        // being upgraded to target a newer SDK, in which case dangerous permissions
8276        // are transformed from install time to runtime ones.
8277
8278        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8279        if (ps == null) {
8280            return;
8281        }
8282
8283        PermissionsState permissionsState = ps.getPermissionsState();
8284        PermissionsState origPermissions = permissionsState;
8285
8286        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8287
8288        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8289
8290        boolean changedInstallPermission = false;
8291
8292        if (replace) {
8293            ps.installPermissionsFixed = false;
8294            if (!ps.isSharedUser()) {
8295                origPermissions = new PermissionsState(permissionsState);
8296                permissionsState.reset();
8297            }
8298        }
8299
8300        permissionsState.setGlobalGids(mGlobalGids);
8301
8302        final int N = pkg.requestedPermissions.size();
8303        for (int i=0; i<N; i++) {
8304            final String name = pkg.requestedPermissions.get(i);
8305            final BasePermission bp = mSettings.mPermissions.get(name);
8306
8307            if (DEBUG_INSTALL) {
8308                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8309            }
8310
8311            if (bp == null || bp.packageSetting == null) {
8312                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8313                    Slog.w(TAG, "Unknown permission " + name
8314                            + " in package " + pkg.packageName);
8315                }
8316                continue;
8317            }
8318
8319            final String perm = bp.name;
8320            boolean allowedSig = false;
8321            int grant = GRANT_DENIED;
8322
8323            // Keep track of app op permissions.
8324            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8325                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8326                if (pkgs == null) {
8327                    pkgs = new ArraySet<>();
8328                    mAppOpPermissionPackages.put(bp.name, pkgs);
8329                }
8330                pkgs.add(pkg.packageName);
8331            }
8332
8333            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8334            switch (level) {
8335                case PermissionInfo.PROTECTION_NORMAL: {
8336                    // For all apps normal permissions are install time ones.
8337                    grant = GRANT_INSTALL;
8338                } break;
8339
8340                case PermissionInfo.PROTECTION_DANGEROUS: {
8341                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8342                        // For legacy apps dangerous permissions are install time ones.
8343                        grant = GRANT_INSTALL_LEGACY;
8344                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8345                        // For legacy apps that became modern, install becomes runtime.
8346                        grant = GRANT_UPGRADE;
8347                    } else {
8348                        // For modern apps keep runtime permissions unchanged.
8349                        grant = GRANT_RUNTIME;
8350                    }
8351                } break;
8352
8353                case PermissionInfo.PROTECTION_SIGNATURE: {
8354                    // For all apps signature permissions are install time ones.
8355                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8356                    if (allowedSig) {
8357                        grant = GRANT_INSTALL;
8358                    }
8359                } break;
8360            }
8361
8362            if (DEBUG_INSTALL) {
8363                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8364            }
8365
8366            if (grant != GRANT_DENIED) {
8367                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8368                    // If this is an existing, non-system package, then
8369                    // we can't add any new permissions to it.
8370                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8371                        // Except...  if this is a permission that was added
8372                        // to the platform (note: need to only do this when
8373                        // updating the platform).
8374                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8375                            grant = GRANT_DENIED;
8376                        }
8377                    }
8378                }
8379
8380                switch (grant) {
8381                    case GRANT_INSTALL: {
8382                        // Revoke this as runtime permission to handle the case of
8383                        // a runtime permission being downgraded to an install one.
8384                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8385                            if (origPermissions.getRuntimePermissionState(
8386                                    bp.name, userId) != null) {
8387                                // Revoke the runtime permission and clear the flags.
8388                                origPermissions.revokeRuntimePermission(bp, userId);
8389                                origPermissions.updatePermissionFlags(bp, userId,
8390                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8391                                // If we revoked a permission permission, we have to write.
8392                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8393                                        changedRuntimePermissionUserIds, userId);
8394                            }
8395                        }
8396                        // Grant an install permission.
8397                        if (permissionsState.grantInstallPermission(bp) !=
8398                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8399                            changedInstallPermission = true;
8400                        }
8401                    } break;
8402
8403                    case GRANT_INSTALL_LEGACY: {
8404                        // Grant an install permission.
8405                        if (permissionsState.grantInstallPermission(bp) !=
8406                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8407                            changedInstallPermission = true;
8408                        }
8409                    } break;
8410
8411                    case GRANT_RUNTIME: {
8412                        // Grant previously granted runtime permissions.
8413                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8414                            PermissionState permissionState = origPermissions
8415                                    .getRuntimePermissionState(bp.name, userId);
8416                            final int flags = permissionState != null
8417                                    ? permissionState.getFlags() : 0;
8418                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8419                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8420                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8421                                    // If we cannot put the permission as it was, we have to write.
8422                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8423                                            changedRuntimePermissionUserIds, userId);
8424                                }
8425                            }
8426                            // Propagate the permission flags.
8427                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8428                        }
8429                    } break;
8430
8431                    case GRANT_UPGRADE: {
8432                        // Grant runtime permissions for a previously held install permission.
8433                        PermissionState permissionState = origPermissions
8434                                .getInstallPermissionState(bp.name);
8435                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8436
8437                        if (origPermissions.revokeInstallPermission(bp)
8438                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8439                            // We will be transferring the permission flags, so clear them.
8440                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8441                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8442                            changedInstallPermission = true;
8443                        }
8444
8445                        // If the permission is not to be promoted to runtime we ignore it and
8446                        // also its other flags as they are not applicable to install permissions.
8447                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8448                            for (int userId : currentUserIds) {
8449                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8450                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8451                                    // Transfer the permission flags.
8452                                    permissionsState.updatePermissionFlags(bp, userId,
8453                                            flags, flags);
8454                                    // If we granted the permission, we have to write.
8455                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8456                                            changedRuntimePermissionUserIds, userId);
8457                                }
8458                            }
8459                        }
8460                    } break;
8461
8462                    default: {
8463                        if (packageOfInterest == null
8464                                || packageOfInterest.equals(pkg.packageName)) {
8465                            Slog.w(TAG, "Not granting permission " + perm
8466                                    + " to package " + pkg.packageName
8467                                    + " because it was previously installed without");
8468                        }
8469                    } break;
8470                }
8471            } else {
8472                if (permissionsState.revokeInstallPermission(bp) !=
8473                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8474                    // Also drop the permission flags.
8475                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8476                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8477                    changedInstallPermission = true;
8478                    Slog.i(TAG, "Un-granting permission " + perm
8479                            + " from package " + pkg.packageName
8480                            + " (protectionLevel=" + bp.protectionLevel
8481                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8482                            + ")");
8483                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8484                    // Don't print warning for app op permissions, since it is fine for them
8485                    // not to be granted, there is a UI for the user to decide.
8486                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8487                        Slog.w(TAG, "Not granting permission " + perm
8488                                + " to package " + pkg.packageName
8489                                + " (protectionLevel=" + bp.protectionLevel
8490                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8491                                + ")");
8492                    }
8493                }
8494            }
8495        }
8496
8497        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8498                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8499            // This is the first that we have heard about this package, so the
8500            // permissions we have now selected are fixed until explicitly
8501            // changed.
8502            ps.installPermissionsFixed = true;
8503        }
8504
8505        // Persist the runtime permissions state for users with changes.
8506        for (int userId : changedRuntimePermissionUserIds) {
8507            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8508        }
8509    }
8510
8511    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8512        boolean allowed = false;
8513        final int NP = PackageParser.NEW_PERMISSIONS.length;
8514        for (int ip=0; ip<NP; ip++) {
8515            final PackageParser.NewPermissionInfo npi
8516                    = PackageParser.NEW_PERMISSIONS[ip];
8517            if (npi.name.equals(perm)
8518                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8519                allowed = true;
8520                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8521                        + pkg.packageName);
8522                break;
8523            }
8524        }
8525        return allowed;
8526    }
8527
8528    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8529            BasePermission bp, PermissionsState origPermissions) {
8530        boolean allowed;
8531        allowed = (compareSignatures(
8532                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8533                        == PackageManager.SIGNATURE_MATCH)
8534                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8535                        == PackageManager.SIGNATURE_MATCH);
8536        if (!allowed && (bp.protectionLevel
8537                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8538            if (isSystemApp(pkg)) {
8539                // For updated system applications, a system permission
8540                // is granted only if it had been defined by the original application.
8541                if (pkg.isUpdatedSystemApp()) {
8542                    final PackageSetting sysPs = mSettings
8543                            .getDisabledSystemPkgLPr(pkg.packageName);
8544                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8545                        // If the original was granted this permission, we take
8546                        // that grant decision as read and propagate it to the
8547                        // update.
8548                        if (sysPs.isPrivileged()) {
8549                            allowed = true;
8550                        }
8551                    } else {
8552                        // The system apk may have been updated with an older
8553                        // version of the one on the data partition, but which
8554                        // granted a new system permission that it didn't have
8555                        // before.  In this case we do want to allow the app to
8556                        // now get the new permission if the ancestral apk is
8557                        // privileged to get it.
8558                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8559                            for (int j=0;
8560                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8561                                if (perm.equals(
8562                                        sysPs.pkg.requestedPermissions.get(j))) {
8563                                    allowed = true;
8564                                    break;
8565                                }
8566                            }
8567                        }
8568                    }
8569                } else {
8570                    allowed = isPrivilegedApp(pkg);
8571                }
8572            }
8573        }
8574        if (!allowed) {
8575            if (!allowed && (bp.protectionLevel
8576                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8577                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8578                // If this was a previously normal/dangerous permission that got moved
8579                // to a system permission as part of the runtime permission redesign, then
8580                // we still want to blindly grant it to old apps.
8581                allowed = true;
8582            }
8583            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8584                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8585                // If this permission is to be granted to the system installer and
8586                // this app is an installer, then it gets the permission.
8587                allowed = true;
8588            }
8589            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8590                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8591                // If this permission is to be granted to the system verifier and
8592                // this app is a verifier, then it gets the permission.
8593                allowed = true;
8594            }
8595            if (!allowed && (bp.protectionLevel
8596                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8597                    && isSystemApp(pkg)) {
8598                // Any pre-installed system app is allowed to get this permission.
8599                allowed = true;
8600            }
8601            if (!allowed && (bp.protectionLevel
8602                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8603                // For development permissions, a development permission
8604                // is granted only if it was already granted.
8605                allowed = origPermissions.hasInstallPermission(perm);
8606            }
8607        }
8608        return allowed;
8609    }
8610
8611    final class ActivityIntentResolver
8612            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8613        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8614                boolean defaultOnly, int userId) {
8615            if (!sUserManager.exists(userId)) return null;
8616            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8617            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8618        }
8619
8620        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8621                int userId) {
8622            if (!sUserManager.exists(userId)) return null;
8623            mFlags = flags;
8624            return super.queryIntent(intent, resolvedType,
8625                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8626        }
8627
8628        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8629                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8630            if (!sUserManager.exists(userId)) return null;
8631            if (packageActivities == null) {
8632                return null;
8633            }
8634            mFlags = flags;
8635            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8636            final int N = packageActivities.size();
8637            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8638                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8639
8640            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8641            for (int i = 0; i < N; ++i) {
8642                intentFilters = packageActivities.get(i).intents;
8643                if (intentFilters != null && intentFilters.size() > 0) {
8644                    PackageParser.ActivityIntentInfo[] array =
8645                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8646                    intentFilters.toArray(array);
8647                    listCut.add(array);
8648                }
8649            }
8650            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8651        }
8652
8653        public final void addActivity(PackageParser.Activity a, String type) {
8654            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8655            mActivities.put(a.getComponentName(), a);
8656            if (DEBUG_SHOW_INFO)
8657                Log.v(
8658                TAG, "  " + type + " " +
8659                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8660            if (DEBUG_SHOW_INFO)
8661                Log.v(TAG, "    Class=" + a.info.name);
8662            final int NI = a.intents.size();
8663            for (int j=0; j<NI; j++) {
8664                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8665                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8666                    intent.setPriority(0);
8667                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8668                            + a.className + " with priority > 0, forcing to 0");
8669                }
8670                if (DEBUG_SHOW_INFO) {
8671                    Log.v(TAG, "    IntentFilter:");
8672                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8673                }
8674                if (!intent.debugCheck()) {
8675                    Log.w(TAG, "==> For Activity " + a.info.name);
8676                }
8677                addFilter(intent);
8678            }
8679        }
8680
8681        public final void removeActivity(PackageParser.Activity a, String type) {
8682            mActivities.remove(a.getComponentName());
8683            if (DEBUG_SHOW_INFO) {
8684                Log.v(TAG, "  " + type + " "
8685                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8686                                : a.info.name) + ":");
8687                Log.v(TAG, "    Class=" + a.info.name);
8688            }
8689            final int NI = a.intents.size();
8690            for (int j=0; j<NI; j++) {
8691                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8692                if (DEBUG_SHOW_INFO) {
8693                    Log.v(TAG, "    IntentFilter:");
8694                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8695                }
8696                removeFilter(intent);
8697            }
8698        }
8699
8700        @Override
8701        protected boolean allowFilterResult(
8702                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8703            ActivityInfo filterAi = filter.activity.info;
8704            for (int i=dest.size()-1; i>=0; i--) {
8705                ActivityInfo destAi = dest.get(i).activityInfo;
8706                if (destAi.name == filterAi.name
8707                        && destAi.packageName == filterAi.packageName) {
8708                    return false;
8709                }
8710            }
8711            return true;
8712        }
8713
8714        @Override
8715        protected ActivityIntentInfo[] newArray(int size) {
8716            return new ActivityIntentInfo[size];
8717        }
8718
8719        @Override
8720        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8721            if (!sUserManager.exists(userId)) return true;
8722            PackageParser.Package p = filter.activity.owner;
8723            if (p != null) {
8724                PackageSetting ps = (PackageSetting)p.mExtras;
8725                if (ps != null) {
8726                    // System apps are never considered stopped for purposes of
8727                    // filtering, because there may be no way for the user to
8728                    // actually re-launch them.
8729                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8730                            && ps.getStopped(userId);
8731                }
8732            }
8733            return false;
8734        }
8735
8736        @Override
8737        protected boolean isPackageForFilter(String packageName,
8738                PackageParser.ActivityIntentInfo info) {
8739            return packageName.equals(info.activity.owner.packageName);
8740        }
8741
8742        @Override
8743        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8744                int match, int userId) {
8745            if (!sUserManager.exists(userId)) return null;
8746            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8747                return null;
8748            }
8749            final PackageParser.Activity activity = info.activity;
8750            if (mSafeMode && (activity.info.applicationInfo.flags
8751                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8752                return null;
8753            }
8754            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8755            if (ps == null) {
8756                return null;
8757            }
8758            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8759                    ps.readUserState(userId), userId);
8760            if (ai == null) {
8761                return null;
8762            }
8763            final ResolveInfo res = new ResolveInfo();
8764            res.activityInfo = ai;
8765            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8766                res.filter = info;
8767            }
8768            if (info != null) {
8769                res.handleAllWebDataURI = info.handleAllWebDataURI();
8770            }
8771            res.priority = info.getPriority();
8772            res.preferredOrder = activity.owner.mPreferredOrder;
8773            //System.out.println("Result: " + res.activityInfo.className +
8774            //                   " = " + res.priority);
8775            res.match = match;
8776            res.isDefault = info.hasDefault;
8777            res.labelRes = info.labelRes;
8778            res.nonLocalizedLabel = info.nonLocalizedLabel;
8779            if (userNeedsBadging(userId)) {
8780                res.noResourceId = true;
8781            } else {
8782                res.icon = info.icon;
8783            }
8784            res.iconResourceId = info.icon;
8785            res.system = res.activityInfo.applicationInfo.isSystemApp();
8786            return res;
8787        }
8788
8789        @Override
8790        protected void sortResults(List<ResolveInfo> results) {
8791            Collections.sort(results, mResolvePrioritySorter);
8792        }
8793
8794        @Override
8795        protected void dumpFilter(PrintWriter out, String prefix,
8796                PackageParser.ActivityIntentInfo filter) {
8797            out.print(prefix); out.print(
8798                    Integer.toHexString(System.identityHashCode(filter.activity)));
8799                    out.print(' ');
8800                    filter.activity.printComponentShortName(out);
8801                    out.print(" filter ");
8802                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8803        }
8804
8805        @Override
8806        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8807            return filter.activity;
8808        }
8809
8810        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8811            PackageParser.Activity activity = (PackageParser.Activity)label;
8812            out.print(prefix); out.print(
8813                    Integer.toHexString(System.identityHashCode(activity)));
8814                    out.print(' ');
8815                    activity.printComponentShortName(out);
8816            if (count > 1) {
8817                out.print(" ("); out.print(count); out.print(" filters)");
8818            }
8819            out.println();
8820        }
8821
8822//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8823//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8824//            final List<ResolveInfo> retList = Lists.newArrayList();
8825//            while (i.hasNext()) {
8826//                final ResolveInfo resolveInfo = i.next();
8827//                if (isEnabledLP(resolveInfo.activityInfo)) {
8828//                    retList.add(resolveInfo);
8829//                }
8830//            }
8831//            return retList;
8832//        }
8833
8834        // Keys are String (activity class name), values are Activity.
8835        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8836                = new ArrayMap<ComponentName, PackageParser.Activity>();
8837        private int mFlags;
8838    }
8839
8840    private final class ServiceIntentResolver
8841            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8842        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8843                boolean defaultOnly, int userId) {
8844            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8845            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8846        }
8847
8848        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8849                int userId) {
8850            if (!sUserManager.exists(userId)) return null;
8851            mFlags = flags;
8852            return super.queryIntent(intent, resolvedType,
8853                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8854        }
8855
8856        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8857                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8858            if (!sUserManager.exists(userId)) return null;
8859            if (packageServices == null) {
8860                return null;
8861            }
8862            mFlags = flags;
8863            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8864            final int N = packageServices.size();
8865            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8866                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8867
8868            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8869            for (int i = 0; i < N; ++i) {
8870                intentFilters = packageServices.get(i).intents;
8871                if (intentFilters != null && intentFilters.size() > 0) {
8872                    PackageParser.ServiceIntentInfo[] array =
8873                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8874                    intentFilters.toArray(array);
8875                    listCut.add(array);
8876                }
8877            }
8878            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8879        }
8880
8881        public final void addService(PackageParser.Service s) {
8882            mServices.put(s.getComponentName(), s);
8883            if (DEBUG_SHOW_INFO) {
8884                Log.v(TAG, "  "
8885                        + (s.info.nonLocalizedLabel != null
8886                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8887                Log.v(TAG, "    Class=" + s.info.name);
8888            }
8889            final int NI = s.intents.size();
8890            int j;
8891            for (j=0; j<NI; j++) {
8892                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8893                if (DEBUG_SHOW_INFO) {
8894                    Log.v(TAG, "    IntentFilter:");
8895                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8896                }
8897                if (!intent.debugCheck()) {
8898                    Log.w(TAG, "==> For Service " + s.info.name);
8899                }
8900                addFilter(intent);
8901            }
8902        }
8903
8904        public final void removeService(PackageParser.Service s) {
8905            mServices.remove(s.getComponentName());
8906            if (DEBUG_SHOW_INFO) {
8907                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8908                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8909                Log.v(TAG, "    Class=" + s.info.name);
8910            }
8911            final int NI = s.intents.size();
8912            int j;
8913            for (j=0; j<NI; j++) {
8914                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8915                if (DEBUG_SHOW_INFO) {
8916                    Log.v(TAG, "    IntentFilter:");
8917                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8918                }
8919                removeFilter(intent);
8920            }
8921        }
8922
8923        @Override
8924        protected boolean allowFilterResult(
8925                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8926            ServiceInfo filterSi = filter.service.info;
8927            for (int i=dest.size()-1; i>=0; i--) {
8928                ServiceInfo destAi = dest.get(i).serviceInfo;
8929                if (destAi.name == filterSi.name
8930                        && destAi.packageName == filterSi.packageName) {
8931                    return false;
8932                }
8933            }
8934            return true;
8935        }
8936
8937        @Override
8938        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8939            return new PackageParser.ServiceIntentInfo[size];
8940        }
8941
8942        @Override
8943        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8944            if (!sUserManager.exists(userId)) return true;
8945            PackageParser.Package p = filter.service.owner;
8946            if (p != null) {
8947                PackageSetting ps = (PackageSetting)p.mExtras;
8948                if (ps != null) {
8949                    // System apps are never considered stopped for purposes of
8950                    // filtering, because there may be no way for the user to
8951                    // actually re-launch them.
8952                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8953                            && ps.getStopped(userId);
8954                }
8955            }
8956            return false;
8957        }
8958
8959        @Override
8960        protected boolean isPackageForFilter(String packageName,
8961                PackageParser.ServiceIntentInfo info) {
8962            return packageName.equals(info.service.owner.packageName);
8963        }
8964
8965        @Override
8966        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8967                int match, int userId) {
8968            if (!sUserManager.exists(userId)) return null;
8969            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8970            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8971                return null;
8972            }
8973            final PackageParser.Service service = info.service;
8974            if (mSafeMode && (service.info.applicationInfo.flags
8975                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8976                return null;
8977            }
8978            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8979            if (ps == null) {
8980                return null;
8981            }
8982            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8983                    ps.readUserState(userId), userId);
8984            if (si == null) {
8985                return null;
8986            }
8987            final ResolveInfo res = new ResolveInfo();
8988            res.serviceInfo = si;
8989            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8990                res.filter = filter;
8991            }
8992            res.priority = info.getPriority();
8993            res.preferredOrder = service.owner.mPreferredOrder;
8994            res.match = match;
8995            res.isDefault = info.hasDefault;
8996            res.labelRes = info.labelRes;
8997            res.nonLocalizedLabel = info.nonLocalizedLabel;
8998            res.icon = info.icon;
8999            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9000            return res;
9001        }
9002
9003        @Override
9004        protected void sortResults(List<ResolveInfo> results) {
9005            Collections.sort(results, mResolvePrioritySorter);
9006        }
9007
9008        @Override
9009        protected void dumpFilter(PrintWriter out, String prefix,
9010                PackageParser.ServiceIntentInfo filter) {
9011            out.print(prefix); out.print(
9012                    Integer.toHexString(System.identityHashCode(filter.service)));
9013                    out.print(' ');
9014                    filter.service.printComponentShortName(out);
9015                    out.print(" filter ");
9016                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9017        }
9018
9019        @Override
9020        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9021            return filter.service;
9022        }
9023
9024        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9025            PackageParser.Service service = (PackageParser.Service)label;
9026            out.print(prefix); out.print(
9027                    Integer.toHexString(System.identityHashCode(service)));
9028                    out.print(' ');
9029                    service.printComponentShortName(out);
9030            if (count > 1) {
9031                out.print(" ("); out.print(count); out.print(" filters)");
9032            }
9033            out.println();
9034        }
9035
9036//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9037//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9038//            final List<ResolveInfo> retList = Lists.newArrayList();
9039//            while (i.hasNext()) {
9040//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9041//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9042//                    retList.add(resolveInfo);
9043//                }
9044//            }
9045//            return retList;
9046//        }
9047
9048        // Keys are String (activity class name), values are Activity.
9049        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9050                = new ArrayMap<ComponentName, PackageParser.Service>();
9051        private int mFlags;
9052    };
9053
9054    private final class ProviderIntentResolver
9055            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9056        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9057                boolean defaultOnly, int userId) {
9058            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9059            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9060        }
9061
9062        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9063                int userId) {
9064            if (!sUserManager.exists(userId))
9065                return null;
9066            mFlags = flags;
9067            return super.queryIntent(intent, resolvedType,
9068                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9069        }
9070
9071        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9072                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9073            if (!sUserManager.exists(userId))
9074                return null;
9075            if (packageProviders == null) {
9076                return null;
9077            }
9078            mFlags = flags;
9079            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9080            final int N = packageProviders.size();
9081            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9082                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9083
9084            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9085            for (int i = 0; i < N; ++i) {
9086                intentFilters = packageProviders.get(i).intents;
9087                if (intentFilters != null && intentFilters.size() > 0) {
9088                    PackageParser.ProviderIntentInfo[] array =
9089                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9090                    intentFilters.toArray(array);
9091                    listCut.add(array);
9092                }
9093            }
9094            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9095        }
9096
9097        public final void addProvider(PackageParser.Provider p) {
9098            if (mProviders.containsKey(p.getComponentName())) {
9099                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9100                return;
9101            }
9102
9103            mProviders.put(p.getComponentName(), p);
9104            if (DEBUG_SHOW_INFO) {
9105                Log.v(TAG, "  "
9106                        + (p.info.nonLocalizedLabel != null
9107                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9108                Log.v(TAG, "    Class=" + p.info.name);
9109            }
9110            final int NI = p.intents.size();
9111            int j;
9112            for (j = 0; j < NI; j++) {
9113                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9114                if (DEBUG_SHOW_INFO) {
9115                    Log.v(TAG, "    IntentFilter:");
9116                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9117                }
9118                if (!intent.debugCheck()) {
9119                    Log.w(TAG, "==> For Provider " + p.info.name);
9120                }
9121                addFilter(intent);
9122            }
9123        }
9124
9125        public final void removeProvider(PackageParser.Provider p) {
9126            mProviders.remove(p.getComponentName());
9127            if (DEBUG_SHOW_INFO) {
9128                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9129                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9130                Log.v(TAG, "    Class=" + p.info.name);
9131            }
9132            final int NI = p.intents.size();
9133            int j;
9134            for (j = 0; j < NI; j++) {
9135                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9136                if (DEBUG_SHOW_INFO) {
9137                    Log.v(TAG, "    IntentFilter:");
9138                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9139                }
9140                removeFilter(intent);
9141            }
9142        }
9143
9144        @Override
9145        protected boolean allowFilterResult(
9146                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9147            ProviderInfo filterPi = filter.provider.info;
9148            for (int i = dest.size() - 1; i >= 0; i--) {
9149                ProviderInfo destPi = dest.get(i).providerInfo;
9150                if (destPi.name == filterPi.name
9151                        && destPi.packageName == filterPi.packageName) {
9152                    return false;
9153                }
9154            }
9155            return true;
9156        }
9157
9158        @Override
9159        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9160            return new PackageParser.ProviderIntentInfo[size];
9161        }
9162
9163        @Override
9164        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9165            if (!sUserManager.exists(userId))
9166                return true;
9167            PackageParser.Package p = filter.provider.owner;
9168            if (p != null) {
9169                PackageSetting ps = (PackageSetting) p.mExtras;
9170                if (ps != null) {
9171                    // System apps are never considered stopped for purposes of
9172                    // filtering, because there may be no way for the user to
9173                    // actually re-launch them.
9174                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9175                            && ps.getStopped(userId);
9176                }
9177            }
9178            return false;
9179        }
9180
9181        @Override
9182        protected boolean isPackageForFilter(String packageName,
9183                PackageParser.ProviderIntentInfo info) {
9184            return packageName.equals(info.provider.owner.packageName);
9185        }
9186
9187        @Override
9188        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9189                int match, int userId) {
9190            if (!sUserManager.exists(userId))
9191                return null;
9192            final PackageParser.ProviderIntentInfo info = filter;
9193            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9194                return null;
9195            }
9196            final PackageParser.Provider provider = info.provider;
9197            if (mSafeMode && (provider.info.applicationInfo.flags
9198                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9199                return null;
9200            }
9201            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9202            if (ps == null) {
9203                return null;
9204            }
9205            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9206                    ps.readUserState(userId), userId);
9207            if (pi == null) {
9208                return null;
9209            }
9210            final ResolveInfo res = new ResolveInfo();
9211            res.providerInfo = pi;
9212            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9213                res.filter = filter;
9214            }
9215            res.priority = info.getPriority();
9216            res.preferredOrder = provider.owner.mPreferredOrder;
9217            res.match = match;
9218            res.isDefault = info.hasDefault;
9219            res.labelRes = info.labelRes;
9220            res.nonLocalizedLabel = info.nonLocalizedLabel;
9221            res.icon = info.icon;
9222            res.system = res.providerInfo.applicationInfo.isSystemApp();
9223            return res;
9224        }
9225
9226        @Override
9227        protected void sortResults(List<ResolveInfo> results) {
9228            Collections.sort(results, mResolvePrioritySorter);
9229        }
9230
9231        @Override
9232        protected void dumpFilter(PrintWriter out, String prefix,
9233                PackageParser.ProviderIntentInfo filter) {
9234            out.print(prefix);
9235            out.print(
9236                    Integer.toHexString(System.identityHashCode(filter.provider)));
9237            out.print(' ');
9238            filter.provider.printComponentShortName(out);
9239            out.print(" filter ");
9240            out.println(Integer.toHexString(System.identityHashCode(filter)));
9241        }
9242
9243        @Override
9244        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9245            return filter.provider;
9246        }
9247
9248        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9249            PackageParser.Provider provider = (PackageParser.Provider)label;
9250            out.print(prefix); out.print(
9251                    Integer.toHexString(System.identityHashCode(provider)));
9252                    out.print(' ');
9253                    provider.printComponentShortName(out);
9254            if (count > 1) {
9255                out.print(" ("); out.print(count); out.print(" filters)");
9256            }
9257            out.println();
9258        }
9259
9260        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9261                = new ArrayMap<ComponentName, PackageParser.Provider>();
9262        private int mFlags;
9263    };
9264
9265    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9266            new Comparator<ResolveInfo>() {
9267        public int compare(ResolveInfo r1, ResolveInfo r2) {
9268            int v1 = r1.priority;
9269            int v2 = r2.priority;
9270            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9271            if (v1 != v2) {
9272                return (v1 > v2) ? -1 : 1;
9273            }
9274            v1 = r1.preferredOrder;
9275            v2 = r2.preferredOrder;
9276            if (v1 != v2) {
9277                return (v1 > v2) ? -1 : 1;
9278            }
9279            if (r1.isDefault != r2.isDefault) {
9280                return r1.isDefault ? -1 : 1;
9281            }
9282            v1 = r1.match;
9283            v2 = r2.match;
9284            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9285            if (v1 != v2) {
9286                return (v1 > v2) ? -1 : 1;
9287            }
9288            if (r1.system != r2.system) {
9289                return r1.system ? -1 : 1;
9290            }
9291            return 0;
9292        }
9293    };
9294
9295    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9296            new Comparator<ProviderInfo>() {
9297        public int compare(ProviderInfo p1, ProviderInfo p2) {
9298            final int v1 = p1.initOrder;
9299            final int v2 = p2.initOrder;
9300            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9301        }
9302    };
9303
9304    final void sendPackageBroadcast(final String action, final String pkg,
9305            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9306            final int[] userIds) {
9307        mHandler.post(new Runnable() {
9308            @Override
9309            public void run() {
9310                try {
9311                    final IActivityManager am = ActivityManagerNative.getDefault();
9312                    if (am == null) return;
9313                    final int[] resolvedUserIds;
9314                    if (userIds == null) {
9315                        resolvedUserIds = am.getRunningUserIds();
9316                    } else {
9317                        resolvedUserIds = userIds;
9318                    }
9319                    for (int id : resolvedUserIds) {
9320                        final Intent intent = new Intent(action,
9321                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9322                        if (extras != null) {
9323                            intent.putExtras(extras);
9324                        }
9325                        if (targetPkg != null) {
9326                            intent.setPackage(targetPkg);
9327                        }
9328                        // Modify the UID when posting to other users
9329                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9330                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9331                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9332                            intent.putExtra(Intent.EXTRA_UID, uid);
9333                        }
9334                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9335                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9336                        if (DEBUG_BROADCASTS) {
9337                            RuntimeException here = new RuntimeException("here");
9338                            here.fillInStackTrace();
9339                            Slog.d(TAG, "Sending to user " + id + ": "
9340                                    + intent.toShortString(false, true, false, false)
9341                                    + " " + intent.getExtras(), here);
9342                        }
9343                        am.broadcastIntent(null, intent, null, finishedReceiver,
9344                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9345                                null, finishedReceiver != null, false, id);
9346                    }
9347                } catch (RemoteException ex) {
9348                }
9349            }
9350        });
9351    }
9352
9353    /**
9354     * Check if the external storage media is available. This is true if there
9355     * is a mounted external storage medium or if the external storage is
9356     * emulated.
9357     */
9358    private boolean isExternalMediaAvailable() {
9359        return mMediaMounted || Environment.isExternalStorageEmulated();
9360    }
9361
9362    @Override
9363    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9364        // writer
9365        synchronized (mPackages) {
9366            if (!isExternalMediaAvailable()) {
9367                // If the external storage is no longer mounted at this point,
9368                // the caller may not have been able to delete all of this
9369                // packages files and can not delete any more.  Bail.
9370                return null;
9371            }
9372            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9373            if (lastPackage != null) {
9374                pkgs.remove(lastPackage);
9375            }
9376            if (pkgs.size() > 0) {
9377                return pkgs.get(0);
9378            }
9379        }
9380        return null;
9381    }
9382
9383    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9384        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9385                userId, andCode ? 1 : 0, packageName);
9386        if (mSystemReady) {
9387            msg.sendToTarget();
9388        } else {
9389            if (mPostSystemReadyMessages == null) {
9390                mPostSystemReadyMessages = new ArrayList<>();
9391            }
9392            mPostSystemReadyMessages.add(msg);
9393        }
9394    }
9395
9396    void startCleaningPackages() {
9397        // reader
9398        synchronized (mPackages) {
9399            if (!isExternalMediaAvailable()) {
9400                return;
9401            }
9402            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9403                return;
9404            }
9405        }
9406        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9407        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9408        IActivityManager am = ActivityManagerNative.getDefault();
9409        if (am != null) {
9410            try {
9411                am.startService(null, intent, null, mContext.getOpPackageName(),
9412                        UserHandle.USER_OWNER);
9413            } catch (RemoteException e) {
9414            }
9415        }
9416    }
9417
9418    @Override
9419    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9420            int installFlags, String installerPackageName, VerificationParams verificationParams,
9421            String packageAbiOverride) {
9422        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9423                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9424    }
9425
9426    @Override
9427    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9428            int installFlags, String installerPackageName, VerificationParams verificationParams,
9429            String packageAbiOverride, int userId) {
9430        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9431
9432        final int callingUid = Binder.getCallingUid();
9433        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9434
9435        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9436            try {
9437                if (observer != null) {
9438                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9439                }
9440            } catch (RemoteException re) {
9441            }
9442            return;
9443        }
9444
9445        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9446            installFlags |= PackageManager.INSTALL_FROM_ADB;
9447
9448        } else {
9449            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9450            // about installerPackageName.
9451
9452            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9453            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9454        }
9455
9456        UserHandle user;
9457        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9458            user = UserHandle.ALL;
9459        } else {
9460            user = new UserHandle(userId);
9461        }
9462
9463        // Only system components can circumvent runtime permissions when installing.
9464        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9465                && mContext.checkCallingOrSelfPermission(Manifest.permission
9466                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9467            throw new SecurityException("You need the "
9468                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9469                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9470        }
9471
9472        verificationParams.setInstallerUid(callingUid);
9473
9474        final File originFile = new File(originPath);
9475        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9476
9477        final Message msg = mHandler.obtainMessage(INIT_COPY);
9478        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9479                null, verificationParams, user, packageAbiOverride, null);
9480        mHandler.sendMessage(msg);
9481    }
9482
9483    void installStage(String packageName, File stagedDir, String stagedCid,
9484            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9485            String installerPackageName, int installerUid, UserHandle user) {
9486        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9487                params.referrerUri, installerUid, null);
9488        verifParams.setInstallerUid(installerUid);
9489
9490        final OriginInfo origin;
9491        if (stagedDir != null) {
9492            origin = OriginInfo.fromStagedFile(stagedDir);
9493        } else {
9494            origin = OriginInfo.fromStagedContainer(stagedCid);
9495        }
9496
9497        final Message msg = mHandler.obtainMessage(INIT_COPY);
9498        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9499                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9500                params.grantedRuntimePermissions);
9501        mHandler.sendMessage(msg);
9502    }
9503
9504    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9505        Bundle extras = new Bundle(1);
9506        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9507
9508        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9509                packageName, extras, null, null, new int[] {userId});
9510        try {
9511            IActivityManager am = ActivityManagerNative.getDefault();
9512            final boolean isSystem =
9513                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9514            if (isSystem && am.isUserRunning(userId, false)) {
9515                // The just-installed/enabled app is bundled on the system, so presumed
9516                // to be able to run automatically without needing an explicit launch.
9517                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9518                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9519                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9520                        .setPackage(packageName);
9521                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9522                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9523            }
9524        } catch (RemoteException e) {
9525            // shouldn't happen
9526            Slog.w(TAG, "Unable to bootstrap installed package", e);
9527        }
9528    }
9529
9530    @Override
9531    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9532            int userId) {
9533        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9534        PackageSetting pkgSetting;
9535        final int uid = Binder.getCallingUid();
9536        enforceCrossUserPermission(uid, userId, true, true,
9537                "setApplicationHiddenSetting for user " + userId);
9538
9539        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9540            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9541            return false;
9542        }
9543
9544        long callingId = Binder.clearCallingIdentity();
9545        try {
9546            boolean sendAdded = false;
9547            boolean sendRemoved = false;
9548            // writer
9549            synchronized (mPackages) {
9550                pkgSetting = mSettings.mPackages.get(packageName);
9551                if (pkgSetting == null) {
9552                    return false;
9553                }
9554                if (pkgSetting.getHidden(userId) != hidden) {
9555                    pkgSetting.setHidden(hidden, userId);
9556                    mSettings.writePackageRestrictionsLPr(userId);
9557                    if (hidden) {
9558                        sendRemoved = true;
9559                    } else {
9560                        sendAdded = true;
9561                    }
9562                }
9563            }
9564            if (sendAdded) {
9565                sendPackageAddedForUser(packageName, pkgSetting, userId);
9566                return true;
9567            }
9568            if (sendRemoved) {
9569                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9570                        "hiding pkg");
9571                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9572            }
9573        } finally {
9574            Binder.restoreCallingIdentity(callingId);
9575        }
9576        return false;
9577    }
9578
9579    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9580            int userId) {
9581        final PackageRemovedInfo info = new PackageRemovedInfo();
9582        info.removedPackage = packageName;
9583        info.removedUsers = new int[] {userId};
9584        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9585        info.sendBroadcast(false, false, false);
9586    }
9587
9588    /**
9589     * Returns true if application is not found or there was an error. Otherwise it returns
9590     * the hidden state of the package for the given user.
9591     */
9592    @Override
9593    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9595        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9596                false, "getApplicationHidden for user " + userId);
9597        PackageSetting pkgSetting;
9598        long callingId = Binder.clearCallingIdentity();
9599        try {
9600            // writer
9601            synchronized (mPackages) {
9602                pkgSetting = mSettings.mPackages.get(packageName);
9603                if (pkgSetting == null) {
9604                    return true;
9605                }
9606                return pkgSetting.getHidden(userId);
9607            }
9608        } finally {
9609            Binder.restoreCallingIdentity(callingId);
9610        }
9611    }
9612
9613    /**
9614     * @hide
9615     */
9616    @Override
9617    public int installExistingPackageAsUser(String packageName, int userId) {
9618        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9619                null);
9620        PackageSetting pkgSetting;
9621        final int uid = Binder.getCallingUid();
9622        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9623                + userId);
9624        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9625            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9626        }
9627
9628        long callingId = Binder.clearCallingIdentity();
9629        try {
9630            boolean sendAdded = false;
9631
9632            // writer
9633            synchronized (mPackages) {
9634                pkgSetting = mSettings.mPackages.get(packageName);
9635                if (pkgSetting == null) {
9636                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9637                }
9638                if (!pkgSetting.getInstalled(userId)) {
9639                    pkgSetting.setInstalled(true, userId);
9640                    pkgSetting.setHidden(false, userId);
9641                    mSettings.writePackageRestrictionsLPr(userId);
9642                    sendAdded = true;
9643                }
9644            }
9645
9646            if (sendAdded) {
9647                sendPackageAddedForUser(packageName, pkgSetting, userId);
9648            }
9649        } finally {
9650            Binder.restoreCallingIdentity(callingId);
9651        }
9652
9653        return PackageManager.INSTALL_SUCCEEDED;
9654    }
9655
9656    boolean isUserRestricted(int userId, String restrictionKey) {
9657        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9658        if (restrictions.getBoolean(restrictionKey, false)) {
9659            Log.w(TAG, "User is restricted: " + restrictionKey);
9660            return true;
9661        }
9662        return false;
9663    }
9664
9665    @Override
9666    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9667        mContext.enforceCallingOrSelfPermission(
9668                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9669                "Only package verification agents can verify applications");
9670
9671        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9672        final PackageVerificationResponse response = new PackageVerificationResponse(
9673                verificationCode, Binder.getCallingUid());
9674        msg.arg1 = id;
9675        msg.obj = response;
9676        mHandler.sendMessage(msg);
9677    }
9678
9679    @Override
9680    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9681            long millisecondsToDelay) {
9682        mContext.enforceCallingOrSelfPermission(
9683                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9684                "Only package verification agents can extend verification timeouts");
9685
9686        final PackageVerificationState state = mPendingVerification.get(id);
9687        final PackageVerificationResponse response = new PackageVerificationResponse(
9688                verificationCodeAtTimeout, Binder.getCallingUid());
9689
9690        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9691            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9692        }
9693        if (millisecondsToDelay < 0) {
9694            millisecondsToDelay = 0;
9695        }
9696        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9697                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9698            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9699        }
9700
9701        if ((state != null) && !state.timeoutExtended()) {
9702            state.extendTimeout();
9703
9704            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9705            msg.arg1 = id;
9706            msg.obj = response;
9707            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9708        }
9709    }
9710
9711    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9712            int verificationCode, UserHandle user) {
9713        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9714        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9715        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9716        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9717        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9718
9719        mContext.sendBroadcastAsUser(intent, user,
9720                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9721    }
9722
9723    private ComponentName matchComponentForVerifier(String packageName,
9724            List<ResolveInfo> receivers) {
9725        ActivityInfo targetReceiver = null;
9726
9727        final int NR = receivers.size();
9728        for (int i = 0; i < NR; i++) {
9729            final ResolveInfo info = receivers.get(i);
9730            if (info.activityInfo == null) {
9731                continue;
9732            }
9733
9734            if (packageName.equals(info.activityInfo.packageName)) {
9735                targetReceiver = info.activityInfo;
9736                break;
9737            }
9738        }
9739
9740        if (targetReceiver == null) {
9741            return null;
9742        }
9743
9744        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9745    }
9746
9747    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9748            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9749        if (pkgInfo.verifiers.length == 0) {
9750            return null;
9751        }
9752
9753        final int N = pkgInfo.verifiers.length;
9754        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9755        for (int i = 0; i < N; i++) {
9756            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9757
9758            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9759                    receivers);
9760            if (comp == null) {
9761                continue;
9762            }
9763
9764            final int verifierUid = getUidForVerifier(verifierInfo);
9765            if (verifierUid == -1) {
9766                continue;
9767            }
9768
9769            if (DEBUG_VERIFY) {
9770                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9771                        + " with the correct signature");
9772            }
9773            sufficientVerifiers.add(comp);
9774            verificationState.addSufficientVerifier(verifierUid);
9775        }
9776
9777        return sufficientVerifiers;
9778    }
9779
9780    private int getUidForVerifier(VerifierInfo verifierInfo) {
9781        synchronized (mPackages) {
9782            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9783            if (pkg == null) {
9784                return -1;
9785            } else if (pkg.mSignatures.length != 1) {
9786                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9787                        + " has more than one signature; ignoring");
9788                return -1;
9789            }
9790
9791            /*
9792             * If the public key of the package's signature does not match
9793             * our expected public key, then this is a different package and
9794             * we should skip.
9795             */
9796
9797            final byte[] expectedPublicKey;
9798            try {
9799                final Signature verifierSig = pkg.mSignatures[0];
9800                final PublicKey publicKey = verifierSig.getPublicKey();
9801                expectedPublicKey = publicKey.getEncoded();
9802            } catch (CertificateException e) {
9803                return -1;
9804            }
9805
9806            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9807
9808            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9809                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9810                        + " does not have the expected public key; ignoring");
9811                return -1;
9812            }
9813
9814            return pkg.applicationInfo.uid;
9815        }
9816    }
9817
9818    @Override
9819    public void finishPackageInstall(int token) {
9820        enforceSystemOrRoot("Only the system is allowed to finish installs");
9821
9822        if (DEBUG_INSTALL) {
9823            Slog.v(TAG, "BM finishing package install for " + token);
9824        }
9825
9826        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9827        mHandler.sendMessage(msg);
9828    }
9829
9830    /**
9831     * Get the verification agent timeout.
9832     *
9833     * @return verification timeout in milliseconds
9834     */
9835    private long getVerificationTimeout() {
9836        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9837                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9838                DEFAULT_VERIFICATION_TIMEOUT);
9839    }
9840
9841    /**
9842     * Get the default verification agent response code.
9843     *
9844     * @return default verification response code
9845     */
9846    private int getDefaultVerificationResponse() {
9847        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9848                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9849                DEFAULT_VERIFICATION_RESPONSE);
9850    }
9851
9852    /**
9853     * Check whether or not package verification has been enabled.
9854     *
9855     * @return true if verification should be performed
9856     */
9857    private boolean isVerificationEnabled(int userId, int installFlags) {
9858        if (!DEFAULT_VERIFY_ENABLE) {
9859            return false;
9860        }
9861
9862        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9863
9864        // Check if installing from ADB
9865        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9866            // Do not run verification in a test harness environment
9867            if (ActivityManager.isRunningInTestHarness()) {
9868                return false;
9869            }
9870            if (ensureVerifyAppsEnabled) {
9871                return true;
9872            }
9873            // Check if the developer does not want package verification for ADB installs
9874            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9875                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9876                return false;
9877            }
9878        }
9879
9880        if (ensureVerifyAppsEnabled) {
9881            return true;
9882        }
9883
9884        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9885                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9886    }
9887
9888    @Override
9889    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9890            throws RemoteException {
9891        mContext.enforceCallingOrSelfPermission(
9892                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9893                "Only intentfilter verification agents can verify applications");
9894
9895        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9896        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9897                Binder.getCallingUid(), verificationCode, failedDomains);
9898        msg.arg1 = id;
9899        msg.obj = response;
9900        mHandler.sendMessage(msg);
9901    }
9902
9903    @Override
9904    public int getIntentVerificationStatus(String packageName, int userId) {
9905        synchronized (mPackages) {
9906            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9907        }
9908    }
9909
9910    @Override
9911    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9912        mContext.enforceCallingOrSelfPermission(
9913                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9914
9915        boolean result = false;
9916        synchronized (mPackages) {
9917            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9918        }
9919        if (result) {
9920            scheduleWritePackageRestrictionsLocked(userId);
9921        }
9922        return result;
9923    }
9924
9925    @Override
9926    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9927        synchronized (mPackages) {
9928            return mSettings.getIntentFilterVerificationsLPr(packageName);
9929        }
9930    }
9931
9932    @Override
9933    public List<IntentFilter> getAllIntentFilters(String packageName) {
9934        if (TextUtils.isEmpty(packageName)) {
9935            return Collections.<IntentFilter>emptyList();
9936        }
9937        synchronized (mPackages) {
9938            PackageParser.Package pkg = mPackages.get(packageName);
9939            if (pkg == null || pkg.activities == null) {
9940                return Collections.<IntentFilter>emptyList();
9941            }
9942            final int count = pkg.activities.size();
9943            ArrayList<IntentFilter> result = new ArrayList<>();
9944            for (int n=0; n<count; n++) {
9945                PackageParser.Activity activity = pkg.activities.get(n);
9946                if (activity.intents != null || activity.intents.size() > 0) {
9947                    result.addAll(activity.intents);
9948                }
9949            }
9950            return result;
9951        }
9952    }
9953
9954    @Override
9955    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9956        mContext.enforceCallingOrSelfPermission(
9957                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9958
9959        synchronized (mPackages) {
9960            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9961            if (packageName != null) {
9962                result |= updateIntentVerificationStatus(packageName,
9963                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9964                        userId);
9965                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9966                        packageName, userId);
9967            }
9968            return result;
9969        }
9970    }
9971
9972    @Override
9973    public String getDefaultBrowserPackageName(int userId) {
9974        synchronized (mPackages) {
9975            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9976        }
9977    }
9978
9979    /**
9980     * Get the "allow unknown sources" setting.
9981     *
9982     * @return the current "allow unknown sources" setting
9983     */
9984    private int getUnknownSourcesSettings() {
9985        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9986                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9987                -1);
9988    }
9989
9990    @Override
9991    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9992        final int uid = Binder.getCallingUid();
9993        // writer
9994        synchronized (mPackages) {
9995            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9996            if (targetPackageSetting == null) {
9997                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9998            }
9999
10000            PackageSetting installerPackageSetting;
10001            if (installerPackageName != null) {
10002                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10003                if (installerPackageSetting == null) {
10004                    throw new IllegalArgumentException("Unknown installer package: "
10005                            + installerPackageName);
10006                }
10007            } else {
10008                installerPackageSetting = null;
10009            }
10010
10011            Signature[] callerSignature;
10012            Object obj = mSettings.getUserIdLPr(uid);
10013            if (obj != null) {
10014                if (obj instanceof SharedUserSetting) {
10015                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10016                } else if (obj instanceof PackageSetting) {
10017                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10018                } else {
10019                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10020                }
10021            } else {
10022                throw new SecurityException("Unknown calling uid " + uid);
10023            }
10024
10025            // Verify: can't set installerPackageName to a package that is
10026            // not signed with the same cert as the caller.
10027            if (installerPackageSetting != null) {
10028                if (compareSignatures(callerSignature,
10029                        installerPackageSetting.signatures.mSignatures)
10030                        != PackageManager.SIGNATURE_MATCH) {
10031                    throw new SecurityException(
10032                            "Caller does not have same cert as new installer package "
10033                            + installerPackageName);
10034                }
10035            }
10036
10037            // Verify: if target already has an installer package, it must
10038            // be signed with the same cert as the caller.
10039            if (targetPackageSetting.installerPackageName != null) {
10040                PackageSetting setting = mSettings.mPackages.get(
10041                        targetPackageSetting.installerPackageName);
10042                // If the currently set package isn't valid, then it's always
10043                // okay to change it.
10044                if (setting != null) {
10045                    if (compareSignatures(callerSignature,
10046                            setting.signatures.mSignatures)
10047                            != PackageManager.SIGNATURE_MATCH) {
10048                        throw new SecurityException(
10049                                "Caller does not have same cert as old installer package "
10050                                + targetPackageSetting.installerPackageName);
10051                    }
10052                }
10053            }
10054
10055            // Okay!
10056            targetPackageSetting.installerPackageName = installerPackageName;
10057            scheduleWriteSettingsLocked();
10058        }
10059    }
10060
10061    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10062        // Queue up an async operation since the package installation may take a little while.
10063        mHandler.post(new Runnable() {
10064            public void run() {
10065                mHandler.removeCallbacks(this);
10066                 // Result object to be returned
10067                PackageInstalledInfo res = new PackageInstalledInfo();
10068                res.returnCode = currentStatus;
10069                res.uid = -1;
10070                res.pkg = null;
10071                res.removedInfo = new PackageRemovedInfo();
10072                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10073                    args.doPreInstall(res.returnCode);
10074                    synchronized (mInstallLock) {
10075                        installPackageLI(args, res);
10076                    }
10077                    args.doPostInstall(res.returnCode, res.uid);
10078                }
10079
10080                // A restore should be performed at this point if (a) the install
10081                // succeeded, (b) the operation is not an update, and (c) the new
10082                // package has not opted out of backup participation.
10083                final boolean update = res.removedInfo.removedPackage != null;
10084                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10085                boolean doRestore = !update
10086                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10087
10088                // Set up the post-install work request bookkeeping.  This will be used
10089                // and cleaned up by the post-install event handling regardless of whether
10090                // there's a restore pass performed.  Token values are >= 1.
10091                int token;
10092                if (mNextInstallToken < 0) mNextInstallToken = 1;
10093                token = mNextInstallToken++;
10094
10095                PostInstallData data = new PostInstallData(args, res);
10096                mRunningInstalls.put(token, data);
10097                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10098
10099                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10100                    // Pass responsibility to the Backup Manager.  It will perform a
10101                    // restore if appropriate, then pass responsibility back to the
10102                    // Package Manager to run the post-install observer callbacks
10103                    // and broadcasts.
10104                    IBackupManager bm = IBackupManager.Stub.asInterface(
10105                            ServiceManager.getService(Context.BACKUP_SERVICE));
10106                    if (bm != null) {
10107                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10108                                + " to BM for possible restore");
10109                        try {
10110                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10111                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10112                            } else {
10113                                doRestore = false;
10114                            }
10115                        } catch (RemoteException e) {
10116                            // can't happen; the backup manager is local
10117                        } catch (Exception e) {
10118                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10119                            doRestore = false;
10120                        }
10121                    } else {
10122                        Slog.e(TAG, "Backup Manager not found!");
10123                        doRestore = false;
10124                    }
10125                }
10126
10127                if (!doRestore) {
10128                    // No restore possible, or the Backup Manager was mysteriously not
10129                    // available -- just fire the post-install work request directly.
10130                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10131                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10132                    mHandler.sendMessage(msg);
10133                }
10134            }
10135        });
10136    }
10137
10138    private abstract class HandlerParams {
10139        private static final int MAX_RETRIES = 4;
10140
10141        /**
10142         * Number of times startCopy() has been attempted and had a non-fatal
10143         * error.
10144         */
10145        private int mRetries = 0;
10146
10147        /** User handle for the user requesting the information or installation. */
10148        private final UserHandle mUser;
10149
10150        HandlerParams(UserHandle user) {
10151            mUser = user;
10152        }
10153
10154        UserHandle getUser() {
10155            return mUser;
10156        }
10157
10158        final boolean startCopy() {
10159            boolean res;
10160            try {
10161                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10162
10163                if (++mRetries > MAX_RETRIES) {
10164                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10165                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10166                    handleServiceError();
10167                    return false;
10168                } else {
10169                    handleStartCopy();
10170                    res = true;
10171                }
10172            } catch (RemoteException e) {
10173                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10174                mHandler.sendEmptyMessage(MCS_RECONNECT);
10175                res = false;
10176            }
10177            handleReturnCode();
10178            return res;
10179        }
10180
10181        final void serviceError() {
10182            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10183            handleServiceError();
10184            handleReturnCode();
10185        }
10186
10187        abstract void handleStartCopy() throws RemoteException;
10188        abstract void handleServiceError();
10189        abstract void handleReturnCode();
10190    }
10191
10192    class MeasureParams extends HandlerParams {
10193        private final PackageStats mStats;
10194        private boolean mSuccess;
10195
10196        private final IPackageStatsObserver mObserver;
10197
10198        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10199            super(new UserHandle(stats.userHandle));
10200            mObserver = observer;
10201            mStats = stats;
10202        }
10203
10204        @Override
10205        public String toString() {
10206            return "MeasureParams{"
10207                + Integer.toHexString(System.identityHashCode(this))
10208                + " " + mStats.packageName + "}";
10209        }
10210
10211        @Override
10212        void handleStartCopy() throws RemoteException {
10213            synchronized (mInstallLock) {
10214                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10215            }
10216
10217            if (mSuccess) {
10218                final boolean mounted;
10219                if (Environment.isExternalStorageEmulated()) {
10220                    mounted = true;
10221                } else {
10222                    final String status = Environment.getExternalStorageState();
10223                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10224                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10225                }
10226
10227                if (mounted) {
10228                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10229
10230                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10231                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10232
10233                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10234                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10235
10236                    // Always subtract cache size, since it's a subdirectory
10237                    mStats.externalDataSize -= mStats.externalCacheSize;
10238
10239                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10240                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10241
10242                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10243                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10244                }
10245            }
10246        }
10247
10248        @Override
10249        void handleReturnCode() {
10250            if (mObserver != null) {
10251                try {
10252                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10253                } catch (RemoteException e) {
10254                    Slog.i(TAG, "Observer no longer exists.");
10255                }
10256            }
10257        }
10258
10259        @Override
10260        void handleServiceError() {
10261            Slog.e(TAG, "Could not measure application " + mStats.packageName
10262                            + " external storage");
10263        }
10264    }
10265
10266    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10267            throws RemoteException {
10268        long result = 0;
10269        for (File path : paths) {
10270            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10271        }
10272        return result;
10273    }
10274
10275    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10276        for (File path : paths) {
10277            try {
10278                mcs.clearDirectory(path.getAbsolutePath());
10279            } catch (RemoteException e) {
10280            }
10281        }
10282    }
10283
10284    static class OriginInfo {
10285        /**
10286         * Location where install is coming from, before it has been
10287         * copied/renamed into place. This could be a single monolithic APK
10288         * file, or a cluster directory. This location may be untrusted.
10289         */
10290        final File file;
10291        final String cid;
10292
10293        /**
10294         * Flag indicating that {@link #file} or {@link #cid} has already been
10295         * staged, meaning downstream users don't need to defensively copy the
10296         * contents.
10297         */
10298        final boolean staged;
10299
10300        /**
10301         * Flag indicating that {@link #file} or {@link #cid} is an already
10302         * installed app that is being moved.
10303         */
10304        final boolean existing;
10305
10306        final String resolvedPath;
10307        final File resolvedFile;
10308
10309        static OriginInfo fromNothing() {
10310            return new OriginInfo(null, null, false, false);
10311        }
10312
10313        static OriginInfo fromUntrustedFile(File file) {
10314            return new OriginInfo(file, null, false, false);
10315        }
10316
10317        static OriginInfo fromExistingFile(File file) {
10318            return new OriginInfo(file, null, false, true);
10319        }
10320
10321        static OriginInfo fromStagedFile(File file) {
10322            return new OriginInfo(file, null, true, false);
10323        }
10324
10325        static OriginInfo fromStagedContainer(String cid) {
10326            return new OriginInfo(null, cid, true, false);
10327        }
10328
10329        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10330            this.file = file;
10331            this.cid = cid;
10332            this.staged = staged;
10333            this.existing = existing;
10334
10335            if (cid != null) {
10336                resolvedPath = PackageHelper.getSdDir(cid);
10337                resolvedFile = new File(resolvedPath);
10338            } else if (file != null) {
10339                resolvedPath = file.getAbsolutePath();
10340                resolvedFile = file;
10341            } else {
10342                resolvedPath = null;
10343                resolvedFile = null;
10344            }
10345        }
10346    }
10347
10348    class MoveInfo {
10349        final int moveId;
10350        final String fromUuid;
10351        final String toUuid;
10352        final String packageName;
10353        final String dataAppName;
10354        final int appId;
10355        final String seinfo;
10356
10357        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10358                String dataAppName, int appId, String seinfo) {
10359            this.moveId = moveId;
10360            this.fromUuid = fromUuid;
10361            this.toUuid = toUuid;
10362            this.packageName = packageName;
10363            this.dataAppName = dataAppName;
10364            this.appId = appId;
10365            this.seinfo = seinfo;
10366        }
10367    }
10368
10369    class InstallParams extends HandlerParams {
10370        final OriginInfo origin;
10371        final MoveInfo move;
10372        final IPackageInstallObserver2 observer;
10373        int installFlags;
10374        final String installerPackageName;
10375        final String volumeUuid;
10376        final VerificationParams verificationParams;
10377        private InstallArgs mArgs;
10378        private int mRet;
10379        final String packageAbiOverride;
10380        final String[] grantedRuntimePermissions;
10381
10382
10383        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10384                int installFlags, String installerPackageName, String volumeUuid,
10385                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10386                String[] grantedPermissions) {
10387            super(user);
10388            this.origin = origin;
10389            this.move = move;
10390            this.observer = observer;
10391            this.installFlags = installFlags;
10392            this.installerPackageName = installerPackageName;
10393            this.volumeUuid = volumeUuid;
10394            this.verificationParams = verificationParams;
10395            this.packageAbiOverride = packageAbiOverride;
10396            this.grantedRuntimePermissions = grantedPermissions;
10397        }
10398
10399        @Override
10400        public String toString() {
10401            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10402                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10403        }
10404
10405        public ManifestDigest getManifestDigest() {
10406            if (verificationParams == null) {
10407                return null;
10408            }
10409            return verificationParams.getManifestDigest();
10410        }
10411
10412        private int installLocationPolicy(PackageInfoLite pkgLite) {
10413            String packageName = pkgLite.packageName;
10414            int installLocation = pkgLite.installLocation;
10415            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10416            // reader
10417            synchronized (mPackages) {
10418                PackageParser.Package pkg = mPackages.get(packageName);
10419                if (pkg != null) {
10420                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10421                        // Check for downgrading.
10422                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10423                            try {
10424                                checkDowngrade(pkg, pkgLite);
10425                            } catch (PackageManagerException e) {
10426                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10427                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10428                            }
10429                        }
10430                        // Check for updated system application.
10431                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10432                            if (onSd) {
10433                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10434                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10435                            }
10436                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10437                        } else {
10438                            if (onSd) {
10439                                // Install flag overrides everything.
10440                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10441                            }
10442                            // If current upgrade specifies particular preference
10443                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10444                                // Application explicitly specified internal.
10445                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10446                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10447                                // App explictly prefers external. Let policy decide
10448                            } else {
10449                                // Prefer previous location
10450                                if (isExternal(pkg)) {
10451                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10452                                }
10453                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10454                            }
10455                        }
10456                    } else {
10457                        // Invalid install. Return error code
10458                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10459                    }
10460                }
10461            }
10462            // All the special cases have been taken care of.
10463            // Return result based on recommended install location.
10464            if (onSd) {
10465                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10466            }
10467            return pkgLite.recommendedInstallLocation;
10468        }
10469
10470        /*
10471         * Invoke remote method to get package information and install
10472         * location values. Override install location based on default
10473         * policy if needed and then create install arguments based
10474         * on the install location.
10475         */
10476        public void handleStartCopy() throws RemoteException {
10477            int ret = PackageManager.INSTALL_SUCCEEDED;
10478
10479            // If we're already staged, we've firmly committed to an install location
10480            if (origin.staged) {
10481                if (origin.file != null) {
10482                    installFlags |= PackageManager.INSTALL_INTERNAL;
10483                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10484                } else if (origin.cid != null) {
10485                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10486                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10487                } else {
10488                    throw new IllegalStateException("Invalid stage location");
10489                }
10490            }
10491
10492            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10493            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10494
10495            PackageInfoLite pkgLite = null;
10496
10497            if (onInt && onSd) {
10498                // Check if both bits are set.
10499                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10500                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10501            } else {
10502                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10503                        packageAbiOverride);
10504
10505                /*
10506                 * If we have too little free space, try to free cache
10507                 * before giving up.
10508                 */
10509                if (!origin.staged && pkgLite.recommendedInstallLocation
10510                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10511                    // TODO: focus freeing disk space on the target device
10512                    final StorageManager storage = StorageManager.from(mContext);
10513                    final long lowThreshold = storage.getStorageLowBytes(
10514                            Environment.getDataDirectory());
10515
10516                    final long sizeBytes = mContainerService.calculateInstalledSize(
10517                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10518
10519                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10520                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10521                                installFlags, packageAbiOverride);
10522                    }
10523
10524                    /*
10525                     * The cache free must have deleted the file we
10526                     * downloaded to install.
10527                     *
10528                     * TODO: fix the "freeCache" call to not delete
10529                     *       the file we care about.
10530                     */
10531                    if (pkgLite.recommendedInstallLocation
10532                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10533                        pkgLite.recommendedInstallLocation
10534                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10535                    }
10536                }
10537            }
10538
10539            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10540                int loc = pkgLite.recommendedInstallLocation;
10541                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10542                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10543                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10544                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10545                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10546                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10547                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10548                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10549                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10550                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10551                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10552                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10553                } else {
10554                    // Override with defaults if needed.
10555                    loc = installLocationPolicy(pkgLite);
10556                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10557                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10558                    } else if (!onSd && !onInt) {
10559                        // Override install location with flags
10560                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10561                            // Set the flag to install on external media.
10562                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10563                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10564                        } else {
10565                            // Make sure the flag for installing on external
10566                            // media is unset
10567                            installFlags |= PackageManager.INSTALL_INTERNAL;
10568                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10569                        }
10570                    }
10571                }
10572            }
10573
10574            final InstallArgs args = createInstallArgs(this);
10575            mArgs = args;
10576
10577            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10578                 /*
10579                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10580                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10581                 */
10582                int userIdentifier = getUser().getIdentifier();
10583                if (userIdentifier == UserHandle.USER_ALL
10584                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10585                    userIdentifier = UserHandle.USER_OWNER;
10586                }
10587
10588                /*
10589                 * Determine if we have any installed package verifiers. If we
10590                 * do, then we'll defer to them to verify the packages.
10591                 */
10592                final int requiredUid = mRequiredVerifierPackage == null ? -1
10593                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10594                if (!origin.existing && requiredUid != -1
10595                        && isVerificationEnabled(userIdentifier, installFlags)) {
10596                    final Intent verification = new Intent(
10597                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10598                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10599                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10600                            PACKAGE_MIME_TYPE);
10601                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10602
10603                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10604                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10605                            0 /* TODO: Which userId? */);
10606
10607                    if (DEBUG_VERIFY) {
10608                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10609                                + verification.toString() + " with " + pkgLite.verifiers.length
10610                                + " optional verifiers");
10611                    }
10612
10613                    final int verificationId = mPendingVerificationToken++;
10614
10615                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10616
10617                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10618                            installerPackageName);
10619
10620                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10621                            installFlags);
10622
10623                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10624                            pkgLite.packageName);
10625
10626                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10627                            pkgLite.versionCode);
10628
10629                    if (verificationParams != null) {
10630                        if (verificationParams.getVerificationURI() != null) {
10631                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10632                                 verificationParams.getVerificationURI());
10633                        }
10634                        if (verificationParams.getOriginatingURI() != null) {
10635                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10636                                  verificationParams.getOriginatingURI());
10637                        }
10638                        if (verificationParams.getReferrer() != null) {
10639                            verification.putExtra(Intent.EXTRA_REFERRER,
10640                                  verificationParams.getReferrer());
10641                        }
10642                        if (verificationParams.getOriginatingUid() >= 0) {
10643                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10644                                  verificationParams.getOriginatingUid());
10645                        }
10646                        if (verificationParams.getInstallerUid() >= 0) {
10647                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10648                                  verificationParams.getInstallerUid());
10649                        }
10650                    }
10651
10652                    final PackageVerificationState verificationState = new PackageVerificationState(
10653                            requiredUid, args);
10654
10655                    mPendingVerification.append(verificationId, verificationState);
10656
10657                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10658                            receivers, verificationState);
10659
10660                    // Apps installed for "all" users use the device owner to verify the app
10661                    UserHandle verifierUser = getUser();
10662                    if (verifierUser == UserHandle.ALL) {
10663                        verifierUser = UserHandle.OWNER;
10664                    }
10665
10666                    /*
10667                     * If any sufficient verifiers were listed in the package
10668                     * manifest, attempt to ask them.
10669                     */
10670                    if (sufficientVerifiers != null) {
10671                        final int N = sufficientVerifiers.size();
10672                        if (N == 0) {
10673                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10674                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10675                        } else {
10676                            for (int i = 0; i < N; i++) {
10677                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10678
10679                                final Intent sufficientIntent = new Intent(verification);
10680                                sufficientIntent.setComponent(verifierComponent);
10681                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10682                            }
10683                        }
10684                    }
10685
10686                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10687                            mRequiredVerifierPackage, receivers);
10688                    if (ret == PackageManager.INSTALL_SUCCEEDED
10689                            && mRequiredVerifierPackage != null) {
10690                        /*
10691                         * Send the intent to the required verification agent,
10692                         * but only start the verification timeout after the
10693                         * target BroadcastReceivers have run.
10694                         */
10695                        verification.setComponent(requiredVerifierComponent);
10696                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10697                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10698                                new BroadcastReceiver() {
10699                                    @Override
10700                                    public void onReceive(Context context, Intent intent) {
10701                                        final Message msg = mHandler
10702                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10703                                        msg.arg1 = verificationId;
10704                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10705                                    }
10706                                }, null, 0, null, null);
10707
10708                        /*
10709                         * We don't want the copy to proceed until verification
10710                         * succeeds, so null out this field.
10711                         */
10712                        mArgs = null;
10713                    }
10714                } else {
10715                    /*
10716                     * No package verification is enabled, so immediately start
10717                     * the remote call to initiate copy using temporary file.
10718                     */
10719                    ret = args.copyApk(mContainerService, true);
10720                }
10721            }
10722
10723            mRet = ret;
10724        }
10725
10726        @Override
10727        void handleReturnCode() {
10728            // If mArgs is null, then MCS couldn't be reached. When it
10729            // reconnects, it will try again to install. At that point, this
10730            // will succeed.
10731            if (mArgs != null) {
10732                processPendingInstall(mArgs, mRet);
10733            }
10734        }
10735
10736        @Override
10737        void handleServiceError() {
10738            mArgs = createInstallArgs(this);
10739            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10740        }
10741
10742        public boolean isForwardLocked() {
10743            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10744        }
10745    }
10746
10747    /**
10748     * Used during creation of InstallArgs
10749     *
10750     * @param installFlags package installation flags
10751     * @return true if should be installed on external storage
10752     */
10753    private static boolean installOnExternalAsec(int installFlags) {
10754        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10755            return false;
10756        }
10757        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10758            return true;
10759        }
10760        return false;
10761    }
10762
10763    /**
10764     * Used during creation of InstallArgs
10765     *
10766     * @param installFlags package installation flags
10767     * @return true if should be installed as forward locked
10768     */
10769    private static boolean installForwardLocked(int installFlags) {
10770        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10771    }
10772
10773    private InstallArgs createInstallArgs(InstallParams params) {
10774        if (params.move != null) {
10775            return new MoveInstallArgs(params);
10776        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10777            return new AsecInstallArgs(params);
10778        } else {
10779            return new FileInstallArgs(params);
10780        }
10781    }
10782
10783    /**
10784     * Create args that describe an existing installed package. Typically used
10785     * when cleaning up old installs, or used as a move source.
10786     */
10787    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10788            String resourcePath, String[] instructionSets) {
10789        final boolean isInAsec;
10790        if (installOnExternalAsec(installFlags)) {
10791            /* Apps on SD card are always in ASEC containers. */
10792            isInAsec = true;
10793        } else if (installForwardLocked(installFlags)
10794                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10795            /*
10796             * Forward-locked apps are only in ASEC containers if they're the
10797             * new style
10798             */
10799            isInAsec = true;
10800        } else {
10801            isInAsec = false;
10802        }
10803
10804        if (isInAsec) {
10805            return new AsecInstallArgs(codePath, instructionSets,
10806                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10807        } else {
10808            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10809        }
10810    }
10811
10812    static abstract class InstallArgs {
10813        /** @see InstallParams#origin */
10814        final OriginInfo origin;
10815        /** @see InstallParams#move */
10816        final MoveInfo move;
10817
10818        final IPackageInstallObserver2 observer;
10819        // Always refers to PackageManager flags only
10820        final int installFlags;
10821        final String installerPackageName;
10822        final String volumeUuid;
10823        final ManifestDigest manifestDigest;
10824        final UserHandle user;
10825        final String abiOverride;
10826        final String[] installGrantPermissions;
10827
10828        // The list of instruction sets supported by this app. This is currently
10829        // only used during the rmdex() phase to clean up resources. We can get rid of this
10830        // if we move dex files under the common app path.
10831        /* nullable */ String[] instructionSets;
10832
10833        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10834                int installFlags, String installerPackageName, String volumeUuid,
10835                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10836                String abiOverride, String[] installGrantPermissions) {
10837            this.origin = origin;
10838            this.move = move;
10839            this.installFlags = installFlags;
10840            this.observer = observer;
10841            this.installerPackageName = installerPackageName;
10842            this.volumeUuid = volumeUuid;
10843            this.manifestDigest = manifestDigest;
10844            this.user = user;
10845            this.instructionSets = instructionSets;
10846            this.abiOverride = abiOverride;
10847            this.installGrantPermissions = installGrantPermissions;
10848        }
10849
10850        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10851        abstract int doPreInstall(int status);
10852
10853        /**
10854         * Rename package into final resting place. All paths on the given
10855         * scanned package should be updated to reflect the rename.
10856         */
10857        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10858        abstract int doPostInstall(int status, int uid);
10859
10860        /** @see PackageSettingBase#codePathString */
10861        abstract String getCodePath();
10862        /** @see PackageSettingBase#resourcePathString */
10863        abstract String getResourcePath();
10864
10865        // Need installer lock especially for dex file removal.
10866        abstract void cleanUpResourcesLI();
10867        abstract boolean doPostDeleteLI(boolean delete);
10868
10869        /**
10870         * Called before the source arguments are copied. This is used mostly
10871         * for MoveParams when it needs to read the source file to put it in the
10872         * destination.
10873         */
10874        int doPreCopy() {
10875            return PackageManager.INSTALL_SUCCEEDED;
10876        }
10877
10878        /**
10879         * Called after the source arguments are copied. This is used mostly for
10880         * MoveParams when it needs to read the source file to put it in the
10881         * destination.
10882         *
10883         * @return
10884         */
10885        int doPostCopy(int uid) {
10886            return PackageManager.INSTALL_SUCCEEDED;
10887        }
10888
10889        protected boolean isFwdLocked() {
10890            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10891        }
10892
10893        protected boolean isExternalAsec() {
10894            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10895        }
10896
10897        UserHandle getUser() {
10898            return user;
10899        }
10900    }
10901
10902    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10903        if (!allCodePaths.isEmpty()) {
10904            if (instructionSets == null) {
10905                throw new IllegalStateException("instructionSet == null");
10906            }
10907            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10908            for (String codePath : allCodePaths) {
10909                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10910                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10911                    if (retCode < 0) {
10912                        Slog.w(TAG, "Couldn't remove dex file for package: "
10913                                + " at location " + codePath + ", retcode=" + retCode);
10914                        // we don't consider this to be a failure of the core package deletion
10915                    }
10916                }
10917            }
10918        }
10919    }
10920
10921    /**
10922     * Logic to handle installation of non-ASEC applications, including copying
10923     * and renaming logic.
10924     */
10925    class FileInstallArgs extends InstallArgs {
10926        private File codeFile;
10927        private File resourceFile;
10928
10929        // Example topology:
10930        // /data/app/com.example/base.apk
10931        // /data/app/com.example/split_foo.apk
10932        // /data/app/com.example/lib/arm/libfoo.so
10933        // /data/app/com.example/lib/arm64/libfoo.so
10934        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10935
10936        /** New install */
10937        FileInstallArgs(InstallParams params) {
10938            super(params.origin, params.move, params.observer, params.installFlags,
10939                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10940                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10941                    params.grantedRuntimePermissions);
10942            if (isFwdLocked()) {
10943                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10944            }
10945        }
10946
10947        /** Existing install */
10948        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10949            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10950                    null, null);
10951            this.codeFile = (codePath != null) ? new File(codePath) : null;
10952            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10953        }
10954
10955        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10956            if (origin.staged) {
10957                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10958                codeFile = origin.file;
10959                resourceFile = origin.file;
10960                return PackageManager.INSTALL_SUCCEEDED;
10961            }
10962
10963            try {
10964                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10965                codeFile = tempDir;
10966                resourceFile = tempDir;
10967            } catch (IOException e) {
10968                Slog.w(TAG, "Failed to create copy file: " + e);
10969                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10970            }
10971
10972            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10973                @Override
10974                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10975                    if (!FileUtils.isValidExtFilename(name)) {
10976                        throw new IllegalArgumentException("Invalid filename: " + name);
10977                    }
10978                    try {
10979                        final File file = new File(codeFile, name);
10980                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10981                                O_RDWR | O_CREAT, 0644);
10982                        Os.chmod(file.getAbsolutePath(), 0644);
10983                        return new ParcelFileDescriptor(fd);
10984                    } catch (ErrnoException e) {
10985                        throw new RemoteException("Failed to open: " + e.getMessage());
10986                    }
10987                }
10988            };
10989
10990            int ret = PackageManager.INSTALL_SUCCEEDED;
10991            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10992            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10993                Slog.e(TAG, "Failed to copy package");
10994                return ret;
10995            }
10996
10997            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10998            NativeLibraryHelper.Handle handle = null;
10999            try {
11000                handle = NativeLibraryHelper.Handle.create(codeFile);
11001                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11002                        abiOverride);
11003            } catch (IOException e) {
11004                Slog.e(TAG, "Copying native libraries failed", e);
11005                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11006            } finally {
11007                IoUtils.closeQuietly(handle);
11008            }
11009
11010            return ret;
11011        }
11012
11013        int doPreInstall(int status) {
11014            if (status != PackageManager.INSTALL_SUCCEEDED) {
11015                cleanUp();
11016            }
11017            return status;
11018        }
11019
11020        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11021            if (status != PackageManager.INSTALL_SUCCEEDED) {
11022                cleanUp();
11023                return false;
11024            }
11025
11026            final File targetDir = codeFile.getParentFile();
11027            final File beforeCodeFile = codeFile;
11028            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11029
11030            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11031            try {
11032                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11033            } catch (ErrnoException e) {
11034                Slog.w(TAG, "Failed to rename", e);
11035                return false;
11036            }
11037
11038            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11039                Slog.w(TAG, "Failed to restorecon");
11040                return false;
11041            }
11042
11043            // Reflect the rename internally
11044            codeFile = afterCodeFile;
11045            resourceFile = afterCodeFile;
11046
11047            // Reflect the rename in scanned details
11048            pkg.codePath = afterCodeFile.getAbsolutePath();
11049            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11050                    pkg.baseCodePath);
11051            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11052                    pkg.splitCodePaths);
11053
11054            // Reflect the rename in app info
11055            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11056            pkg.applicationInfo.setCodePath(pkg.codePath);
11057            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11058            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11059            pkg.applicationInfo.setResourcePath(pkg.codePath);
11060            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11061            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11062
11063            return true;
11064        }
11065
11066        int doPostInstall(int status, int uid) {
11067            if (status != PackageManager.INSTALL_SUCCEEDED) {
11068                cleanUp();
11069            }
11070            return status;
11071        }
11072
11073        @Override
11074        String getCodePath() {
11075            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11076        }
11077
11078        @Override
11079        String getResourcePath() {
11080            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11081        }
11082
11083        private boolean cleanUp() {
11084            if (codeFile == null || !codeFile.exists()) {
11085                return false;
11086            }
11087
11088            if (codeFile.isDirectory()) {
11089                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11090            } else {
11091                codeFile.delete();
11092            }
11093
11094            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11095                resourceFile.delete();
11096            }
11097
11098            return true;
11099        }
11100
11101        void cleanUpResourcesLI() {
11102            // Try enumerating all code paths before deleting
11103            List<String> allCodePaths = Collections.EMPTY_LIST;
11104            if (codeFile != null && codeFile.exists()) {
11105                try {
11106                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11107                    allCodePaths = pkg.getAllCodePaths();
11108                } catch (PackageParserException e) {
11109                    // Ignored; we tried our best
11110                }
11111            }
11112
11113            cleanUp();
11114            removeDexFiles(allCodePaths, instructionSets);
11115        }
11116
11117        boolean doPostDeleteLI(boolean delete) {
11118            // XXX err, shouldn't we respect the delete flag?
11119            cleanUpResourcesLI();
11120            return true;
11121        }
11122    }
11123
11124    private boolean isAsecExternal(String cid) {
11125        final String asecPath = PackageHelper.getSdFilesystem(cid);
11126        return !asecPath.startsWith(mAsecInternalPath);
11127    }
11128
11129    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11130            PackageManagerException {
11131        if (copyRet < 0) {
11132            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11133                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11134                throw new PackageManagerException(copyRet, message);
11135            }
11136        }
11137    }
11138
11139    /**
11140     * Extract the MountService "container ID" from the full code path of an
11141     * .apk.
11142     */
11143    static String cidFromCodePath(String fullCodePath) {
11144        int eidx = fullCodePath.lastIndexOf("/");
11145        String subStr1 = fullCodePath.substring(0, eidx);
11146        int sidx = subStr1.lastIndexOf("/");
11147        return subStr1.substring(sidx+1, eidx);
11148    }
11149
11150    /**
11151     * Logic to handle installation of ASEC applications, including copying and
11152     * renaming logic.
11153     */
11154    class AsecInstallArgs extends InstallArgs {
11155        static final String RES_FILE_NAME = "pkg.apk";
11156        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11157
11158        String cid;
11159        String packagePath;
11160        String resourcePath;
11161
11162        /** New install */
11163        AsecInstallArgs(InstallParams params) {
11164            super(params.origin, params.move, params.observer, params.installFlags,
11165                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11166                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11167                    params.grantedRuntimePermissions);
11168        }
11169
11170        /** Existing install */
11171        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11172                        boolean isExternal, boolean isForwardLocked) {
11173            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11174                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11175                    instructionSets, null, null);
11176            // Hackily pretend we're still looking at a full code path
11177            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11178                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11179            }
11180
11181            // Extract cid from fullCodePath
11182            int eidx = fullCodePath.lastIndexOf("/");
11183            String subStr1 = fullCodePath.substring(0, eidx);
11184            int sidx = subStr1.lastIndexOf("/");
11185            cid = subStr1.substring(sidx+1, eidx);
11186            setMountPath(subStr1);
11187        }
11188
11189        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11190            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11191                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11192                    instructionSets, null, null);
11193            this.cid = cid;
11194            setMountPath(PackageHelper.getSdDir(cid));
11195        }
11196
11197        void createCopyFile() {
11198            cid = mInstallerService.allocateExternalStageCidLegacy();
11199        }
11200
11201        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11202            if (origin.staged) {
11203                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11204                cid = origin.cid;
11205                setMountPath(PackageHelper.getSdDir(cid));
11206                return PackageManager.INSTALL_SUCCEEDED;
11207            }
11208
11209            if (temp) {
11210                createCopyFile();
11211            } else {
11212                /*
11213                 * Pre-emptively destroy the container since it's destroyed if
11214                 * copying fails due to it existing anyway.
11215                 */
11216                PackageHelper.destroySdDir(cid);
11217            }
11218
11219            final String newMountPath = imcs.copyPackageToContainer(
11220                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11221                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11222
11223            if (newMountPath != null) {
11224                setMountPath(newMountPath);
11225                return PackageManager.INSTALL_SUCCEEDED;
11226            } else {
11227                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11228            }
11229        }
11230
11231        @Override
11232        String getCodePath() {
11233            return packagePath;
11234        }
11235
11236        @Override
11237        String getResourcePath() {
11238            return resourcePath;
11239        }
11240
11241        int doPreInstall(int status) {
11242            if (status != PackageManager.INSTALL_SUCCEEDED) {
11243                // Destroy container
11244                PackageHelper.destroySdDir(cid);
11245            } else {
11246                boolean mounted = PackageHelper.isContainerMounted(cid);
11247                if (!mounted) {
11248                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11249                            Process.SYSTEM_UID);
11250                    if (newMountPath != null) {
11251                        setMountPath(newMountPath);
11252                    } else {
11253                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11254                    }
11255                }
11256            }
11257            return status;
11258        }
11259
11260        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11261            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11262            String newMountPath = null;
11263            if (PackageHelper.isContainerMounted(cid)) {
11264                // Unmount the container
11265                if (!PackageHelper.unMountSdDir(cid)) {
11266                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11267                    return false;
11268                }
11269            }
11270            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11271                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11272                        " which might be stale. Will try to clean up.");
11273                // Clean up the stale container and proceed to recreate.
11274                if (!PackageHelper.destroySdDir(newCacheId)) {
11275                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11276                    return false;
11277                }
11278                // Successfully cleaned up stale container. Try to rename again.
11279                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11280                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11281                            + " inspite of cleaning it up.");
11282                    return false;
11283                }
11284            }
11285            if (!PackageHelper.isContainerMounted(newCacheId)) {
11286                Slog.w(TAG, "Mounting container " + newCacheId);
11287                newMountPath = PackageHelper.mountSdDir(newCacheId,
11288                        getEncryptKey(), Process.SYSTEM_UID);
11289            } else {
11290                newMountPath = PackageHelper.getSdDir(newCacheId);
11291            }
11292            if (newMountPath == null) {
11293                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11294                return false;
11295            }
11296            Log.i(TAG, "Succesfully renamed " + cid +
11297                    " to " + newCacheId +
11298                    " at new path: " + newMountPath);
11299            cid = newCacheId;
11300
11301            final File beforeCodeFile = new File(packagePath);
11302            setMountPath(newMountPath);
11303            final File afterCodeFile = new File(packagePath);
11304
11305            // Reflect the rename in scanned details
11306            pkg.codePath = afterCodeFile.getAbsolutePath();
11307            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11308                    pkg.baseCodePath);
11309            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11310                    pkg.splitCodePaths);
11311
11312            // Reflect the rename in app info
11313            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11314            pkg.applicationInfo.setCodePath(pkg.codePath);
11315            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11316            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11317            pkg.applicationInfo.setResourcePath(pkg.codePath);
11318            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11319            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11320
11321            return true;
11322        }
11323
11324        private void setMountPath(String mountPath) {
11325            final File mountFile = new File(mountPath);
11326
11327            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11328            if (monolithicFile.exists()) {
11329                packagePath = monolithicFile.getAbsolutePath();
11330                if (isFwdLocked()) {
11331                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11332                } else {
11333                    resourcePath = packagePath;
11334                }
11335            } else {
11336                packagePath = mountFile.getAbsolutePath();
11337                resourcePath = packagePath;
11338            }
11339        }
11340
11341        int doPostInstall(int status, int uid) {
11342            if (status != PackageManager.INSTALL_SUCCEEDED) {
11343                cleanUp();
11344            } else {
11345                final int groupOwner;
11346                final String protectedFile;
11347                if (isFwdLocked()) {
11348                    groupOwner = UserHandle.getSharedAppGid(uid);
11349                    protectedFile = RES_FILE_NAME;
11350                } else {
11351                    groupOwner = -1;
11352                    protectedFile = null;
11353                }
11354
11355                if (uid < Process.FIRST_APPLICATION_UID
11356                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11357                    Slog.e(TAG, "Failed to finalize " + cid);
11358                    PackageHelper.destroySdDir(cid);
11359                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11360                }
11361
11362                boolean mounted = PackageHelper.isContainerMounted(cid);
11363                if (!mounted) {
11364                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11365                }
11366            }
11367            return status;
11368        }
11369
11370        private void cleanUp() {
11371            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11372
11373            // Destroy secure container
11374            PackageHelper.destroySdDir(cid);
11375        }
11376
11377        private List<String> getAllCodePaths() {
11378            final File codeFile = new File(getCodePath());
11379            if (codeFile != null && codeFile.exists()) {
11380                try {
11381                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11382                    return pkg.getAllCodePaths();
11383                } catch (PackageParserException e) {
11384                    // Ignored; we tried our best
11385                }
11386            }
11387            return Collections.EMPTY_LIST;
11388        }
11389
11390        void cleanUpResourcesLI() {
11391            // Enumerate all code paths before deleting
11392            cleanUpResourcesLI(getAllCodePaths());
11393        }
11394
11395        private void cleanUpResourcesLI(List<String> allCodePaths) {
11396            cleanUp();
11397            removeDexFiles(allCodePaths, instructionSets);
11398        }
11399
11400        String getPackageName() {
11401            return getAsecPackageName(cid);
11402        }
11403
11404        boolean doPostDeleteLI(boolean delete) {
11405            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11406            final List<String> allCodePaths = getAllCodePaths();
11407            boolean mounted = PackageHelper.isContainerMounted(cid);
11408            if (mounted) {
11409                // Unmount first
11410                if (PackageHelper.unMountSdDir(cid)) {
11411                    mounted = false;
11412                }
11413            }
11414            if (!mounted && delete) {
11415                cleanUpResourcesLI(allCodePaths);
11416            }
11417            return !mounted;
11418        }
11419
11420        @Override
11421        int doPreCopy() {
11422            if (isFwdLocked()) {
11423                if (!PackageHelper.fixSdPermissions(cid,
11424                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11425                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11426                }
11427            }
11428
11429            return PackageManager.INSTALL_SUCCEEDED;
11430        }
11431
11432        @Override
11433        int doPostCopy(int uid) {
11434            if (isFwdLocked()) {
11435                if (uid < Process.FIRST_APPLICATION_UID
11436                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11437                                RES_FILE_NAME)) {
11438                    Slog.e(TAG, "Failed to finalize " + cid);
11439                    PackageHelper.destroySdDir(cid);
11440                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11441                }
11442            }
11443
11444            return PackageManager.INSTALL_SUCCEEDED;
11445        }
11446    }
11447
11448    /**
11449     * Logic to handle movement of existing installed applications.
11450     */
11451    class MoveInstallArgs extends InstallArgs {
11452        private File codeFile;
11453        private File resourceFile;
11454
11455        /** New install */
11456        MoveInstallArgs(InstallParams params) {
11457            super(params.origin, params.move, params.observer, params.installFlags,
11458                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11459                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11460                    params.grantedRuntimePermissions);
11461        }
11462
11463        int copyApk(IMediaContainerService imcs, boolean temp) {
11464            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11465                    + move.fromUuid + " to " + move.toUuid);
11466            synchronized (mInstaller) {
11467                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11468                        move.dataAppName, move.appId, move.seinfo) != 0) {
11469                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11470                }
11471            }
11472
11473            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11474            resourceFile = codeFile;
11475            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11476
11477            return PackageManager.INSTALL_SUCCEEDED;
11478        }
11479
11480        int doPreInstall(int status) {
11481            if (status != PackageManager.INSTALL_SUCCEEDED) {
11482                cleanUp(move.toUuid);
11483            }
11484            return status;
11485        }
11486
11487        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11488            if (status != PackageManager.INSTALL_SUCCEEDED) {
11489                cleanUp(move.toUuid);
11490                return false;
11491            }
11492
11493            // Reflect the move in app info
11494            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11495            pkg.applicationInfo.setCodePath(pkg.codePath);
11496            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11497            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11498            pkg.applicationInfo.setResourcePath(pkg.codePath);
11499            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11500            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11501
11502            return true;
11503        }
11504
11505        int doPostInstall(int status, int uid) {
11506            if (status == PackageManager.INSTALL_SUCCEEDED) {
11507                cleanUp(move.fromUuid);
11508            } else {
11509                cleanUp(move.toUuid);
11510            }
11511            return status;
11512        }
11513
11514        @Override
11515        String getCodePath() {
11516            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11517        }
11518
11519        @Override
11520        String getResourcePath() {
11521            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11522        }
11523
11524        private boolean cleanUp(String volumeUuid) {
11525            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11526                    move.dataAppName);
11527            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11528            synchronized (mInstallLock) {
11529                // Clean up both app data and code
11530                removeDataDirsLI(volumeUuid, move.packageName);
11531                if (codeFile.isDirectory()) {
11532                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11533                } else {
11534                    codeFile.delete();
11535                }
11536            }
11537            return true;
11538        }
11539
11540        void cleanUpResourcesLI() {
11541            throw new UnsupportedOperationException();
11542        }
11543
11544        boolean doPostDeleteLI(boolean delete) {
11545            throw new UnsupportedOperationException();
11546        }
11547    }
11548
11549    static String getAsecPackageName(String packageCid) {
11550        int idx = packageCid.lastIndexOf("-");
11551        if (idx == -1) {
11552            return packageCid;
11553        }
11554        return packageCid.substring(0, idx);
11555    }
11556
11557    // Utility method used to create code paths based on package name and available index.
11558    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11559        String idxStr = "";
11560        int idx = 1;
11561        // Fall back to default value of idx=1 if prefix is not
11562        // part of oldCodePath
11563        if (oldCodePath != null) {
11564            String subStr = oldCodePath;
11565            // Drop the suffix right away
11566            if (suffix != null && subStr.endsWith(suffix)) {
11567                subStr = subStr.substring(0, subStr.length() - suffix.length());
11568            }
11569            // If oldCodePath already contains prefix find out the
11570            // ending index to either increment or decrement.
11571            int sidx = subStr.lastIndexOf(prefix);
11572            if (sidx != -1) {
11573                subStr = subStr.substring(sidx + prefix.length());
11574                if (subStr != null) {
11575                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11576                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11577                    }
11578                    try {
11579                        idx = Integer.parseInt(subStr);
11580                        if (idx <= 1) {
11581                            idx++;
11582                        } else {
11583                            idx--;
11584                        }
11585                    } catch(NumberFormatException e) {
11586                    }
11587                }
11588            }
11589        }
11590        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11591        return prefix + idxStr;
11592    }
11593
11594    private File getNextCodePath(File targetDir, String packageName) {
11595        int suffix = 1;
11596        File result;
11597        do {
11598            result = new File(targetDir, packageName + "-" + suffix);
11599            suffix++;
11600        } while (result.exists());
11601        return result;
11602    }
11603
11604    // Utility method that returns the relative package path with respect
11605    // to the installation directory. Like say for /data/data/com.test-1.apk
11606    // string com.test-1 is returned.
11607    static String deriveCodePathName(String codePath) {
11608        if (codePath == null) {
11609            return null;
11610        }
11611        final File codeFile = new File(codePath);
11612        final String name = codeFile.getName();
11613        if (codeFile.isDirectory()) {
11614            return name;
11615        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11616            final int lastDot = name.lastIndexOf('.');
11617            return name.substring(0, lastDot);
11618        } else {
11619            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11620            return null;
11621        }
11622    }
11623
11624    class PackageInstalledInfo {
11625        String name;
11626        int uid;
11627        // The set of users that originally had this package installed.
11628        int[] origUsers;
11629        // The set of users that now have this package installed.
11630        int[] newUsers;
11631        PackageParser.Package pkg;
11632        int returnCode;
11633        String returnMsg;
11634        PackageRemovedInfo removedInfo;
11635
11636        public void setError(int code, String msg) {
11637            returnCode = code;
11638            returnMsg = msg;
11639            Slog.w(TAG, msg);
11640        }
11641
11642        public void setError(String msg, PackageParserException e) {
11643            returnCode = e.error;
11644            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11645            Slog.w(TAG, msg, e);
11646        }
11647
11648        public void setError(String msg, PackageManagerException e) {
11649            returnCode = e.error;
11650            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11651            Slog.w(TAG, msg, e);
11652        }
11653
11654        // In some error cases we want to convey more info back to the observer
11655        String origPackage;
11656        String origPermission;
11657    }
11658
11659    /*
11660     * Install a non-existing package.
11661     */
11662    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11663            UserHandle user, String installerPackageName, String volumeUuid,
11664            PackageInstalledInfo res) {
11665        // Remember this for later, in case we need to rollback this install
11666        String pkgName = pkg.packageName;
11667
11668        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11669        final boolean dataDirExists = Environment
11670                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11671        synchronized(mPackages) {
11672            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11673                // A package with the same name is already installed, though
11674                // it has been renamed to an older name.  The package we
11675                // are trying to install should be installed as an update to
11676                // the existing one, but that has not been requested, so bail.
11677                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11678                        + " without first uninstalling package running as "
11679                        + mSettings.mRenamedPackages.get(pkgName));
11680                return;
11681            }
11682            if (mPackages.containsKey(pkgName)) {
11683                // Don't allow installation over an existing package with the same name.
11684                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11685                        + " without first uninstalling.");
11686                return;
11687            }
11688        }
11689
11690        try {
11691            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11692                    System.currentTimeMillis(), user);
11693
11694            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11695            // delete the partially installed application. the data directory will have to be
11696            // restored if it was already existing
11697            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11698                // remove package from internal structures.  Note that we want deletePackageX to
11699                // delete the package data and cache directories that it created in
11700                // scanPackageLocked, unless those directories existed before we even tried to
11701                // install.
11702                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11703                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11704                                res.removedInfo, true);
11705            }
11706
11707        } catch (PackageManagerException e) {
11708            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11709        }
11710    }
11711
11712    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11713        // Can't rotate keys during boot or if sharedUser.
11714        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11715                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11716            return false;
11717        }
11718        // app is using upgradeKeySets; make sure all are valid
11719        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11720        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11721        for (int i = 0; i < upgradeKeySets.length; i++) {
11722            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11723                Slog.wtf(TAG, "Package "
11724                         + (oldPs.name != null ? oldPs.name : "<null>")
11725                         + " contains upgrade-key-set reference to unknown key-set: "
11726                         + upgradeKeySets[i]
11727                         + " reverting to signatures check.");
11728                return false;
11729            }
11730        }
11731        return true;
11732    }
11733
11734    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11735        // Upgrade keysets are being used.  Determine if new package has a superset of the
11736        // required keys.
11737        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11738        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11739        for (int i = 0; i < upgradeKeySets.length; i++) {
11740            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11741            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11742                return true;
11743            }
11744        }
11745        return false;
11746    }
11747
11748    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11749            UserHandle user, String installerPackageName, String volumeUuid,
11750            PackageInstalledInfo res) {
11751        final PackageParser.Package oldPackage;
11752        final String pkgName = pkg.packageName;
11753        final int[] allUsers;
11754        final boolean[] perUserInstalled;
11755        final boolean weFroze;
11756
11757        // First find the old package info and check signatures
11758        synchronized(mPackages) {
11759            oldPackage = mPackages.get(pkgName);
11760            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11761            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11762            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11763                if(!checkUpgradeKeySetLP(ps, pkg)) {
11764                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11765                            "New package not signed by keys specified by upgrade-keysets: "
11766                            + pkgName);
11767                    return;
11768                }
11769            } else {
11770                // default to original signature matching
11771                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11772                    != PackageManager.SIGNATURE_MATCH) {
11773                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11774                            "New package has a different signature: " + pkgName);
11775                    return;
11776                }
11777            }
11778
11779            // In case of rollback, remember per-user/profile install state
11780            allUsers = sUserManager.getUserIds();
11781            perUserInstalled = new boolean[allUsers.length];
11782            for (int i = 0; i < allUsers.length; i++) {
11783                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11784            }
11785
11786            // Mark the app as frozen to prevent launching during the upgrade
11787            // process, and then kill all running instances
11788            if (!ps.frozen) {
11789                ps.frozen = true;
11790                weFroze = true;
11791            } else {
11792                weFroze = false;
11793            }
11794        }
11795
11796        // Now that we're guarded by frozen state, kill app during upgrade
11797        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11798
11799        try {
11800            boolean sysPkg = (isSystemApp(oldPackage));
11801            if (sysPkg) {
11802                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11803                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11804            } else {
11805                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11806                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11807            }
11808        } finally {
11809            // Regardless of success or failure of upgrade steps above, always
11810            // unfreeze the package if we froze it
11811            if (weFroze) {
11812                unfreezePackage(pkgName);
11813            }
11814        }
11815    }
11816
11817    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11818            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11819            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11820            String volumeUuid, PackageInstalledInfo res) {
11821        String pkgName = deletedPackage.packageName;
11822        boolean deletedPkg = true;
11823        boolean updatedSettings = false;
11824
11825        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11826                + deletedPackage);
11827        long origUpdateTime;
11828        if (pkg.mExtras != null) {
11829            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11830        } else {
11831            origUpdateTime = 0;
11832        }
11833
11834        // First delete the existing package while retaining the data directory
11835        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11836                res.removedInfo, true)) {
11837            // If the existing package wasn't successfully deleted
11838            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11839            deletedPkg = false;
11840        } else {
11841            // Successfully deleted the old package; proceed with replace.
11842
11843            // If deleted package lived in a container, give users a chance to
11844            // relinquish resources before killing.
11845            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11846                if (DEBUG_INSTALL) {
11847                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11848                }
11849                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11850                final ArrayList<String> pkgList = new ArrayList<String>(1);
11851                pkgList.add(deletedPackage.applicationInfo.packageName);
11852                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11853            }
11854
11855            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11856            try {
11857                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11858                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11859                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11860                        perUserInstalled, res, user);
11861                updatedSettings = true;
11862            } catch (PackageManagerException e) {
11863                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11864            }
11865        }
11866
11867        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11868            // remove package from internal structures.  Note that we want deletePackageX to
11869            // delete the package data and cache directories that it created in
11870            // scanPackageLocked, unless those directories existed before we even tried to
11871            // install.
11872            if(updatedSettings) {
11873                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11874                deletePackageLI(
11875                        pkgName, null, true, allUsers, perUserInstalled,
11876                        PackageManager.DELETE_KEEP_DATA,
11877                                res.removedInfo, true);
11878            }
11879            // Since we failed to install the new package we need to restore the old
11880            // package that we deleted.
11881            if (deletedPkg) {
11882                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11883                File restoreFile = new File(deletedPackage.codePath);
11884                // Parse old package
11885                boolean oldExternal = isExternal(deletedPackage);
11886                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11887                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11888                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11889                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11890                try {
11891                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11892                } catch (PackageManagerException e) {
11893                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11894                            + e.getMessage());
11895                    return;
11896                }
11897                // Restore of old package succeeded. Update permissions.
11898                // writer
11899                synchronized (mPackages) {
11900                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11901                            UPDATE_PERMISSIONS_ALL);
11902                    // can downgrade to reader
11903                    mSettings.writeLPr();
11904                }
11905                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11906            }
11907        }
11908    }
11909
11910    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11911            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11912            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11913            String volumeUuid, PackageInstalledInfo res) {
11914        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11915                + ", old=" + deletedPackage);
11916        boolean disabledSystem = false;
11917        boolean updatedSettings = false;
11918        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11919        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11920                != 0) {
11921            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11922        }
11923        String packageName = deletedPackage.packageName;
11924        if (packageName == null) {
11925            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11926                    "Attempt to delete null packageName.");
11927            return;
11928        }
11929        PackageParser.Package oldPkg;
11930        PackageSetting oldPkgSetting;
11931        // reader
11932        synchronized (mPackages) {
11933            oldPkg = mPackages.get(packageName);
11934            oldPkgSetting = mSettings.mPackages.get(packageName);
11935            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11936                    (oldPkgSetting == null)) {
11937                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11938                        "Couldn't find package:" + packageName + " information");
11939                return;
11940            }
11941        }
11942
11943        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11944        res.removedInfo.removedPackage = packageName;
11945        // Remove existing system package
11946        removePackageLI(oldPkgSetting, true);
11947        // writer
11948        synchronized (mPackages) {
11949            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11950            if (!disabledSystem && deletedPackage != null) {
11951                // We didn't need to disable the .apk as a current system package,
11952                // which means we are replacing another update that is already
11953                // installed.  We need to make sure to delete the older one's .apk.
11954                res.removedInfo.args = createInstallArgsForExisting(0,
11955                        deletedPackage.applicationInfo.getCodePath(),
11956                        deletedPackage.applicationInfo.getResourcePath(),
11957                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11958            } else {
11959                res.removedInfo.args = null;
11960            }
11961        }
11962
11963        // Successfully disabled the old package. Now proceed with re-installation
11964        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11965
11966        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11967        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11968
11969        PackageParser.Package newPackage = null;
11970        try {
11971            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11972            if (newPackage.mExtras != null) {
11973                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11974                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11975                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11976
11977                // is the update attempting to change shared user? that isn't going to work...
11978                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11979                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11980                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11981                            + " to " + newPkgSetting.sharedUser);
11982                    updatedSettings = true;
11983                }
11984            }
11985
11986            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11987                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11988                        perUserInstalled, res, user);
11989                updatedSettings = true;
11990            }
11991
11992        } catch (PackageManagerException e) {
11993            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11994        }
11995
11996        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11997            // Re installation failed. Restore old information
11998            // Remove new pkg information
11999            if (newPackage != null) {
12000                removeInstalledPackageLI(newPackage, true);
12001            }
12002            // Add back the old system package
12003            try {
12004                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12005            } catch (PackageManagerException e) {
12006                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12007            }
12008            // Restore the old system information in Settings
12009            synchronized (mPackages) {
12010                if (disabledSystem) {
12011                    mSettings.enableSystemPackageLPw(packageName);
12012                }
12013                if (updatedSettings) {
12014                    mSettings.setInstallerPackageName(packageName,
12015                            oldPkgSetting.installerPackageName);
12016                }
12017                mSettings.writeLPr();
12018            }
12019        }
12020    }
12021
12022    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12023            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12024            UserHandle user) {
12025        String pkgName = newPackage.packageName;
12026        synchronized (mPackages) {
12027            //write settings. the installStatus will be incomplete at this stage.
12028            //note that the new package setting would have already been
12029            //added to mPackages. It hasn't been persisted yet.
12030            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12031            mSettings.writeLPr();
12032        }
12033
12034        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12035
12036        synchronized (mPackages) {
12037            updatePermissionsLPw(newPackage.packageName, newPackage,
12038                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12039                            ? UPDATE_PERMISSIONS_ALL : 0));
12040            // For system-bundled packages, we assume that installing an upgraded version
12041            // of the package implies that the user actually wants to run that new code,
12042            // so we enable the package.
12043            PackageSetting ps = mSettings.mPackages.get(pkgName);
12044            if (ps != null) {
12045                if (isSystemApp(newPackage)) {
12046                    // NB: implicit assumption that system package upgrades apply to all users
12047                    if (DEBUG_INSTALL) {
12048                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12049                    }
12050                    if (res.origUsers != null) {
12051                        for (int userHandle : res.origUsers) {
12052                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12053                                    userHandle, installerPackageName);
12054                        }
12055                    }
12056                    // Also convey the prior install/uninstall state
12057                    if (allUsers != null && perUserInstalled != null) {
12058                        for (int i = 0; i < allUsers.length; i++) {
12059                            if (DEBUG_INSTALL) {
12060                                Slog.d(TAG, "    user " + allUsers[i]
12061                                        + " => " + perUserInstalled[i]);
12062                            }
12063                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12064                        }
12065                        // these install state changes will be persisted in the
12066                        // upcoming call to mSettings.writeLPr().
12067                    }
12068                }
12069                // It's implied that when a user requests installation, they want the app to be
12070                // installed and enabled.
12071                int userId = user.getIdentifier();
12072                if (userId != UserHandle.USER_ALL) {
12073                    ps.setInstalled(true, userId);
12074                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12075                }
12076            }
12077            res.name = pkgName;
12078            res.uid = newPackage.applicationInfo.uid;
12079            res.pkg = newPackage;
12080            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12081            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12082            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12083            //to update install status
12084            mSettings.writeLPr();
12085        }
12086    }
12087
12088    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12089        final int installFlags = args.installFlags;
12090        final String installerPackageName = args.installerPackageName;
12091        final String volumeUuid = args.volumeUuid;
12092        final File tmpPackageFile = new File(args.getCodePath());
12093        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12094        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12095                || (args.volumeUuid != null));
12096        boolean replace = false;
12097        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12098        if (args.move != null) {
12099            // moving a complete application; perfom an initial scan on the new install location
12100            scanFlags |= SCAN_INITIAL;
12101        }
12102        // Result object to be returned
12103        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12104
12105        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12106        // Retrieve PackageSettings and parse package
12107        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12108                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12109                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12110        PackageParser pp = new PackageParser();
12111        pp.setSeparateProcesses(mSeparateProcesses);
12112        pp.setDisplayMetrics(mMetrics);
12113
12114        final PackageParser.Package pkg;
12115        try {
12116            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12117        } catch (PackageParserException e) {
12118            res.setError("Failed parse during installPackageLI", e);
12119            return;
12120        }
12121
12122        // Mark that we have an install time CPU ABI override.
12123        pkg.cpuAbiOverride = args.abiOverride;
12124
12125        String pkgName = res.name = pkg.packageName;
12126        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12127            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12128                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12129                return;
12130            }
12131        }
12132
12133        try {
12134            pp.collectCertificates(pkg, parseFlags);
12135            pp.collectManifestDigest(pkg);
12136        } catch (PackageParserException e) {
12137            res.setError("Failed collect during installPackageLI", e);
12138            return;
12139        }
12140
12141        /* If the installer passed in a manifest digest, compare it now. */
12142        if (args.manifestDigest != null) {
12143            if (DEBUG_INSTALL) {
12144                final String parsedManifest = pkg.manifestDigest == null ? "null"
12145                        : pkg.manifestDigest.toString();
12146                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12147                        + parsedManifest);
12148            }
12149
12150            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12151                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12152                return;
12153            }
12154        } else if (DEBUG_INSTALL) {
12155            final String parsedManifest = pkg.manifestDigest == null
12156                    ? "null" : pkg.manifestDigest.toString();
12157            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12158        }
12159
12160        // Get rid of all references to package scan path via parser.
12161        pp = null;
12162        String oldCodePath = null;
12163        boolean systemApp = false;
12164        synchronized (mPackages) {
12165            // Check if installing already existing package
12166            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12167                String oldName = mSettings.mRenamedPackages.get(pkgName);
12168                if (pkg.mOriginalPackages != null
12169                        && pkg.mOriginalPackages.contains(oldName)
12170                        && mPackages.containsKey(oldName)) {
12171                    // This package is derived from an original package,
12172                    // and this device has been updating from that original
12173                    // name.  We must continue using the original name, so
12174                    // rename the new package here.
12175                    pkg.setPackageName(oldName);
12176                    pkgName = pkg.packageName;
12177                    replace = true;
12178                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12179                            + oldName + " pkgName=" + pkgName);
12180                } else if (mPackages.containsKey(pkgName)) {
12181                    // This package, under its official name, already exists
12182                    // on the device; we should replace it.
12183                    replace = true;
12184                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12185                }
12186
12187                // Prevent apps opting out from runtime permissions
12188                if (replace) {
12189                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12190                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12191                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12192                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12193                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12194                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12195                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12196                                        + " doesn't support runtime permissions but the old"
12197                                        + " target SDK " + oldTargetSdk + " does.");
12198                        return;
12199                    }
12200                }
12201            }
12202
12203            PackageSetting ps = mSettings.mPackages.get(pkgName);
12204            if (ps != null) {
12205                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12206
12207                // Quick sanity check that we're signed correctly if updating;
12208                // we'll check this again later when scanning, but we want to
12209                // bail early here before tripping over redefined permissions.
12210                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12211                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12212                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12213                                + pkg.packageName + " upgrade keys do not match the "
12214                                + "previously installed version");
12215                        return;
12216                    }
12217                } else {
12218                    try {
12219                        verifySignaturesLP(ps, pkg);
12220                    } catch (PackageManagerException e) {
12221                        res.setError(e.error, e.getMessage());
12222                        return;
12223                    }
12224                }
12225
12226                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12227                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12228                    systemApp = (ps.pkg.applicationInfo.flags &
12229                            ApplicationInfo.FLAG_SYSTEM) != 0;
12230                }
12231                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12232            }
12233
12234            // Check whether the newly-scanned package wants to define an already-defined perm
12235            int N = pkg.permissions.size();
12236            for (int i = N-1; i >= 0; i--) {
12237                PackageParser.Permission perm = pkg.permissions.get(i);
12238                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12239                if (bp != null) {
12240                    // If the defining package is signed with our cert, it's okay.  This
12241                    // also includes the "updating the same package" case, of course.
12242                    // "updating same package" could also involve key-rotation.
12243                    final boolean sigsOk;
12244                    if (bp.sourcePackage.equals(pkg.packageName)
12245                            && (bp.packageSetting instanceof PackageSetting)
12246                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12247                                    scanFlags))) {
12248                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12249                    } else {
12250                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12251                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12252                    }
12253                    if (!sigsOk) {
12254                        // If the owning package is the system itself, we log but allow
12255                        // install to proceed; we fail the install on all other permission
12256                        // redefinitions.
12257                        if (!bp.sourcePackage.equals("android")) {
12258                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12259                                    + pkg.packageName + " attempting to redeclare permission "
12260                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12261                            res.origPermission = perm.info.name;
12262                            res.origPackage = bp.sourcePackage;
12263                            return;
12264                        } else {
12265                            Slog.w(TAG, "Package " + pkg.packageName
12266                                    + " attempting to redeclare system permission "
12267                                    + perm.info.name + "; ignoring new declaration");
12268                            pkg.permissions.remove(i);
12269                        }
12270                    }
12271                }
12272            }
12273
12274        }
12275
12276        if (systemApp && onExternal) {
12277            // Disable updates to system apps on sdcard
12278            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12279                    "Cannot install updates to system apps on sdcard");
12280            return;
12281        }
12282
12283        if (args.move != null) {
12284            // We did an in-place move, so dex is ready to roll
12285            scanFlags |= SCAN_NO_DEX;
12286            scanFlags |= SCAN_MOVE;
12287
12288            synchronized (mPackages) {
12289                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12290                if (ps == null) {
12291                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12292                            "Missing settings for moved package " + pkgName);
12293                }
12294
12295                // We moved the entire application as-is, so bring over the
12296                // previously derived ABI information.
12297                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12298                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12299            }
12300
12301        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12302            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12303            scanFlags |= SCAN_NO_DEX;
12304
12305            try {
12306                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12307                        true /* extract libs */);
12308            } catch (PackageManagerException pme) {
12309                Slog.e(TAG, "Error deriving application ABI", pme);
12310                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12311                return;
12312            }
12313
12314            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12315            int result = mPackageDexOptimizer
12316                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12317                            false /* defer */, false /* inclDependencies */);
12318            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12319                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12320                return;
12321            }
12322        }
12323
12324        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12325            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12326            return;
12327        }
12328
12329        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12330
12331        if (replace) {
12332            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12333                    installerPackageName, volumeUuid, res);
12334        } else {
12335            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12336                    args.user, installerPackageName, volumeUuid, res);
12337        }
12338        synchronized (mPackages) {
12339            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12340            if (ps != null) {
12341                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12342            }
12343        }
12344    }
12345
12346    private void startIntentFilterVerifications(int userId, boolean replacing,
12347            PackageParser.Package pkg) {
12348        if (mIntentFilterVerifierComponent == null) {
12349            Slog.w(TAG, "No IntentFilter verification will not be done as "
12350                    + "there is no IntentFilterVerifier available!");
12351            return;
12352        }
12353
12354        final int verifierUid = getPackageUid(
12355                mIntentFilterVerifierComponent.getPackageName(),
12356                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12357
12358        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12359        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12360        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12361        mHandler.sendMessage(msg);
12362    }
12363
12364    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12365            PackageParser.Package pkg) {
12366        int size = pkg.activities.size();
12367        if (size == 0) {
12368            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12369                    "No activity, so no need to verify any IntentFilter!");
12370            return;
12371        }
12372
12373        final boolean hasDomainURLs = hasDomainURLs(pkg);
12374        if (!hasDomainURLs) {
12375            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12376                    "No domain URLs, so no need to verify any IntentFilter!");
12377            return;
12378        }
12379
12380        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12381                + " if any IntentFilter from the " + size
12382                + " Activities needs verification ...");
12383
12384        int count = 0;
12385        final String packageName = pkg.packageName;
12386
12387        synchronized (mPackages) {
12388            // If this is a new install and we see that we've already run verification for this
12389            // package, we have nothing to do: it means the state was restored from backup.
12390            if (!replacing) {
12391                IntentFilterVerificationInfo ivi =
12392                        mSettings.getIntentFilterVerificationLPr(packageName);
12393                if (ivi != null) {
12394                    if (DEBUG_DOMAIN_VERIFICATION) {
12395                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12396                                + ivi.getStatusString());
12397                    }
12398                    return;
12399                }
12400            }
12401
12402            // If any filters need to be verified, then all need to be.
12403            boolean needToVerify = false;
12404            for (PackageParser.Activity a : pkg.activities) {
12405                for (ActivityIntentInfo filter : a.intents) {
12406                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12407                        if (DEBUG_DOMAIN_VERIFICATION) {
12408                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12409                        }
12410                        needToVerify = true;
12411                        break;
12412                    }
12413                }
12414            }
12415
12416            if (needToVerify) {
12417                final int verificationId = mIntentFilterVerificationToken++;
12418                for (PackageParser.Activity a : pkg.activities) {
12419                    for (ActivityIntentInfo filter : a.intents) {
12420                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12421                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12422                                    "Verification needed for IntentFilter:" + filter.toString());
12423                            mIntentFilterVerifier.addOneIntentFilterVerification(
12424                                    verifierUid, userId, verificationId, filter, packageName);
12425                            count++;
12426                        }
12427                    }
12428                }
12429            }
12430        }
12431
12432        if (count > 0) {
12433            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12434                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12435                    +  " for userId:" + userId);
12436            mIntentFilterVerifier.startVerifications(userId);
12437        } else {
12438            if (DEBUG_DOMAIN_VERIFICATION) {
12439                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12440            }
12441        }
12442    }
12443
12444    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12445        final ComponentName cn  = filter.activity.getComponentName();
12446        final String packageName = cn.getPackageName();
12447
12448        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12449                packageName);
12450        if (ivi == null) {
12451            return true;
12452        }
12453        int status = ivi.getStatus();
12454        switch (status) {
12455            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12456            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12457                return true;
12458
12459            default:
12460                // Nothing to do
12461                return false;
12462        }
12463    }
12464
12465    private static boolean isMultiArch(PackageSetting ps) {
12466        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12467    }
12468
12469    private static boolean isMultiArch(ApplicationInfo info) {
12470        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12471    }
12472
12473    private static boolean isExternal(PackageParser.Package pkg) {
12474        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12475    }
12476
12477    private static boolean isExternal(PackageSetting ps) {
12478        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12479    }
12480
12481    private static boolean isExternal(ApplicationInfo info) {
12482        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12483    }
12484
12485    private static boolean isSystemApp(PackageParser.Package pkg) {
12486        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12487    }
12488
12489    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12490        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12491    }
12492
12493    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12494        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12495    }
12496
12497    private static boolean isSystemApp(PackageSetting ps) {
12498        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12499    }
12500
12501    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12502        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12503    }
12504
12505    private int packageFlagsToInstallFlags(PackageSetting ps) {
12506        int installFlags = 0;
12507        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12508            // This existing package was an external ASEC install when we have
12509            // the external flag without a UUID
12510            installFlags |= PackageManager.INSTALL_EXTERNAL;
12511        }
12512        if (ps.isForwardLocked()) {
12513            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12514        }
12515        return installFlags;
12516    }
12517
12518    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12519        if (isExternal(pkg)) {
12520            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12521                return mSettings.getExternalVersion();
12522            } else {
12523                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12524            }
12525        } else {
12526            return mSettings.getInternalVersion();
12527        }
12528    }
12529
12530    private void deleteTempPackageFiles() {
12531        final FilenameFilter filter = new FilenameFilter() {
12532            public boolean accept(File dir, String name) {
12533                return name.startsWith("vmdl") && name.endsWith(".tmp");
12534            }
12535        };
12536        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12537            file.delete();
12538        }
12539    }
12540
12541    @Override
12542    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12543            int flags) {
12544        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12545                flags);
12546    }
12547
12548    @Override
12549    public void deletePackage(final String packageName,
12550            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12551        mContext.enforceCallingOrSelfPermission(
12552                android.Manifest.permission.DELETE_PACKAGES, null);
12553        Preconditions.checkNotNull(packageName);
12554        Preconditions.checkNotNull(observer);
12555        final int uid = Binder.getCallingUid();
12556        if (UserHandle.getUserId(uid) != userId) {
12557            mContext.enforceCallingPermission(
12558                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12559                    "deletePackage for user " + userId);
12560        }
12561        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12562            try {
12563                observer.onPackageDeleted(packageName,
12564                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12565            } catch (RemoteException re) {
12566            }
12567            return;
12568        }
12569
12570        boolean uninstallBlocked = false;
12571        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12572            int[] users = sUserManager.getUserIds();
12573            for (int i = 0; i < users.length; ++i) {
12574                if (getBlockUninstallForUser(packageName, users[i])) {
12575                    uninstallBlocked = true;
12576                    break;
12577                }
12578            }
12579        } else {
12580            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12581        }
12582        if (uninstallBlocked) {
12583            try {
12584                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12585                        null);
12586            } catch (RemoteException re) {
12587            }
12588            return;
12589        }
12590
12591        if (DEBUG_REMOVE) {
12592            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12593        }
12594        // Queue up an async operation since the package deletion may take a little while.
12595        mHandler.post(new Runnable() {
12596            public void run() {
12597                mHandler.removeCallbacks(this);
12598                final int returnCode = deletePackageX(packageName, userId, flags);
12599                if (observer != null) {
12600                    try {
12601                        observer.onPackageDeleted(packageName, returnCode, null);
12602                    } catch (RemoteException e) {
12603                        Log.i(TAG, "Observer no longer exists.");
12604                    } //end catch
12605                } //end if
12606            } //end run
12607        });
12608    }
12609
12610    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12611        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12612                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12613        try {
12614            if (dpm != null) {
12615                if (dpm.isDeviceOwner(packageName)) {
12616                    return true;
12617                }
12618                int[] users;
12619                if (userId == UserHandle.USER_ALL) {
12620                    users = sUserManager.getUserIds();
12621                } else {
12622                    users = new int[]{userId};
12623                }
12624                for (int i = 0; i < users.length; ++i) {
12625                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12626                        return true;
12627                    }
12628                }
12629            }
12630        } catch (RemoteException e) {
12631        }
12632        return false;
12633    }
12634
12635    /**
12636     *  This method is an internal method that could be get invoked either
12637     *  to delete an installed package or to clean up a failed installation.
12638     *  After deleting an installed package, a broadcast is sent to notify any
12639     *  listeners that the package has been installed. For cleaning up a failed
12640     *  installation, the broadcast is not necessary since the package's
12641     *  installation wouldn't have sent the initial broadcast either
12642     *  The key steps in deleting a package are
12643     *  deleting the package information in internal structures like mPackages,
12644     *  deleting the packages base directories through installd
12645     *  updating mSettings to reflect current status
12646     *  persisting settings for later use
12647     *  sending a broadcast if necessary
12648     */
12649    private int deletePackageX(String packageName, int userId, int flags) {
12650        final PackageRemovedInfo info = new PackageRemovedInfo();
12651        final boolean res;
12652
12653        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12654                ? UserHandle.ALL : new UserHandle(userId);
12655
12656        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12657            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12658            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12659        }
12660
12661        boolean removedForAllUsers = false;
12662        boolean systemUpdate = false;
12663
12664        // for the uninstall-updates case and restricted profiles, remember the per-
12665        // userhandle installed state
12666        int[] allUsers;
12667        boolean[] perUserInstalled;
12668        synchronized (mPackages) {
12669            PackageSetting ps = mSettings.mPackages.get(packageName);
12670            allUsers = sUserManager.getUserIds();
12671            perUserInstalled = new boolean[allUsers.length];
12672            for (int i = 0; i < allUsers.length; i++) {
12673                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12674            }
12675        }
12676
12677        synchronized (mInstallLock) {
12678            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12679            res = deletePackageLI(packageName, removeForUser,
12680                    true, allUsers, perUserInstalled,
12681                    flags | REMOVE_CHATTY, info, true);
12682            systemUpdate = info.isRemovedPackageSystemUpdate;
12683            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12684                removedForAllUsers = true;
12685            }
12686            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12687                    + " removedForAllUsers=" + removedForAllUsers);
12688        }
12689
12690        if (res) {
12691            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12692
12693            // If the removed package was a system update, the old system package
12694            // was re-enabled; we need to broadcast this information
12695            if (systemUpdate) {
12696                Bundle extras = new Bundle(1);
12697                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12698                        ? info.removedAppId : info.uid);
12699                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12700
12701                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12702                        extras, null, null, null);
12703                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12704                        extras, null, null, null);
12705                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12706                        null, packageName, null, null);
12707            }
12708        }
12709        // Force a gc here.
12710        Runtime.getRuntime().gc();
12711        // Delete the resources here after sending the broadcast to let
12712        // other processes clean up before deleting resources.
12713        if (info.args != null) {
12714            synchronized (mInstallLock) {
12715                info.args.doPostDeleteLI(true);
12716            }
12717        }
12718
12719        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12720    }
12721
12722    class PackageRemovedInfo {
12723        String removedPackage;
12724        int uid = -1;
12725        int removedAppId = -1;
12726        int[] removedUsers = null;
12727        boolean isRemovedPackageSystemUpdate = false;
12728        // Clean up resources deleted packages.
12729        InstallArgs args = null;
12730
12731        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12732            Bundle extras = new Bundle(1);
12733            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12734            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12735            if (replacing) {
12736                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12737            }
12738            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12739            if (removedPackage != null) {
12740                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12741                        extras, null, null, removedUsers);
12742                if (fullRemove && !replacing) {
12743                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12744                            extras, null, null, removedUsers);
12745                }
12746            }
12747            if (removedAppId >= 0) {
12748                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12749                        removedUsers);
12750            }
12751        }
12752    }
12753
12754    /*
12755     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12756     * flag is not set, the data directory is removed as well.
12757     * make sure this flag is set for partially installed apps. If not its meaningless to
12758     * delete a partially installed application.
12759     */
12760    private void removePackageDataLI(PackageSetting ps,
12761            int[] allUserHandles, boolean[] perUserInstalled,
12762            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12763        String packageName = ps.name;
12764        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12765        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12766        // Retrieve object to delete permissions for shared user later on
12767        final PackageSetting deletedPs;
12768        // reader
12769        synchronized (mPackages) {
12770            deletedPs = mSettings.mPackages.get(packageName);
12771            if (outInfo != null) {
12772                outInfo.removedPackage = packageName;
12773                outInfo.removedUsers = deletedPs != null
12774                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12775                        : null;
12776            }
12777        }
12778        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12779            removeDataDirsLI(ps.volumeUuid, packageName);
12780            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12781        }
12782        // writer
12783        synchronized (mPackages) {
12784            if (deletedPs != null) {
12785                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12786                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12787                    clearDefaultBrowserIfNeeded(packageName);
12788                    if (outInfo != null) {
12789                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12790                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12791                    }
12792                    updatePermissionsLPw(deletedPs.name, null, 0);
12793                    if (deletedPs.sharedUser != null) {
12794                        // Remove permissions associated with package. Since runtime
12795                        // permissions are per user we have to kill the removed package
12796                        // or packages running under the shared user of the removed
12797                        // package if revoking the permissions requested only by the removed
12798                        // package is successful and this causes a change in gids.
12799                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12800                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12801                                    userId);
12802                            if (userIdToKill == UserHandle.USER_ALL
12803                                    || userIdToKill >= UserHandle.USER_OWNER) {
12804                                // If gids changed for this user, kill all affected packages.
12805                                mHandler.post(new Runnable() {
12806                                    @Override
12807                                    public void run() {
12808                                        // This has to happen with no lock held.
12809                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12810                                                KILL_APP_REASON_GIDS_CHANGED);
12811                                    }
12812                                });
12813                                break;
12814                            }
12815                        }
12816                    }
12817                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12818                }
12819                // make sure to preserve per-user disabled state if this removal was just
12820                // a downgrade of a system app to the factory package
12821                if (allUserHandles != null && perUserInstalled != null) {
12822                    if (DEBUG_REMOVE) {
12823                        Slog.d(TAG, "Propagating install state across downgrade");
12824                    }
12825                    for (int i = 0; i < allUserHandles.length; i++) {
12826                        if (DEBUG_REMOVE) {
12827                            Slog.d(TAG, "    user " + allUserHandles[i]
12828                                    + " => " + perUserInstalled[i]);
12829                        }
12830                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12831                    }
12832                }
12833            }
12834            // can downgrade to reader
12835            if (writeSettings) {
12836                // Save settings now
12837                mSettings.writeLPr();
12838            }
12839        }
12840        if (outInfo != null) {
12841            // A user ID was deleted here. Go through all users and remove it
12842            // from KeyStore.
12843            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12844        }
12845    }
12846
12847    static boolean locationIsPrivileged(File path) {
12848        try {
12849            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12850                    .getCanonicalPath();
12851            return path.getCanonicalPath().startsWith(privilegedAppDir);
12852        } catch (IOException e) {
12853            Slog.e(TAG, "Unable to access code path " + path);
12854        }
12855        return false;
12856    }
12857
12858    /*
12859     * Tries to delete system package.
12860     */
12861    private boolean deleteSystemPackageLI(PackageSetting newPs,
12862            int[] allUserHandles, boolean[] perUserInstalled,
12863            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12864        final boolean applyUserRestrictions
12865                = (allUserHandles != null) && (perUserInstalled != null);
12866        PackageSetting disabledPs = null;
12867        // Confirm if the system package has been updated
12868        // An updated system app can be deleted. This will also have to restore
12869        // the system pkg from system partition
12870        // reader
12871        synchronized (mPackages) {
12872            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12873        }
12874        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12875                + " disabledPs=" + disabledPs);
12876        if (disabledPs == null) {
12877            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12878            return false;
12879        } else if (DEBUG_REMOVE) {
12880            Slog.d(TAG, "Deleting system pkg from data partition");
12881        }
12882        if (DEBUG_REMOVE) {
12883            if (applyUserRestrictions) {
12884                Slog.d(TAG, "Remembering install states:");
12885                for (int i = 0; i < allUserHandles.length; i++) {
12886                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12887                }
12888            }
12889        }
12890        // Delete the updated package
12891        outInfo.isRemovedPackageSystemUpdate = true;
12892        if (disabledPs.versionCode < newPs.versionCode) {
12893            // Delete data for downgrades
12894            flags &= ~PackageManager.DELETE_KEEP_DATA;
12895        } else {
12896            // Preserve data by setting flag
12897            flags |= PackageManager.DELETE_KEEP_DATA;
12898        }
12899        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12900                allUserHandles, perUserInstalled, outInfo, writeSettings);
12901        if (!ret) {
12902            return false;
12903        }
12904        // writer
12905        synchronized (mPackages) {
12906            // Reinstate the old system package
12907            mSettings.enableSystemPackageLPw(newPs.name);
12908            // Remove any native libraries from the upgraded package.
12909            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12910        }
12911        // Install the system package
12912        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12913        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12914        if (locationIsPrivileged(disabledPs.codePath)) {
12915            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12916        }
12917
12918        final PackageParser.Package newPkg;
12919        try {
12920            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12921        } catch (PackageManagerException e) {
12922            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12923            return false;
12924        }
12925
12926        // writer
12927        synchronized (mPackages) {
12928            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12929
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                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12945                }
12946                // Regardless of writeSettings we need to ensure that this restriction
12947                // state propagation is persisted
12948                mSettings.writeAllUsersPackageRestrictionsLPr();
12949            }
12950            // can downgrade to reader here
12951            if (writeSettings) {
12952                mSettings.writeLPr();
12953            }
12954        }
12955        return true;
12956    }
12957
12958    private boolean deleteInstalledPackageLI(PackageSetting ps,
12959            boolean deleteCodeAndResources, int flags,
12960            int[] allUserHandles, boolean[] perUserInstalled,
12961            PackageRemovedInfo outInfo, boolean writeSettings) {
12962        if (outInfo != null) {
12963            outInfo.uid = ps.appId;
12964        }
12965
12966        // Delete package data from internal structures and also remove data if flag is set
12967        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12968
12969        // Delete application code and resources
12970        if (deleteCodeAndResources && (outInfo != null)) {
12971            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12972                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12973            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12974        }
12975        return true;
12976    }
12977
12978    @Override
12979    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12980            int userId) {
12981        mContext.enforceCallingOrSelfPermission(
12982                android.Manifest.permission.DELETE_PACKAGES, null);
12983        synchronized (mPackages) {
12984            PackageSetting ps = mSettings.mPackages.get(packageName);
12985            if (ps == null) {
12986                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12987                return false;
12988            }
12989            if (!ps.getInstalled(userId)) {
12990                // Can't block uninstall for an app that is not installed or enabled.
12991                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12992                return false;
12993            }
12994            ps.setBlockUninstall(blockUninstall, userId);
12995            mSettings.writePackageRestrictionsLPr(userId);
12996        }
12997        return true;
12998    }
12999
13000    @Override
13001    public boolean getBlockUninstallForUser(String packageName, int userId) {
13002        synchronized (mPackages) {
13003            PackageSetting ps = mSettings.mPackages.get(packageName);
13004            if (ps == null) {
13005                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13006                return false;
13007            }
13008            return ps.getBlockUninstall(userId);
13009        }
13010    }
13011
13012    /*
13013     * This method handles package deletion in general
13014     */
13015    private boolean deletePackageLI(String packageName, UserHandle user,
13016            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13017            int flags, PackageRemovedInfo outInfo,
13018            boolean writeSettings) {
13019        if (packageName == null) {
13020            Slog.w(TAG, "Attempt to delete null packageName.");
13021            return false;
13022        }
13023        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13024        PackageSetting ps;
13025        boolean dataOnly = false;
13026        int removeUser = -1;
13027        int appId = -1;
13028        synchronized (mPackages) {
13029            ps = mSettings.mPackages.get(packageName);
13030            if (ps == null) {
13031                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13032                return false;
13033            }
13034            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13035                    && user.getIdentifier() != UserHandle.USER_ALL) {
13036                // The caller is asking that the package only be deleted for a single
13037                // user.  To do this, we just mark its uninstalled state and delete
13038                // its data.  If this is a system app, we only allow this to happen if
13039                // they have set the special DELETE_SYSTEM_APP which requests different
13040                // semantics than normal for uninstalling system apps.
13041                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13042                ps.setUserState(user.getIdentifier(),
13043                        COMPONENT_ENABLED_STATE_DEFAULT,
13044                        false, //installed
13045                        true,  //stopped
13046                        true,  //notLaunched
13047                        false, //hidden
13048                        null, null, null,
13049                        false, // blockUninstall
13050                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13051                if (!isSystemApp(ps)) {
13052                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13053                        // Other user still have this package installed, so all
13054                        // we need to do is clear this user's data and save that
13055                        // it is uninstalled.
13056                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13057                        removeUser = user.getIdentifier();
13058                        appId = ps.appId;
13059                        scheduleWritePackageRestrictionsLocked(removeUser);
13060                    } else {
13061                        // We need to set it back to 'installed' so the uninstall
13062                        // broadcasts will be sent correctly.
13063                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13064                        ps.setInstalled(true, user.getIdentifier());
13065                    }
13066                } else {
13067                    // This is a system app, so we assume that the
13068                    // other users still have this package installed, so all
13069                    // we need to do is clear this user's data and save that
13070                    // it is uninstalled.
13071                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13072                    removeUser = user.getIdentifier();
13073                    appId = ps.appId;
13074                    scheduleWritePackageRestrictionsLocked(removeUser);
13075                }
13076            }
13077        }
13078
13079        if (removeUser >= 0) {
13080            // From above, we determined that we are deleting this only
13081            // for a single user.  Continue the work here.
13082            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13083            if (outInfo != null) {
13084                outInfo.removedPackage = packageName;
13085                outInfo.removedAppId = appId;
13086                outInfo.removedUsers = new int[] {removeUser};
13087            }
13088            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13089            removeKeystoreDataIfNeeded(removeUser, appId);
13090            schedulePackageCleaning(packageName, removeUser, false);
13091            synchronized (mPackages) {
13092                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13093                    scheduleWritePackageRestrictionsLocked(removeUser);
13094                }
13095                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13096            }
13097            return true;
13098        }
13099
13100        if (dataOnly) {
13101            // Delete application data first
13102            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13103            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13104            return true;
13105        }
13106
13107        boolean ret = false;
13108        if (isSystemApp(ps)) {
13109            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13110            // When an updated system application is deleted we delete the existing resources as well and
13111            // fall back to existing code in system partition
13112            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13113                    flags, outInfo, writeSettings);
13114        } else {
13115            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13116            // Kill application pre-emptively especially for apps on sd.
13117            killApplication(packageName, ps.appId, "uninstall pkg");
13118            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13119                    allUserHandles, perUserInstalled,
13120                    outInfo, writeSettings);
13121        }
13122
13123        return ret;
13124    }
13125
13126    private final class ClearStorageConnection implements ServiceConnection {
13127        IMediaContainerService mContainerService;
13128
13129        @Override
13130        public void onServiceConnected(ComponentName name, IBinder service) {
13131            synchronized (this) {
13132                mContainerService = IMediaContainerService.Stub.asInterface(service);
13133                notifyAll();
13134            }
13135        }
13136
13137        @Override
13138        public void onServiceDisconnected(ComponentName name) {
13139        }
13140    }
13141
13142    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13143        final boolean mounted;
13144        if (Environment.isExternalStorageEmulated()) {
13145            mounted = true;
13146        } else {
13147            final String status = Environment.getExternalStorageState();
13148
13149            mounted = status.equals(Environment.MEDIA_MOUNTED)
13150                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13151        }
13152
13153        if (!mounted) {
13154            return;
13155        }
13156
13157        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13158        int[] users;
13159        if (userId == UserHandle.USER_ALL) {
13160            users = sUserManager.getUserIds();
13161        } else {
13162            users = new int[] { userId };
13163        }
13164        final ClearStorageConnection conn = new ClearStorageConnection();
13165        if (mContext.bindServiceAsUser(
13166                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13167            try {
13168                for (int curUser : users) {
13169                    long timeout = SystemClock.uptimeMillis() + 5000;
13170                    synchronized (conn) {
13171                        long now = SystemClock.uptimeMillis();
13172                        while (conn.mContainerService == null && now < timeout) {
13173                            try {
13174                                conn.wait(timeout - now);
13175                            } catch (InterruptedException e) {
13176                            }
13177                        }
13178                    }
13179                    if (conn.mContainerService == null) {
13180                        return;
13181                    }
13182
13183                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13184                    clearDirectory(conn.mContainerService,
13185                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13186                    if (allData) {
13187                        clearDirectory(conn.mContainerService,
13188                                userEnv.buildExternalStorageAppDataDirs(packageName));
13189                        clearDirectory(conn.mContainerService,
13190                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13191                    }
13192                }
13193            } finally {
13194                mContext.unbindService(conn);
13195            }
13196        }
13197    }
13198
13199    @Override
13200    public void clearApplicationUserData(final String packageName,
13201            final IPackageDataObserver observer, final int userId) {
13202        mContext.enforceCallingOrSelfPermission(
13203                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13204        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13205        // Queue up an async operation since the package deletion may take a little while.
13206        mHandler.post(new Runnable() {
13207            public void run() {
13208                mHandler.removeCallbacks(this);
13209                final boolean succeeded;
13210                synchronized (mInstallLock) {
13211                    succeeded = clearApplicationUserDataLI(packageName, userId);
13212                }
13213                clearExternalStorageDataSync(packageName, userId, true);
13214                if (succeeded) {
13215                    // invoke DeviceStorageMonitor's update method to clear any notifications
13216                    DeviceStorageMonitorInternal
13217                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13218                    if (dsm != null) {
13219                        dsm.checkMemory();
13220                    }
13221                }
13222                if(observer != null) {
13223                    try {
13224                        observer.onRemoveCompleted(packageName, succeeded);
13225                    } catch (RemoteException e) {
13226                        Log.i(TAG, "Observer no longer exists.");
13227                    }
13228                } //end if observer
13229            } //end run
13230        });
13231    }
13232
13233    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13234        if (packageName == null) {
13235            Slog.w(TAG, "Attempt to delete null packageName.");
13236            return false;
13237        }
13238
13239        // Try finding details about the requested package
13240        PackageParser.Package pkg;
13241        synchronized (mPackages) {
13242            pkg = mPackages.get(packageName);
13243            if (pkg == null) {
13244                final PackageSetting ps = mSettings.mPackages.get(packageName);
13245                if (ps != null) {
13246                    pkg = ps.pkg;
13247                }
13248            }
13249
13250            if (pkg == null) {
13251                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13252                return false;
13253            }
13254
13255            PackageSetting ps = (PackageSetting) pkg.mExtras;
13256            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13257        }
13258
13259        // Always delete data directories for package, even if we found no other
13260        // record of app. This helps users recover from UID mismatches without
13261        // resorting to a full data wipe.
13262        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13263        if (retCode < 0) {
13264            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13265            return false;
13266        }
13267
13268        final int appId = pkg.applicationInfo.uid;
13269        removeKeystoreDataIfNeeded(userId, appId);
13270
13271        // Create a native library symlink only if we have native libraries
13272        // and if the native libraries are 32 bit libraries. We do not provide
13273        // this symlink for 64 bit libraries.
13274        if (pkg.applicationInfo.primaryCpuAbi != null &&
13275                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13276            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13277            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13278                    nativeLibPath, userId) < 0) {
13279                Slog.w(TAG, "Failed linking native library dir");
13280                return false;
13281            }
13282        }
13283
13284        return true;
13285    }
13286
13287    /**
13288     * Reverts user permission state changes (permissions and flags) in
13289     * all packages for a given user.
13290     *
13291     * @param userId The device user for which to do a reset.
13292     */
13293    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13294        final int packageCount = mPackages.size();
13295        for (int i = 0; i < packageCount; i++) {
13296            PackageParser.Package pkg = mPackages.valueAt(i);
13297            PackageSetting ps = (PackageSetting) pkg.mExtras;
13298            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13299        }
13300    }
13301
13302    /**
13303     * Reverts user permission state changes (permissions and flags).
13304     *
13305     * @param ps The package for which to reset.
13306     * @param userId The device user for which to do a reset.
13307     */
13308    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13309            final PackageSetting ps, final int userId) {
13310        if (ps.pkg == null) {
13311            return;
13312        }
13313
13314        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13315                | FLAG_PERMISSION_USER_FIXED
13316                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13317
13318        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13319                | FLAG_PERMISSION_POLICY_FIXED;
13320
13321        boolean writeInstallPermissions = false;
13322        boolean writeRuntimePermissions = false;
13323
13324        final int permissionCount = ps.pkg.requestedPermissions.size();
13325        for (int i = 0; i < permissionCount; i++) {
13326            String permission = ps.pkg.requestedPermissions.get(i);
13327
13328            BasePermission bp = mSettings.mPermissions.get(permission);
13329            if (bp == null) {
13330                continue;
13331            }
13332
13333            // If shared user we just reset the state to which only this app contributed.
13334            if (ps.sharedUser != null) {
13335                boolean used = false;
13336                final int packageCount = ps.sharedUser.packages.size();
13337                for (int j = 0; j < packageCount; j++) {
13338                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13339                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13340                            && pkg.pkg.requestedPermissions.contains(permission)) {
13341                        used = true;
13342                        break;
13343                    }
13344                }
13345                if (used) {
13346                    continue;
13347                }
13348            }
13349
13350            PermissionsState permissionsState = ps.getPermissionsState();
13351
13352            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13353
13354            // Always clear the user settable flags.
13355            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13356                    bp.name) != null;
13357            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13358                if (hasInstallState) {
13359                    writeInstallPermissions = true;
13360                } else {
13361                    writeRuntimePermissions = true;
13362                }
13363            }
13364
13365            // Below is only runtime permission handling.
13366            if (!bp.isRuntime()) {
13367                continue;
13368            }
13369
13370            // Never clobber system or policy.
13371            if ((oldFlags & policyOrSystemFlags) != 0) {
13372                continue;
13373            }
13374
13375            // If this permission was granted by default, make sure it is.
13376            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13377                if (permissionsState.grantRuntimePermission(bp, userId)
13378                        != PERMISSION_OPERATION_FAILURE) {
13379                    writeRuntimePermissions = true;
13380                }
13381            } else {
13382                // Otherwise, reset the permission.
13383                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13384                switch (revokeResult) {
13385                    case PERMISSION_OPERATION_SUCCESS: {
13386                        writeRuntimePermissions = true;
13387                    } break;
13388
13389                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13390                        writeRuntimePermissions = true;
13391                        // If gids changed for this user, kill all affected packages.
13392                        mHandler.post(new Runnable() {
13393                            @Override
13394                            public void run() {
13395                                // This has to happen with no lock held.
13396                                killSettingPackagesForUser(ps, userId,
13397                                        KILL_APP_REASON_GIDS_CHANGED);
13398                            }
13399                        });
13400                    } break;
13401                }
13402            }
13403        }
13404
13405        // Synchronously write as we are taking permissions away.
13406        if (writeRuntimePermissions) {
13407            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13408        }
13409
13410        // Synchronously write as we are taking permissions away.
13411        if (writeInstallPermissions) {
13412            mSettings.writeLPr();
13413        }
13414    }
13415
13416    /**
13417     * Remove entries from the keystore daemon. Will only remove it if the
13418     * {@code appId} is valid.
13419     */
13420    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13421        if (appId < 0) {
13422            return;
13423        }
13424
13425        final KeyStore keyStore = KeyStore.getInstance();
13426        if (keyStore != null) {
13427            if (userId == UserHandle.USER_ALL) {
13428                for (final int individual : sUserManager.getUserIds()) {
13429                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13430                }
13431            } else {
13432                keyStore.clearUid(UserHandle.getUid(userId, appId));
13433            }
13434        } else {
13435            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13436        }
13437    }
13438
13439    @Override
13440    public void deleteApplicationCacheFiles(final String packageName,
13441            final IPackageDataObserver observer) {
13442        mContext.enforceCallingOrSelfPermission(
13443                android.Manifest.permission.DELETE_CACHE_FILES, null);
13444        // Queue up an async operation since the package deletion may take a little while.
13445        final int userId = UserHandle.getCallingUserId();
13446        mHandler.post(new Runnable() {
13447            public void run() {
13448                mHandler.removeCallbacks(this);
13449                final boolean succeded;
13450                synchronized (mInstallLock) {
13451                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13452                }
13453                clearExternalStorageDataSync(packageName, userId, false);
13454                if (observer != null) {
13455                    try {
13456                        observer.onRemoveCompleted(packageName, succeded);
13457                    } catch (RemoteException e) {
13458                        Log.i(TAG, "Observer no longer exists.");
13459                    }
13460                } //end if observer
13461            } //end run
13462        });
13463    }
13464
13465    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13466        if (packageName == null) {
13467            Slog.w(TAG, "Attempt to delete null packageName.");
13468            return false;
13469        }
13470        PackageParser.Package p;
13471        synchronized (mPackages) {
13472            p = mPackages.get(packageName);
13473        }
13474        if (p == null) {
13475            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13476            return false;
13477        }
13478        final ApplicationInfo applicationInfo = p.applicationInfo;
13479        if (applicationInfo == null) {
13480            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13481            return false;
13482        }
13483        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13484        if (retCode < 0) {
13485            Slog.w(TAG, "Couldn't remove cache files for package: "
13486                       + packageName + " u" + userId);
13487            return false;
13488        }
13489        return true;
13490    }
13491
13492    @Override
13493    public void getPackageSizeInfo(final String packageName, int userHandle,
13494            final IPackageStatsObserver observer) {
13495        mContext.enforceCallingOrSelfPermission(
13496                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13497        if (packageName == null) {
13498            throw new IllegalArgumentException("Attempt to get size of null packageName");
13499        }
13500
13501        PackageStats stats = new PackageStats(packageName, userHandle);
13502
13503        /*
13504         * Queue up an async operation since the package measurement may take a
13505         * little while.
13506         */
13507        Message msg = mHandler.obtainMessage(INIT_COPY);
13508        msg.obj = new MeasureParams(stats, observer);
13509        mHandler.sendMessage(msg);
13510    }
13511
13512    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13513            PackageStats pStats) {
13514        if (packageName == null) {
13515            Slog.w(TAG, "Attempt to get size of null packageName.");
13516            return false;
13517        }
13518        PackageParser.Package p;
13519        boolean dataOnly = false;
13520        String libDirRoot = null;
13521        String asecPath = null;
13522        PackageSetting ps = null;
13523        synchronized (mPackages) {
13524            p = mPackages.get(packageName);
13525            ps = mSettings.mPackages.get(packageName);
13526            if(p == null) {
13527                dataOnly = true;
13528                if((ps == null) || (ps.pkg == null)) {
13529                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13530                    return false;
13531                }
13532                p = ps.pkg;
13533            }
13534            if (ps != null) {
13535                libDirRoot = ps.legacyNativeLibraryPathString;
13536            }
13537            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13538                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13539                if (secureContainerId != null) {
13540                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13541                }
13542            }
13543        }
13544        String publicSrcDir = null;
13545        if(!dataOnly) {
13546            final ApplicationInfo applicationInfo = p.applicationInfo;
13547            if (applicationInfo == null) {
13548                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13549                return false;
13550            }
13551            if (p.isForwardLocked()) {
13552                publicSrcDir = applicationInfo.getBaseResourcePath();
13553            }
13554        }
13555        // TODO: extend to measure size of split APKs
13556        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13557        // not just the first level.
13558        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13559        // just the primary.
13560        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13561        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13562                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13563        if (res < 0) {
13564            return false;
13565        }
13566
13567        // Fix-up for forward-locked applications in ASEC containers.
13568        if (!isExternal(p)) {
13569            pStats.codeSize += pStats.externalCodeSize;
13570            pStats.externalCodeSize = 0L;
13571        }
13572
13573        return true;
13574    }
13575
13576
13577    @Override
13578    public void addPackageToPreferred(String packageName) {
13579        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13580    }
13581
13582    @Override
13583    public void removePackageFromPreferred(String packageName) {
13584        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13585    }
13586
13587    @Override
13588    public List<PackageInfo> getPreferredPackages(int flags) {
13589        return new ArrayList<PackageInfo>();
13590    }
13591
13592    private int getUidTargetSdkVersionLockedLPr(int uid) {
13593        Object obj = mSettings.getUserIdLPr(uid);
13594        if (obj instanceof SharedUserSetting) {
13595            final SharedUserSetting sus = (SharedUserSetting) obj;
13596            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13597            final Iterator<PackageSetting> it = sus.packages.iterator();
13598            while (it.hasNext()) {
13599                final PackageSetting ps = it.next();
13600                if (ps.pkg != null) {
13601                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13602                    if (v < vers) vers = v;
13603                }
13604            }
13605            return vers;
13606        } else if (obj instanceof PackageSetting) {
13607            final PackageSetting ps = (PackageSetting) obj;
13608            if (ps.pkg != null) {
13609                return ps.pkg.applicationInfo.targetSdkVersion;
13610            }
13611        }
13612        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13613    }
13614
13615    @Override
13616    public void addPreferredActivity(IntentFilter filter, int match,
13617            ComponentName[] set, ComponentName activity, int userId) {
13618        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13619                "Adding preferred");
13620    }
13621
13622    private void addPreferredActivityInternal(IntentFilter filter, int match,
13623            ComponentName[] set, ComponentName activity, boolean always, int userId,
13624            String opname) {
13625        // writer
13626        int callingUid = Binder.getCallingUid();
13627        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13628        if (filter.countActions() == 0) {
13629            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13630            return;
13631        }
13632        synchronized (mPackages) {
13633            if (mContext.checkCallingOrSelfPermission(
13634                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13635                    != PackageManager.PERMISSION_GRANTED) {
13636                if (getUidTargetSdkVersionLockedLPr(callingUid)
13637                        < Build.VERSION_CODES.FROYO) {
13638                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13639                            + callingUid);
13640                    return;
13641                }
13642                mContext.enforceCallingOrSelfPermission(
13643                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13644            }
13645
13646            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13647            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13648                    + userId + ":");
13649            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13650            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13651            scheduleWritePackageRestrictionsLocked(userId);
13652        }
13653    }
13654
13655    @Override
13656    public void replacePreferredActivity(IntentFilter filter, int match,
13657            ComponentName[] set, ComponentName activity, int userId) {
13658        if (filter.countActions() != 1) {
13659            throw new IllegalArgumentException(
13660                    "replacePreferredActivity expects filter to have only 1 action.");
13661        }
13662        if (filter.countDataAuthorities() != 0
13663                || filter.countDataPaths() != 0
13664                || filter.countDataSchemes() > 1
13665                || filter.countDataTypes() != 0) {
13666            throw new IllegalArgumentException(
13667                    "replacePreferredActivity expects filter to have no data authorities, " +
13668                    "paths, or types; and at most one scheme.");
13669        }
13670
13671        final int callingUid = Binder.getCallingUid();
13672        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13673        synchronized (mPackages) {
13674            if (mContext.checkCallingOrSelfPermission(
13675                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13676                    != PackageManager.PERMISSION_GRANTED) {
13677                if (getUidTargetSdkVersionLockedLPr(callingUid)
13678                        < Build.VERSION_CODES.FROYO) {
13679                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13680                            + Binder.getCallingUid());
13681                    return;
13682                }
13683                mContext.enforceCallingOrSelfPermission(
13684                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13685            }
13686
13687            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13688            if (pir != null) {
13689                // Get all of the existing entries that exactly match this filter.
13690                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13691                if (existing != null && existing.size() == 1) {
13692                    PreferredActivity cur = existing.get(0);
13693                    if (DEBUG_PREFERRED) {
13694                        Slog.i(TAG, "Checking replace of preferred:");
13695                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13696                        if (!cur.mPref.mAlways) {
13697                            Slog.i(TAG, "  -- CUR; not mAlways!");
13698                        } else {
13699                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13700                            Slog.i(TAG, "  -- CUR: mSet="
13701                                    + Arrays.toString(cur.mPref.mSetComponents));
13702                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13703                            Slog.i(TAG, "  -- NEW: mMatch="
13704                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13705                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13706                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13707                        }
13708                    }
13709                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13710                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13711                            && cur.mPref.sameSet(set)) {
13712                        // Setting the preferred activity to what it happens to be already
13713                        if (DEBUG_PREFERRED) {
13714                            Slog.i(TAG, "Replacing with same preferred activity "
13715                                    + cur.mPref.mShortComponent + " for user "
13716                                    + userId + ":");
13717                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13718                        }
13719                        return;
13720                    }
13721                }
13722
13723                if (existing != null) {
13724                    if (DEBUG_PREFERRED) {
13725                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13726                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13727                    }
13728                    for (int i = 0; i < existing.size(); i++) {
13729                        PreferredActivity pa = existing.get(i);
13730                        if (DEBUG_PREFERRED) {
13731                            Slog.i(TAG, "Removing existing preferred activity "
13732                                    + pa.mPref.mComponent + ":");
13733                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13734                        }
13735                        pir.removeFilter(pa);
13736                    }
13737                }
13738            }
13739            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13740                    "Replacing preferred");
13741        }
13742    }
13743
13744    @Override
13745    public void clearPackagePreferredActivities(String packageName) {
13746        final int uid = Binder.getCallingUid();
13747        // writer
13748        synchronized (mPackages) {
13749            PackageParser.Package pkg = mPackages.get(packageName);
13750            if (pkg == null || pkg.applicationInfo.uid != uid) {
13751                if (mContext.checkCallingOrSelfPermission(
13752                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13753                        != PackageManager.PERMISSION_GRANTED) {
13754                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13755                            < Build.VERSION_CODES.FROYO) {
13756                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13757                                + Binder.getCallingUid());
13758                        return;
13759                    }
13760                    mContext.enforceCallingOrSelfPermission(
13761                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13762                }
13763            }
13764
13765            int user = UserHandle.getCallingUserId();
13766            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13767                scheduleWritePackageRestrictionsLocked(user);
13768            }
13769        }
13770    }
13771
13772    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13773    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13774        ArrayList<PreferredActivity> removed = null;
13775        boolean changed = false;
13776        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13777            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13778            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13779            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13780                continue;
13781            }
13782            Iterator<PreferredActivity> it = pir.filterIterator();
13783            while (it.hasNext()) {
13784                PreferredActivity pa = it.next();
13785                // Mark entry for removal only if it matches the package name
13786                // and the entry is of type "always".
13787                if (packageName == null ||
13788                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13789                                && pa.mPref.mAlways)) {
13790                    if (removed == null) {
13791                        removed = new ArrayList<PreferredActivity>();
13792                    }
13793                    removed.add(pa);
13794                }
13795            }
13796            if (removed != null) {
13797                for (int j=0; j<removed.size(); j++) {
13798                    PreferredActivity pa = removed.get(j);
13799                    pir.removeFilter(pa);
13800                }
13801                changed = true;
13802            }
13803        }
13804        return changed;
13805    }
13806
13807    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13808    private void clearIntentFilterVerificationsLPw(int userId) {
13809        final int packageCount = mPackages.size();
13810        for (int i = 0; i < packageCount; i++) {
13811            PackageParser.Package pkg = mPackages.valueAt(i);
13812            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13813        }
13814    }
13815
13816    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13817    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13818        if (userId == UserHandle.USER_ALL) {
13819            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13820                    sUserManager.getUserIds())) {
13821                for (int oneUserId : sUserManager.getUserIds()) {
13822                    scheduleWritePackageRestrictionsLocked(oneUserId);
13823                }
13824            }
13825        } else {
13826            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13827                scheduleWritePackageRestrictionsLocked(userId);
13828            }
13829        }
13830    }
13831
13832    void clearDefaultBrowserIfNeeded(String packageName) {
13833        for (int oneUserId : sUserManager.getUserIds()) {
13834            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13835            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13836            if (packageName.equals(defaultBrowserPackageName)) {
13837                setDefaultBrowserPackageName(null, oneUserId);
13838            }
13839        }
13840    }
13841
13842    @Override
13843    public void resetApplicationPreferences(int userId) {
13844        mContext.enforceCallingOrSelfPermission(
13845                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13846        // writer
13847        synchronized (mPackages) {
13848            final long identity = Binder.clearCallingIdentity();
13849            try {
13850                clearPackagePreferredActivitiesLPw(null, userId);
13851                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13852                // TODO: We have to reset the default SMS and Phone. This requires
13853                // significant refactoring to keep all default apps in the package
13854                // manager (cleaner but more work) or have the services provide
13855                // callbacks to the package manager to request a default app reset.
13856                applyFactoryDefaultBrowserLPw(userId);
13857                clearIntentFilterVerificationsLPw(userId);
13858                primeDomainVerificationsLPw(userId);
13859                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13860                scheduleWritePackageRestrictionsLocked(userId);
13861            } finally {
13862                Binder.restoreCallingIdentity(identity);
13863            }
13864        }
13865    }
13866
13867    @Override
13868    public int getPreferredActivities(List<IntentFilter> outFilters,
13869            List<ComponentName> outActivities, String packageName) {
13870
13871        int num = 0;
13872        final int userId = UserHandle.getCallingUserId();
13873        // reader
13874        synchronized (mPackages) {
13875            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13876            if (pir != null) {
13877                final Iterator<PreferredActivity> it = pir.filterIterator();
13878                while (it.hasNext()) {
13879                    final PreferredActivity pa = it.next();
13880                    if (packageName == null
13881                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13882                                    && pa.mPref.mAlways)) {
13883                        if (outFilters != null) {
13884                            outFilters.add(new IntentFilter(pa));
13885                        }
13886                        if (outActivities != null) {
13887                            outActivities.add(pa.mPref.mComponent);
13888                        }
13889                    }
13890                }
13891            }
13892        }
13893
13894        return num;
13895    }
13896
13897    @Override
13898    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13899            int userId) {
13900        int callingUid = Binder.getCallingUid();
13901        if (callingUid != Process.SYSTEM_UID) {
13902            throw new SecurityException(
13903                    "addPersistentPreferredActivity can only be run by the system");
13904        }
13905        if (filter.countActions() == 0) {
13906            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13907            return;
13908        }
13909        synchronized (mPackages) {
13910            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13911                    " :");
13912            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13913            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13914                    new PersistentPreferredActivity(filter, activity));
13915            scheduleWritePackageRestrictionsLocked(userId);
13916        }
13917    }
13918
13919    @Override
13920    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13921        int callingUid = Binder.getCallingUid();
13922        if (callingUid != Process.SYSTEM_UID) {
13923            throw new SecurityException(
13924                    "clearPackagePersistentPreferredActivities can only be run by the system");
13925        }
13926        ArrayList<PersistentPreferredActivity> removed = null;
13927        boolean changed = false;
13928        synchronized (mPackages) {
13929            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13930                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13931                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13932                        .valueAt(i);
13933                if (userId != thisUserId) {
13934                    continue;
13935                }
13936                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13937                while (it.hasNext()) {
13938                    PersistentPreferredActivity ppa = it.next();
13939                    // Mark entry for removal only if it matches the package name.
13940                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13941                        if (removed == null) {
13942                            removed = new ArrayList<PersistentPreferredActivity>();
13943                        }
13944                        removed.add(ppa);
13945                    }
13946                }
13947                if (removed != null) {
13948                    for (int j=0; j<removed.size(); j++) {
13949                        PersistentPreferredActivity ppa = removed.get(j);
13950                        ppir.removeFilter(ppa);
13951                    }
13952                    changed = true;
13953                }
13954            }
13955
13956            if (changed) {
13957                scheduleWritePackageRestrictionsLocked(userId);
13958            }
13959        }
13960    }
13961
13962    /**
13963     * Common machinery for picking apart a restored XML blob and passing
13964     * it to a caller-supplied functor to be applied to the running system.
13965     */
13966    private void restoreFromXml(XmlPullParser parser, int userId,
13967            String expectedStartTag, BlobXmlRestorer functor)
13968            throws IOException, XmlPullParserException {
13969        int type;
13970        while ((type = parser.next()) != XmlPullParser.START_TAG
13971                && type != XmlPullParser.END_DOCUMENT) {
13972        }
13973        if (type != XmlPullParser.START_TAG) {
13974            // oops didn't find a start tag?!
13975            if (DEBUG_BACKUP) {
13976                Slog.e(TAG, "Didn't find start tag during restore");
13977            }
13978            return;
13979        }
13980
13981        // this is supposed to be TAG_PREFERRED_BACKUP
13982        if (!expectedStartTag.equals(parser.getName())) {
13983            if (DEBUG_BACKUP) {
13984                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13985            }
13986            return;
13987        }
13988
13989        // skip interfering stuff, then we're aligned with the backing implementation
13990        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13991        functor.apply(parser, userId);
13992    }
13993
13994    private interface BlobXmlRestorer {
13995        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13996    }
13997
13998    /**
13999     * Non-Binder method, support for the backup/restore mechanism: write the
14000     * full set of preferred activities in its canonical XML format.  Returns the
14001     * XML output as a byte array, or null if there is none.
14002     */
14003    @Override
14004    public byte[] getPreferredActivityBackup(int userId) {
14005        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14006            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14007        }
14008
14009        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14010        try {
14011            final XmlSerializer serializer = new FastXmlSerializer();
14012            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14013            serializer.startDocument(null, true);
14014            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14015
14016            synchronized (mPackages) {
14017                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14018            }
14019
14020            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14021            serializer.endDocument();
14022            serializer.flush();
14023        } catch (Exception e) {
14024            if (DEBUG_BACKUP) {
14025                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14026            }
14027            return null;
14028        }
14029
14030        return dataStream.toByteArray();
14031    }
14032
14033    @Override
14034    public void restorePreferredActivities(byte[] backup, int userId) {
14035        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14036            throw new SecurityException("Only the system may call restorePreferredActivities()");
14037        }
14038
14039        try {
14040            final XmlPullParser parser = Xml.newPullParser();
14041            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14042            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14043                    new BlobXmlRestorer() {
14044                        @Override
14045                        public void apply(XmlPullParser parser, int userId)
14046                                throws XmlPullParserException, IOException {
14047                            synchronized (mPackages) {
14048                                mSettings.readPreferredActivitiesLPw(parser, userId);
14049                            }
14050                        }
14051                    } );
14052        } catch (Exception e) {
14053            if (DEBUG_BACKUP) {
14054                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14055            }
14056        }
14057    }
14058
14059    /**
14060     * Non-Binder method, support for the backup/restore mechanism: write the
14061     * default browser (etc) settings in its canonical XML format.  Returns the default
14062     * browser XML representation as a byte array, or null if there is none.
14063     */
14064    @Override
14065    public byte[] getDefaultAppsBackup(int userId) {
14066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14067            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14068        }
14069
14070        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14071        try {
14072            final XmlSerializer serializer = new FastXmlSerializer();
14073            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14074            serializer.startDocument(null, true);
14075            serializer.startTag(null, TAG_DEFAULT_APPS);
14076
14077            synchronized (mPackages) {
14078                mSettings.writeDefaultAppsLPr(serializer, userId);
14079            }
14080
14081            serializer.endTag(null, TAG_DEFAULT_APPS);
14082            serializer.endDocument();
14083            serializer.flush();
14084        } catch (Exception e) {
14085            if (DEBUG_BACKUP) {
14086                Slog.e(TAG, "Unable to write default apps for backup", e);
14087            }
14088            return null;
14089        }
14090
14091        return dataStream.toByteArray();
14092    }
14093
14094    @Override
14095    public void restoreDefaultApps(byte[] backup, int userId) {
14096        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14097            throw new SecurityException("Only the system may call restoreDefaultApps()");
14098        }
14099
14100        try {
14101            final XmlPullParser parser = Xml.newPullParser();
14102            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14103            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14104                    new BlobXmlRestorer() {
14105                        @Override
14106                        public void apply(XmlPullParser parser, int userId)
14107                                throws XmlPullParserException, IOException {
14108                            synchronized (mPackages) {
14109                                mSettings.readDefaultAppsLPw(parser, userId);
14110                            }
14111                        }
14112                    } );
14113        } catch (Exception e) {
14114            if (DEBUG_BACKUP) {
14115                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14116            }
14117        }
14118    }
14119
14120    @Override
14121    public byte[] getIntentFilterVerificationBackup(int userId) {
14122        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14123            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14124        }
14125
14126        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14127        try {
14128            final XmlSerializer serializer = new FastXmlSerializer();
14129            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14130            serializer.startDocument(null, true);
14131            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14132
14133            synchronized (mPackages) {
14134                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14135            }
14136
14137            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14138            serializer.endDocument();
14139            serializer.flush();
14140        } catch (Exception e) {
14141            if (DEBUG_BACKUP) {
14142                Slog.e(TAG, "Unable to write default apps for backup", e);
14143            }
14144            return null;
14145        }
14146
14147        return dataStream.toByteArray();
14148    }
14149
14150    @Override
14151    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14152        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14153            throw new SecurityException("Only the system may call restorePreferredActivities()");
14154        }
14155
14156        try {
14157            final XmlPullParser parser = Xml.newPullParser();
14158            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14159            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14160                    new BlobXmlRestorer() {
14161                        @Override
14162                        public void apply(XmlPullParser parser, int userId)
14163                                throws XmlPullParserException, IOException {
14164                            synchronized (mPackages) {
14165                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14166                                mSettings.writeLPr();
14167                            }
14168                        }
14169                    } );
14170        } catch (Exception e) {
14171            if (DEBUG_BACKUP) {
14172                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14173            }
14174        }
14175    }
14176
14177    @Override
14178    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14179            int sourceUserId, int targetUserId, int flags) {
14180        mContext.enforceCallingOrSelfPermission(
14181                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14182        int callingUid = Binder.getCallingUid();
14183        enforceOwnerRights(ownerPackage, callingUid);
14184        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14185        if (intentFilter.countActions() == 0) {
14186            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14187            return;
14188        }
14189        synchronized (mPackages) {
14190            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14191                    ownerPackage, targetUserId, flags);
14192            CrossProfileIntentResolver resolver =
14193                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14194            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14195            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14196            if (existing != null) {
14197                int size = existing.size();
14198                for (int i = 0; i < size; i++) {
14199                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14200                        return;
14201                    }
14202                }
14203            }
14204            resolver.addFilter(newFilter);
14205            scheduleWritePackageRestrictionsLocked(sourceUserId);
14206        }
14207    }
14208
14209    @Override
14210    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14211        mContext.enforceCallingOrSelfPermission(
14212                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14213        int callingUid = Binder.getCallingUid();
14214        enforceOwnerRights(ownerPackage, callingUid);
14215        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14216        synchronized (mPackages) {
14217            CrossProfileIntentResolver resolver =
14218                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14219            ArraySet<CrossProfileIntentFilter> set =
14220                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14221            for (CrossProfileIntentFilter filter : set) {
14222                if (filter.getOwnerPackage().equals(ownerPackage)) {
14223                    resolver.removeFilter(filter);
14224                }
14225            }
14226            scheduleWritePackageRestrictionsLocked(sourceUserId);
14227        }
14228    }
14229
14230    // Enforcing that callingUid is owning pkg on userId
14231    private void enforceOwnerRights(String pkg, int callingUid) {
14232        // The system owns everything.
14233        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14234            return;
14235        }
14236        int callingUserId = UserHandle.getUserId(callingUid);
14237        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14238        if (pi == null) {
14239            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14240                    + callingUserId);
14241        }
14242        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14243            throw new SecurityException("Calling uid " + callingUid
14244                    + " does not own package " + pkg);
14245        }
14246    }
14247
14248    @Override
14249    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14250        Intent intent = new Intent(Intent.ACTION_MAIN);
14251        intent.addCategory(Intent.CATEGORY_HOME);
14252
14253        final int callingUserId = UserHandle.getCallingUserId();
14254        List<ResolveInfo> list = queryIntentActivities(intent, null,
14255                PackageManager.GET_META_DATA, callingUserId);
14256        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14257                true, false, false, callingUserId);
14258
14259        allHomeCandidates.clear();
14260        if (list != null) {
14261            for (ResolveInfo ri : list) {
14262                allHomeCandidates.add(ri);
14263            }
14264        }
14265        return (preferred == null || preferred.activityInfo == null)
14266                ? null
14267                : new ComponentName(preferred.activityInfo.packageName,
14268                        preferred.activityInfo.name);
14269    }
14270
14271    @Override
14272    public void setApplicationEnabledSetting(String appPackageName,
14273            int newState, int flags, int userId, String callingPackage) {
14274        if (!sUserManager.exists(userId)) return;
14275        if (callingPackage == null) {
14276            callingPackage = Integer.toString(Binder.getCallingUid());
14277        }
14278        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14279    }
14280
14281    @Override
14282    public void setComponentEnabledSetting(ComponentName componentName,
14283            int newState, int flags, int userId) {
14284        if (!sUserManager.exists(userId)) return;
14285        setEnabledSetting(componentName.getPackageName(),
14286                componentName.getClassName(), newState, flags, userId, null);
14287    }
14288
14289    private void setEnabledSetting(final String packageName, String className, int newState,
14290            final int flags, int userId, String callingPackage) {
14291        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14292              || newState == COMPONENT_ENABLED_STATE_ENABLED
14293              || newState == COMPONENT_ENABLED_STATE_DISABLED
14294              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14295              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14296            throw new IllegalArgumentException("Invalid new component state: "
14297                    + newState);
14298        }
14299        PackageSetting pkgSetting;
14300        final int uid = Binder.getCallingUid();
14301        final int permission = mContext.checkCallingOrSelfPermission(
14302                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14303        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14304        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14305        boolean sendNow = false;
14306        boolean isApp = (className == null);
14307        String componentName = isApp ? packageName : className;
14308        int packageUid = -1;
14309        ArrayList<String> components;
14310
14311        // writer
14312        synchronized (mPackages) {
14313            pkgSetting = mSettings.mPackages.get(packageName);
14314            if (pkgSetting == null) {
14315                if (className == null) {
14316                    throw new IllegalArgumentException(
14317                            "Unknown package: " + packageName);
14318                }
14319                throw new IllegalArgumentException(
14320                        "Unknown component: " + packageName
14321                        + "/" + className);
14322            }
14323            // Allow root and verify that userId is not being specified by a different user
14324            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14325                throw new SecurityException(
14326                        "Permission Denial: attempt to change component state from pid="
14327                        + Binder.getCallingPid()
14328                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14329            }
14330            if (className == null) {
14331                // We're dealing with an application/package level state change
14332                if (pkgSetting.getEnabled(userId) == newState) {
14333                    // Nothing to do
14334                    return;
14335                }
14336                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14337                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14338                    // Don't care about who enables an app.
14339                    callingPackage = null;
14340                }
14341                pkgSetting.setEnabled(newState, userId, callingPackage);
14342                // pkgSetting.pkg.mSetEnabled = newState;
14343            } else {
14344                // We're dealing with a component level state change
14345                // First, verify that this is a valid class name.
14346                PackageParser.Package pkg = pkgSetting.pkg;
14347                if (pkg == null || !pkg.hasComponentClassName(className)) {
14348                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14349                        throw new IllegalArgumentException("Component class " + className
14350                                + " does not exist in " + packageName);
14351                    } else {
14352                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14353                                + className + " does not exist in " + packageName);
14354                    }
14355                }
14356                switch (newState) {
14357                case COMPONENT_ENABLED_STATE_ENABLED:
14358                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14359                        return;
14360                    }
14361                    break;
14362                case COMPONENT_ENABLED_STATE_DISABLED:
14363                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14364                        return;
14365                    }
14366                    break;
14367                case COMPONENT_ENABLED_STATE_DEFAULT:
14368                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14369                        return;
14370                    }
14371                    break;
14372                default:
14373                    Slog.e(TAG, "Invalid new component state: " + newState);
14374                    return;
14375                }
14376            }
14377            scheduleWritePackageRestrictionsLocked(userId);
14378            components = mPendingBroadcasts.get(userId, packageName);
14379            final boolean newPackage = components == null;
14380            if (newPackage) {
14381                components = new ArrayList<String>();
14382            }
14383            if (!components.contains(componentName)) {
14384                components.add(componentName);
14385            }
14386            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14387                sendNow = true;
14388                // Purge entry from pending broadcast list if another one exists already
14389                // since we are sending one right away.
14390                mPendingBroadcasts.remove(userId, packageName);
14391            } else {
14392                if (newPackage) {
14393                    mPendingBroadcasts.put(userId, packageName, components);
14394                }
14395                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14396                    // Schedule a message
14397                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14398                }
14399            }
14400        }
14401
14402        long callingId = Binder.clearCallingIdentity();
14403        try {
14404            if (sendNow) {
14405                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14406                sendPackageChangedBroadcast(packageName,
14407                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14408            }
14409        } finally {
14410            Binder.restoreCallingIdentity(callingId);
14411        }
14412    }
14413
14414    private void sendPackageChangedBroadcast(String packageName,
14415            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14416        if (DEBUG_INSTALL)
14417            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14418                    + componentNames);
14419        Bundle extras = new Bundle(4);
14420        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14421        String nameList[] = new String[componentNames.size()];
14422        componentNames.toArray(nameList);
14423        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14424        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14425        extras.putInt(Intent.EXTRA_UID, packageUid);
14426        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14427                new int[] {UserHandle.getUserId(packageUid)});
14428    }
14429
14430    @Override
14431    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14432        if (!sUserManager.exists(userId)) return;
14433        final int uid = Binder.getCallingUid();
14434        final int permission = mContext.checkCallingOrSelfPermission(
14435                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14436        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14437        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14438        // writer
14439        synchronized (mPackages) {
14440            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14441                    allowedByPermission, uid, userId)) {
14442                scheduleWritePackageRestrictionsLocked(userId);
14443            }
14444        }
14445    }
14446
14447    @Override
14448    public String getInstallerPackageName(String packageName) {
14449        // reader
14450        synchronized (mPackages) {
14451            return mSettings.getInstallerPackageNameLPr(packageName);
14452        }
14453    }
14454
14455    @Override
14456    public int getApplicationEnabledSetting(String packageName, int userId) {
14457        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14458        int uid = Binder.getCallingUid();
14459        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14460        // reader
14461        synchronized (mPackages) {
14462            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14463        }
14464    }
14465
14466    @Override
14467    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14468        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14469        int uid = Binder.getCallingUid();
14470        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14471        // reader
14472        synchronized (mPackages) {
14473            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14474        }
14475    }
14476
14477    @Override
14478    public void enterSafeMode() {
14479        enforceSystemOrRoot("Only the system can request entering safe mode");
14480
14481        if (!mSystemReady) {
14482            mSafeMode = true;
14483        }
14484    }
14485
14486    @Override
14487    public void systemReady() {
14488        mSystemReady = true;
14489
14490        // Read the compatibilty setting when the system is ready.
14491        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14492                mContext.getContentResolver(),
14493                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14494        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14495        if (DEBUG_SETTINGS) {
14496            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14497        }
14498
14499        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14500
14501        synchronized (mPackages) {
14502            // Verify that all of the preferred activity components actually
14503            // exist.  It is possible for applications to be updated and at
14504            // that point remove a previously declared activity component that
14505            // had been set as a preferred activity.  We try to clean this up
14506            // the next time we encounter that preferred activity, but it is
14507            // possible for the user flow to never be able to return to that
14508            // situation so here we do a sanity check to make sure we haven't
14509            // left any junk around.
14510            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14511            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14512                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14513                removed.clear();
14514                for (PreferredActivity pa : pir.filterSet()) {
14515                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14516                        removed.add(pa);
14517                    }
14518                }
14519                if (removed.size() > 0) {
14520                    for (int r=0; r<removed.size(); r++) {
14521                        PreferredActivity pa = removed.get(r);
14522                        Slog.w(TAG, "Removing dangling preferred activity: "
14523                                + pa.mPref.mComponent);
14524                        pir.removeFilter(pa);
14525                    }
14526                    mSettings.writePackageRestrictionsLPr(
14527                            mSettings.mPreferredActivities.keyAt(i));
14528                }
14529            }
14530
14531            for (int userId : UserManagerService.getInstance().getUserIds()) {
14532                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14533                    grantPermissionsUserIds = ArrayUtils.appendInt(
14534                            grantPermissionsUserIds, userId);
14535                }
14536            }
14537        }
14538        sUserManager.systemReady();
14539
14540        // If we upgraded grant all default permissions before kicking off.
14541        for (int userId : grantPermissionsUserIds) {
14542            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14543        }
14544
14545        // Kick off any messages waiting for system ready
14546        if (mPostSystemReadyMessages != null) {
14547            for (Message msg : mPostSystemReadyMessages) {
14548                msg.sendToTarget();
14549            }
14550            mPostSystemReadyMessages = null;
14551        }
14552
14553        // Watch for external volumes that come and go over time
14554        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14555        storage.registerListener(mStorageListener);
14556
14557        mInstallerService.systemReady();
14558        mPackageDexOptimizer.systemReady();
14559
14560        MountServiceInternal mountServiceInternal = LocalServices.getService(
14561                MountServiceInternal.class);
14562        mountServiceInternal.addExternalStoragePolicy(
14563                new MountServiceInternal.ExternalStorageMountPolicy() {
14564            @Override
14565            public int getMountMode(int uid, String packageName) {
14566                if (Process.isIsolated(uid)) {
14567                    return Zygote.MOUNT_EXTERNAL_NONE;
14568                }
14569                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14570                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14571                }
14572                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14573                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14574                }
14575                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14576                    return Zygote.MOUNT_EXTERNAL_READ;
14577                }
14578                return Zygote.MOUNT_EXTERNAL_WRITE;
14579            }
14580
14581            @Override
14582            public boolean hasExternalStorage(int uid, String packageName) {
14583                return true;
14584            }
14585        });
14586    }
14587
14588    @Override
14589    public boolean isSafeMode() {
14590        return mSafeMode;
14591    }
14592
14593    @Override
14594    public boolean hasSystemUidErrors() {
14595        return mHasSystemUidErrors;
14596    }
14597
14598    static String arrayToString(int[] array) {
14599        StringBuffer buf = new StringBuffer(128);
14600        buf.append('[');
14601        if (array != null) {
14602            for (int i=0; i<array.length; i++) {
14603                if (i > 0) buf.append(", ");
14604                buf.append(array[i]);
14605            }
14606        }
14607        buf.append(']');
14608        return buf.toString();
14609    }
14610
14611    static class DumpState {
14612        public static final int DUMP_LIBS = 1 << 0;
14613        public static final int DUMP_FEATURES = 1 << 1;
14614        public static final int DUMP_RESOLVERS = 1 << 2;
14615        public static final int DUMP_PERMISSIONS = 1 << 3;
14616        public static final int DUMP_PACKAGES = 1 << 4;
14617        public static final int DUMP_SHARED_USERS = 1 << 5;
14618        public static final int DUMP_MESSAGES = 1 << 6;
14619        public static final int DUMP_PROVIDERS = 1 << 7;
14620        public static final int DUMP_VERIFIERS = 1 << 8;
14621        public static final int DUMP_PREFERRED = 1 << 9;
14622        public static final int DUMP_PREFERRED_XML = 1 << 10;
14623        public static final int DUMP_KEYSETS = 1 << 11;
14624        public static final int DUMP_VERSION = 1 << 12;
14625        public static final int DUMP_INSTALLS = 1 << 13;
14626        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14627        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14628
14629        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14630
14631        private int mTypes;
14632
14633        private int mOptions;
14634
14635        private boolean mTitlePrinted;
14636
14637        private SharedUserSetting mSharedUser;
14638
14639        public boolean isDumping(int type) {
14640            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14641                return true;
14642            }
14643
14644            return (mTypes & type) != 0;
14645        }
14646
14647        public void setDump(int type) {
14648            mTypes |= type;
14649        }
14650
14651        public boolean isOptionEnabled(int option) {
14652            return (mOptions & option) != 0;
14653        }
14654
14655        public void setOptionEnabled(int option) {
14656            mOptions |= option;
14657        }
14658
14659        public boolean onTitlePrinted() {
14660            final boolean printed = mTitlePrinted;
14661            mTitlePrinted = true;
14662            return printed;
14663        }
14664
14665        public boolean getTitlePrinted() {
14666            return mTitlePrinted;
14667        }
14668
14669        public void setTitlePrinted(boolean enabled) {
14670            mTitlePrinted = enabled;
14671        }
14672
14673        public SharedUserSetting getSharedUser() {
14674            return mSharedUser;
14675        }
14676
14677        public void setSharedUser(SharedUserSetting user) {
14678            mSharedUser = user;
14679        }
14680    }
14681
14682    @Override
14683    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14684        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14685                != PackageManager.PERMISSION_GRANTED) {
14686            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14687                    + Binder.getCallingPid()
14688                    + ", uid=" + Binder.getCallingUid()
14689                    + " without permission "
14690                    + android.Manifest.permission.DUMP);
14691            return;
14692        }
14693
14694        DumpState dumpState = new DumpState();
14695        boolean fullPreferred = false;
14696        boolean checkin = false;
14697
14698        String packageName = null;
14699        ArraySet<String> permissionNames = null;
14700
14701        int opti = 0;
14702        while (opti < args.length) {
14703            String opt = args[opti];
14704            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14705                break;
14706            }
14707            opti++;
14708
14709            if ("-a".equals(opt)) {
14710                // Right now we only know how to print all.
14711            } else if ("-h".equals(opt)) {
14712                pw.println("Package manager dump options:");
14713                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14714                pw.println("    --checkin: dump for a checkin");
14715                pw.println("    -f: print details of intent filters");
14716                pw.println("    -h: print this help");
14717                pw.println("  cmd may be one of:");
14718                pw.println("    l[ibraries]: list known shared libraries");
14719                pw.println("    f[ibraries]: list device features");
14720                pw.println("    k[eysets]: print known keysets");
14721                pw.println("    r[esolvers]: dump intent resolvers");
14722                pw.println("    perm[issions]: dump permissions");
14723                pw.println("    permission [name ...]: dump declaration and use of given permission");
14724                pw.println("    pref[erred]: print preferred package settings");
14725                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14726                pw.println("    prov[iders]: dump content providers");
14727                pw.println("    p[ackages]: dump installed packages");
14728                pw.println("    s[hared-users]: dump shared user IDs");
14729                pw.println("    m[essages]: print collected runtime messages");
14730                pw.println("    v[erifiers]: print package verifier info");
14731                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14732                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14733                pw.println("    version: print database version info");
14734                pw.println("    write: write current settings now");
14735                pw.println("    installs: details about install sessions");
14736                pw.println("    <package.name>: info about given package");
14737                return;
14738            } else if ("--checkin".equals(opt)) {
14739                checkin = true;
14740            } else if ("-f".equals(opt)) {
14741                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14742            } else {
14743                pw.println("Unknown argument: " + opt + "; use -h for help");
14744            }
14745        }
14746
14747        // Is the caller requesting to dump a particular piece of data?
14748        if (opti < args.length) {
14749            String cmd = args[opti];
14750            opti++;
14751            // Is this a package name?
14752            if ("android".equals(cmd) || cmd.contains(".")) {
14753                packageName = cmd;
14754                // When dumping a single package, we always dump all of its
14755                // filter information since the amount of data will be reasonable.
14756                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14757            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14758                dumpState.setDump(DumpState.DUMP_LIBS);
14759            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14760                dumpState.setDump(DumpState.DUMP_FEATURES);
14761            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14762                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14763            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14764                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14765            } else if ("permission".equals(cmd)) {
14766                if (opti >= args.length) {
14767                    pw.println("Error: permission requires permission name");
14768                    return;
14769                }
14770                permissionNames = new ArraySet<>();
14771                while (opti < args.length) {
14772                    permissionNames.add(args[opti]);
14773                    opti++;
14774                }
14775                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14776                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14777            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14778                dumpState.setDump(DumpState.DUMP_PREFERRED);
14779            } else if ("preferred-xml".equals(cmd)) {
14780                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14781                if (opti < args.length && "--full".equals(args[opti])) {
14782                    fullPreferred = true;
14783                    opti++;
14784                }
14785            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14786                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14787            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14788                dumpState.setDump(DumpState.DUMP_PACKAGES);
14789            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14790                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14791            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14792                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14793            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14794                dumpState.setDump(DumpState.DUMP_MESSAGES);
14795            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14796                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14797            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14798                    || "intent-filter-verifiers".equals(cmd)) {
14799                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14800            } else if ("version".equals(cmd)) {
14801                dumpState.setDump(DumpState.DUMP_VERSION);
14802            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14803                dumpState.setDump(DumpState.DUMP_KEYSETS);
14804            } else if ("installs".equals(cmd)) {
14805                dumpState.setDump(DumpState.DUMP_INSTALLS);
14806            } else if ("write".equals(cmd)) {
14807                synchronized (mPackages) {
14808                    mSettings.writeLPr();
14809                    pw.println("Settings written.");
14810                    return;
14811                }
14812            }
14813        }
14814
14815        if (checkin) {
14816            pw.println("vers,1");
14817        }
14818
14819        // reader
14820        synchronized (mPackages) {
14821            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14822                if (!checkin) {
14823                    if (dumpState.onTitlePrinted())
14824                        pw.println();
14825                    pw.println("Database versions:");
14826                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14827                }
14828            }
14829
14830            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14831                if (!checkin) {
14832                    if (dumpState.onTitlePrinted())
14833                        pw.println();
14834                    pw.println("Verifiers:");
14835                    pw.print("  Required: ");
14836                    pw.print(mRequiredVerifierPackage);
14837                    pw.print(" (uid=");
14838                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14839                    pw.println(")");
14840                } else if (mRequiredVerifierPackage != null) {
14841                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14842                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14843                }
14844            }
14845
14846            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14847                    packageName == null) {
14848                if (mIntentFilterVerifierComponent != null) {
14849                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14850                    if (!checkin) {
14851                        if (dumpState.onTitlePrinted())
14852                            pw.println();
14853                        pw.println("Intent Filter Verifier:");
14854                        pw.print("  Using: ");
14855                        pw.print(verifierPackageName);
14856                        pw.print(" (uid=");
14857                        pw.print(getPackageUid(verifierPackageName, 0));
14858                        pw.println(")");
14859                    } else if (verifierPackageName != null) {
14860                        pw.print("ifv,"); pw.print(verifierPackageName);
14861                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14862                    }
14863                } else {
14864                    pw.println();
14865                    pw.println("No Intent Filter Verifier available!");
14866                }
14867            }
14868
14869            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14870                boolean printedHeader = false;
14871                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14872                while (it.hasNext()) {
14873                    String name = it.next();
14874                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14875                    if (!checkin) {
14876                        if (!printedHeader) {
14877                            if (dumpState.onTitlePrinted())
14878                                pw.println();
14879                            pw.println("Libraries:");
14880                            printedHeader = true;
14881                        }
14882                        pw.print("  ");
14883                    } else {
14884                        pw.print("lib,");
14885                    }
14886                    pw.print(name);
14887                    if (!checkin) {
14888                        pw.print(" -> ");
14889                    }
14890                    if (ent.path != null) {
14891                        if (!checkin) {
14892                            pw.print("(jar) ");
14893                            pw.print(ent.path);
14894                        } else {
14895                            pw.print(",jar,");
14896                            pw.print(ent.path);
14897                        }
14898                    } else {
14899                        if (!checkin) {
14900                            pw.print("(apk) ");
14901                            pw.print(ent.apk);
14902                        } else {
14903                            pw.print(",apk,");
14904                            pw.print(ent.apk);
14905                        }
14906                    }
14907                    pw.println();
14908                }
14909            }
14910
14911            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14912                if (dumpState.onTitlePrinted())
14913                    pw.println();
14914                if (!checkin) {
14915                    pw.println("Features:");
14916                }
14917                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14918                while (it.hasNext()) {
14919                    String name = it.next();
14920                    if (!checkin) {
14921                        pw.print("  ");
14922                    } else {
14923                        pw.print("feat,");
14924                    }
14925                    pw.println(name);
14926                }
14927            }
14928
14929            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14930                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14931                        : "Activity Resolver Table:", "  ", packageName,
14932                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14933                    dumpState.setTitlePrinted(true);
14934                }
14935                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14936                        : "Receiver Resolver Table:", "  ", packageName,
14937                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14938                    dumpState.setTitlePrinted(true);
14939                }
14940                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14941                        : "Service Resolver Table:", "  ", packageName,
14942                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14943                    dumpState.setTitlePrinted(true);
14944                }
14945                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14946                        : "Provider Resolver Table:", "  ", packageName,
14947                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14948                    dumpState.setTitlePrinted(true);
14949                }
14950            }
14951
14952            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14953                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14954                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14955                    int user = mSettings.mPreferredActivities.keyAt(i);
14956                    if (pir.dump(pw,
14957                            dumpState.getTitlePrinted()
14958                                ? "\nPreferred Activities User " + user + ":"
14959                                : "Preferred Activities User " + user + ":", "  ",
14960                            packageName, true, false)) {
14961                        dumpState.setTitlePrinted(true);
14962                    }
14963                }
14964            }
14965
14966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14967                pw.flush();
14968                FileOutputStream fout = new FileOutputStream(fd);
14969                BufferedOutputStream str = new BufferedOutputStream(fout);
14970                XmlSerializer serializer = new FastXmlSerializer();
14971                try {
14972                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14973                    serializer.startDocument(null, true);
14974                    serializer.setFeature(
14975                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14976                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14977                    serializer.endDocument();
14978                    serializer.flush();
14979                } catch (IllegalArgumentException e) {
14980                    pw.println("Failed writing: " + e);
14981                } catch (IllegalStateException e) {
14982                    pw.println("Failed writing: " + e);
14983                } catch (IOException e) {
14984                    pw.println("Failed writing: " + e);
14985                }
14986            }
14987
14988            if (!checkin
14989                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14990                    && packageName == null) {
14991                pw.println();
14992                int count = mSettings.mPackages.size();
14993                if (count == 0) {
14994                    pw.println("No applications!");
14995                    pw.println();
14996                } else {
14997                    final String prefix = "  ";
14998                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14999                    if (allPackageSettings.size() == 0) {
15000                        pw.println("No domain preferred apps!");
15001                        pw.println();
15002                    } else {
15003                        pw.println("App verification status:");
15004                        pw.println();
15005                        count = 0;
15006                        for (PackageSetting ps : allPackageSettings) {
15007                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15008                            if (ivi == null || ivi.getPackageName() == null) continue;
15009                            pw.println(prefix + "Package: " + ivi.getPackageName());
15010                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15011                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15012                            pw.println();
15013                            count++;
15014                        }
15015                        if (count == 0) {
15016                            pw.println(prefix + "No app verification established.");
15017                            pw.println();
15018                        }
15019                        for (int userId : sUserManager.getUserIds()) {
15020                            pw.println("App linkages for user " + userId + ":");
15021                            pw.println();
15022                            count = 0;
15023                            for (PackageSetting ps : allPackageSettings) {
15024                                final long status = ps.getDomainVerificationStatusForUser(userId);
15025                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15026                                    continue;
15027                                }
15028                                pw.println(prefix + "Package: " + ps.name);
15029                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15030                                String statusStr = IntentFilterVerificationInfo.
15031                                        getStatusStringFromValue(status);
15032                                pw.println(prefix + "Status:  " + statusStr);
15033                                pw.println();
15034                                count++;
15035                            }
15036                            if (count == 0) {
15037                                pw.println(prefix + "No configured app linkages.");
15038                                pw.println();
15039                            }
15040                        }
15041                    }
15042                }
15043            }
15044
15045            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15046                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15047                if (packageName == null && permissionNames == null) {
15048                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15049                        if (iperm == 0) {
15050                            if (dumpState.onTitlePrinted())
15051                                pw.println();
15052                            pw.println("AppOp Permissions:");
15053                        }
15054                        pw.print("  AppOp Permission ");
15055                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15056                        pw.println(":");
15057                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15058                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15059                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15060                        }
15061                    }
15062                }
15063            }
15064
15065            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15066                boolean printedSomething = false;
15067                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15068                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15069                        continue;
15070                    }
15071                    if (!printedSomething) {
15072                        if (dumpState.onTitlePrinted())
15073                            pw.println();
15074                        pw.println("Registered ContentProviders:");
15075                        printedSomething = true;
15076                    }
15077                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15078                    pw.print("    "); pw.println(p.toString());
15079                }
15080                printedSomething = false;
15081                for (Map.Entry<String, PackageParser.Provider> entry :
15082                        mProvidersByAuthority.entrySet()) {
15083                    PackageParser.Provider p = entry.getValue();
15084                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15085                        continue;
15086                    }
15087                    if (!printedSomething) {
15088                        if (dumpState.onTitlePrinted())
15089                            pw.println();
15090                        pw.println("ContentProvider Authorities:");
15091                        printedSomething = true;
15092                    }
15093                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15094                    pw.print("    "); pw.println(p.toString());
15095                    if (p.info != null && p.info.applicationInfo != null) {
15096                        final String appInfo = p.info.applicationInfo.toString();
15097                        pw.print("      applicationInfo="); pw.println(appInfo);
15098                    }
15099                }
15100            }
15101
15102            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15103                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15104            }
15105
15106            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15107                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15108            }
15109
15110            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15111                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15112            }
15113
15114            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15115                // XXX should handle packageName != null by dumping only install data that
15116                // the given package is involved with.
15117                if (dumpState.onTitlePrinted()) pw.println();
15118                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15119            }
15120
15121            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15122                if (dumpState.onTitlePrinted()) pw.println();
15123                mSettings.dumpReadMessagesLPr(pw, dumpState);
15124
15125                pw.println();
15126                pw.println("Package warning messages:");
15127                BufferedReader in = null;
15128                String line = null;
15129                try {
15130                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15131                    while ((line = in.readLine()) != null) {
15132                        if (line.contains("ignored: updated version")) continue;
15133                        pw.println(line);
15134                    }
15135                } catch (IOException ignored) {
15136                } finally {
15137                    IoUtils.closeQuietly(in);
15138                }
15139            }
15140
15141            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15142                BufferedReader in = null;
15143                String line = null;
15144                try {
15145                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15146                    while ((line = in.readLine()) != null) {
15147                        if (line.contains("ignored: updated version")) continue;
15148                        pw.print("msg,");
15149                        pw.println(line);
15150                    }
15151                } catch (IOException ignored) {
15152                } finally {
15153                    IoUtils.closeQuietly(in);
15154                }
15155            }
15156        }
15157    }
15158
15159    private String dumpDomainString(String packageName) {
15160        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15161        List<IntentFilter> filters = getAllIntentFilters(packageName);
15162
15163        ArraySet<String> result = new ArraySet<>();
15164        if (iviList.size() > 0) {
15165            for (IntentFilterVerificationInfo ivi : iviList) {
15166                for (String host : ivi.getDomains()) {
15167                    result.add(host);
15168                }
15169            }
15170        }
15171        if (filters != null && filters.size() > 0) {
15172            for (IntentFilter filter : filters) {
15173                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15174                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15175                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15176                    result.addAll(filter.getHostsList());
15177                }
15178            }
15179        }
15180
15181        StringBuilder sb = new StringBuilder(result.size() * 16);
15182        for (String domain : result) {
15183            if (sb.length() > 0) sb.append(" ");
15184            sb.append(domain);
15185        }
15186        return sb.toString();
15187    }
15188
15189    // ------- apps on sdcard specific code -------
15190    static final boolean DEBUG_SD_INSTALL = false;
15191
15192    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15193
15194    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15195
15196    private boolean mMediaMounted = false;
15197
15198    static String getEncryptKey() {
15199        try {
15200            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15201                    SD_ENCRYPTION_KEYSTORE_NAME);
15202            if (sdEncKey == null) {
15203                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15204                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15205                if (sdEncKey == null) {
15206                    Slog.e(TAG, "Failed to create encryption keys");
15207                    return null;
15208                }
15209            }
15210            return sdEncKey;
15211        } catch (NoSuchAlgorithmException nsae) {
15212            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15213            return null;
15214        } catch (IOException ioe) {
15215            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15216            return null;
15217        }
15218    }
15219
15220    /*
15221     * Update media status on PackageManager.
15222     */
15223    @Override
15224    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15225        int callingUid = Binder.getCallingUid();
15226        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15227            throw new SecurityException("Media status can only be updated by the system");
15228        }
15229        // reader; this apparently protects mMediaMounted, but should probably
15230        // be a different lock in that case.
15231        synchronized (mPackages) {
15232            Log.i(TAG, "Updating external media status from "
15233                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15234                    + (mediaStatus ? "mounted" : "unmounted"));
15235            if (DEBUG_SD_INSTALL)
15236                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15237                        + ", mMediaMounted=" + mMediaMounted);
15238            if (mediaStatus == mMediaMounted) {
15239                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15240                        : 0, -1);
15241                mHandler.sendMessage(msg);
15242                return;
15243            }
15244            mMediaMounted = mediaStatus;
15245        }
15246        // Queue up an async operation since the package installation may take a
15247        // little while.
15248        mHandler.post(new Runnable() {
15249            public void run() {
15250                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15251            }
15252        });
15253    }
15254
15255    /**
15256     * Called by MountService when the initial ASECs to scan are available.
15257     * Should block until all the ASEC containers are finished being scanned.
15258     */
15259    public void scanAvailableAsecs() {
15260        updateExternalMediaStatusInner(true, false, false);
15261        if (mShouldRestoreconData) {
15262            SELinuxMMAC.setRestoreconDone();
15263            mShouldRestoreconData = false;
15264        }
15265    }
15266
15267    /*
15268     * Collect information of applications on external media, map them against
15269     * existing containers and update information based on current mount status.
15270     * Please note that we always have to report status if reportStatus has been
15271     * set to true especially when unloading packages.
15272     */
15273    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15274            boolean externalStorage) {
15275        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15276        int[] uidArr = EmptyArray.INT;
15277
15278        final String[] list = PackageHelper.getSecureContainerList();
15279        if (ArrayUtils.isEmpty(list)) {
15280            Log.i(TAG, "No secure containers found");
15281        } else {
15282            // Process list of secure containers and categorize them
15283            // as active or stale based on their package internal state.
15284
15285            // reader
15286            synchronized (mPackages) {
15287                for (String cid : list) {
15288                    // Leave stages untouched for now; installer service owns them
15289                    if (PackageInstallerService.isStageName(cid)) continue;
15290
15291                    if (DEBUG_SD_INSTALL)
15292                        Log.i(TAG, "Processing container " + cid);
15293                    String pkgName = getAsecPackageName(cid);
15294                    if (pkgName == null) {
15295                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15296                        continue;
15297                    }
15298                    if (DEBUG_SD_INSTALL)
15299                        Log.i(TAG, "Looking for pkg : " + pkgName);
15300
15301                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15302                    if (ps == null) {
15303                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15304                        continue;
15305                    }
15306
15307                    /*
15308                     * Skip packages that are not external if we're unmounting
15309                     * external storage.
15310                     */
15311                    if (externalStorage && !isMounted && !isExternal(ps)) {
15312                        continue;
15313                    }
15314
15315                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15316                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15317                    // The package status is changed only if the code path
15318                    // matches between settings and the container id.
15319                    if (ps.codePathString != null
15320                            && ps.codePathString.startsWith(args.getCodePath())) {
15321                        if (DEBUG_SD_INSTALL) {
15322                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15323                                    + " at code path: " + ps.codePathString);
15324                        }
15325
15326                        // We do have a valid package installed on sdcard
15327                        processCids.put(args, ps.codePathString);
15328                        final int uid = ps.appId;
15329                        if (uid != -1) {
15330                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15331                        }
15332                    } else {
15333                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15334                                + ps.codePathString);
15335                    }
15336                }
15337            }
15338
15339            Arrays.sort(uidArr);
15340        }
15341
15342        // Process packages with valid entries.
15343        if (isMounted) {
15344            if (DEBUG_SD_INSTALL)
15345                Log.i(TAG, "Loading packages");
15346            loadMediaPackages(processCids, uidArr);
15347            startCleaningPackages();
15348            mInstallerService.onSecureContainersAvailable();
15349        } else {
15350            if (DEBUG_SD_INSTALL)
15351                Log.i(TAG, "Unloading packages");
15352            unloadMediaPackages(processCids, uidArr, reportStatus);
15353        }
15354    }
15355
15356    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15357            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15358        final int size = infos.size();
15359        final String[] packageNames = new String[size];
15360        final int[] packageUids = new int[size];
15361        for (int i = 0; i < size; i++) {
15362            final ApplicationInfo info = infos.get(i);
15363            packageNames[i] = info.packageName;
15364            packageUids[i] = info.uid;
15365        }
15366        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15367                finishedReceiver);
15368    }
15369
15370    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15371            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15372        sendResourcesChangedBroadcast(mediaStatus, replacing,
15373                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15374    }
15375
15376    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15377            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15378        int size = pkgList.length;
15379        if (size > 0) {
15380            // Send broadcasts here
15381            Bundle extras = new Bundle();
15382            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15383            if (uidArr != null) {
15384                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15385            }
15386            if (replacing) {
15387                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15388            }
15389            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15390                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15391            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15392        }
15393    }
15394
15395   /*
15396     * Look at potentially valid container ids from processCids If package
15397     * information doesn't match the one on record or package scanning fails,
15398     * the cid is added to list of removeCids. We currently don't delete stale
15399     * containers.
15400     */
15401    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15402        ArrayList<String> pkgList = new ArrayList<String>();
15403        Set<AsecInstallArgs> keys = processCids.keySet();
15404
15405        for (AsecInstallArgs args : keys) {
15406            String codePath = processCids.get(args);
15407            if (DEBUG_SD_INSTALL)
15408                Log.i(TAG, "Loading container : " + args.cid);
15409            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15410            try {
15411                // Make sure there are no container errors first.
15412                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15413                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15414                            + " when installing from sdcard");
15415                    continue;
15416                }
15417                // Check code path here.
15418                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15419                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15420                            + " does not match one in settings " + codePath);
15421                    continue;
15422                }
15423                // Parse package
15424                int parseFlags = mDefParseFlags;
15425                if (args.isExternalAsec()) {
15426                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15427                }
15428                if (args.isFwdLocked()) {
15429                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15430                }
15431
15432                synchronized (mInstallLock) {
15433                    PackageParser.Package pkg = null;
15434                    try {
15435                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15436                    } catch (PackageManagerException e) {
15437                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15438                    }
15439                    // Scan the package
15440                    if (pkg != null) {
15441                        /*
15442                         * TODO why is the lock being held? doPostInstall is
15443                         * called in other places without the lock. This needs
15444                         * to be straightened out.
15445                         */
15446                        // writer
15447                        synchronized (mPackages) {
15448                            retCode = PackageManager.INSTALL_SUCCEEDED;
15449                            pkgList.add(pkg.packageName);
15450                            // Post process args
15451                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15452                                    pkg.applicationInfo.uid);
15453                        }
15454                    } else {
15455                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15456                    }
15457                }
15458
15459            } finally {
15460                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15461                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15462                }
15463            }
15464        }
15465        // writer
15466        synchronized (mPackages) {
15467            // If the platform SDK has changed since the last time we booted,
15468            // we need to re-grant app permission to catch any new ones that
15469            // appear. This is really a hack, and means that apps can in some
15470            // cases get permissions that the user didn't initially explicitly
15471            // allow... it would be nice to have some better way to handle
15472            // this situation.
15473            final VersionInfo ver = mSettings.getExternalVersion();
15474
15475            int updateFlags = UPDATE_PERMISSIONS_ALL;
15476            if (ver.sdkVersion != mSdkVersion) {
15477                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15478                        + mSdkVersion + "; regranting permissions for external");
15479                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15480            }
15481            updatePermissionsLPw(null, null, updateFlags);
15482
15483            // Yay, everything is now upgraded
15484            ver.forceCurrent();
15485
15486            // can downgrade to reader
15487            // Persist settings
15488            mSettings.writeLPr();
15489        }
15490        // Send a broadcast to let everyone know we are done processing
15491        if (pkgList.size() > 0) {
15492            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15493        }
15494    }
15495
15496   /*
15497     * Utility method to unload a list of specified containers
15498     */
15499    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15500        // Just unmount all valid containers.
15501        for (AsecInstallArgs arg : cidArgs) {
15502            synchronized (mInstallLock) {
15503                arg.doPostDeleteLI(false);
15504           }
15505       }
15506   }
15507
15508    /*
15509     * Unload packages mounted on external media. This involves deleting package
15510     * data from internal structures, sending broadcasts about diabled packages,
15511     * gc'ing to free up references, unmounting all secure containers
15512     * corresponding to packages on external media, and posting a
15513     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15514     * that we always have to post this message if status has been requested no
15515     * matter what.
15516     */
15517    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15518            final boolean reportStatus) {
15519        if (DEBUG_SD_INSTALL)
15520            Log.i(TAG, "unloading media packages");
15521        ArrayList<String> pkgList = new ArrayList<String>();
15522        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15523        final Set<AsecInstallArgs> keys = processCids.keySet();
15524        for (AsecInstallArgs args : keys) {
15525            String pkgName = args.getPackageName();
15526            if (DEBUG_SD_INSTALL)
15527                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15528            // Delete package internally
15529            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15530            synchronized (mInstallLock) {
15531                boolean res = deletePackageLI(pkgName, null, false, null, null,
15532                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15533                if (res) {
15534                    pkgList.add(pkgName);
15535                } else {
15536                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15537                    failedList.add(args);
15538                }
15539            }
15540        }
15541
15542        // reader
15543        synchronized (mPackages) {
15544            // We didn't update the settings after removing each package;
15545            // write them now for all packages.
15546            mSettings.writeLPr();
15547        }
15548
15549        // We have to absolutely send UPDATED_MEDIA_STATUS only
15550        // after confirming that all the receivers processed the ordered
15551        // broadcast when packages get disabled, force a gc to clean things up.
15552        // and unload all the containers.
15553        if (pkgList.size() > 0) {
15554            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15555                    new IIntentReceiver.Stub() {
15556                public void performReceive(Intent intent, int resultCode, String data,
15557                        Bundle extras, boolean ordered, boolean sticky,
15558                        int sendingUser) throws RemoteException {
15559                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15560                            reportStatus ? 1 : 0, 1, keys);
15561                    mHandler.sendMessage(msg);
15562                }
15563            });
15564        } else {
15565            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15566                    keys);
15567            mHandler.sendMessage(msg);
15568        }
15569    }
15570
15571    private void loadPrivatePackages(VolumeInfo vol) {
15572        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15573        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15574        synchronized (mInstallLock) {
15575        synchronized (mPackages) {
15576            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15577            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15578            for (PackageSetting ps : packages) {
15579                final PackageParser.Package pkg;
15580                try {
15581                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15582                    loaded.add(pkg.applicationInfo);
15583                } catch (PackageManagerException e) {
15584                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15585                }
15586
15587                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15588                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15589                }
15590            }
15591
15592            int updateFlags = UPDATE_PERMISSIONS_ALL;
15593            if (ver.sdkVersion != mSdkVersion) {
15594                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15595                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15596                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15597            }
15598            updatePermissionsLPw(null, null, updateFlags);
15599
15600            // Yay, everything is now upgraded
15601            ver.forceCurrent();
15602
15603            mSettings.writeLPr();
15604        }
15605        }
15606
15607        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15608        sendResourcesChangedBroadcast(true, false, loaded, null);
15609    }
15610
15611    private void unloadPrivatePackages(VolumeInfo vol) {
15612        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15613        synchronized (mInstallLock) {
15614        synchronized (mPackages) {
15615            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15616            for (PackageSetting ps : packages) {
15617                if (ps.pkg == null) continue;
15618
15619                final ApplicationInfo info = ps.pkg.applicationInfo;
15620                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15621                if (deletePackageLI(ps.name, null, false, null, null,
15622                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15623                    unloaded.add(info);
15624                } else {
15625                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15626                }
15627            }
15628
15629            mSettings.writeLPr();
15630        }
15631        }
15632
15633        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15634        sendResourcesChangedBroadcast(false, false, unloaded, null);
15635    }
15636
15637    /**
15638     * Examine all users present on given mounted volume, and destroy data
15639     * belonging to users that are no longer valid, or whose user ID has been
15640     * recycled.
15641     */
15642    private void reconcileUsers(String volumeUuid) {
15643        final File[] files = FileUtils
15644                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15645        for (File file : files) {
15646            if (!file.isDirectory()) continue;
15647
15648            final int userId;
15649            final UserInfo info;
15650            try {
15651                userId = Integer.parseInt(file.getName());
15652                info = sUserManager.getUserInfo(userId);
15653            } catch (NumberFormatException e) {
15654                Slog.w(TAG, "Invalid user directory " + file);
15655                continue;
15656            }
15657
15658            boolean destroyUser = false;
15659            if (info == null) {
15660                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15661                        + " because no matching user was found");
15662                destroyUser = true;
15663            } else {
15664                try {
15665                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15666                } catch (IOException e) {
15667                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15668                            + " because we failed to enforce serial number: " + e);
15669                    destroyUser = true;
15670                }
15671            }
15672
15673            if (destroyUser) {
15674                synchronized (mInstallLock) {
15675                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15676                }
15677            }
15678        }
15679
15680        final UserManager um = mContext.getSystemService(UserManager.class);
15681        for (UserInfo user : um.getUsers()) {
15682            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15683            if (userDir.exists()) continue;
15684
15685            try {
15686                UserManagerService.prepareUserDirectory(userDir);
15687                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15688            } catch (IOException e) {
15689                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15690            }
15691        }
15692    }
15693
15694    /**
15695     * Examine all apps present on given mounted volume, and destroy apps that
15696     * aren't expected, either due to uninstallation or reinstallation on
15697     * another volume.
15698     */
15699    private void reconcileApps(String volumeUuid) {
15700        final File[] files = FileUtils
15701                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15702        for (File file : files) {
15703            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15704                    && !PackageInstallerService.isStageName(file.getName());
15705            if (!isPackage) {
15706                // Ignore entries which are not packages
15707                continue;
15708            }
15709
15710            boolean destroyApp = false;
15711            String packageName = null;
15712            try {
15713                final PackageLite pkg = PackageParser.parsePackageLite(file,
15714                        PackageParser.PARSE_MUST_BE_APK);
15715                packageName = pkg.packageName;
15716
15717                synchronized (mPackages) {
15718                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15719                    if (ps == null) {
15720                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15721                                + volumeUuid + " because we found no install record");
15722                        destroyApp = true;
15723                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15724                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15725                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15726                        destroyApp = true;
15727                    }
15728                }
15729
15730            } catch (PackageParserException e) {
15731                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15732                destroyApp = true;
15733            }
15734
15735            if (destroyApp) {
15736                synchronized (mInstallLock) {
15737                    if (packageName != null) {
15738                        removeDataDirsLI(volumeUuid, packageName);
15739                    }
15740                    if (file.isDirectory()) {
15741                        mInstaller.rmPackageDir(file.getAbsolutePath());
15742                    } else {
15743                        file.delete();
15744                    }
15745                }
15746            }
15747        }
15748    }
15749
15750    private void unfreezePackage(String packageName) {
15751        synchronized (mPackages) {
15752            final PackageSetting ps = mSettings.mPackages.get(packageName);
15753            if (ps != null) {
15754                ps.frozen = false;
15755            }
15756        }
15757    }
15758
15759    @Override
15760    public int movePackage(final String packageName, final String volumeUuid) {
15761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15762
15763        final int moveId = mNextMoveId.getAndIncrement();
15764        try {
15765            movePackageInternal(packageName, volumeUuid, moveId);
15766        } catch (PackageManagerException e) {
15767            Slog.w(TAG, "Failed to move " + packageName, e);
15768            mMoveCallbacks.notifyStatusChanged(moveId,
15769                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15770        }
15771        return moveId;
15772    }
15773
15774    private void movePackageInternal(final String packageName, final String volumeUuid,
15775            final int moveId) throws PackageManagerException {
15776        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15777        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15778        final PackageManager pm = mContext.getPackageManager();
15779
15780        final boolean currentAsec;
15781        final String currentVolumeUuid;
15782        final File codeFile;
15783        final String installerPackageName;
15784        final String packageAbiOverride;
15785        final int appId;
15786        final String seinfo;
15787        final String label;
15788
15789        // reader
15790        synchronized (mPackages) {
15791            final PackageParser.Package pkg = mPackages.get(packageName);
15792            final PackageSetting ps = mSettings.mPackages.get(packageName);
15793            if (pkg == null || ps == null) {
15794                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15795            }
15796
15797            if (pkg.applicationInfo.isSystemApp()) {
15798                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15799                        "Cannot move system application");
15800            }
15801
15802            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15803                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15804                        "Package already moved to " + volumeUuid);
15805            }
15806
15807            final File probe = new File(pkg.codePath);
15808            final File probeOat = new File(probe, "oat");
15809            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15811                        "Move only supported for modern cluster style installs");
15812            }
15813
15814            if (ps.frozen) {
15815                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15816                        "Failed to move already frozen package");
15817            }
15818            ps.frozen = true;
15819
15820            currentAsec = pkg.applicationInfo.isForwardLocked()
15821                    || pkg.applicationInfo.isExternalAsec();
15822            currentVolumeUuid = ps.volumeUuid;
15823            codeFile = new File(pkg.codePath);
15824            installerPackageName = ps.installerPackageName;
15825            packageAbiOverride = ps.cpuAbiOverrideString;
15826            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15827            seinfo = pkg.applicationInfo.seinfo;
15828            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15829        }
15830
15831        // Now that we're guarded by frozen state, kill app during move
15832        final long token = Binder.clearCallingIdentity();
15833        try {
15834            killApplication(packageName, appId, "move pkg");
15835        } finally {
15836            Binder.restoreCallingIdentity(token);
15837        }
15838
15839        final Bundle extras = new Bundle();
15840        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15841        extras.putString(Intent.EXTRA_TITLE, label);
15842        mMoveCallbacks.notifyCreated(moveId, extras);
15843
15844        int installFlags;
15845        final boolean moveCompleteApp;
15846        final File measurePath;
15847
15848        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15849            installFlags = INSTALL_INTERNAL;
15850            moveCompleteApp = !currentAsec;
15851            measurePath = Environment.getDataAppDirectory(volumeUuid);
15852        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15853            installFlags = INSTALL_EXTERNAL;
15854            moveCompleteApp = false;
15855            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15856        } else {
15857            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15858            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15859                    || !volume.isMountedWritable()) {
15860                unfreezePackage(packageName);
15861                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15862                        "Move location not mounted private volume");
15863            }
15864
15865            Preconditions.checkState(!currentAsec);
15866
15867            installFlags = INSTALL_INTERNAL;
15868            moveCompleteApp = true;
15869            measurePath = Environment.getDataAppDirectory(volumeUuid);
15870        }
15871
15872        final PackageStats stats = new PackageStats(null, -1);
15873        synchronized (mInstaller) {
15874            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15875                unfreezePackage(packageName);
15876                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15877                        "Failed to measure package size");
15878            }
15879        }
15880
15881        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15882                + stats.dataSize);
15883
15884        final long startFreeBytes = measurePath.getFreeSpace();
15885        final long sizeBytes;
15886        if (moveCompleteApp) {
15887            sizeBytes = stats.codeSize + stats.dataSize;
15888        } else {
15889            sizeBytes = stats.codeSize;
15890        }
15891
15892        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15893            unfreezePackage(packageName);
15894            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15895                    "Not enough free space to move");
15896        }
15897
15898        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15899
15900        final CountDownLatch installedLatch = new CountDownLatch(1);
15901        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15902            @Override
15903            public void onUserActionRequired(Intent intent) throws RemoteException {
15904                throw new IllegalStateException();
15905            }
15906
15907            @Override
15908            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15909                    Bundle extras) throws RemoteException {
15910                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15911                        + PackageManager.installStatusToString(returnCode, msg));
15912
15913                installedLatch.countDown();
15914
15915                // Regardless of success or failure of the move operation,
15916                // always unfreeze the package
15917                unfreezePackage(packageName);
15918
15919                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15920                switch (status) {
15921                    case PackageInstaller.STATUS_SUCCESS:
15922                        mMoveCallbacks.notifyStatusChanged(moveId,
15923                                PackageManager.MOVE_SUCCEEDED);
15924                        break;
15925                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15926                        mMoveCallbacks.notifyStatusChanged(moveId,
15927                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15928                        break;
15929                    default:
15930                        mMoveCallbacks.notifyStatusChanged(moveId,
15931                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15932                        break;
15933                }
15934            }
15935        };
15936
15937        final MoveInfo move;
15938        if (moveCompleteApp) {
15939            // Kick off a thread to report progress estimates
15940            new Thread() {
15941                @Override
15942                public void run() {
15943                    while (true) {
15944                        try {
15945                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15946                                break;
15947                            }
15948                        } catch (InterruptedException ignored) {
15949                        }
15950
15951                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15952                        final int progress = 10 + (int) MathUtils.constrain(
15953                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15954                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15955                    }
15956                }
15957            }.start();
15958
15959            final String dataAppName = codeFile.getName();
15960            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15961                    dataAppName, appId, seinfo);
15962        } else {
15963            move = null;
15964        }
15965
15966        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15967
15968        final Message msg = mHandler.obtainMessage(INIT_COPY);
15969        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15970        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15971                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15972        mHandler.sendMessage(msg);
15973    }
15974
15975    @Override
15976    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15978
15979        final int realMoveId = mNextMoveId.getAndIncrement();
15980        final Bundle extras = new Bundle();
15981        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15982        mMoveCallbacks.notifyCreated(realMoveId, extras);
15983
15984        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15985            @Override
15986            public void onCreated(int moveId, Bundle extras) {
15987                // Ignored
15988            }
15989
15990            @Override
15991            public void onStatusChanged(int moveId, int status, long estMillis) {
15992                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15993            }
15994        };
15995
15996        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15997        storage.setPrimaryStorageUuid(volumeUuid, callback);
15998        return realMoveId;
15999    }
16000
16001    @Override
16002    public int getMoveStatus(int moveId) {
16003        mContext.enforceCallingOrSelfPermission(
16004                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16005        return mMoveCallbacks.mLastStatus.get(moveId);
16006    }
16007
16008    @Override
16009    public void registerMoveCallback(IPackageMoveObserver callback) {
16010        mContext.enforceCallingOrSelfPermission(
16011                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16012        mMoveCallbacks.register(callback);
16013    }
16014
16015    @Override
16016    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16017        mContext.enforceCallingOrSelfPermission(
16018                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16019        mMoveCallbacks.unregister(callback);
16020    }
16021
16022    @Override
16023    public boolean setInstallLocation(int loc) {
16024        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16025                null);
16026        if (getInstallLocation() == loc) {
16027            return true;
16028        }
16029        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16030                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16031            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16032                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16033            return true;
16034        }
16035        return false;
16036   }
16037
16038    @Override
16039    public int getInstallLocation() {
16040        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16041                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16042                PackageHelper.APP_INSTALL_AUTO);
16043    }
16044
16045    /** Called by UserManagerService */
16046    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16047        mDirtyUsers.remove(userHandle);
16048        mSettings.removeUserLPw(userHandle);
16049        mPendingBroadcasts.remove(userHandle);
16050        if (mInstaller != null) {
16051            // Technically, we shouldn't be doing this with the package lock
16052            // held.  However, this is very rare, and there is already so much
16053            // other disk I/O going on, that we'll let it slide for now.
16054            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16055            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16056                final String volumeUuid = vol.getFsUuid();
16057                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16058                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16059            }
16060        }
16061        mUserNeedsBadging.delete(userHandle);
16062        removeUnusedPackagesLILPw(userManager, userHandle);
16063    }
16064
16065    /**
16066     * We're removing userHandle and would like to remove any downloaded packages
16067     * that are no longer in use by any other user.
16068     * @param userHandle the user being removed
16069     */
16070    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16071        final boolean DEBUG_CLEAN_APKS = false;
16072        int [] users = userManager.getUserIdsLPr();
16073        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16074        while (psit.hasNext()) {
16075            PackageSetting ps = psit.next();
16076            if (ps.pkg == null) {
16077                continue;
16078            }
16079            final String packageName = ps.pkg.packageName;
16080            // Skip over if system app
16081            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16082                continue;
16083            }
16084            if (DEBUG_CLEAN_APKS) {
16085                Slog.i(TAG, "Checking package " + packageName);
16086            }
16087            boolean keep = false;
16088            for (int i = 0; i < users.length; i++) {
16089                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16090                    keep = true;
16091                    if (DEBUG_CLEAN_APKS) {
16092                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16093                                + users[i]);
16094                    }
16095                    break;
16096                }
16097            }
16098            if (!keep) {
16099                if (DEBUG_CLEAN_APKS) {
16100                    Slog.i(TAG, "  Removing package " + packageName);
16101                }
16102                mHandler.post(new Runnable() {
16103                    public void run() {
16104                        deletePackageX(packageName, userHandle, 0);
16105                    } //end run
16106                });
16107            }
16108        }
16109    }
16110
16111    /** Called by UserManagerService */
16112    void createNewUserLILPw(int userHandle) {
16113        if (mInstaller != null) {
16114            mInstaller.createUserConfig(userHandle);
16115            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16116            applyFactoryDefaultBrowserLPw(userHandle);
16117            primeDomainVerificationsLPw(userHandle);
16118        }
16119    }
16120
16121    void newUserCreated(final int userHandle) {
16122        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16123    }
16124
16125    @Override
16126    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16127        mContext.enforceCallingOrSelfPermission(
16128                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16129                "Only package verification agents can read the verifier device identity");
16130
16131        synchronized (mPackages) {
16132            return mSettings.getVerifierDeviceIdentityLPw();
16133        }
16134    }
16135
16136    @Override
16137    public void setPermissionEnforced(String permission, boolean enforced) {
16138        // TODO: Now that we no longer change GID for storage, this should to away.
16139        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16140                "setPermissionEnforced");
16141        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16142            synchronized (mPackages) {
16143                if (mSettings.mReadExternalStorageEnforced == null
16144                        || mSettings.mReadExternalStorageEnforced != enforced) {
16145                    mSettings.mReadExternalStorageEnforced = enforced;
16146                    mSettings.writeLPr();
16147                }
16148            }
16149            // kill any non-foreground processes so we restart them and
16150            // grant/revoke the GID.
16151            final IActivityManager am = ActivityManagerNative.getDefault();
16152            if (am != null) {
16153                final long token = Binder.clearCallingIdentity();
16154                try {
16155                    am.killProcessesBelowForeground("setPermissionEnforcement");
16156                } catch (RemoteException e) {
16157                } finally {
16158                    Binder.restoreCallingIdentity(token);
16159                }
16160            }
16161        } else {
16162            throw new IllegalArgumentException("No selective enforcement for " + permission);
16163        }
16164    }
16165
16166    @Override
16167    @Deprecated
16168    public boolean isPermissionEnforced(String permission) {
16169        return true;
16170    }
16171
16172    @Override
16173    public boolean isStorageLow() {
16174        final long token = Binder.clearCallingIdentity();
16175        try {
16176            final DeviceStorageMonitorInternal
16177                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16178            if (dsm != null) {
16179                return dsm.isMemoryLow();
16180            } else {
16181                return false;
16182            }
16183        } finally {
16184            Binder.restoreCallingIdentity(token);
16185        }
16186    }
16187
16188    @Override
16189    public IPackageInstaller getPackageInstaller() {
16190        return mInstallerService;
16191    }
16192
16193    private boolean userNeedsBadging(int userId) {
16194        int index = mUserNeedsBadging.indexOfKey(userId);
16195        if (index < 0) {
16196            final UserInfo userInfo;
16197            final long token = Binder.clearCallingIdentity();
16198            try {
16199                userInfo = sUserManager.getUserInfo(userId);
16200            } finally {
16201                Binder.restoreCallingIdentity(token);
16202            }
16203            final boolean b;
16204            if (userInfo != null && userInfo.isManagedProfile()) {
16205                b = true;
16206            } else {
16207                b = false;
16208            }
16209            mUserNeedsBadging.put(userId, b);
16210            return b;
16211        }
16212        return mUserNeedsBadging.valueAt(index);
16213    }
16214
16215    @Override
16216    public KeySet getKeySetByAlias(String packageName, String alias) {
16217        if (packageName == null || alias == null) {
16218            return null;
16219        }
16220        synchronized(mPackages) {
16221            final PackageParser.Package pkg = mPackages.get(packageName);
16222            if (pkg == null) {
16223                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16224                throw new IllegalArgumentException("Unknown package: " + packageName);
16225            }
16226            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16227            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16228        }
16229    }
16230
16231    @Override
16232    public KeySet getSigningKeySet(String packageName) {
16233        if (packageName == null) {
16234            return null;
16235        }
16236        synchronized(mPackages) {
16237            final PackageParser.Package pkg = mPackages.get(packageName);
16238            if (pkg == null) {
16239                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16240                throw new IllegalArgumentException("Unknown package: " + packageName);
16241            }
16242            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16243                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16244                throw new SecurityException("May not access signing KeySet of other apps.");
16245            }
16246            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16247            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16248        }
16249    }
16250
16251    @Override
16252    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16253        if (packageName == null || ks == null) {
16254            return false;
16255        }
16256        synchronized(mPackages) {
16257            final PackageParser.Package pkg = mPackages.get(packageName);
16258            if (pkg == null) {
16259                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16260                throw new IllegalArgumentException("Unknown package: " + packageName);
16261            }
16262            IBinder ksh = ks.getToken();
16263            if (ksh instanceof KeySetHandle) {
16264                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16265                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16266            }
16267            return false;
16268        }
16269    }
16270
16271    @Override
16272    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16273        if (packageName == null || ks == null) {
16274            return false;
16275        }
16276        synchronized(mPackages) {
16277            final PackageParser.Package pkg = mPackages.get(packageName);
16278            if (pkg == null) {
16279                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16280                throw new IllegalArgumentException("Unknown package: " + packageName);
16281            }
16282            IBinder ksh = ks.getToken();
16283            if (ksh instanceof KeySetHandle) {
16284                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16285                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16286            }
16287            return false;
16288        }
16289    }
16290
16291    public void getUsageStatsIfNoPackageUsageInfo() {
16292        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16293            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16294            if (usm == null) {
16295                throw new IllegalStateException("UsageStatsManager must be initialized");
16296            }
16297            long now = System.currentTimeMillis();
16298            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16299            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16300                String packageName = entry.getKey();
16301                PackageParser.Package pkg = mPackages.get(packageName);
16302                if (pkg == null) {
16303                    continue;
16304                }
16305                UsageStats usage = entry.getValue();
16306                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16307                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16308            }
16309        }
16310    }
16311
16312    /**
16313     * Check and throw if the given before/after packages would be considered a
16314     * downgrade.
16315     */
16316    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16317            throws PackageManagerException {
16318        if (after.versionCode < before.mVersionCode) {
16319            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16320                    "Update version code " + after.versionCode + " is older than current "
16321                    + before.mVersionCode);
16322        } else if (after.versionCode == before.mVersionCode) {
16323            if (after.baseRevisionCode < before.baseRevisionCode) {
16324                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16325                        "Update base revision code " + after.baseRevisionCode
16326                        + " is older than current " + before.baseRevisionCode);
16327            }
16328
16329            if (!ArrayUtils.isEmpty(after.splitNames)) {
16330                for (int i = 0; i < after.splitNames.length; i++) {
16331                    final String splitName = after.splitNames[i];
16332                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16333                    if (j != -1) {
16334                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16335                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16336                                    "Update split " + splitName + " revision code "
16337                                    + after.splitRevisionCodes[i] + " is older than current "
16338                                    + before.splitRevisionCodes[j]);
16339                        }
16340                    }
16341                }
16342            }
16343        }
16344    }
16345
16346    private static class MoveCallbacks extends Handler {
16347        private static final int MSG_CREATED = 1;
16348        private static final int MSG_STATUS_CHANGED = 2;
16349
16350        private final RemoteCallbackList<IPackageMoveObserver>
16351                mCallbacks = new RemoteCallbackList<>();
16352
16353        private final SparseIntArray mLastStatus = new SparseIntArray();
16354
16355        public MoveCallbacks(Looper looper) {
16356            super(looper);
16357        }
16358
16359        public void register(IPackageMoveObserver callback) {
16360            mCallbacks.register(callback);
16361        }
16362
16363        public void unregister(IPackageMoveObserver callback) {
16364            mCallbacks.unregister(callback);
16365        }
16366
16367        @Override
16368        public void handleMessage(Message msg) {
16369            final SomeArgs args = (SomeArgs) msg.obj;
16370            final int n = mCallbacks.beginBroadcast();
16371            for (int i = 0; i < n; i++) {
16372                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16373                try {
16374                    invokeCallback(callback, msg.what, args);
16375                } catch (RemoteException ignored) {
16376                }
16377            }
16378            mCallbacks.finishBroadcast();
16379            args.recycle();
16380        }
16381
16382        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16383                throws RemoteException {
16384            switch (what) {
16385                case MSG_CREATED: {
16386                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16387                    break;
16388                }
16389                case MSG_STATUS_CHANGED: {
16390                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16391                    break;
16392                }
16393            }
16394        }
16395
16396        private void notifyCreated(int moveId, Bundle extras) {
16397            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16398
16399            final SomeArgs args = SomeArgs.obtain();
16400            args.argi1 = moveId;
16401            args.arg2 = extras;
16402            obtainMessage(MSG_CREATED, args).sendToTarget();
16403        }
16404
16405        private void notifyStatusChanged(int moveId, int status) {
16406            notifyStatusChanged(moveId, status, -1);
16407        }
16408
16409        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16410            Slog.v(TAG, "Move " + moveId + " status " + status);
16411
16412            final SomeArgs args = SomeArgs.obtain();
16413            args.argi1 = moveId;
16414            args.argi2 = status;
16415            args.arg3 = estMillis;
16416            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16417
16418            synchronized (mLastStatus) {
16419                mLastStatus.put(moveId, status);
16420            }
16421        }
16422    }
16423
16424    private final class OnPermissionChangeListeners extends Handler {
16425        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16426
16427        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16428                new RemoteCallbackList<>();
16429
16430        public OnPermissionChangeListeners(Looper looper) {
16431            super(looper);
16432        }
16433
16434        @Override
16435        public void handleMessage(Message msg) {
16436            switch (msg.what) {
16437                case MSG_ON_PERMISSIONS_CHANGED: {
16438                    final int uid = msg.arg1;
16439                    handleOnPermissionsChanged(uid);
16440                } break;
16441            }
16442        }
16443
16444        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16445            mPermissionListeners.register(listener);
16446
16447        }
16448
16449        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16450            mPermissionListeners.unregister(listener);
16451        }
16452
16453        public void onPermissionsChanged(int uid) {
16454            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16455                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16456            }
16457        }
16458
16459        private void handleOnPermissionsChanged(int uid) {
16460            final int count = mPermissionListeners.beginBroadcast();
16461            try {
16462                for (int i = 0; i < count; i++) {
16463                    IOnPermissionsChangeListener callback = mPermissionListeners
16464                            .getBroadcastItem(i);
16465                    try {
16466                        callback.onPermissionsChanged(uid);
16467                    } catch (RemoteException e) {
16468                        Log.e(TAG, "Permission listener is dead", e);
16469                    }
16470                }
16471            } finally {
16472                mPermissionListeners.finishBroadcast();
16473            }
16474        }
16475    }
16476
16477    private class PackageManagerInternalImpl extends PackageManagerInternal {
16478        @Override
16479        public void setLocationPackagesProvider(PackagesProvider provider) {
16480            synchronized (mPackages) {
16481                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16482            }
16483        }
16484
16485        @Override
16486        public void setImePackagesProvider(PackagesProvider provider) {
16487            synchronized (mPackages) {
16488                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16489            }
16490        }
16491
16492        @Override
16493        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16494            synchronized (mPackages) {
16495                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16496            }
16497        }
16498
16499        @Override
16500        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16501            synchronized (mPackages) {
16502                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16503            }
16504        }
16505
16506        @Override
16507        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16508            synchronized (mPackages) {
16509                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16510            }
16511        }
16512
16513        @Override
16514        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16515            synchronized (mPackages) {
16516                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16517            }
16518        }
16519
16520        @Override
16521        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16522            synchronized (mPackages) {
16523                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16524                        packageName, userId);
16525            }
16526        }
16527
16528        @Override
16529        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16530            synchronized (mPackages) {
16531                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16532                        packageName, userId);
16533            }
16534        }
16535    }
16536
16537    @Override
16538    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16539        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16540        synchronized (mPackages) {
16541            final long identity = Binder.clearCallingIdentity();
16542            try {
16543                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16544                        packageNames, userId);
16545            } finally {
16546                Binder.restoreCallingIdentity(identity);
16547            }
16548        }
16549    }
16550
16551    private static void enforceSystemOrPhoneCaller(String tag) {
16552        int callingUid = Binder.getCallingUid();
16553        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16554            throw new SecurityException(
16555                    "Cannot call " + tag + " from UID " + callingUid);
16556        }
16557    }
16558}
16559