PackageManagerService.java revision 8b3e6b0df102901f938cd0687f9994a3ff767fcf
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 = false;
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_REPLACING = 1<<11;
327    static final int SCAN_REQUIRE_KNOWN = 1<<12;
328    static final int SCAN_MOVE = 1<<13;
329    static final int SCAN_INITIAL = 1<<14;
330
331    static final int REMOVE_CHATTY = 1<<16;
332
333    private static final int[] EMPTY_INT_ARRAY = new int[0];
334
335    /**
336     * Timeout (in milliseconds) after which the watchdog should declare that
337     * our handler thread is wedged.  The usual default for such things is one
338     * minute but we sometimes do very lengthy I/O operations on this thread,
339     * such as installing multi-gigabyte applications, so ours needs to be longer.
340     */
341    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
342
343    /**
344     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
345     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
346     * settings entry if available, otherwise we use the hardcoded default.  If it's been
347     * more than this long since the last fstrim, we force one during the boot sequence.
348     *
349     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
350     * one gets run at the next available charging+idle time.  This final mandatory
351     * no-fstrim check kicks in only of the other scheduling criteria is never met.
352     */
353    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
354
355    /**
356     * Whether verification is enabled by default.
357     */
358    private static final boolean DEFAULT_VERIFY_ENABLE = true;
359
360    /**
361     * The default maximum time to wait for the verification agent to return in
362     * milliseconds.
363     */
364    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
365
366    /**
367     * The default response for package verification timeout.
368     *
369     * This can be either PackageManager.VERIFICATION_ALLOW or
370     * PackageManager.VERIFICATION_REJECT.
371     */
372    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
373
374    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
375
376    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
377            DEFAULT_CONTAINER_PACKAGE,
378            "com.android.defcontainer.DefaultContainerService");
379
380    private static final String KILL_APP_REASON_GIDS_CHANGED =
381            "permission grant or revoke changed gids";
382
383    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
384            "permissions revoked";
385
386    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
387
388    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
389
390    /** Permission grant: not grant the permission. */
391    private static final int GRANT_DENIED = 1;
392
393    /** Permission grant: grant the permission as an install permission. */
394    private static final int GRANT_INSTALL = 2;
395
396    /** Permission grant: grant the permission as an install permission for a legacy app. */
397    private static final int GRANT_INSTALL_LEGACY = 3;
398
399    /** Permission grant: grant the permission as a runtime one. */
400    private static final int GRANT_RUNTIME = 4;
401
402    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
403    private static final int GRANT_UPGRADE = 5;
404
405    /** Canonical intent used to identify what counts as a "web browser" app */
406    private static final Intent sBrowserIntent;
407    static {
408        sBrowserIntent = new Intent();
409        sBrowserIntent.setAction(Intent.ACTION_VIEW);
410        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
411        sBrowserIntent.setData(Uri.parse("http:"));
412    }
413
414    final ServiceThread mHandlerThread;
415
416    final PackageHandler mHandler;
417
418    /**
419     * Messages for {@link #mHandler} that need to wait for system ready before
420     * being dispatched.
421     */
422    private ArrayList<Message> mPostSystemReadyMessages;
423
424    final int mSdkVersion = Build.VERSION.SDK_INT;
425
426    final Context mContext;
427    final boolean mFactoryTest;
428    final boolean mOnlyCore;
429    final boolean mLazyDexOpt;
430    final long mDexOptLRUThresholdInMills;
431    final DisplayMetrics mMetrics;
432    final int mDefParseFlags;
433    final String[] mSeparateProcesses;
434    final boolean mIsUpgrade;
435
436    // This is where all application persistent data goes.
437    final File mAppDataDir;
438
439    // This is where all application persistent data goes for secondary users.
440    final File mUserAppDataDir;
441
442    /** The location for ASEC container files on internal storage. */
443    final String mAsecInternalPath;
444
445    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
446    // LOCK HELD.  Can be called with mInstallLock held.
447    @GuardedBy("mInstallLock")
448    final Installer mInstaller;
449
450    /** Directory where installed third-party apps stored */
451    final File mAppInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [received in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    /**
491     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
492     */
493    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
494    /**
495     * Whether or not system app permissions should be promoted from install to runtime.
496     */
497    boolean mPromoteSystemApps;
498
499    final Settings mSettings;
500    boolean mRestoredSettings;
501
502    // System configuration read by SystemConfig.
503    final int[] mGlobalGids;
504    final SparseArray<ArraySet<String>> mSystemPermissions;
505    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
506
507    // If mac_permissions.xml was found for seinfo labeling.
508    boolean mFoundPolicyFile;
509
510    // If a recursive restorecon of /data/data/<pkg> is needed.
511    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
512
513    public static final class SharedLibraryEntry {
514        public final String path;
515        public final String apk;
516
517        SharedLibraryEntry(String _path, String _apk) {
518            path = _path;
519            apk = _apk;
520        }
521    }
522
523    // Currently known shared libraries.
524    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
525            new ArrayMap<String, SharedLibraryEntry>();
526
527    // All available activities, for your resolving pleasure.
528    final ActivityIntentResolver mActivities =
529            new ActivityIntentResolver();
530
531    // All available receivers, for your resolving pleasure.
532    final ActivityIntentResolver mReceivers =
533            new ActivityIntentResolver();
534
535    // All available services, for your resolving pleasure.
536    final ServiceIntentResolver mServices = new ServiceIntentResolver();
537
538    // All available providers, for your resolving pleasure.
539    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
540
541    // Mapping from provider base names (first directory in content URI codePath)
542    // to the provider information.
543    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
544            new ArrayMap<String, PackageParser.Provider>();
545
546    // Mapping from instrumentation class names to info about them.
547    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
548            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
549
550    // Mapping from permission names to info about them.
551    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
552            new ArrayMap<String, PackageParser.PermissionGroup>();
553
554    // Packages whose data we have transfered into another package, thus
555    // should no longer exist.
556    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
557
558    // Broadcast actions that are only available to the system.
559    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
560
561    /** List of packages waiting for verification. */
562    final SparseArray<PackageVerificationState> mPendingVerification
563            = new SparseArray<PackageVerificationState>();
564
565    /** Set of packages associated with each app op permission. */
566    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
567
568    final PackageInstallerService mInstallerService;
569
570    private final PackageDexOptimizer mPackageDexOptimizer;
571
572    private AtomicInteger mNextMoveId = new AtomicInteger();
573    private final MoveCallbacks mMoveCallbacks;
574
575    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
576
577    // Cache of users who need badging.
578    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
579
580    /** Token for keys in mPendingVerification. */
581    private int mPendingVerificationToken = 0;
582
583    volatile boolean mSystemReady;
584    volatile boolean mSafeMode;
585    volatile boolean mHasSystemUidErrors;
586
587    ApplicationInfo mAndroidApplication;
588    final ActivityInfo mResolveActivity = new ActivityInfo();
589    final ResolveInfo mResolveInfo = new ResolveInfo();
590    ComponentName mResolveComponentName;
591    PackageParser.Package mPlatformPackage;
592    ComponentName mCustomResolverComponentName;
593
594    boolean mResolverReplaced = false;
595
596    private final ComponentName mIntentFilterVerifierComponent;
597    private int mIntentFilterVerificationToken = 0;
598
599    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
600            = new SparseArray<IntentFilterVerificationState>();
601
602    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
603            new DefaultPermissionGrantPolicy(this);
604
605    private static class IFVerificationParams {
606        PackageParser.Package pkg;
607        boolean replacing;
608        int userId;
609        int verifierUid;
610
611        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
612                int _userId, int _verifierUid) {
613            pkg = _pkg;
614            replacing = _replacing;
615            userId = _userId;
616            replacing = _replacing;
617            verifierUid = _verifierUid;
618        }
619    }
620
621    private interface IntentFilterVerifier<T extends IntentFilter> {
622        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
623                                               T filter, String packageName);
624        void startVerifications(int userId);
625        void receiveVerificationResponse(int verificationId);
626    }
627
628    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
629        private Context mContext;
630        private ComponentName mIntentFilterVerifierComponent;
631        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
632
633        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
634            mContext = context;
635            mIntentFilterVerifierComponent = verifierComponent;
636        }
637
638        private String getDefaultScheme() {
639            return IntentFilter.SCHEME_HTTPS;
640        }
641
642        @Override
643        public void startVerifications(int userId) {
644            // Launch verifications requests
645            int count = mCurrentIntentFilterVerifications.size();
646            for (int n=0; n<count; n++) {
647                int verificationId = mCurrentIntentFilterVerifications.get(n);
648                final IntentFilterVerificationState ivs =
649                        mIntentFilterVerificationStates.get(verificationId);
650
651                String packageName = ivs.getPackageName();
652
653                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
654                final int filterCount = filters.size();
655                ArraySet<String> domainsSet = new ArraySet<>();
656                for (int m=0; m<filterCount; m++) {
657                    PackageParser.ActivityIntentInfo filter = filters.get(m);
658                    domainsSet.addAll(filter.getHostsList());
659                }
660                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
661                synchronized (mPackages) {
662                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
663                            packageName, domainsList) != null) {
664                        scheduleWriteSettingsLocked();
665                    }
666                }
667                sendVerificationRequest(userId, verificationId, ivs);
668            }
669            mCurrentIntentFilterVerifications.clear();
670        }
671
672        private void sendVerificationRequest(int userId, int verificationId,
673                IntentFilterVerificationState ivs) {
674
675            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
676            verificationIntent.putExtra(
677                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
678                    verificationId);
679            verificationIntent.putExtra(
680                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
681                    getDefaultScheme());
682            verificationIntent.putExtra(
683                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
684                    ivs.getHostsString());
685            verificationIntent.putExtra(
686                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
687                    ivs.getPackageName());
688            verificationIntent.setComponent(mIntentFilterVerifierComponent);
689            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
690
691            UserHandle user = new UserHandle(userId);
692            mContext.sendBroadcastAsUser(verificationIntent, user);
693            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
694                    "Sending IntentFilter verification broadcast");
695        }
696
697        public void receiveVerificationResponse(int verificationId) {
698            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
699
700            final boolean verified = ivs.isVerified();
701
702            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
703            final int count = filters.size();
704            if (DEBUG_DOMAIN_VERIFICATION) {
705                Slog.i(TAG, "Received verification response " + verificationId
706                        + " for " + count + " filters, verified=" + verified);
707            }
708            for (int n=0; n<count; n++) {
709                PackageParser.ActivityIntentInfo filter = filters.get(n);
710                filter.setVerified(verified);
711
712                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
713                        + " verified with result:" + verified + " and hosts:"
714                        + ivs.getHostsString());
715            }
716
717            mIntentFilterVerificationStates.remove(verificationId);
718
719            final String packageName = ivs.getPackageName();
720            IntentFilterVerificationInfo ivi = null;
721
722            synchronized (mPackages) {
723                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
724            }
725            if (ivi == null) {
726                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
727                        + verificationId + " packageName:" + packageName);
728                return;
729            }
730            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
731                    "Updating IntentFilterVerificationInfo for package " + packageName
732                            +" verificationId:" + verificationId);
733
734            synchronized (mPackages) {
735                if (verified) {
736                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
737                } else {
738                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
739                }
740                scheduleWriteSettingsLocked();
741
742                final int userId = ivs.getUserId();
743                if (userId != UserHandle.USER_ALL) {
744                    final int userStatus =
745                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
746
747                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
748                    boolean needUpdate = false;
749
750                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
751                    // already been set by the User thru the Disambiguation dialog
752                    switch (userStatus) {
753                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
754                            if (verified) {
755                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
756                            } else {
757                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
758                            }
759                            needUpdate = true;
760                            break;
761
762                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
763                            if (verified) {
764                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
765                                needUpdate = true;
766                            }
767                            break;
768
769                        default:
770                            // Nothing to do
771                    }
772
773                    if (needUpdate) {
774                        mSettings.updateIntentFilterVerificationStatusLPw(
775                                packageName, updatedStatus, userId);
776                        scheduleWritePackageRestrictionsLocked(userId);
777                    }
778                }
779            }
780        }
781
782        @Override
783        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
784                    ActivityIntentInfo filter, String packageName) {
785            if (!hasValidDomains(filter)) {
786                return false;
787            }
788            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
789            if (ivs == null) {
790                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
791                        packageName);
792            }
793            if (DEBUG_DOMAIN_VERIFICATION) {
794                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
795            }
796            ivs.addFilter(filter);
797            return true;
798        }
799
800        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
801                int userId, int verificationId, String packageName) {
802            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
803                    verifierUid, userId, packageName);
804            ivs.setPendingState();
805            synchronized (mPackages) {
806                mIntentFilterVerificationStates.append(verificationId, ivs);
807                mCurrentIntentFilterVerifications.add(verificationId);
808            }
809            return ivs;
810        }
811    }
812
813    private static boolean hasValidDomains(ActivityIntentInfo filter) {
814        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
815                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
816                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
817    }
818
819    private IntentFilterVerifier mIntentFilterVerifier;
820
821    // Set of pending broadcasts for aggregating enable/disable of components.
822    static class PendingPackageBroadcasts {
823        // for each user id, a map of <package name -> components within that package>
824        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
825
826        public PendingPackageBroadcasts() {
827            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
828        }
829
830        public ArrayList<String> get(int userId, String packageName) {
831            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
832            return packages.get(packageName);
833        }
834
835        public void put(int userId, String packageName, ArrayList<String> components) {
836            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
837            packages.put(packageName, components);
838        }
839
840        public void remove(int userId, String packageName) {
841            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
842            if (packages != null) {
843                packages.remove(packageName);
844            }
845        }
846
847        public void remove(int userId) {
848            mUidMap.remove(userId);
849        }
850
851        public int userIdCount() {
852            return mUidMap.size();
853        }
854
855        public int userIdAt(int n) {
856            return mUidMap.keyAt(n);
857        }
858
859        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
860            return mUidMap.get(userId);
861        }
862
863        public int size() {
864            // total number of pending broadcast entries across all userIds
865            int num = 0;
866            for (int i = 0; i< mUidMap.size(); i++) {
867                num += mUidMap.valueAt(i).size();
868            }
869            return num;
870        }
871
872        public void clear() {
873            mUidMap.clear();
874        }
875
876        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
877            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
878            if (map == null) {
879                map = new ArrayMap<String, ArrayList<String>>();
880                mUidMap.put(userId, map);
881            }
882            return map;
883        }
884    }
885    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
886
887    // Service Connection to remote media container service to copy
888    // package uri's from external media onto secure containers
889    // or internal storage.
890    private IMediaContainerService mContainerService = null;
891
892    static final int SEND_PENDING_BROADCAST = 1;
893    static final int MCS_BOUND = 3;
894    static final int END_COPY = 4;
895    static final int INIT_COPY = 5;
896    static final int MCS_UNBIND = 6;
897    static final int START_CLEANING_PACKAGE = 7;
898    static final int FIND_INSTALL_LOC = 8;
899    static final int POST_INSTALL = 9;
900    static final int MCS_RECONNECT = 10;
901    static final int MCS_GIVE_UP = 11;
902    static final int UPDATED_MEDIA_STATUS = 12;
903    static final int WRITE_SETTINGS = 13;
904    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
905    static final int PACKAGE_VERIFIED = 15;
906    static final int CHECK_PENDING_VERIFICATION = 16;
907    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
908    static final int INTENT_FILTER_VERIFIED = 18;
909
910    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
911
912    // Delay time in millisecs
913    static final int BROADCAST_DELAY = 10 * 1000;
914
915    static UserManagerService sUserManager;
916
917    // Stores a list of users whose package restrictions file needs to be updated
918    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
919
920    final private DefaultContainerConnection mDefContainerConn =
921            new DefaultContainerConnection();
922    class DefaultContainerConnection implements ServiceConnection {
923        public void onServiceConnected(ComponentName name, IBinder service) {
924            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
925            IMediaContainerService imcs =
926                IMediaContainerService.Stub.asInterface(service);
927            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
928        }
929
930        public void onServiceDisconnected(ComponentName name) {
931            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
932        }
933    }
934
935    // Recordkeeping of restore-after-install operations that are currently in flight
936    // between the Package Manager and the Backup Manager
937    class PostInstallData {
938        public InstallArgs args;
939        public PackageInstalledInfo res;
940
941        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
942            args = _a;
943            res = _r;
944        }
945    }
946
947    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
948    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
949
950    // XML tags for backup/restore of various bits of state
951    private static final String TAG_PREFERRED_BACKUP = "pa";
952    private static final String TAG_DEFAULT_APPS = "da";
953    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
954
955    final String mRequiredVerifierPackage;
956    final String mRequiredInstallerPackage;
957
958    private final PackageUsage mPackageUsage = new PackageUsage();
959
960    private class PackageUsage {
961        private static final int WRITE_INTERVAL
962            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
963
964        private final Object mFileLock = new Object();
965        private final AtomicLong mLastWritten = new AtomicLong(0);
966        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
967
968        private boolean mIsHistoricalPackageUsageAvailable = true;
969
970        boolean isHistoricalPackageUsageAvailable() {
971            return mIsHistoricalPackageUsageAvailable;
972        }
973
974        void write(boolean force) {
975            if (force) {
976                writeInternal();
977                return;
978            }
979            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
980                && !DEBUG_DEXOPT) {
981                return;
982            }
983            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
984                new Thread("PackageUsage_DiskWriter") {
985                    @Override
986                    public void run() {
987                        try {
988                            writeInternal();
989                        } finally {
990                            mBackgroundWriteRunning.set(false);
991                        }
992                    }
993                }.start();
994            }
995        }
996
997        private void writeInternal() {
998            synchronized (mPackages) {
999                synchronized (mFileLock) {
1000                    AtomicFile file = getFile();
1001                    FileOutputStream f = null;
1002                    try {
1003                        f = file.startWrite();
1004                        BufferedOutputStream out = new BufferedOutputStream(f);
1005                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1006                        StringBuilder sb = new StringBuilder();
1007                        for (PackageParser.Package pkg : mPackages.values()) {
1008                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1009                                continue;
1010                            }
1011                            sb.setLength(0);
1012                            sb.append(pkg.packageName);
1013                            sb.append(' ');
1014                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1015                            sb.append('\n');
1016                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1017                        }
1018                        out.flush();
1019                        file.finishWrite(f);
1020                    } catch (IOException e) {
1021                        if (f != null) {
1022                            file.failWrite(f);
1023                        }
1024                        Log.e(TAG, "Failed to write package usage times", e);
1025                    }
1026                }
1027            }
1028            mLastWritten.set(SystemClock.elapsedRealtime());
1029        }
1030
1031        void readLP() {
1032            synchronized (mFileLock) {
1033                AtomicFile file = getFile();
1034                BufferedInputStream in = null;
1035                try {
1036                    in = new BufferedInputStream(file.openRead());
1037                    StringBuffer sb = new StringBuffer();
1038                    while (true) {
1039                        String packageName = readToken(in, sb, ' ');
1040                        if (packageName == null) {
1041                            break;
1042                        }
1043                        String timeInMillisString = readToken(in, sb, '\n');
1044                        if (timeInMillisString == null) {
1045                            throw new IOException("Failed to find last usage time for package "
1046                                                  + packageName);
1047                        }
1048                        PackageParser.Package pkg = mPackages.get(packageName);
1049                        if (pkg == null) {
1050                            continue;
1051                        }
1052                        long timeInMillis;
1053                        try {
1054                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1055                        } catch (NumberFormatException e) {
1056                            throw new IOException("Failed to parse " + timeInMillisString
1057                                                  + " as a long.", e);
1058                        }
1059                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1060                    }
1061                } catch (FileNotFoundException expected) {
1062                    mIsHistoricalPackageUsageAvailable = false;
1063                } catch (IOException e) {
1064                    Log.w(TAG, "Failed to read package usage times", e);
1065                } finally {
1066                    IoUtils.closeQuietly(in);
1067                }
1068            }
1069            mLastWritten.set(SystemClock.elapsedRealtime());
1070        }
1071
1072        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1073                throws IOException {
1074            sb.setLength(0);
1075            while (true) {
1076                int ch = in.read();
1077                if (ch == -1) {
1078                    if (sb.length() == 0) {
1079                        return null;
1080                    }
1081                    throw new IOException("Unexpected EOF");
1082                }
1083                if (ch == endOfToken) {
1084                    return sb.toString();
1085                }
1086                sb.append((char)ch);
1087            }
1088        }
1089
1090        private AtomicFile getFile() {
1091            File dataDir = Environment.getDataDirectory();
1092            File systemDir = new File(dataDir, "system");
1093            File fname = new File(systemDir, "package-usage.list");
1094            return new AtomicFile(fname);
1095        }
1096    }
1097
1098    class PackageHandler extends Handler {
1099        private boolean mBound = false;
1100        final ArrayList<HandlerParams> mPendingInstalls =
1101            new ArrayList<HandlerParams>();
1102
1103        private boolean connectToService() {
1104            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1105                    " DefaultContainerService");
1106            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1107            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1108            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1109                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1110                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111                mBound = true;
1112                return true;
1113            }
1114            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115            return false;
1116        }
1117
1118        private void disconnectService() {
1119            mContainerService = null;
1120            mBound = false;
1121            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1122            mContext.unbindService(mDefContainerConn);
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1124        }
1125
1126        PackageHandler(Looper looper) {
1127            super(looper);
1128        }
1129
1130        public void handleMessage(Message msg) {
1131            try {
1132                doHandleMessage(msg);
1133            } finally {
1134                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1135            }
1136        }
1137
1138        void doHandleMessage(Message msg) {
1139            switch (msg.what) {
1140                case INIT_COPY: {
1141                    HandlerParams params = (HandlerParams) msg.obj;
1142                    int idx = mPendingInstalls.size();
1143                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1144                    // If a bind was already initiated we dont really
1145                    // need to do anything. The pending install
1146                    // will be processed later on.
1147                    if (!mBound) {
1148                        // If this is the only one pending we might
1149                        // have to bind to the service again.
1150                        if (!connectToService()) {
1151                            Slog.e(TAG, "Failed to bind to media container service");
1152                            params.serviceError();
1153                            return;
1154                        } else {
1155                            // Once we bind to the service, the first
1156                            // pending request will be processed.
1157                            mPendingInstalls.add(idx, params);
1158                        }
1159                    } else {
1160                        mPendingInstalls.add(idx, params);
1161                        // Already bound to the service. Just make
1162                        // sure we trigger off processing the first request.
1163                        if (idx == 0) {
1164                            mHandler.sendEmptyMessage(MCS_BOUND);
1165                        }
1166                    }
1167                    break;
1168                }
1169                case MCS_BOUND: {
1170                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1171                    if (msg.obj != null) {
1172                        mContainerService = (IMediaContainerService) msg.obj;
1173                    }
1174                    if (mContainerService == null) {
1175                        if (!mBound) {
1176                            // Something seriously wrong since we are not bound and we are not
1177                            // waiting for connection. Bail out.
1178                            Slog.e(TAG, "Cannot bind to media container service");
1179                            for (HandlerParams params : mPendingInstalls) {
1180                                // Indicate service bind error
1181                                params.serviceError();
1182                            }
1183                            mPendingInstalls.clear();
1184                        } else {
1185                            Slog.w(TAG, "Waiting to connect to media container service");
1186                        }
1187                    } else if (mPendingInstalls.size() > 0) {
1188                        HandlerParams params = mPendingInstalls.get(0);
1189                        if (params != null) {
1190                            if (params.startCopy()) {
1191                                // We are done...  look for more work or to
1192                                // go idle.
1193                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1194                                        "Checking for more work or unbind...");
1195                                // Delete pending install
1196                                if (mPendingInstalls.size() > 0) {
1197                                    mPendingInstalls.remove(0);
1198                                }
1199                                if (mPendingInstalls.size() == 0) {
1200                                    if (mBound) {
1201                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1202                                                "Posting delayed MCS_UNBIND");
1203                                        removeMessages(MCS_UNBIND);
1204                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1205                                        // Unbind after a little delay, to avoid
1206                                        // continual thrashing.
1207                                        sendMessageDelayed(ubmsg, 10000);
1208                                    }
1209                                } else {
1210                                    // There are more pending requests in queue.
1211                                    // Just post MCS_BOUND message to trigger processing
1212                                    // of next pending install.
1213                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1214                                            "Posting MCS_BOUND for next work");
1215                                    mHandler.sendEmptyMessage(MCS_BOUND);
1216                                }
1217                            }
1218                        }
1219                    } else {
1220                        // Should never happen ideally.
1221                        Slog.w(TAG, "Empty queue");
1222                    }
1223                    break;
1224                }
1225                case MCS_RECONNECT: {
1226                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1227                    if (mPendingInstalls.size() > 0) {
1228                        if (mBound) {
1229                            disconnectService();
1230                        }
1231                        if (!connectToService()) {
1232                            Slog.e(TAG, "Failed to bind to media container service");
1233                            for (HandlerParams params : mPendingInstalls) {
1234                                // Indicate service bind error
1235                                params.serviceError();
1236                            }
1237                            mPendingInstalls.clear();
1238                        }
1239                    }
1240                    break;
1241                }
1242                case MCS_UNBIND: {
1243                    // If there is no actual work left, then time to unbind.
1244                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1245
1246                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1247                        if (mBound) {
1248                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1249
1250                            disconnectService();
1251                        }
1252                    } else if (mPendingInstalls.size() > 0) {
1253                        // There are more pending requests in queue.
1254                        // Just post MCS_BOUND message to trigger processing
1255                        // of next pending install.
1256                        mHandler.sendEmptyMessage(MCS_BOUND);
1257                    }
1258
1259                    break;
1260                }
1261                case MCS_GIVE_UP: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1263                    mPendingInstalls.remove(0);
1264                    break;
1265                }
1266                case SEND_PENDING_BROADCAST: {
1267                    String packages[];
1268                    ArrayList<String> components[];
1269                    int size = 0;
1270                    int uids[];
1271                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1272                    synchronized (mPackages) {
1273                        if (mPendingBroadcasts == null) {
1274                            return;
1275                        }
1276                        size = mPendingBroadcasts.size();
1277                        if (size <= 0) {
1278                            // Nothing to be done. Just return
1279                            return;
1280                        }
1281                        packages = new String[size];
1282                        components = new ArrayList[size];
1283                        uids = new int[size];
1284                        int i = 0;  // filling out the above arrays
1285
1286                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1287                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1288                            Iterator<Map.Entry<String, ArrayList<String>>> it
1289                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1290                                            .entrySet().iterator();
1291                            while (it.hasNext() && i < size) {
1292                                Map.Entry<String, ArrayList<String>> ent = it.next();
1293                                packages[i] = ent.getKey();
1294                                components[i] = ent.getValue();
1295                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1296                                uids[i] = (ps != null)
1297                                        ? UserHandle.getUid(packageUserId, ps.appId)
1298                                        : -1;
1299                                i++;
1300                            }
1301                        }
1302                        size = i;
1303                        mPendingBroadcasts.clear();
1304                    }
1305                    // Send broadcasts
1306                    for (int i = 0; i < size; i++) {
1307                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1308                    }
1309                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1310                    break;
1311                }
1312                case START_CLEANING_PACKAGE: {
1313                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1314                    final String packageName = (String)msg.obj;
1315                    final int userId = msg.arg1;
1316                    final boolean andCode = msg.arg2 != 0;
1317                    synchronized (mPackages) {
1318                        if (userId == UserHandle.USER_ALL) {
1319                            int[] users = sUserManager.getUserIds();
1320                            for (int user : users) {
1321                                mSettings.addPackageToCleanLPw(
1322                                        new PackageCleanItem(user, packageName, andCode));
1323                            }
1324                        } else {
1325                            mSettings.addPackageToCleanLPw(
1326                                    new PackageCleanItem(userId, packageName, andCode));
1327                        }
1328                    }
1329                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1330                    startCleaningPackages();
1331                } break;
1332                case POST_INSTALL: {
1333                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1334                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1335                    mRunningInstalls.delete(msg.arg1);
1336                    boolean deleteOld = false;
1337
1338                    if (data != null) {
1339                        InstallArgs args = data.args;
1340                        PackageInstalledInfo res = data.res;
1341
1342                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1343                            final String packageName = res.pkg.applicationInfo.packageName;
1344                            res.removedInfo.sendBroadcast(false, true, false);
1345                            Bundle extras = new Bundle(1);
1346                            extras.putInt(Intent.EXTRA_UID, res.uid);
1347
1348                            // Now that we successfully installed the package, grant runtime
1349                            // permissions if requested before broadcasting the install.
1350                            if ((args.installFlags
1351                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1352                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1353                                        args.installGrantPermissions);
1354                            }
1355
1356                            // Determine the set of users who are adding this
1357                            // package for the first time vs. those who are seeing
1358                            // an update.
1359                            int[] firstUsers;
1360                            int[] updateUsers = new int[0];
1361                            if (res.origUsers == null || res.origUsers.length == 0) {
1362                                firstUsers = res.newUsers;
1363                            } else {
1364                                firstUsers = new int[0];
1365                                for (int i=0; i<res.newUsers.length; i++) {
1366                                    int user = res.newUsers[i];
1367                                    boolean isNew = true;
1368                                    for (int j=0; j<res.origUsers.length; j++) {
1369                                        if (res.origUsers[j] == user) {
1370                                            isNew = false;
1371                                            break;
1372                                        }
1373                                    }
1374                                    if (isNew) {
1375                                        int[] newFirst = new int[firstUsers.length+1];
1376                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1377                                                firstUsers.length);
1378                                        newFirst[firstUsers.length] = user;
1379                                        firstUsers = newFirst;
1380                                    } else {
1381                                        int[] newUpdate = new int[updateUsers.length+1];
1382                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1383                                                updateUsers.length);
1384                                        newUpdate[updateUsers.length] = user;
1385                                        updateUsers = newUpdate;
1386                                    }
1387                                }
1388                            }
1389                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1390                                    packageName, extras, null, null, firstUsers);
1391                            final boolean update = res.removedInfo.removedPackage != null;
1392                            if (update) {
1393                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1394                            }
1395                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1396                                    packageName, extras, null, null, updateUsers);
1397                            if (update) {
1398                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1399                                        packageName, extras, null, null, updateUsers);
1400                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1401                                        null, null, packageName, null, updateUsers);
1402
1403                                // treat asec-hosted packages like removable media on upgrade
1404                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1405                                    if (DEBUG_INSTALL) {
1406                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1407                                                + " is ASEC-hosted -> AVAILABLE");
1408                                    }
1409                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1410                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1411                                    pkgList.add(packageName);
1412                                    sendResourcesChangedBroadcast(true, true,
1413                                            pkgList,uidArray, null);
1414                                }
1415                            }
1416                            if (res.removedInfo.args != null) {
1417                                // Remove the replaced package's older resources safely now
1418                                deleteOld = true;
1419                            }
1420
1421                            // If this app is a browser and it's newly-installed for some
1422                            // users, clear any default-browser state in those users
1423                            if (firstUsers.length > 0) {
1424                                // the app's nature doesn't depend on the user, so we can just
1425                                // check its browser nature in any user and generalize.
1426                                if (packageIsBrowser(packageName, firstUsers[0])) {
1427                                    synchronized (mPackages) {
1428                                        for (int userId : firstUsers) {
1429                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1430                                        }
1431                                    }
1432                                }
1433                            }
1434                            // Log current value of "unknown sources" setting
1435                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1436                                getUnknownSourcesSettings());
1437                        }
1438                        // Force a gc to clear up things
1439                        Runtime.getRuntime().gc();
1440                        // We delete after a gc for applications  on sdcard.
1441                        if (deleteOld) {
1442                            synchronized (mInstallLock) {
1443                                res.removedInfo.args.doPostDeleteLI(true);
1444                            }
1445                        }
1446                        if (args.observer != null) {
1447                            try {
1448                                Bundle extras = extrasForInstallResult(res);
1449                                args.observer.onPackageInstalled(res.name, res.returnCode,
1450                                        res.returnMsg, extras);
1451                            } catch (RemoteException e) {
1452                                Slog.i(TAG, "Observer no longer exists.");
1453                            }
1454                        }
1455                    } else {
1456                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1457                    }
1458                } break;
1459                case UPDATED_MEDIA_STATUS: {
1460                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1461                    boolean reportStatus = msg.arg1 == 1;
1462                    boolean doGc = msg.arg2 == 1;
1463                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1464                    if (doGc) {
1465                        // Force a gc to clear up stale containers.
1466                        Runtime.getRuntime().gc();
1467                    }
1468                    if (msg.obj != null) {
1469                        @SuppressWarnings("unchecked")
1470                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1471                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1472                        // Unload containers
1473                        unloadAllContainers(args);
1474                    }
1475                    if (reportStatus) {
1476                        try {
1477                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1478                            PackageHelper.getMountService().finishMediaUpdate();
1479                        } catch (RemoteException e) {
1480                            Log.e(TAG, "MountService not running?");
1481                        }
1482                    }
1483                } break;
1484                case WRITE_SETTINGS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_SETTINGS);
1488                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                        mSettings.writeLPr();
1490                        mDirtyUsers.clear();
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case WRITE_PACKAGE_RESTRICTIONS: {
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1496                    synchronized (mPackages) {
1497                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1498                        for (int userId : mDirtyUsers) {
1499                            mSettings.writePackageRestrictionsLPr(userId);
1500                        }
1501                        mDirtyUsers.clear();
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                } break;
1505                case CHECK_PENDING_VERIFICATION: {
1506                    final int verificationId = msg.arg1;
1507                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                    if ((state != null) && !state.timeoutExtended()) {
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        Slog.i(TAG, "Verification timed out for " + originUri);
1514                        mPendingVerification.remove(verificationId);
1515
1516                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                            Slog.i(TAG, "Continuing with installation of " + originUri);
1520                            state.setVerifierResponse(Binder.getCallingUid(),
1521                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_ALLOW,
1524                                    state.getInstallArgs().getUser());
1525                            try {
1526                                ret = args.copyApk(mContainerService, true);
1527                            } catch (RemoteException e) {
1528                                Slog.e(TAG, "Could not contact the ContainerService");
1529                            }
1530                        } else {
1531                            broadcastPackageVerified(verificationId, originUri,
1532                                    PackageManager.VERIFICATION_REJECT,
1533                                    state.getInstallArgs().getUser());
1534                        }
1535
1536                        processPendingInstall(args, ret);
1537                        mHandler.sendEmptyMessage(MCS_UNBIND);
1538                    }
1539                    break;
1540                }
1541                case PACKAGE_VERIFIED: {
1542                    final int verificationId = msg.arg1;
1543
1544                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1545                    if (state == null) {
1546                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1547                        break;
1548                    }
1549
1550                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1551
1552                    state.setVerifierResponse(response.callerUid, response.code);
1553
1554                    if (state.isVerificationComplete()) {
1555                        mPendingVerification.remove(verificationId);
1556
1557                        final InstallArgs args = state.getInstallArgs();
1558                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1559
1560                        int ret;
1561                        if (state.isInstallAllowed()) {
1562                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1563                            broadcastPackageVerified(verificationId, originUri,
1564                                    response.code, state.getInstallArgs().getUser());
1565                            try {
1566                                ret = args.copyApk(mContainerService, true);
1567                            } catch (RemoteException e) {
1568                                Slog.e(TAG, "Could not contact the ContainerService");
1569                            }
1570                        } else {
1571                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1572                        }
1573
1574                        processPendingInstall(args, ret);
1575
1576                        mHandler.sendEmptyMessage(MCS_UNBIND);
1577                    }
1578
1579                    break;
1580                }
1581                case START_INTENT_FILTER_VERIFICATIONS: {
1582                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1583                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1584                            params.replacing, params.pkg);
1585                    break;
1586                }
1587                case INTENT_FILTER_VERIFIED: {
1588                    final int verificationId = msg.arg1;
1589
1590                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1591                            verificationId);
1592                    if (state == null) {
1593                        Slog.w(TAG, "Invalid IntentFilter verification token "
1594                                + verificationId + " received");
1595                        break;
1596                    }
1597
1598                    final int userId = state.getUserId();
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "Processing IntentFilter verification with token:"
1602                            + verificationId + " and userId:" + userId);
1603
1604                    final IntentFilterVerificationResponse response =
1605                            (IntentFilterVerificationResponse) msg.obj;
1606
1607                    state.setVerifierResponse(response.callerUid, response.code);
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "IntentFilter verification with token:" + verificationId
1611                            + " and userId:" + userId
1612                            + " is settings verifier response with response code:"
1613                            + response.code);
1614
1615                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1616                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1617                                + response.getFailedDomainsString());
1618                    }
1619
1620                    if (state.isVerificationComplete()) {
1621                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1622                    } else {
1623                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1624                                "IntentFilter verification with token:" + verificationId
1625                                + " was not said to be complete");
1626                    }
1627
1628                    break;
1629                }
1630            }
1631        }
1632    }
1633
1634    private StorageEventListener mStorageListener = new StorageEventListener() {
1635        @Override
1636        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1637            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1638                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1639                    final String volumeUuid = vol.getFsUuid();
1640
1641                    // Clean up any users or apps that were removed or recreated
1642                    // while this volume was missing
1643                    reconcileUsers(volumeUuid);
1644                    reconcileApps(volumeUuid);
1645
1646                    // Clean up any install sessions that expired or were
1647                    // cancelled while this volume was missing
1648                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1649
1650                    loadPrivatePackages(vol);
1651
1652                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1653                    unloadPrivatePackages(vol);
1654                }
1655            }
1656
1657            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1658                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1659                    updateExternalMediaStatus(true, false);
1660                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1661                    updateExternalMediaStatus(false, false);
1662                }
1663            }
1664        }
1665
1666        @Override
1667        public void onVolumeForgotten(String fsUuid) {
1668            if (TextUtils.isEmpty(fsUuid)) {
1669                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1670                return;
1671            }
1672
1673            // Remove any apps installed on the forgotten volume
1674            synchronized (mPackages) {
1675                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1676                for (PackageSetting ps : packages) {
1677                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1678                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1679                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1680                }
1681
1682                mSettings.onVolumeForgotten(fsUuid);
1683                mSettings.writeLPr();
1684            }
1685        }
1686    };
1687
1688    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1689            String[] grantedPermissions) {
1690        if (userId >= UserHandle.USER_OWNER) {
1691            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1692        } else if (userId == UserHandle.USER_ALL) {
1693            final int[] userIds;
1694            synchronized (mPackages) {
1695                userIds = UserManagerService.getInstance().getUserIds();
1696            }
1697            for (int someUserId : userIds) {
1698                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1699            }
1700        }
1701
1702        // We could have touched GID membership, so flush out packages.list
1703        synchronized (mPackages) {
1704            mSettings.writePackageListLPr();
1705        }
1706    }
1707
1708    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1709            String[] grantedPermissions) {
1710        SettingBase sb = (SettingBase) pkg.mExtras;
1711        if (sb == null) {
1712            return;
1713        }
1714
1715        PermissionsState permissionsState = sb.getPermissionsState();
1716
1717        for (String permission : pkg.requestedPermissions) {
1718            BasePermission bp = mSettings.mPermissions.get(permission);
1719            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1720                    || ArrayUtils.contains(grantedPermissions, permission))) {
1721                permissionsState.grantRuntimePermission(bp, userId);
1722            }
1723        }
1724    }
1725
1726    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1727        Bundle extras = null;
1728        switch (res.returnCode) {
1729            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1730                extras = new Bundle();
1731                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1732                        res.origPermission);
1733                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1734                        res.origPackage);
1735                break;
1736            }
1737            case PackageManager.INSTALL_SUCCEEDED: {
1738                extras = new Bundle();
1739                extras.putBoolean(Intent.EXTRA_REPLACING,
1740                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1741                break;
1742            }
1743        }
1744        return extras;
1745    }
1746
1747    void scheduleWriteSettingsLocked() {
1748        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1749            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1750        }
1751    }
1752
1753    void scheduleWritePackageRestrictionsLocked(int userId) {
1754        if (!sUserManager.exists(userId)) return;
1755        mDirtyUsers.add(userId);
1756        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1757            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1758        }
1759    }
1760
1761    public static PackageManagerService main(Context context, Installer installer,
1762            boolean factoryTest, boolean onlyCore) {
1763        PackageManagerService m = new PackageManagerService(context, installer,
1764                factoryTest, onlyCore);
1765        ServiceManager.addService("package", m);
1766        return m;
1767    }
1768
1769    static String[] splitString(String str, char sep) {
1770        int count = 1;
1771        int i = 0;
1772        while ((i=str.indexOf(sep, i)) >= 0) {
1773            count++;
1774            i++;
1775        }
1776
1777        String[] res = new String[count];
1778        i=0;
1779        count = 0;
1780        int lastI=0;
1781        while ((i=str.indexOf(sep, i)) >= 0) {
1782            res[count] = str.substring(lastI, i);
1783            count++;
1784            i++;
1785            lastI = i;
1786        }
1787        res[count] = str.substring(lastI, str.length());
1788        return res;
1789    }
1790
1791    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1792        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1793                Context.DISPLAY_SERVICE);
1794        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1795    }
1796
1797    public PackageManagerService(Context context, Installer installer,
1798            boolean factoryTest, boolean onlyCore) {
1799        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1800                SystemClock.uptimeMillis());
1801
1802        if (mSdkVersion <= 0) {
1803            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1804        }
1805
1806        mContext = context;
1807        mFactoryTest = factoryTest;
1808        mOnlyCore = onlyCore;
1809        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1810        mMetrics = new DisplayMetrics();
1811        mSettings = new Settings(mPackages);
1812        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1813                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1814        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1815                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1817                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1819                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1821                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1823                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824
1825        // TODO: add a property to control this?
1826        long dexOptLRUThresholdInMinutes;
1827        if (mLazyDexOpt) {
1828            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1829        } else {
1830            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1831        }
1832        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1833
1834        String separateProcesses = SystemProperties.get("debug.separate_processes");
1835        if (separateProcesses != null && separateProcesses.length() > 0) {
1836            if ("*".equals(separateProcesses)) {
1837                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1838                mSeparateProcesses = null;
1839                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1840            } else {
1841                mDefParseFlags = 0;
1842                mSeparateProcesses = separateProcesses.split(",");
1843                Slog.w(TAG, "Running with debug.separate_processes: "
1844                        + separateProcesses);
1845            }
1846        } else {
1847            mDefParseFlags = 0;
1848            mSeparateProcesses = null;
1849        }
1850
1851        mInstaller = installer;
1852        mPackageDexOptimizer = new PackageDexOptimizer(this);
1853        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1854
1855        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1856                FgThread.get().getLooper());
1857
1858        getDefaultDisplayMetrics(context, mMetrics);
1859
1860        SystemConfig systemConfig = SystemConfig.getInstance();
1861        mGlobalGids = systemConfig.getGlobalGids();
1862        mSystemPermissions = systemConfig.getSystemPermissions();
1863        mAvailableFeatures = systemConfig.getAvailableFeatures();
1864
1865        synchronized (mInstallLock) {
1866        // writer
1867        synchronized (mPackages) {
1868            mHandlerThread = new ServiceThread(TAG,
1869                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1870            mHandlerThread.start();
1871            mHandler = new PackageHandler(mHandlerThread.getLooper());
1872            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1873
1874            File dataDir = Environment.getDataDirectory();
1875            mAppDataDir = new File(dataDir, "data");
1876            mAppInstallDir = new File(dataDir, "app");
1877            mAppLib32InstallDir = new File(dataDir, "app-lib");
1878            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1879            mUserAppDataDir = new File(dataDir, "user");
1880            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1881
1882            sUserManager = new UserManagerService(context, this,
1883                    mInstallLock, mPackages);
1884
1885            // Propagate permission configuration in to package manager.
1886            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1887                    = systemConfig.getPermissions();
1888            for (int i=0; i<permConfig.size(); i++) {
1889                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1890                BasePermission bp = mSettings.mPermissions.get(perm.name);
1891                if (bp == null) {
1892                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1893                    mSettings.mPermissions.put(perm.name, bp);
1894                }
1895                if (perm.gids != null) {
1896                    bp.setGids(perm.gids, perm.perUser);
1897                }
1898            }
1899
1900            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1901            for (int i=0; i<libConfig.size(); i++) {
1902                mSharedLibraries.put(libConfig.keyAt(i),
1903                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1904            }
1905
1906            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1907
1908            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1909                    mSdkVersion, mOnlyCore);
1910
1911            String customResolverActivity = Resources.getSystem().getString(
1912                    R.string.config_customResolverActivity);
1913            if (TextUtils.isEmpty(customResolverActivity)) {
1914                customResolverActivity = null;
1915            } else {
1916                mCustomResolverComponentName = ComponentName.unflattenFromString(
1917                        customResolverActivity);
1918            }
1919
1920            long startTime = SystemClock.uptimeMillis();
1921
1922            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1923                    startTime);
1924
1925            // Set flag to monitor and not change apk file paths when
1926            // scanning install directories.
1927            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1928
1929            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1930
1931            /**
1932             * Add everything in the in the boot class path to the
1933             * list of process files because dexopt will have been run
1934             * if necessary during zygote startup.
1935             */
1936            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1937            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1938
1939            if (bootClassPath != null) {
1940                String[] bootClassPathElements = splitString(bootClassPath, ':');
1941                for (String element : bootClassPathElements) {
1942                    alreadyDexOpted.add(element);
1943                }
1944            } else {
1945                Slog.w(TAG, "No BOOTCLASSPATH found!");
1946            }
1947
1948            if (systemServerClassPath != null) {
1949                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1950                for (String element : systemServerClassPathElements) {
1951                    alreadyDexOpted.add(element);
1952                }
1953            } else {
1954                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1955            }
1956
1957            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1958            final String[] dexCodeInstructionSets =
1959                    getDexCodeInstructionSets(
1960                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1961
1962            /**
1963             * Ensure all external libraries have had dexopt run on them.
1964             */
1965            if (mSharedLibraries.size() > 0) {
1966                // NOTE: For now, we're compiling these system "shared libraries"
1967                // (and framework jars) into all available architectures. It's possible
1968                // to compile them only when we come across an app that uses them (there's
1969                // already logic for that in scanPackageLI) but that adds some complexity.
1970                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1971                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1972                        final String lib = libEntry.path;
1973                        if (lib == null) {
1974                            continue;
1975                        }
1976
1977                        try {
1978                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1979                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1980                                alreadyDexOpted.add(lib);
1981                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1982                            }
1983                        } catch (FileNotFoundException e) {
1984                            Slog.w(TAG, "Library not found: " + lib);
1985                        } catch (IOException e) {
1986                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1987                                    + e.getMessage());
1988                        }
1989                    }
1990                }
1991            }
1992
1993            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1994
1995            // Gross hack for now: we know this file doesn't contain any
1996            // code, so don't dexopt it to avoid the resulting log spew.
1997            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1998
1999            // Gross hack for now: we know this file is only part of
2000            // the boot class path for art, so don't dexopt it to
2001            // avoid the resulting log spew.
2002            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2003
2004            /**
2005             * There are a number of commands implemented in Java, which
2006             * we currently need to do the dexopt on so that they can be
2007             * run from a non-root shell.
2008             */
2009            String[] frameworkFiles = frameworkDir.list();
2010            if (frameworkFiles != null) {
2011                // TODO: We could compile these only for the most preferred ABI. We should
2012                // first double check that the dex files for these commands are not referenced
2013                // by other system apps.
2014                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2015                    for (int i=0; i<frameworkFiles.length; i++) {
2016                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2017                        String path = libPath.getPath();
2018                        // Skip the file if we already did it.
2019                        if (alreadyDexOpted.contains(path)) {
2020                            continue;
2021                        }
2022                        // Skip the file if it is not a type we want to dexopt.
2023                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2024                            continue;
2025                        }
2026                        try {
2027                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2028                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2029                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2030                            }
2031                        } catch (FileNotFoundException e) {
2032                            Slog.w(TAG, "Jar not found: " + path);
2033                        } catch (IOException e) {
2034                            Slog.w(TAG, "Exception reading jar: " + path, e);
2035                        }
2036                    }
2037                }
2038            }
2039
2040            final VersionInfo ver = mSettings.getInternalVersion();
2041            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2042            // when upgrading from pre-M, promote system app permissions from install to runtime
2043            mPromoteSystemApps =
2044                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2045
2046            // save off the names of pre-existing system packages prior to scanning; we don't
2047            // want to automatically grant runtime permissions for new system apps
2048            if (mPromoteSystemApps) {
2049                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2050                while (pkgSettingIter.hasNext()) {
2051                    PackageSetting ps = pkgSettingIter.next();
2052                    if (isSystemApp(ps)) {
2053                        mExistingSystemPackages.add(ps.name);
2054                    }
2055                }
2056            }
2057
2058            // Collect vendor overlay packages.
2059            // (Do this before scanning any apps.)
2060            // For security and version matching reason, only consider
2061            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2062            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2063            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2064                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2065
2066            // Find base frameworks (resource packages without code).
2067            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR
2069                    | PackageParser.PARSE_IS_PRIVILEGED,
2070                    scanFlags | SCAN_NO_DEX, 0);
2071
2072            // Collected privileged system packages.
2073            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2074            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2075                    | PackageParser.PARSE_IS_SYSTEM_DIR
2076                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2077
2078            // Collect ordinary system packages.
2079            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2080            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2081                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2082
2083            // Collect all vendor packages.
2084            File vendorAppDir = new File("/vendor/app");
2085            try {
2086                vendorAppDir = vendorAppDir.getCanonicalFile();
2087            } catch (IOException e) {
2088                // failed to look up canonical path, continue with original one
2089            }
2090            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2091                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2092
2093            // Collect all OEM packages.
2094            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2095            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2096                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2097
2098            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2099            mInstaller.moveFiles();
2100
2101            // Prune any system packages that no longer exist.
2102            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2103            if (!mOnlyCore) {
2104                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2105                while (psit.hasNext()) {
2106                    PackageSetting ps = psit.next();
2107
2108                    /*
2109                     * If this is not a system app, it can't be a
2110                     * disable system app.
2111                     */
2112                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2113                        continue;
2114                    }
2115
2116                    /*
2117                     * If the package is scanned, it's not erased.
2118                     */
2119                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2120                    if (scannedPkg != null) {
2121                        /*
2122                         * If the system app is both scanned and in the
2123                         * disabled packages list, then it must have been
2124                         * added via OTA. Remove it from the currently
2125                         * scanned package so the previously user-installed
2126                         * application can be scanned.
2127                         */
2128                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2129                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2130                                    + ps.name + "; removing system app.  Last known codePath="
2131                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2132                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2133                                    + scannedPkg.mVersionCode);
2134                            removePackageLI(ps, true);
2135                            mExpectingBetter.put(ps.name, ps.codePath);
2136                        }
2137
2138                        continue;
2139                    }
2140
2141                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2142                        psit.remove();
2143                        logCriticalInfo(Log.WARN, "System package " + ps.name
2144                                + " no longer exists; wiping its data");
2145                        removeDataDirsLI(null, ps.name);
2146                    } else {
2147                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2148                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2149                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2150                        }
2151                    }
2152                }
2153            }
2154
2155            //look for any incomplete package installations
2156            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2157            //clean up list
2158            for(int i = 0; i < deletePkgsList.size(); i++) {
2159                //clean up here
2160                cleanupInstallFailedPackage(deletePkgsList.get(i));
2161            }
2162            //delete tmp files
2163            deleteTempPackageFiles();
2164
2165            // Remove any shared userIDs that have no associated packages
2166            mSettings.pruneSharedUsersLPw();
2167
2168            if (!mOnlyCore) {
2169                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2170                        SystemClock.uptimeMillis());
2171                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2172
2173                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2174                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2175
2176                /**
2177                 * Remove disable package settings for any updated system
2178                 * apps that were removed via an OTA. If they're not a
2179                 * previously-updated app, remove them completely.
2180                 * Otherwise, just revoke their system-level permissions.
2181                 */
2182                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2183                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2184                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2185
2186                    String msg;
2187                    if (deletedPkg == null) {
2188                        msg = "Updated system package " + deletedAppName
2189                                + " no longer exists; wiping its data";
2190                        removeDataDirsLI(null, deletedAppName);
2191                    } else {
2192                        msg = "Updated system app + " + deletedAppName
2193                                + " no longer present; removing system privileges for "
2194                                + deletedAppName;
2195
2196                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2197
2198                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2199                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2200                    }
2201                    logCriticalInfo(Log.WARN, msg);
2202                }
2203
2204                /**
2205                 * Make sure all system apps that we expected to appear on
2206                 * the userdata partition actually showed up. If they never
2207                 * appeared, crawl back and revive the system version.
2208                 */
2209                for (int i = 0; i < mExpectingBetter.size(); i++) {
2210                    final String packageName = mExpectingBetter.keyAt(i);
2211                    if (!mPackages.containsKey(packageName)) {
2212                        final File scanFile = mExpectingBetter.valueAt(i);
2213
2214                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2215                                + " but never showed up; reverting to system");
2216
2217                        final int reparseFlags;
2218                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2219                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2220                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2221                                    | PackageParser.PARSE_IS_PRIVILEGED;
2222                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2223                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2224                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2225                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2226                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2227                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2228                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2229                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2230                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2231                        } else {
2232                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2233                            continue;
2234                        }
2235
2236                        mSettings.enableSystemPackageLPw(packageName);
2237
2238                        try {
2239                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2240                        } catch (PackageManagerException e) {
2241                            Slog.e(TAG, "Failed to parse original system package: "
2242                                    + e.getMessage());
2243                        }
2244                    }
2245                }
2246            }
2247            mExpectingBetter.clear();
2248
2249            // Now that we know all of the shared libraries, update all clients to have
2250            // the correct library paths.
2251            updateAllSharedLibrariesLPw();
2252
2253            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2254                // NOTE: We ignore potential failures here during a system scan (like
2255                // the rest of the commands above) because there's precious little we
2256                // can do about it. A settings error is reported, though.
2257                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2258                        false /* force dexopt */, false /* defer dexopt */);
2259            }
2260
2261            // Now that we know all the packages we are keeping,
2262            // read and update their last usage times.
2263            mPackageUsage.readLP();
2264
2265            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2266                    SystemClock.uptimeMillis());
2267            Slog.i(TAG, "Time to scan packages: "
2268                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2269                    + " seconds");
2270
2271            // If the platform SDK has changed since the last time we booted,
2272            // we need to re-grant app permission to catch any new ones that
2273            // appear.  This is really a hack, and means that apps can in some
2274            // cases get permissions that the user didn't initially explicitly
2275            // allow...  it would be nice to have some better way to handle
2276            // this situation.
2277            int updateFlags = UPDATE_PERMISSIONS_ALL;
2278            if (ver.sdkVersion != mSdkVersion) {
2279                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2280                        + mSdkVersion + "; regranting permissions for internal storage");
2281                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2282            }
2283            updatePermissionsLPw(null, null, updateFlags);
2284            ver.sdkVersion = mSdkVersion;
2285            // clear only after permissions have been updated
2286            mExistingSystemPackages.clear();
2287            mPromoteSystemApps = false;
2288
2289            // If this is the first boot, and it is a normal boot, then
2290            // we need to initialize the default preferred apps.
2291            if (!mRestoredSettings && !onlyCore) {
2292                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2293                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2294                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2295            }
2296
2297            // If this is first boot after an OTA, and a normal boot, then
2298            // we need to clear code cache directories.
2299            if (mIsUpgrade && !onlyCore) {
2300                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2301                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2302                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2303                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2304                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2305                    }
2306                }
2307                ver.fingerprint = Build.FINGERPRINT;
2308            }
2309
2310            checkDefaultBrowser();
2311
2312            // All the changes are done during package scanning.
2313            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2314
2315            // can downgrade to reader
2316            mSettings.writeLPr();
2317
2318            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2319                    SystemClock.uptimeMillis());
2320
2321            mRequiredVerifierPackage = getRequiredVerifierLPr();
2322            mRequiredInstallerPackage = getRequiredInstallerLPr();
2323
2324            mInstallerService = new PackageInstallerService(context, this);
2325
2326            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2327            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2328                    mIntentFilterVerifierComponent);
2329
2330        } // synchronized (mPackages)
2331        } // synchronized (mInstallLock)
2332
2333        // Now after opening every single application zip, make sure they
2334        // are all flushed.  Not really needed, but keeps things nice and
2335        // tidy.
2336        Runtime.getRuntime().gc();
2337
2338        // Expose private service for system components to use.
2339        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2340    }
2341
2342    @Override
2343    public boolean isFirstBoot() {
2344        return !mRestoredSettings;
2345    }
2346
2347    @Override
2348    public boolean isOnlyCoreApps() {
2349        return mOnlyCore;
2350    }
2351
2352    @Override
2353    public boolean isUpgrade() {
2354        return mIsUpgrade;
2355    }
2356
2357    private String getRequiredVerifierLPr() {
2358        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2359        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2360                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2361
2362        String requiredVerifier = null;
2363
2364        final int N = receivers.size();
2365        for (int i = 0; i < N; i++) {
2366            final ResolveInfo info = receivers.get(i);
2367
2368            if (info.activityInfo == null) {
2369                continue;
2370            }
2371
2372            final String packageName = info.activityInfo.packageName;
2373
2374            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2375                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2376                continue;
2377            }
2378
2379            if (requiredVerifier != null) {
2380                throw new RuntimeException("There can be only one required verifier");
2381            }
2382
2383            requiredVerifier = packageName;
2384        }
2385
2386        return requiredVerifier;
2387    }
2388
2389    private String getRequiredInstallerLPr() {
2390        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2391        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2392        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2393
2394        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2395                PACKAGE_MIME_TYPE, 0, 0);
2396
2397        String requiredInstaller = null;
2398
2399        final int N = installers.size();
2400        for (int i = 0; i < N; i++) {
2401            final ResolveInfo info = installers.get(i);
2402            final String packageName = info.activityInfo.packageName;
2403
2404            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2405                continue;
2406            }
2407
2408            if (requiredInstaller != null) {
2409                throw new RuntimeException("There must be one required installer");
2410            }
2411
2412            requiredInstaller = packageName;
2413        }
2414
2415        if (requiredInstaller == null) {
2416            throw new RuntimeException("There must be one required installer");
2417        }
2418
2419        return requiredInstaller;
2420    }
2421
2422    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2423        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2424        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2425                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2426
2427        ComponentName verifierComponentName = null;
2428
2429        int priority = -1000;
2430        final int N = receivers.size();
2431        for (int i = 0; i < N; i++) {
2432            final ResolveInfo info = receivers.get(i);
2433
2434            if (info.activityInfo == null) {
2435                continue;
2436            }
2437
2438            final String packageName = info.activityInfo.packageName;
2439
2440            final PackageSetting ps = mSettings.mPackages.get(packageName);
2441            if (ps == null) {
2442                continue;
2443            }
2444
2445            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2446                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2447                continue;
2448            }
2449
2450            // Select the IntentFilterVerifier with the highest priority
2451            if (priority < info.priority) {
2452                priority = info.priority;
2453                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2454                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2455                        + verifierComponentName + " with priority: " + info.priority);
2456            }
2457        }
2458
2459        return verifierComponentName;
2460    }
2461
2462    private void primeDomainVerificationsLPw(int userId) {
2463        if (DEBUG_DOMAIN_VERIFICATION) {
2464            Slog.d(TAG, "Priming domain verifications in user " + userId);
2465        }
2466
2467        SystemConfig systemConfig = SystemConfig.getInstance();
2468        ArraySet<String> packages = systemConfig.getLinkedApps();
2469        ArraySet<String> domains = new ArraySet<String>();
2470
2471        for (String packageName : packages) {
2472            PackageParser.Package pkg = mPackages.get(packageName);
2473            if (pkg != null) {
2474                if (!pkg.isSystemApp()) {
2475                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2476                    continue;
2477                }
2478
2479                domains.clear();
2480                for (PackageParser.Activity a : pkg.activities) {
2481                    for (ActivityIntentInfo filter : a.intents) {
2482                        if (hasValidDomains(filter)) {
2483                            domains.addAll(filter.getHostsList());
2484                        }
2485                    }
2486                }
2487
2488                if (domains.size() > 0) {
2489                    if (DEBUG_DOMAIN_VERIFICATION) {
2490                        Slog.v(TAG, "      + " + packageName);
2491                    }
2492                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2493                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2494                    // and then 'always' in the per-user state actually used for intent resolution.
2495                    final IntentFilterVerificationInfo ivi;
2496                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2497                            new ArrayList<String>(domains));
2498                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2499                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2500                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2501                } else {
2502                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2503                            + "' does not handle web links");
2504                }
2505            } else {
2506                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2507            }
2508        }
2509
2510        scheduleWritePackageRestrictionsLocked(userId);
2511        scheduleWriteSettingsLocked();
2512    }
2513
2514    private void applyFactoryDefaultBrowserLPw(int userId) {
2515        // The default browser app's package name is stored in a string resource,
2516        // with a product-specific overlay used for vendor customization.
2517        String browserPkg = mContext.getResources().getString(
2518                com.android.internal.R.string.default_browser);
2519        if (!TextUtils.isEmpty(browserPkg)) {
2520            // non-empty string => required to be a known package
2521            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2522            if (ps == null) {
2523                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2524                browserPkg = null;
2525            } else {
2526                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2527            }
2528        }
2529
2530        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2531        // default.  If there's more than one, just leave everything alone.
2532        if (browserPkg == null) {
2533            calculateDefaultBrowserLPw(userId);
2534        }
2535    }
2536
2537    private void calculateDefaultBrowserLPw(int userId) {
2538        List<String> allBrowsers = resolveAllBrowserApps(userId);
2539        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2540        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2541    }
2542
2543    private List<String> resolveAllBrowserApps(int userId) {
2544        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2545        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2546                PackageManager.MATCH_ALL, userId);
2547
2548        final int count = list.size();
2549        List<String> result = new ArrayList<String>(count);
2550        for (int i=0; i<count; i++) {
2551            ResolveInfo info = list.get(i);
2552            if (info.activityInfo == null
2553                    || !info.handleAllWebDataURI
2554                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2555                    || result.contains(info.activityInfo.packageName)) {
2556                continue;
2557            }
2558            result.add(info.activityInfo.packageName);
2559        }
2560
2561        return result;
2562    }
2563
2564    private boolean packageIsBrowser(String packageName, int userId) {
2565        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2566                PackageManager.MATCH_ALL, userId);
2567        final int N = list.size();
2568        for (int i = 0; i < N; i++) {
2569            ResolveInfo info = list.get(i);
2570            if (packageName.equals(info.activityInfo.packageName)) {
2571                return true;
2572            }
2573        }
2574        return false;
2575    }
2576
2577    private void checkDefaultBrowser() {
2578        final int myUserId = UserHandle.myUserId();
2579        final String packageName = getDefaultBrowserPackageName(myUserId);
2580        if (packageName != null) {
2581            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2582            if (info == null) {
2583                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2584                synchronized (mPackages) {
2585                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2586                }
2587            }
2588        }
2589    }
2590
2591    @Override
2592    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2593            throws RemoteException {
2594        try {
2595            return super.onTransact(code, data, reply, flags);
2596        } catch (RuntimeException e) {
2597            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2598                Slog.wtf(TAG, "Package Manager Crash", e);
2599            }
2600            throw e;
2601        }
2602    }
2603
2604    void cleanupInstallFailedPackage(PackageSetting ps) {
2605        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2606
2607        removeDataDirsLI(ps.volumeUuid, ps.name);
2608        if (ps.codePath != null) {
2609            if (ps.codePath.isDirectory()) {
2610                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2611            } else {
2612                ps.codePath.delete();
2613            }
2614        }
2615        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2616            if (ps.resourcePath.isDirectory()) {
2617                FileUtils.deleteContents(ps.resourcePath);
2618            }
2619            ps.resourcePath.delete();
2620        }
2621        mSettings.removePackageLPw(ps.name);
2622    }
2623
2624    static int[] appendInts(int[] cur, int[] add) {
2625        if (add == null) return cur;
2626        if (cur == null) return add;
2627        final int N = add.length;
2628        for (int i=0; i<N; i++) {
2629            cur = appendInt(cur, add[i]);
2630        }
2631        return cur;
2632    }
2633
2634    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2635        if (!sUserManager.exists(userId)) return null;
2636        final PackageSetting ps = (PackageSetting) p.mExtras;
2637        if (ps == null) {
2638            return null;
2639        }
2640
2641        final PermissionsState permissionsState = ps.getPermissionsState();
2642
2643        final int[] gids = permissionsState.computeGids(userId);
2644        final Set<String> permissions = permissionsState.getPermissions(userId);
2645        final PackageUserState state = ps.readUserState(userId);
2646
2647        return PackageParser.generatePackageInfo(p, gids, flags,
2648                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2649    }
2650
2651    @Override
2652    public boolean isPackageFrozen(String packageName) {
2653        synchronized (mPackages) {
2654            final PackageSetting ps = mSettings.mPackages.get(packageName);
2655            if (ps != null) {
2656                return ps.frozen;
2657            }
2658        }
2659        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2660        return true;
2661    }
2662
2663    @Override
2664    public boolean isPackageAvailable(String packageName, int userId) {
2665        if (!sUserManager.exists(userId)) return false;
2666        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2667        synchronized (mPackages) {
2668            PackageParser.Package p = mPackages.get(packageName);
2669            if (p != null) {
2670                final PackageSetting ps = (PackageSetting) p.mExtras;
2671                if (ps != null) {
2672                    final PackageUserState state = ps.readUserState(userId);
2673                    if (state != null) {
2674                        return PackageParser.isAvailable(state);
2675                    }
2676                }
2677            }
2678        }
2679        return false;
2680    }
2681
2682    @Override
2683    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2684        if (!sUserManager.exists(userId)) return null;
2685        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2686        // reader
2687        synchronized (mPackages) {
2688            PackageParser.Package p = mPackages.get(packageName);
2689            if (DEBUG_PACKAGE_INFO)
2690                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2691            if (p != null) {
2692                return generatePackageInfo(p, flags, userId);
2693            }
2694            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2695                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2696            }
2697        }
2698        return null;
2699    }
2700
2701    @Override
2702    public String[] currentToCanonicalPackageNames(String[] names) {
2703        String[] out = new String[names.length];
2704        // reader
2705        synchronized (mPackages) {
2706            for (int i=names.length-1; i>=0; i--) {
2707                PackageSetting ps = mSettings.mPackages.get(names[i]);
2708                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2709            }
2710        }
2711        return out;
2712    }
2713
2714    @Override
2715    public String[] canonicalToCurrentPackageNames(String[] names) {
2716        String[] out = new String[names.length];
2717        // reader
2718        synchronized (mPackages) {
2719            for (int i=names.length-1; i>=0; i--) {
2720                String cur = mSettings.mRenamedPackages.get(names[i]);
2721                out[i] = cur != null ? cur : names[i];
2722            }
2723        }
2724        return out;
2725    }
2726
2727    @Override
2728    public int getPackageUid(String packageName, int userId) {
2729        if (!sUserManager.exists(userId)) return -1;
2730        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2731
2732        // reader
2733        synchronized (mPackages) {
2734            PackageParser.Package p = mPackages.get(packageName);
2735            if(p != null) {
2736                return UserHandle.getUid(userId, p.applicationInfo.uid);
2737            }
2738            PackageSetting ps = mSettings.mPackages.get(packageName);
2739            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2740                return -1;
2741            }
2742            p = ps.pkg;
2743            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2744        }
2745    }
2746
2747    @Override
2748    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2749        if (!sUserManager.exists(userId)) {
2750            return null;
2751        }
2752
2753        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2754                "getPackageGids");
2755
2756        // reader
2757        synchronized (mPackages) {
2758            PackageParser.Package p = mPackages.get(packageName);
2759            if (DEBUG_PACKAGE_INFO) {
2760                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2761            }
2762            if (p != null) {
2763                PackageSetting ps = (PackageSetting) p.mExtras;
2764                return ps.getPermissionsState().computeGids(userId);
2765            }
2766        }
2767
2768        return null;
2769    }
2770
2771    static PermissionInfo generatePermissionInfo(
2772            BasePermission bp, int flags) {
2773        if (bp.perm != null) {
2774            return PackageParser.generatePermissionInfo(bp.perm, flags);
2775        }
2776        PermissionInfo pi = new PermissionInfo();
2777        pi.name = bp.name;
2778        pi.packageName = bp.sourcePackage;
2779        pi.nonLocalizedLabel = bp.name;
2780        pi.protectionLevel = bp.protectionLevel;
2781        return pi;
2782    }
2783
2784    @Override
2785    public PermissionInfo getPermissionInfo(String name, int flags) {
2786        // reader
2787        synchronized (mPackages) {
2788            final BasePermission p = mSettings.mPermissions.get(name);
2789            if (p != null) {
2790                return generatePermissionInfo(p, flags);
2791            }
2792            return null;
2793        }
2794    }
2795
2796    @Override
2797    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2798        // reader
2799        synchronized (mPackages) {
2800            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2801            for (BasePermission p : mSettings.mPermissions.values()) {
2802                if (group == null) {
2803                    if (p.perm == null || p.perm.info.group == null) {
2804                        out.add(generatePermissionInfo(p, flags));
2805                    }
2806                } else {
2807                    if (p.perm != null && group.equals(p.perm.info.group)) {
2808                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2809                    }
2810                }
2811            }
2812
2813            if (out.size() > 0) {
2814                return out;
2815            }
2816            return mPermissionGroups.containsKey(group) ? out : null;
2817        }
2818    }
2819
2820    @Override
2821    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2822        // reader
2823        synchronized (mPackages) {
2824            return PackageParser.generatePermissionGroupInfo(
2825                    mPermissionGroups.get(name), flags);
2826        }
2827    }
2828
2829    @Override
2830    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            final int N = mPermissionGroups.size();
2834            ArrayList<PermissionGroupInfo> out
2835                    = new ArrayList<PermissionGroupInfo>(N);
2836            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2837                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2838            }
2839            return out;
2840        }
2841    }
2842
2843    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2844            int userId) {
2845        if (!sUserManager.exists(userId)) return null;
2846        PackageSetting ps = mSettings.mPackages.get(packageName);
2847        if (ps != null) {
2848            if (ps.pkg == null) {
2849                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2850                        flags, userId);
2851                if (pInfo != null) {
2852                    return pInfo.applicationInfo;
2853                }
2854                return null;
2855            }
2856            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2857                    ps.readUserState(userId), userId);
2858        }
2859        return null;
2860    }
2861
2862    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2863            int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        PackageSetting ps = mSettings.mPackages.get(packageName);
2866        if (ps != null) {
2867            PackageParser.Package pkg = ps.pkg;
2868            if (pkg == null) {
2869                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2870                    return null;
2871                }
2872                // Only data remains, so we aren't worried about code paths
2873                pkg = new PackageParser.Package(packageName);
2874                pkg.applicationInfo.packageName = packageName;
2875                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2876                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2877                pkg.applicationInfo.dataDir = Environment
2878                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2879                        .getAbsolutePath();
2880                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2881                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2882            }
2883            return generatePackageInfo(pkg, flags, userId);
2884        }
2885        return null;
2886    }
2887
2888    @Override
2889    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2892        // writer
2893        synchronized (mPackages) {
2894            PackageParser.Package p = mPackages.get(packageName);
2895            if (DEBUG_PACKAGE_INFO) Log.v(
2896                    TAG, "getApplicationInfo " + packageName
2897                    + ": " + p);
2898            if (p != null) {
2899                PackageSetting ps = mSettings.mPackages.get(packageName);
2900                if (ps == null) return null;
2901                // Note: isEnabledLP() does not apply here - always return info
2902                return PackageParser.generateApplicationInfo(
2903                        p, flags, ps.readUserState(userId), userId);
2904            }
2905            if ("android".equals(packageName)||"system".equals(packageName)) {
2906                return mAndroidApplication;
2907            }
2908            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2909                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2910            }
2911        }
2912        return null;
2913    }
2914
2915    @Override
2916    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2917            final IPackageDataObserver observer) {
2918        mContext.enforceCallingOrSelfPermission(
2919                android.Manifest.permission.CLEAR_APP_CACHE, null);
2920        // Queue up an async operation since clearing cache may take a little while.
2921        mHandler.post(new Runnable() {
2922            public void run() {
2923                mHandler.removeCallbacks(this);
2924                int retCode = -1;
2925                synchronized (mInstallLock) {
2926                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2927                    if (retCode < 0) {
2928                        Slog.w(TAG, "Couldn't clear application caches");
2929                    }
2930                }
2931                if (observer != null) {
2932                    try {
2933                        observer.onRemoveCompleted(null, (retCode >= 0));
2934                    } catch (RemoteException e) {
2935                        Slog.w(TAG, "RemoveException when invoking call back");
2936                    }
2937                }
2938            }
2939        });
2940    }
2941
2942    @Override
2943    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2944            final IntentSender pi) {
2945        mContext.enforceCallingOrSelfPermission(
2946                android.Manifest.permission.CLEAR_APP_CACHE, null);
2947        // Queue up an async operation since clearing cache may take a little while.
2948        mHandler.post(new Runnable() {
2949            public void run() {
2950                mHandler.removeCallbacks(this);
2951                int retCode = -1;
2952                synchronized (mInstallLock) {
2953                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2954                    if (retCode < 0) {
2955                        Slog.w(TAG, "Couldn't clear application caches");
2956                    }
2957                }
2958                if(pi != null) {
2959                    try {
2960                        // Callback via pending intent
2961                        int code = (retCode >= 0) ? 1 : 0;
2962                        pi.sendIntent(null, code, null,
2963                                null, null);
2964                    } catch (SendIntentException e1) {
2965                        Slog.i(TAG, "Failed to send pending intent");
2966                    }
2967                }
2968            }
2969        });
2970    }
2971
2972    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2973        synchronized (mInstallLock) {
2974            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2975                throw new IOException("Failed to free enough space");
2976            }
2977        }
2978    }
2979
2980    @Override
2981    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2982        if (!sUserManager.exists(userId)) return null;
2983        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2984        synchronized (mPackages) {
2985            PackageParser.Activity a = mActivities.mActivities.get(component);
2986
2987            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2988            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2989                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2990                if (ps == null) return null;
2991                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2992                        userId);
2993            }
2994            if (mResolveComponentName.equals(component)) {
2995                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2996                        new PackageUserState(), userId);
2997            }
2998        }
2999        return null;
3000    }
3001
3002    @Override
3003    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3004            String resolvedType) {
3005        synchronized (mPackages) {
3006            if (component.equals(mResolveComponentName)) {
3007                // The resolver supports EVERYTHING!
3008                return true;
3009            }
3010            PackageParser.Activity a = mActivities.mActivities.get(component);
3011            if (a == null) {
3012                return false;
3013            }
3014            for (int i=0; i<a.intents.size(); i++) {
3015                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3016                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3017                    return true;
3018                }
3019            }
3020            return false;
3021        }
3022    }
3023
3024    @Override
3025    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3026        if (!sUserManager.exists(userId)) return null;
3027        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3028        synchronized (mPackages) {
3029            PackageParser.Activity a = mReceivers.mActivities.get(component);
3030            if (DEBUG_PACKAGE_INFO) Log.v(
3031                TAG, "getReceiverInfo " + component + ": " + a);
3032            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3033                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3034                if (ps == null) return null;
3035                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3036                        userId);
3037            }
3038        }
3039        return null;
3040    }
3041
3042    @Override
3043    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3044        if (!sUserManager.exists(userId)) return null;
3045        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3046        synchronized (mPackages) {
3047            PackageParser.Service s = mServices.mServices.get(component);
3048            if (DEBUG_PACKAGE_INFO) Log.v(
3049                TAG, "getServiceInfo " + component + ": " + s);
3050            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3051                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3052                if (ps == null) return null;
3053                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3054                        userId);
3055            }
3056        }
3057        return null;
3058    }
3059
3060    @Override
3061    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3062        if (!sUserManager.exists(userId)) return null;
3063        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3064        synchronized (mPackages) {
3065            PackageParser.Provider p = mProviders.mProviders.get(component);
3066            if (DEBUG_PACKAGE_INFO) Log.v(
3067                TAG, "getProviderInfo " + component + ": " + p);
3068            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3069                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3070                if (ps == null) return null;
3071                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3072                        userId);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public String[] getSystemSharedLibraryNames() {
3080        Set<String> libSet;
3081        synchronized (mPackages) {
3082            libSet = mSharedLibraries.keySet();
3083            int size = libSet.size();
3084            if (size > 0) {
3085                String[] libs = new String[size];
3086                libSet.toArray(libs);
3087                return libs;
3088            }
3089        }
3090        return null;
3091    }
3092
3093    /**
3094     * @hide
3095     */
3096    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3097        synchronized (mPackages) {
3098            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3099            if (lib != null && lib.apk != null) {
3100                return mPackages.get(lib.apk);
3101            }
3102        }
3103        return null;
3104    }
3105
3106    @Override
3107    public FeatureInfo[] getSystemAvailableFeatures() {
3108        Collection<FeatureInfo> featSet;
3109        synchronized (mPackages) {
3110            featSet = mAvailableFeatures.values();
3111            int size = featSet.size();
3112            if (size > 0) {
3113                FeatureInfo[] features = new FeatureInfo[size+1];
3114                featSet.toArray(features);
3115                FeatureInfo fi = new FeatureInfo();
3116                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3117                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3118                features[size] = fi;
3119                return features;
3120            }
3121        }
3122        return null;
3123    }
3124
3125    @Override
3126    public boolean hasSystemFeature(String name) {
3127        synchronized (mPackages) {
3128            return mAvailableFeatures.containsKey(name);
3129        }
3130    }
3131
3132    private void checkValidCaller(int uid, int userId) {
3133        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3134            return;
3135
3136        throw new SecurityException("Caller uid=" + uid
3137                + " is not privileged to communicate with user=" + userId);
3138    }
3139
3140    @Override
3141    public int checkPermission(String permName, String pkgName, int userId) {
3142        if (!sUserManager.exists(userId)) {
3143            return PackageManager.PERMISSION_DENIED;
3144        }
3145
3146        synchronized (mPackages) {
3147            final PackageParser.Package p = mPackages.get(pkgName);
3148            if (p != null && p.mExtras != null) {
3149                final PackageSetting ps = (PackageSetting) p.mExtras;
3150                final PermissionsState permissionsState = ps.getPermissionsState();
3151                if (permissionsState.hasPermission(permName, userId)) {
3152                    return PackageManager.PERMISSION_GRANTED;
3153                }
3154                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3155                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3156                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159            }
3160        }
3161
3162        return PackageManager.PERMISSION_DENIED;
3163    }
3164
3165    @Override
3166    public int checkUidPermission(String permName, int uid) {
3167        final int userId = UserHandle.getUserId(uid);
3168
3169        if (!sUserManager.exists(userId)) {
3170            return PackageManager.PERMISSION_DENIED;
3171        }
3172
3173        synchronized (mPackages) {
3174            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3175            if (obj != null) {
3176                final SettingBase ps = (SettingBase) obj;
3177                final PermissionsState permissionsState = ps.getPermissionsState();
3178                if (permissionsState.hasPermission(permName, userId)) {
3179                    return PackageManager.PERMISSION_GRANTED;
3180                }
3181                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3182                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3183                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3184                    return PackageManager.PERMISSION_GRANTED;
3185                }
3186            } else {
3187                ArraySet<String> perms = mSystemPermissions.get(uid);
3188                if (perms != null) {
3189                    if (perms.contains(permName)) {
3190                        return PackageManager.PERMISSION_GRANTED;
3191                    }
3192                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3193                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3194                        return PackageManager.PERMISSION_GRANTED;
3195                    }
3196                }
3197            }
3198        }
3199
3200        return PackageManager.PERMISSION_DENIED;
3201    }
3202
3203    @Override
3204    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3205        if (UserHandle.getCallingUserId() != userId) {
3206            mContext.enforceCallingPermission(
3207                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3208                    "isPermissionRevokedByPolicy for user " + userId);
3209        }
3210
3211        if (checkPermission(permission, packageName, userId)
3212                == PackageManager.PERMISSION_GRANTED) {
3213            return false;
3214        }
3215
3216        final long identity = Binder.clearCallingIdentity();
3217        try {
3218            final int flags = getPermissionFlags(permission, packageName, userId);
3219            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3220        } finally {
3221            Binder.restoreCallingIdentity(identity);
3222        }
3223    }
3224
3225    @Override
3226    public String getPermissionControllerPackageName() {
3227        synchronized (mPackages) {
3228            return mRequiredInstallerPackage;
3229        }
3230    }
3231
3232    /**
3233     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3234     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3235     * @param checkShell TODO(yamasani):
3236     * @param message the message to log on security exception
3237     */
3238    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3239            boolean checkShell, String message) {
3240        if (userId < 0) {
3241            throw new IllegalArgumentException("Invalid userId " + userId);
3242        }
3243        if (checkShell) {
3244            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3245        }
3246        if (userId == UserHandle.getUserId(callingUid)) return;
3247        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3248            if (requireFullPermission) {
3249                mContext.enforceCallingOrSelfPermission(
3250                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3251            } else {
3252                try {
3253                    mContext.enforceCallingOrSelfPermission(
3254                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3255                } catch (SecurityException se) {
3256                    mContext.enforceCallingOrSelfPermission(
3257                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3258                }
3259            }
3260        }
3261    }
3262
3263    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3264        if (callingUid == Process.SHELL_UID) {
3265            if (userHandle >= 0
3266                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3267                throw new SecurityException("Shell does not have permission to access user "
3268                        + userHandle);
3269            } else if (userHandle < 0) {
3270                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3271                        + Debug.getCallers(3));
3272            }
3273        }
3274    }
3275
3276    private BasePermission findPermissionTreeLP(String permName) {
3277        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3278            if (permName.startsWith(bp.name) &&
3279                    permName.length() > bp.name.length() &&
3280                    permName.charAt(bp.name.length()) == '.') {
3281                return bp;
3282            }
3283        }
3284        return null;
3285    }
3286
3287    private BasePermission checkPermissionTreeLP(String permName) {
3288        if (permName != null) {
3289            BasePermission bp = findPermissionTreeLP(permName);
3290            if (bp != null) {
3291                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3292                    return bp;
3293                }
3294                throw new SecurityException("Calling uid "
3295                        + Binder.getCallingUid()
3296                        + " is not allowed to add to permission tree "
3297                        + bp.name + " owned by uid " + bp.uid);
3298            }
3299        }
3300        throw new SecurityException("No permission tree found for " + permName);
3301    }
3302
3303    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3304        if (s1 == null) {
3305            return s2 == null;
3306        }
3307        if (s2 == null) {
3308            return false;
3309        }
3310        if (s1.getClass() != s2.getClass()) {
3311            return false;
3312        }
3313        return s1.equals(s2);
3314    }
3315
3316    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3317        if (pi1.icon != pi2.icon) return false;
3318        if (pi1.logo != pi2.logo) return false;
3319        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3320        if (!compareStrings(pi1.name, pi2.name)) return false;
3321        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3322        // We'll take care of setting this one.
3323        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3324        // These are not currently stored in settings.
3325        //if (!compareStrings(pi1.group, pi2.group)) return false;
3326        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3327        //if (pi1.labelRes != pi2.labelRes) return false;
3328        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3329        return true;
3330    }
3331
3332    int permissionInfoFootprint(PermissionInfo info) {
3333        int size = info.name.length();
3334        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3335        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3336        return size;
3337    }
3338
3339    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3340        int size = 0;
3341        for (BasePermission perm : mSettings.mPermissions.values()) {
3342            if (perm.uid == tree.uid) {
3343                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3344            }
3345        }
3346        return size;
3347    }
3348
3349    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3350        // We calculate the max size of permissions defined by this uid and throw
3351        // if that plus the size of 'info' would exceed our stated maximum.
3352        if (tree.uid != Process.SYSTEM_UID) {
3353            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3354            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3355                throw new SecurityException("Permission tree size cap exceeded");
3356            }
3357        }
3358    }
3359
3360    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3361        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3362            throw new SecurityException("Label must be specified in permission");
3363        }
3364        BasePermission tree = checkPermissionTreeLP(info.name);
3365        BasePermission bp = mSettings.mPermissions.get(info.name);
3366        boolean added = bp == null;
3367        boolean changed = true;
3368        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3369        if (added) {
3370            enforcePermissionCapLocked(info, tree);
3371            bp = new BasePermission(info.name, tree.sourcePackage,
3372                    BasePermission.TYPE_DYNAMIC);
3373        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3374            throw new SecurityException(
3375                    "Not allowed to modify non-dynamic permission "
3376                    + info.name);
3377        } else {
3378            if (bp.protectionLevel == fixedLevel
3379                    && bp.perm.owner.equals(tree.perm.owner)
3380                    && bp.uid == tree.uid
3381                    && comparePermissionInfos(bp.perm.info, info)) {
3382                changed = false;
3383            }
3384        }
3385        bp.protectionLevel = fixedLevel;
3386        info = new PermissionInfo(info);
3387        info.protectionLevel = fixedLevel;
3388        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3389        bp.perm.info.packageName = tree.perm.info.packageName;
3390        bp.uid = tree.uid;
3391        if (added) {
3392            mSettings.mPermissions.put(info.name, bp);
3393        }
3394        if (changed) {
3395            if (!async) {
3396                mSettings.writeLPr();
3397            } else {
3398                scheduleWriteSettingsLocked();
3399            }
3400        }
3401        return added;
3402    }
3403
3404    @Override
3405    public boolean addPermission(PermissionInfo info) {
3406        synchronized (mPackages) {
3407            return addPermissionLocked(info, false);
3408        }
3409    }
3410
3411    @Override
3412    public boolean addPermissionAsync(PermissionInfo info) {
3413        synchronized (mPackages) {
3414            return addPermissionLocked(info, true);
3415        }
3416    }
3417
3418    @Override
3419    public void removePermission(String name) {
3420        synchronized (mPackages) {
3421            checkPermissionTreeLP(name);
3422            BasePermission bp = mSettings.mPermissions.get(name);
3423            if (bp != null) {
3424                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3425                    throw new SecurityException(
3426                            "Not allowed to modify non-dynamic permission "
3427                            + name);
3428                }
3429                mSettings.mPermissions.remove(name);
3430                mSettings.writeLPr();
3431            }
3432        }
3433    }
3434
3435    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3436            BasePermission bp) {
3437        int index = pkg.requestedPermissions.indexOf(bp.name);
3438        if (index == -1) {
3439            throw new SecurityException("Package " + pkg.packageName
3440                    + " has not requested permission " + bp.name);
3441        }
3442        if (!bp.isRuntime()) {
3443            throw new SecurityException("Permission " + bp.name
3444                    + " is not a changeable permission type");
3445        }
3446    }
3447
3448    @Override
3449    public void grantRuntimePermission(String packageName, String name, final int userId) {
3450        if (!sUserManager.exists(userId)) {
3451            Log.e(TAG, "No such user:" + userId);
3452            return;
3453        }
3454
3455        mContext.enforceCallingOrSelfPermission(
3456                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3457                "grantRuntimePermission");
3458
3459        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3460                "grantRuntimePermission");
3461
3462        final int uid;
3463        final SettingBase sb;
3464
3465        synchronized (mPackages) {
3466            final PackageParser.Package pkg = mPackages.get(packageName);
3467            if (pkg == null) {
3468                throw new IllegalArgumentException("Unknown package: " + packageName);
3469            }
3470
3471            final BasePermission bp = mSettings.mPermissions.get(name);
3472            if (bp == null) {
3473                throw new IllegalArgumentException("Unknown permission: " + name);
3474            }
3475
3476            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3477
3478            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3479            sb = (SettingBase) pkg.mExtras;
3480            if (sb == null) {
3481                throw new IllegalArgumentException("Unknown package: " + packageName);
3482            }
3483
3484            final PermissionsState permissionsState = sb.getPermissionsState();
3485
3486            final int flags = permissionsState.getPermissionFlags(name, userId);
3487            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3488                throw new SecurityException("Cannot grant system fixed permission: "
3489                        + name + " for package: " + packageName);
3490            }
3491
3492            final int result = permissionsState.grantRuntimePermission(bp, userId);
3493            switch (result) {
3494                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3495                    return;
3496                }
3497
3498                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3499                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3500                    mHandler.post(new Runnable() {
3501                        @Override
3502                        public void run() {
3503                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3504                        }
3505                    });
3506                } break;
3507            }
3508
3509            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3510
3511            // Not critical if that is lost - app has to request again.
3512            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3513        }
3514
3515        // Only need to do this if user is initialized. Otherwise it's a new user
3516        // and there are no processes running as the user yet and there's no need
3517        // to make an expensive call to remount processes for the changed permissions.
3518        if (READ_EXTERNAL_STORAGE.equals(name)
3519                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3520            final long token = Binder.clearCallingIdentity();
3521            try {
3522                if (sUserManager.isInitialized(userId)) {
3523                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3524                            MountServiceInternal.class);
3525                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3526                }
3527            } finally {
3528                Binder.restoreCallingIdentity(token);
3529            }
3530        }
3531    }
3532
3533    @Override
3534    public void revokeRuntimePermission(String packageName, String name, int userId) {
3535        if (!sUserManager.exists(userId)) {
3536            Log.e(TAG, "No such user:" + userId);
3537            return;
3538        }
3539
3540        mContext.enforceCallingOrSelfPermission(
3541                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3542                "revokeRuntimePermission");
3543
3544        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3545                "revokeRuntimePermission");
3546
3547        final int appId;
3548
3549        synchronized (mPackages) {
3550            final PackageParser.Package pkg = mPackages.get(packageName);
3551            if (pkg == null) {
3552                throw new IllegalArgumentException("Unknown package: " + packageName);
3553            }
3554
3555            final BasePermission bp = mSettings.mPermissions.get(name);
3556            if (bp == null) {
3557                throw new IllegalArgumentException("Unknown permission: " + name);
3558            }
3559
3560            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3561
3562            SettingBase sb = (SettingBase) pkg.mExtras;
3563            if (sb == null) {
3564                throw new IllegalArgumentException("Unknown package: " + packageName);
3565            }
3566
3567            final PermissionsState permissionsState = sb.getPermissionsState();
3568
3569            final int flags = permissionsState.getPermissionFlags(name, userId);
3570            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3571                throw new SecurityException("Cannot revoke system fixed permission: "
3572                        + name + " for package: " + packageName);
3573            }
3574
3575            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3576                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3577                return;
3578            }
3579
3580            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3581
3582            // Critical, after this call app should never have the permission.
3583            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3584
3585            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3586        }
3587
3588        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3589    }
3590
3591    @Override
3592    public void resetRuntimePermissions() {
3593        mContext.enforceCallingOrSelfPermission(
3594                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3595                "revokeRuntimePermission");
3596
3597        int callingUid = Binder.getCallingUid();
3598        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3599            mContext.enforceCallingOrSelfPermission(
3600                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3601                    "resetRuntimePermissions");
3602        }
3603
3604        synchronized (mPackages) {
3605            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3606            for (int userId : UserManagerService.getInstance().getUserIds()) {
3607                final int packageCount = mPackages.size();
3608                for (int i = 0; i < packageCount; i++) {
3609                    PackageParser.Package pkg = mPackages.valueAt(i);
3610                    if (!(pkg.mExtras instanceof PackageSetting)) {
3611                        continue;
3612                    }
3613                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3614                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3615                }
3616            }
3617        }
3618    }
3619
3620    @Override
3621    public int getPermissionFlags(String name, String packageName, int userId) {
3622        if (!sUserManager.exists(userId)) {
3623            return 0;
3624        }
3625
3626        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3627
3628        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3629                "getPermissionFlags");
3630
3631        synchronized (mPackages) {
3632            final PackageParser.Package pkg = mPackages.get(packageName);
3633            if (pkg == null) {
3634                throw new IllegalArgumentException("Unknown package: " + packageName);
3635            }
3636
3637            final BasePermission bp = mSettings.mPermissions.get(name);
3638            if (bp == null) {
3639                throw new IllegalArgumentException("Unknown permission: " + name);
3640            }
3641
3642            SettingBase sb = (SettingBase) pkg.mExtras;
3643            if (sb == null) {
3644                throw new IllegalArgumentException("Unknown package: " + packageName);
3645            }
3646
3647            PermissionsState permissionsState = sb.getPermissionsState();
3648            return permissionsState.getPermissionFlags(name, userId);
3649        }
3650    }
3651
3652    @Override
3653    public void updatePermissionFlags(String name, String packageName, int flagMask,
3654            int flagValues, int userId) {
3655        if (!sUserManager.exists(userId)) {
3656            return;
3657        }
3658
3659        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3660
3661        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3662                "updatePermissionFlags");
3663
3664        // Only the system can change these flags and nothing else.
3665        if (getCallingUid() != Process.SYSTEM_UID) {
3666            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3667            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3668            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3669            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3670        }
3671
3672        synchronized (mPackages) {
3673            final PackageParser.Package pkg = mPackages.get(packageName);
3674            if (pkg == null) {
3675                throw new IllegalArgumentException("Unknown package: " + packageName);
3676            }
3677
3678            final BasePermission bp = mSettings.mPermissions.get(name);
3679            if (bp == null) {
3680                throw new IllegalArgumentException("Unknown permission: " + name);
3681            }
3682
3683            SettingBase sb = (SettingBase) pkg.mExtras;
3684            if (sb == null) {
3685                throw new IllegalArgumentException("Unknown package: " + packageName);
3686            }
3687
3688            PermissionsState permissionsState = sb.getPermissionsState();
3689
3690            // Only the package manager can change flags for system component permissions.
3691            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3692            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3693                return;
3694            }
3695
3696            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3697
3698            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3699                // Install and runtime permissions are stored in different places,
3700                // so figure out what permission changed and persist the change.
3701                if (permissionsState.getInstallPermissionState(name) != null) {
3702                    scheduleWriteSettingsLocked();
3703                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3704                        || hadState) {
3705                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3706                }
3707            }
3708        }
3709    }
3710
3711    /**
3712     * Update the permission flags for all packages and runtime permissions of a user in order
3713     * to allow device or profile owner to remove POLICY_FIXED.
3714     */
3715    @Override
3716    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3717        if (!sUserManager.exists(userId)) {
3718            return;
3719        }
3720
3721        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3722
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3724                "updatePermissionFlagsForAllApps");
3725
3726        // Only the system can change system fixed flags.
3727        if (getCallingUid() != Process.SYSTEM_UID) {
3728            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3729            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3730        }
3731
3732        synchronized (mPackages) {
3733            boolean changed = false;
3734            final int packageCount = mPackages.size();
3735            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3736                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3737                SettingBase sb = (SettingBase) pkg.mExtras;
3738                if (sb == null) {
3739                    continue;
3740                }
3741                PermissionsState permissionsState = sb.getPermissionsState();
3742                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3743                        userId, flagMask, flagValues);
3744            }
3745            if (changed) {
3746                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3747            }
3748        }
3749    }
3750
3751    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3752        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3753                != PackageManager.PERMISSION_GRANTED
3754            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3755                != PackageManager.PERMISSION_GRANTED) {
3756            throw new SecurityException(message + " requires "
3757                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3758                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3759        }
3760    }
3761
3762    @Override
3763    public boolean shouldShowRequestPermissionRationale(String permissionName,
3764            String packageName, int userId) {
3765        if (UserHandle.getCallingUserId() != userId) {
3766            mContext.enforceCallingPermission(
3767                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3768                    "canShowRequestPermissionRationale for user " + userId);
3769        }
3770
3771        final int uid = getPackageUid(packageName, userId);
3772        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3773            return false;
3774        }
3775
3776        if (checkPermission(permissionName, packageName, userId)
3777                == PackageManager.PERMISSION_GRANTED) {
3778            return false;
3779        }
3780
3781        final int flags;
3782
3783        final long identity = Binder.clearCallingIdentity();
3784        try {
3785            flags = getPermissionFlags(permissionName,
3786                    packageName, userId);
3787        } finally {
3788            Binder.restoreCallingIdentity(identity);
3789        }
3790
3791        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3792                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3793                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3794
3795        if ((flags & fixedFlags) != 0) {
3796            return false;
3797        }
3798
3799        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3800    }
3801
3802    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3803        BasePermission bp = mSettings.mPermissions.get(permission);
3804        if (bp == null) {
3805            throw new SecurityException("Missing " + permission + " permission");
3806        }
3807
3808        SettingBase sb = (SettingBase) pkg.mExtras;
3809        PermissionsState permissionsState = sb.getPermissionsState();
3810
3811        if (permissionsState.grantInstallPermission(bp) !=
3812                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3813            scheduleWriteSettingsLocked();
3814        }
3815    }
3816
3817    @Override
3818    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3819        mContext.enforceCallingOrSelfPermission(
3820                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3821                "addOnPermissionsChangeListener");
3822
3823        synchronized (mPackages) {
3824            mOnPermissionChangeListeners.addListenerLocked(listener);
3825        }
3826    }
3827
3828    @Override
3829    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3830        synchronized (mPackages) {
3831            mOnPermissionChangeListeners.removeListenerLocked(listener);
3832        }
3833    }
3834
3835    @Override
3836    public boolean isProtectedBroadcast(String actionName) {
3837        synchronized (mPackages) {
3838            return mProtectedBroadcasts.contains(actionName);
3839        }
3840    }
3841
3842    @Override
3843    public int checkSignatures(String pkg1, String pkg2) {
3844        synchronized (mPackages) {
3845            final PackageParser.Package p1 = mPackages.get(pkg1);
3846            final PackageParser.Package p2 = mPackages.get(pkg2);
3847            if (p1 == null || p1.mExtras == null
3848                    || p2 == null || p2.mExtras == null) {
3849                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3850            }
3851            return compareSignatures(p1.mSignatures, p2.mSignatures);
3852        }
3853    }
3854
3855    @Override
3856    public int checkUidSignatures(int uid1, int uid2) {
3857        // Map to base uids.
3858        uid1 = UserHandle.getAppId(uid1);
3859        uid2 = UserHandle.getAppId(uid2);
3860        // reader
3861        synchronized (mPackages) {
3862            Signature[] s1;
3863            Signature[] s2;
3864            Object obj = mSettings.getUserIdLPr(uid1);
3865            if (obj != null) {
3866                if (obj instanceof SharedUserSetting) {
3867                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3868                } else if (obj instanceof PackageSetting) {
3869                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3870                } else {
3871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3872                }
3873            } else {
3874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3875            }
3876            obj = mSettings.getUserIdLPr(uid2);
3877            if (obj != null) {
3878                if (obj instanceof SharedUserSetting) {
3879                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3880                } else if (obj instanceof PackageSetting) {
3881                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3882                } else {
3883                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3884                }
3885            } else {
3886                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3887            }
3888            return compareSignatures(s1, s2);
3889        }
3890    }
3891
3892    private void killUid(int appId, int userId, String reason) {
3893        final long identity = Binder.clearCallingIdentity();
3894        try {
3895            IActivityManager am = ActivityManagerNative.getDefault();
3896            if (am != null) {
3897                try {
3898                    am.killUid(appId, userId, reason);
3899                } catch (RemoteException e) {
3900                    /* ignore - same process */
3901                }
3902            }
3903        } finally {
3904            Binder.restoreCallingIdentity(identity);
3905        }
3906    }
3907
3908    /**
3909     * Compares two sets of signatures. Returns:
3910     * <br />
3911     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3912     * <br />
3913     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3914     * <br />
3915     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3916     * <br />
3917     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3918     * <br />
3919     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3920     */
3921    static int compareSignatures(Signature[] s1, Signature[] s2) {
3922        if (s1 == null) {
3923            return s2 == null
3924                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3925                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3926        }
3927
3928        if (s2 == null) {
3929            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3930        }
3931
3932        if (s1.length != s2.length) {
3933            return PackageManager.SIGNATURE_NO_MATCH;
3934        }
3935
3936        // Since both signature sets are of size 1, we can compare without HashSets.
3937        if (s1.length == 1) {
3938            return s1[0].equals(s2[0]) ?
3939                    PackageManager.SIGNATURE_MATCH :
3940                    PackageManager.SIGNATURE_NO_MATCH;
3941        }
3942
3943        ArraySet<Signature> set1 = new ArraySet<Signature>();
3944        for (Signature sig : s1) {
3945            set1.add(sig);
3946        }
3947        ArraySet<Signature> set2 = new ArraySet<Signature>();
3948        for (Signature sig : s2) {
3949            set2.add(sig);
3950        }
3951        // Make sure s2 contains all signatures in s1.
3952        if (set1.equals(set2)) {
3953            return PackageManager.SIGNATURE_MATCH;
3954        }
3955        return PackageManager.SIGNATURE_NO_MATCH;
3956    }
3957
3958    /**
3959     * If the database version for this type of package (internal storage or
3960     * external storage) is less than the version where package signatures
3961     * were updated, return true.
3962     */
3963    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3964        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3965        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3966    }
3967
3968    /**
3969     * Used for backward compatibility to make sure any packages with
3970     * certificate chains get upgraded to the new style. {@code existingSigs}
3971     * will be in the old format (since they were stored on disk from before the
3972     * system upgrade) and {@code scannedSigs} will be in the newer format.
3973     */
3974    private int compareSignaturesCompat(PackageSignatures existingSigs,
3975            PackageParser.Package scannedPkg) {
3976        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3977            return PackageManager.SIGNATURE_NO_MATCH;
3978        }
3979
3980        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3981        for (Signature sig : existingSigs.mSignatures) {
3982            existingSet.add(sig);
3983        }
3984        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3985        for (Signature sig : scannedPkg.mSignatures) {
3986            try {
3987                Signature[] chainSignatures = sig.getChainSignatures();
3988                for (Signature chainSig : chainSignatures) {
3989                    scannedCompatSet.add(chainSig);
3990                }
3991            } catch (CertificateEncodingException e) {
3992                scannedCompatSet.add(sig);
3993            }
3994        }
3995        /*
3996         * Make sure the expanded scanned set contains all signatures in the
3997         * existing one.
3998         */
3999        if (scannedCompatSet.equals(existingSet)) {
4000            // Migrate the old signatures to the new scheme.
4001            existingSigs.assignSignatures(scannedPkg.mSignatures);
4002            // The new KeySets will be re-added later in the scanning process.
4003            synchronized (mPackages) {
4004                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4005            }
4006            return PackageManager.SIGNATURE_MATCH;
4007        }
4008        return PackageManager.SIGNATURE_NO_MATCH;
4009    }
4010
4011    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4012        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4013        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4014    }
4015
4016    private int compareSignaturesRecover(PackageSignatures existingSigs,
4017            PackageParser.Package scannedPkg) {
4018        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4019            return PackageManager.SIGNATURE_NO_MATCH;
4020        }
4021
4022        String msg = null;
4023        try {
4024            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4025                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4026                        + scannedPkg.packageName);
4027                return PackageManager.SIGNATURE_MATCH;
4028            }
4029        } catch (CertificateException e) {
4030            msg = e.getMessage();
4031        }
4032
4033        logCriticalInfo(Log.INFO,
4034                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4035        return PackageManager.SIGNATURE_NO_MATCH;
4036    }
4037
4038    @Override
4039    public String[] getPackagesForUid(int uid) {
4040        uid = UserHandle.getAppId(uid);
4041        // reader
4042        synchronized (mPackages) {
4043            Object obj = mSettings.getUserIdLPr(uid);
4044            if (obj instanceof SharedUserSetting) {
4045                final SharedUserSetting sus = (SharedUserSetting) obj;
4046                final int N = sus.packages.size();
4047                final String[] res = new String[N];
4048                final Iterator<PackageSetting> it = sus.packages.iterator();
4049                int i = 0;
4050                while (it.hasNext()) {
4051                    res[i++] = it.next().name;
4052                }
4053                return res;
4054            } else if (obj instanceof PackageSetting) {
4055                final PackageSetting ps = (PackageSetting) obj;
4056                return new String[] { ps.name };
4057            }
4058        }
4059        return null;
4060    }
4061
4062    @Override
4063    public String getNameForUid(int uid) {
4064        // reader
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.name + ":" + sus.userId;
4070            } else if (obj instanceof PackageSetting) {
4071                final PackageSetting ps = (PackageSetting) obj;
4072                return ps.name;
4073            }
4074        }
4075        return null;
4076    }
4077
4078    @Override
4079    public int getUidForSharedUser(String sharedUserName) {
4080        if(sharedUserName == null) {
4081            return -1;
4082        }
4083        // reader
4084        synchronized (mPackages) {
4085            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4086            if (suid == null) {
4087                return -1;
4088            }
4089            return suid.userId;
4090        }
4091    }
4092
4093    @Override
4094    public int getFlagsForUid(int uid) {
4095        synchronized (mPackages) {
4096            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4097            if (obj instanceof SharedUserSetting) {
4098                final SharedUserSetting sus = (SharedUserSetting) obj;
4099                return sus.pkgFlags;
4100            } else if (obj instanceof PackageSetting) {
4101                final PackageSetting ps = (PackageSetting) obj;
4102                return ps.pkgFlags;
4103            }
4104        }
4105        return 0;
4106    }
4107
4108    @Override
4109    public int getPrivateFlagsForUid(int uid) {
4110        synchronized (mPackages) {
4111            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4112            if (obj instanceof SharedUserSetting) {
4113                final SharedUserSetting sus = (SharedUserSetting) obj;
4114                return sus.pkgPrivateFlags;
4115            } else if (obj instanceof PackageSetting) {
4116                final PackageSetting ps = (PackageSetting) obj;
4117                return ps.pkgPrivateFlags;
4118            }
4119        }
4120        return 0;
4121    }
4122
4123    @Override
4124    public boolean isUidPrivileged(int uid) {
4125        uid = UserHandle.getAppId(uid);
4126        // reader
4127        synchronized (mPackages) {
4128            Object obj = mSettings.getUserIdLPr(uid);
4129            if (obj instanceof SharedUserSetting) {
4130                final SharedUserSetting sus = (SharedUserSetting) obj;
4131                final Iterator<PackageSetting> it = sus.packages.iterator();
4132                while (it.hasNext()) {
4133                    if (it.next().isPrivileged()) {
4134                        return true;
4135                    }
4136                }
4137            } else if (obj instanceof PackageSetting) {
4138                final PackageSetting ps = (PackageSetting) obj;
4139                return ps.isPrivileged();
4140            }
4141        }
4142        return false;
4143    }
4144
4145    @Override
4146    public String[] getAppOpPermissionPackages(String permissionName) {
4147        synchronized (mPackages) {
4148            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4149            if (pkgs == null) {
4150                return null;
4151            }
4152            return pkgs.toArray(new String[pkgs.size()]);
4153        }
4154    }
4155
4156    @Override
4157    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4158            int flags, int userId) {
4159        if (!sUserManager.exists(userId)) return null;
4160        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4161        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4162        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4163    }
4164
4165    @Override
4166    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4167            IntentFilter filter, int match, ComponentName activity) {
4168        final int userId = UserHandle.getCallingUserId();
4169        if (DEBUG_PREFERRED) {
4170            Log.v(TAG, "setLastChosenActivity intent=" + intent
4171                + " resolvedType=" + resolvedType
4172                + " flags=" + flags
4173                + " filter=" + filter
4174                + " match=" + match
4175                + " activity=" + activity);
4176            filter.dump(new PrintStreamPrinter(System.out), "    ");
4177        }
4178        intent.setComponent(null);
4179        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4180        // Find any earlier preferred or last chosen entries and nuke them
4181        findPreferredActivity(intent, resolvedType,
4182                flags, query, 0, false, true, false, userId);
4183        // Add the new activity as the last chosen for this filter
4184        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4185                "Setting last chosen");
4186    }
4187
4188    @Override
4189    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4190        final int userId = UserHandle.getCallingUserId();
4191        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4192        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4193        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4194                false, false, false, userId);
4195    }
4196
4197    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4198            int flags, List<ResolveInfo> query, int userId) {
4199        if (query != null) {
4200            final int N = query.size();
4201            if (N == 1) {
4202                return query.get(0);
4203            } else if (N > 1) {
4204                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4205                // If there is more than one activity with the same priority,
4206                // then let the user decide between them.
4207                ResolveInfo r0 = query.get(0);
4208                ResolveInfo r1 = query.get(1);
4209                if (DEBUG_INTENT_MATCHING || debug) {
4210                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4211                            + r1.activityInfo.name + "=" + r1.priority);
4212                }
4213                // If the first activity has a higher priority, or a different
4214                // default, then it is always desireable to pick it.
4215                if (r0.priority != r1.priority
4216                        || r0.preferredOrder != r1.preferredOrder
4217                        || r0.isDefault != r1.isDefault) {
4218                    return query.get(0);
4219                }
4220                // If we have saved a preference for a preferred activity for
4221                // this Intent, use that.
4222                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4223                        flags, query, r0.priority, true, false, debug, userId);
4224                if (ri != null) {
4225                    return ri;
4226                }
4227                if (userId != 0) {
4228                    ri = new ResolveInfo(mResolveInfo);
4229                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4230                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4231                            ri.activityInfo.applicationInfo);
4232                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4233                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4234                    return ri;
4235                }
4236                return mResolveInfo;
4237            }
4238        }
4239        return null;
4240    }
4241
4242    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4243            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4244        final int N = query.size();
4245        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4246                .get(userId);
4247        // Get the list of persistent preferred activities that handle the intent
4248        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4249        List<PersistentPreferredActivity> pprefs = ppir != null
4250                ? ppir.queryIntent(intent, resolvedType,
4251                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4252                : null;
4253        if (pprefs != null && pprefs.size() > 0) {
4254            final int M = pprefs.size();
4255            for (int i=0; i<M; i++) {
4256                final PersistentPreferredActivity ppa = pprefs.get(i);
4257                if (DEBUG_PREFERRED || debug) {
4258                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4259                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4260                            + "\n  component=" + ppa.mComponent);
4261                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4262                }
4263                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4264                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4265                if (DEBUG_PREFERRED || debug) {
4266                    Slog.v(TAG, "Found persistent preferred activity:");
4267                    if (ai != null) {
4268                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4269                    } else {
4270                        Slog.v(TAG, "  null");
4271                    }
4272                }
4273                if (ai == null) {
4274                    // This previously registered persistent preferred activity
4275                    // component is no longer known. Ignore it and do NOT remove it.
4276                    continue;
4277                }
4278                for (int j=0; j<N; j++) {
4279                    final ResolveInfo ri = query.get(j);
4280                    if (!ri.activityInfo.applicationInfo.packageName
4281                            .equals(ai.applicationInfo.packageName)) {
4282                        continue;
4283                    }
4284                    if (!ri.activityInfo.name.equals(ai.name)) {
4285                        continue;
4286                    }
4287                    //  Found a persistent preference that can handle the intent.
4288                    if (DEBUG_PREFERRED || debug) {
4289                        Slog.v(TAG, "Returning persistent preferred activity: " +
4290                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4291                    }
4292                    return ri;
4293                }
4294            }
4295        }
4296        return null;
4297    }
4298
4299    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4300            List<ResolveInfo> query, int priority, boolean always,
4301            boolean removeMatches, boolean debug, int userId) {
4302        if (!sUserManager.exists(userId)) return null;
4303        // writer
4304        synchronized (mPackages) {
4305            if (intent.getSelector() != null) {
4306                intent = intent.getSelector();
4307            }
4308            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4309
4310            // Try to find a matching persistent preferred activity.
4311            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4312                    debug, userId);
4313
4314            // If a persistent preferred activity matched, use it.
4315            if (pri != null) {
4316                return pri;
4317            }
4318
4319            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4320            // Get the list of preferred activities that handle the intent
4321            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4322            List<PreferredActivity> prefs = pir != null
4323                    ? pir.queryIntent(intent, resolvedType,
4324                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4325                    : null;
4326            if (prefs != null && prefs.size() > 0) {
4327                boolean changed = false;
4328                try {
4329                    // First figure out how good the original match set is.
4330                    // We will only allow preferred activities that came
4331                    // from the same match quality.
4332                    int match = 0;
4333
4334                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4335
4336                    final int N = query.size();
4337                    for (int j=0; j<N; j++) {
4338                        final ResolveInfo ri = query.get(j);
4339                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4340                                + ": 0x" + Integer.toHexString(match));
4341                        if (ri.match > match) {
4342                            match = ri.match;
4343                        }
4344                    }
4345
4346                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4347                            + Integer.toHexString(match));
4348
4349                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4350                    final int M = prefs.size();
4351                    for (int i=0; i<M; i++) {
4352                        final PreferredActivity pa = prefs.get(i);
4353                        if (DEBUG_PREFERRED || debug) {
4354                            Slog.v(TAG, "Checking PreferredActivity ds="
4355                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4356                                    + "\n  component=" + pa.mPref.mComponent);
4357                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4358                        }
4359                        if (pa.mPref.mMatch != match) {
4360                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4361                                    + Integer.toHexString(pa.mPref.mMatch));
4362                            continue;
4363                        }
4364                        // If it's not an "always" type preferred activity and that's what we're
4365                        // looking for, skip it.
4366                        if (always && !pa.mPref.mAlways) {
4367                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4368                            continue;
4369                        }
4370                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4371                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4372                        if (DEBUG_PREFERRED || debug) {
4373                            Slog.v(TAG, "Found preferred activity:");
4374                            if (ai != null) {
4375                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4376                            } else {
4377                                Slog.v(TAG, "  null");
4378                            }
4379                        }
4380                        if (ai == null) {
4381                            // This previously registered preferred activity
4382                            // component is no longer known.  Most likely an update
4383                            // to the app was installed and in the new version this
4384                            // component no longer exists.  Clean it up by removing
4385                            // it from the preferred activities list, and skip it.
4386                            Slog.w(TAG, "Removing dangling preferred activity: "
4387                                    + pa.mPref.mComponent);
4388                            pir.removeFilter(pa);
4389                            changed = true;
4390                            continue;
4391                        }
4392                        for (int j=0; j<N; j++) {
4393                            final ResolveInfo ri = query.get(j);
4394                            if (!ri.activityInfo.applicationInfo.packageName
4395                                    .equals(ai.applicationInfo.packageName)) {
4396                                continue;
4397                            }
4398                            if (!ri.activityInfo.name.equals(ai.name)) {
4399                                continue;
4400                            }
4401
4402                            if (removeMatches) {
4403                                pir.removeFilter(pa);
4404                                changed = true;
4405                                if (DEBUG_PREFERRED) {
4406                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4407                                }
4408                                break;
4409                            }
4410
4411                            // Okay we found a previously set preferred or last chosen app.
4412                            // If the result set is different from when this
4413                            // was created, we need to clear it and re-ask the
4414                            // user their preference, if we're looking for an "always" type entry.
4415                            if (always && !pa.mPref.sameSet(query)) {
4416                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4417                                        + intent + " type " + resolvedType);
4418                                if (DEBUG_PREFERRED) {
4419                                    Slog.v(TAG, "Removing preferred activity since set changed "
4420                                            + pa.mPref.mComponent);
4421                                }
4422                                pir.removeFilter(pa);
4423                                // Re-add the filter as a "last chosen" entry (!always)
4424                                PreferredActivity lastChosen = new PreferredActivity(
4425                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4426                                pir.addFilter(lastChosen);
4427                                changed = true;
4428                                return null;
4429                            }
4430
4431                            // Yay! Either the set matched or we're looking for the last chosen
4432                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4433                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4434                            return ri;
4435                        }
4436                    }
4437                } finally {
4438                    if (changed) {
4439                        if (DEBUG_PREFERRED) {
4440                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4441                        }
4442                        scheduleWritePackageRestrictionsLocked(userId);
4443                    }
4444                }
4445            }
4446        }
4447        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4448        return null;
4449    }
4450
4451    /*
4452     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4453     */
4454    @Override
4455    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4456            int targetUserId) {
4457        mContext.enforceCallingOrSelfPermission(
4458                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4459        List<CrossProfileIntentFilter> matches =
4460                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4461        if (matches != null) {
4462            int size = matches.size();
4463            for (int i = 0; i < size; i++) {
4464                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4465            }
4466        }
4467        if (hasWebURI(intent)) {
4468            // cross-profile app linking works only towards the parent.
4469            final UserInfo parent = getProfileParent(sourceUserId);
4470            synchronized(mPackages) {
4471                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4472                        intent, resolvedType, 0, sourceUserId, parent.id);
4473                return xpDomainInfo != null;
4474            }
4475        }
4476        return false;
4477    }
4478
4479    private UserInfo getProfileParent(int userId) {
4480        final long identity = Binder.clearCallingIdentity();
4481        try {
4482            return sUserManager.getProfileParent(userId);
4483        } finally {
4484            Binder.restoreCallingIdentity(identity);
4485        }
4486    }
4487
4488    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4489            String resolvedType, int userId) {
4490        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4491        if (resolver != null) {
4492            return resolver.queryIntent(intent, resolvedType, false, userId);
4493        }
4494        return null;
4495    }
4496
4497    @Override
4498    public List<ResolveInfo> queryIntentActivities(Intent intent,
4499            String resolvedType, int flags, int userId) {
4500        if (!sUserManager.exists(userId)) return Collections.emptyList();
4501        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4502        ComponentName comp = intent.getComponent();
4503        if (comp == null) {
4504            if (intent.getSelector() != null) {
4505                intent = intent.getSelector();
4506                comp = intent.getComponent();
4507            }
4508        }
4509
4510        if (comp != null) {
4511            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4512            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4513            if (ai != null) {
4514                final ResolveInfo ri = new ResolveInfo();
4515                ri.activityInfo = ai;
4516                list.add(ri);
4517            }
4518            return list;
4519        }
4520
4521        // reader
4522        synchronized (mPackages) {
4523            final String pkgName = intent.getPackage();
4524            if (pkgName == null) {
4525                List<CrossProfileIntentFilter> matchingFilters =
4526                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4527                // Check for results that need to skip the current profile.
4528                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4529                        resolvedType, flags, userId);
4530                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4531                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4532                    result.add(xpResolveInfo);
4533                    return filterIfNotPrimaryUser(result, userId);
4534                }
4535
4536                // Check for results in the current profile.
4537                List<ResolveInfo> result = mActivities.queryIntent(
4538                        intent, resolvedType, flags, userId);
4539
4540                // Check for cross profile results.
4541                xpResolveInfo = queryCrossProfileIntents(
4542                        matchingFilters, intent, resolvedType, flags, userId);
4543                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4544                    result.add(xpResolveInfo);
4545                    Collections.sort(result, mResolvePrioritySorter);
4546                }
4547                result = filterIfNotPrimaryUser(result, userId);
4548                if (hasWebURI(intent)) {
4549                    CrossProfileDomainInfo xpDomainInfo = null;
4550                    final UserInfo parent = getProfileParent(userId);
4551                    if (parent != null) {
4552                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4553                                flags, userId, parent.id);
4554                    }
4555                    if (xpDomainInfo != null) {
4556                        if (xpResolveInfo != null) {
4557                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4558                            // in the result.
4559                            result.remove(xpResolveInfo);
4560                        }
4561                        if (result.size() == 0) {
4562                            result.add(xpDomainInfo.resolveInfo);
4563                            return result;
4564                        }
4565                    } else if (result.size() <= 1) {
4566                        return result;
4567                    }
4568                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4569                            xpDomainInfo, userId);
4570                    Collections.sort(result, mResolvePrioritySorter);
4571                }
4572                return result;
4573            }
4574            final PackageParser.Package pkg = mPackages.get(pkgName);
4575            if (pkg != null) {
4576                return filterIfNotPrimaryUser(
4577                        mActivities.queryIntentForPackage(
4578                                intent, resolvedType, flags, pkg.activities, userId),
4579                        userId);
4580            }
4581            return new ArrayList<ResolveInfo>();
4582        }
4583    }
4584
4585    private static class CrossProfileDomainInfo {
4586        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4587        ResolveInfo resolveInfo;
4588        /* Best domain verification status of the activities found in the other profile */
4589        int bestDomainVerificationStatus;
4590    }
4591
4592    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4593            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4594        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4595                sourceUserId)) {
4596            return null;
4597        }
4598        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4599                resolvedType, flags, parentUserId);
4600
4601        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4602            return null;
4603        }
4604        CrossProfileDomainInfo result = null;
4605        int size = resultTargetUser.size();
4606        for (int i = 0; i < size; i++) {
4607            ResolveInfo riTargetUser = resultTargetUser.get(i);
4608            // Intent filter verification is only for filters that specify a host. So don't return
4609            // those that handle all web uris.
4610            if (riTargetUser.handleAllWebDataURI) {
4611                continue;
4612            }
4613            String packageName = riTargetUser.activityInfo.packageName;
4614            PackageSetting ps = mSettings.mPackages.get(packageName);
4615            if (ps == null) {
4616                continue;
4617            }
4618            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4619            int status = (int)(verificationState >> 32);
4620            if (result == null) {
4621                result = new CrossProfileDomainInfo();
4622                result.resolveInfo =
4623                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4624                result.bestDomainVerificationStatus = status;
4625            } else {
4626                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4627                        result.bestDomainVerificationStatus);
4628            }
4629        }
4630        // Don't consider matches with status NEVER across profiles.
4631        if (result != null && result.bestDomainVerificationStatus
4632                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4633            return null;
4634        }
4635        return result;
4636    }
4637
4638    /**
4639     * Verification statuses are ordered from the worse to the best, except for
4640     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4641     */
4642    private int bestDomainVerificationStatus(int status1, int status2) {
4643        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4644            return status2;
4645        }
4646        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4647            return status1;
4648        }
4649        return (int) MathUtils.max(status1, status2);
4650    }
4651
4652    private boolean isUserEnabled(int userId) {
4653        long callingId = Binder.clearCallingIdentity();
4654        try {
4655            UserInfo userInfo = sUserManager.getUserInfo(userId);
4656            return userInfo != null && userInfo.isEnabled();
4657        } finally {
4658            Binder.restoreCallingIdentity(callingId);
4659        }
4660    }
4661
4662    /**
4663     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4664     *
4665     * @return filtered list
4666     */
4667    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4668        if (userId == UserHandle.USER_OWNER) {
4669            return resolveInfos;
4670        }
4671        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4672            ResolveInfo info = resolveInfos.get(i);
4673            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4674                resolveInfos.remove(i);
4675            }
4676        }
4677        return resolveInfos;
4678    }
4679
4680    private static boolean hasWebURI(Intent intent) {
4681        if (intent.getData() == null) {
4682            return false;
4683        }
4684        final String scheme = intent.getScheme();
4685        if (TextUtils.isEmpty(scheme)) {
4686            return false;
4687        }
4688        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4689    }
4690
4691    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4692            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4693            int userId) {
4694        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4695
4696        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4697            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4698                    candidates.size());
4699        }
4700
4701        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4702        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4703        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4704        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4705        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4706
4707        synchronized (mPackages) {
4708            final int count = candidates.size();
4709            // First, try to use linked apps. Partition the candidates into four lists:
4710            // one for the final results, one for the "do not use ever", one for "undefined status"
4711            // and finally one for "browser app type".
4712            for (int n=0; n<count; n++) {
4713                ResolveInfo info = candidates.get(n);
4714                String packageName = info.activityInfo.packageName;
4715                PackageSetting ps = mSettings.mPackages.get(packageName);
4716                if (ps != null) {
4717                    // Add to the special match all list (Browser use case)
4718                    if (info.handleAllWebDataURI) {
4719                        matchAllList.add(info);
4720                        continue;
4721                    }
4722                    // Try to get the status from User settings first
4723                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4724                    int status = (int)(packedStatus >> 32);
4725                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4726                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4727                        if (DEBUG_DOMAIN_VERIFICATION) {
4728                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4729                                    + " : linkgen=" + linkGeneration);
4730                        }
4731                        // Use link-enabled generation as preferredOrder, i.e.
4732                        // prefer newly-enabled over earlier-enabled.
4733                        info.preferredOrder = linkGeneration;
4734                        alwaysList.add(info);
4735                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4736                        if (DEBUG_DOMAIN_VERIFICATION) {
4737                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4738                        }
4739                        neverList.add(info);
4740                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4741                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4742                        if (DEBUG_DOMAIN_VERIFICATION) {
4743                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4744                        }
4745                        undefinedList.add(info);
4746                    }
4747                }
4748            }
4749            // First try to add the "always" resolution(s) for the current user, if any
4750            if (alwaysList.size() > 0) {
4751                result.addAll(alwaysList);
4752            // if there is an "always" for the parent user, add it.
4753            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4754                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4755                result.add(xpDomainInfo.resolveInfo);
4756            } else {
4757                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4758                result.addAll(undefinedList);
4759                if (xpDomainInfo != null && (
4760                        xpDomainInfo.bestDomainVerificationStatus
4761                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4762                        || xpDomainInfo.bestDomainVerificationStatus
4763                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4764                    result.add(xpDomainInfo.resolveInfo);
4765                }
4766                // Also add Browsers (all of them or only the default one)
4767                if ((matchFlags & MATCH_ALL) != 0) {
4768                    result.addAll(matchAllList);
4769                } else {
4770                    // Browser/generic handling case.  If there's a default browser, go straight
4771                    // to that (but only if there is no other higher-priority match).
4772                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4773                    int maxMatchPrio = 0;
4774                    ResolveInfo defaultBrowserMatch = null;
4775                    final int numCandidates = matchAllList.size();
4776                    for (int n = 0; n < numCandidates; n++) {
4777                        ResolveInfo info = matchAllList.get(n);
4778                        // track the highest overall match priority...
4779                        if (info.priority > maxMatchPrio) {
4780                            maxMatchPrio = info.priority;
4781                        }
4782                        // ...and the highest-priority default browser match
4783                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4784                            if (defaultBrowserMatch == null
4785                                    || (defaultBrowserMatch.priority < info.priority)) {
4786                                if (debug) {
4787                                    Slog.v(TAG, "Considering default browser match " + info);
4788                                }
4789                                defaultBrowserMatch = info;
4790                            }
4791                        }
4792                    }
4793                    if (defaultBrowserMatch != null
4794                            && defaultBrowserMatch.priority >= maxMatchPrio
4795                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4796                    {
4797                        if (debug) {
4798                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4799                        }
4800                        result.add(defaultBrowserMatch);
4801                    } else {
4802                        result.addAll(matchAllList);
4803                    }
4804                }
4805
4806                // If there is nothing selected, add all candidates and remove the ones that the user
4807                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4808                if (result.size() == 0) {
4809                    result.addAll(candidates);
4810                    result.removeAll(neverList);
4811                }
4812            }
4813        }
4814        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4815            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4816                    result.size());
4817            for (ResolveInfo info : result) {
4818                Slog.v(TAG, "  + " + info.activityInfo);
4819            }
4820        }
4821        return result;
4822    }
4823
4824    // Returns a packed value as a long:
4825    //
4826    // high 'int'-sized word: link status: undefined/ask/never/always.
4827    // low 'int'-sized word: relative priority among 'always' results.
4828    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4829        long result = ps.getDomainVerificationStatusForUser(userId);
4830        // if none available, get the master status
4831        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4832            if (ps.getIntentFilterVerificationInfo() != null) {
4833                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4834            }
4835        }
4836        return result;
4837    }
4838
4839    private ResolveInfo querySkipCurrentProfileIntents(
4840            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4841            int flags, int sourceUserId) {
4842        if (matchingFilters != null) {
4843            int size = matchingFilters.size();
4844            for (int i = 0; i < size; i ++) {
4845                CrossProfileIntentFilter filter = matchingFilters.get(i);
4846                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4847                    // Checking if there are activities in the target user that can handle the
4848                    // intent.
4849                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4850                            flags, sourceUserId);
4851                    if (resolveInfo != null) {
4852                        return resolveInfo;
4853                    }
4854                }
4855            }
4856        }
4857        return null;
4858    }
4859
4860    // Return matching ResolveInfo if any for skip current profile intent filters.
4861    private ResolveInfo queryCrossProfileIntents(
4862            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4863            int flags, int sourceUserId) {
4864        if (matchingFilters != null) {
4865            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4866            // match the same intent. For performance reasons, it is better not to
4867            // run queryIntent twice for the same userId
4868            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4869            int size = matchingFilters.size();
4870            for (int i = 0; i < size; i++) {
4871                CrossProfileIntentFilter filter = matchingFilters.get(i);
4872                int targetUserId = filter.getTargetUserId();
4873                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4874                        && !alreadyTriedUserIds.get(targetUserId)) {
4875                    // Checking if there are activities in the target user that can handle the
4876                    // intent.
4877                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4878                            flags, sourceUserId);
4879                    if (resolveInfo != null) return resolveInfo;
4880                    alreadyTriedUserIds.put(targetUserId, true);
4881                }
4882            }
4883        }
4884        return null;
4885    }
4886
4887    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4888            String resolvedType, int flags, int sourceUserId) {
4889        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4890                resolvedType, flags, filter.getTargetUserId());
4891        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4892            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4893        }
4894        return null;
4895    }
4896
4897    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4898            int sourceUserId, int targetUserId) {
4899        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4900        String className;
4901        if (targetUserId == UserHandle.USER_OWNER) {
4902            className = FORWARD_INTENT_TO_USER_OWNER;
4903        } else {
4904            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4905        }
4906        ComponentName forwardingActivityComponentName = new ComponentName(
4907                mAndroidApplication.packageName, className);
4908        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4909                sourceUserId);
4910        if (targetUserId == UserHandle.USER_OWNER) {
4911            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4912            forwardingResolveInfo.noResourceId = true;
4913        }
4914        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4915        forwardingResolveInfo.priority = 0;
4916        forwardingResolveInfo.preferredOrder = 0;
4917        forwardingResolveInfo.match = 0;
4918        forwardingResolveInfo.isDefault = true;
4919        forwardingResolveInfo.filter = filter;
4920        forwardingResolveInfo.targetUserId = targetUserId;
4921        return forwardingResolveInfo;
4922    }
4923
4924    @Override
4925    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4926            Intent[] specifics, String[] specificTypes, Intent intent,
4927            String resolvedType, int flags, int userId) {
4928        if (!sUserManager.exists(userId)) return Collections.emptyList();
4929        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4930                false, "query intent activity options");
4931        final String resultsAction = intent.getAction();
4932
4933        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4934                | PackageManager.GET_RESOLVED_FILTER, userId);
4935
4936        if (DEBUG_INTENT_MATCHING) {
4937            Log.v(TAG, "Query " + intent + ": " + results);
4938        }
4939
4940        int specificsPos = 0;
4941        int N;
4942
4943        // todo: note that the algorithm used here is O(N^2).  This
4944        // isn't a problem in our current environment, but if we start running
4945        // into situations where we have more than 5 or 10 matches then this
4946        // should probably be changed to something smarter...
4947
4948        // First we go through and resolve each of the specific items
4949        // that were supplied, taking care of removing any corresponding
4950        // duplicate items in the generic resolve list.
4951        if (specifics != null) {
4952            for (int i=0; i<specifics.length; i++) {
4953                final Intent sintent = specifics[i];
4954                if (sintent == null) {
4955                    continue;
4956                }
4957
4958                if (DEBUG_INTENT_MATCHING) {
4959                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4960                }
4961
4962                String action = sintent.getAction();
4963                if (resultsAction != null && resultsAction.equals(action)) {
4964                    // If this action was explicitly requested, then don't
4965                    // remove things that have it.
4966                    action = null;
4967                }
4968
4969                ResolveInfo ri = null;
4970                ActivityInfo ai = null;
4971
4972                ComponentName comp = sintent.getComponent();
4973                if (comp == null) {
4974                    ri = resolveIntent(
4975                        sintent,
4976                        specificTypes != null ? specificTypes[i] : null,
4977                            flags, userId);
4978                    if (ri == null) {
4979                        continue;
4980                    }
4981                    if (ri == mResolveInfo) {
4982                        // ACK!  Must do something better with this.
4983                    }
4984                    ai = ri.activityInfo;
4985                    comp = new ComponentName(ai.applicationInfo.packageName,
4986                            ai.name);
4987                } else {
4988                    ai = getActivityInfo(comp, flags, userId);
4989                    if (ai == null) {
4990                        continue;
4991                    }
4992                }
4993
4994                // Look for any generic query activities that are duplicates
4995                // of this specific one, and remove them from the results.
4996                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4997                N = results.size();
4998                int j;
4999                for (j=specificsPos; j<N; j++) {
5000                    ResolveInfo sri = results.get(j);
5001                    if ((sri.activityInfo.name.equals(comp.getClassName())
5002                            && sri.activityInfo.applicationInfo.packageName.equals(
5003                                    comp.getPackageName()))
5004                        || (action != null && sri.filter.matchAction(action))) {
5005                        results.remove(j);
5006                        if (DEBUG_INTENT_MATCHING) Log.v(
5007                            TAG, "Removing duplicate item from " + j
5008                            + " due to specific " + specificsPos);
5009                        if (ri == null) {
5010                            ri = sri;
5011                        }
5012                        j--;
5013                        N--;
5014                    }
5015                }
5016
5017                // Add this specific item to its proper place.
5018                if (ri == null) {
5019                    ri = new ResolveInfo();
5020                    ri.activityInfo = ai;
5021                }
5022                results.add(specificsPos, ri);
5023                ri.specificIndex = i;
5024                specificsPos++;
5025            }
5026        }
5027
5028        // Now we go through the remaining generic results and remove any
5029        // duplicate actions that are found here.
5030        N = results.size();
5031        for (int i=specificsPos; i<N-1; i++) {
5032            final ResolveInfo rii = results.get(i);
5033            if (rii.filter == null) {
5034                continue;
5035            }
5036
5037            // Iterate over all of the actions of this result's intent
5038            // filter...  typically this should be just one.
5039            final Iterator<String> it = rii.filter.actionsIterator();
5040            if (it == null) {
5041                continue;
5042            }
5043            while (it.hasNext()) {
5044                final String action = it.next();
5045                if (resultsAction != null && resultsAction.equals(action)) {
5046                    // If this action was explicitly requested, then don't
5047                    // remove things that have it.
5048                    continue;
5049                }
5050                for (int j=i+1; j<N; j++) {
5051                    final ResolveInfo rij = results.get(j);
5052                    if (rij.filter != null && rij.filter.hasAction(action)) {
5053                        results.remove(j);
5054                        if (DEBUG_INTENT_MATCHING) Log.v(
5055                            TAG, "Removing duplicate item from " + j
5056                            + " due to action " + action + " at " + i);
5057                        j--;
5058                        N--;
5059                    }
5060                }
5061            }
5062
5063            // If the caller didn't request filter information, drop it now
5064            // so we don't have to marshall/unmarshall it.
5065            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5066                rii.filter = null;
5067            }
5068        }
5069
5070        // Filter out the caller activity if so requested.
5071        if (caller != null) {
5072            N = results.size();
5073            for (int i=0; i<N; i++) {
5074                ActivityInfo ainfo = results.get(i).activityInfo;
5075                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5076                        && caller.getClassName().equals(ainfo.name)) {
5077                    results.remove(i);
5078                    break;
5079                }
5080            }
5081        }
5082
5083        // If the caller didn't request filter information,
5084        // drop them now so we don't have to
5085        // marshall/unmarshall it.
5086        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5087            N = results.size();
5088            for (int i=0; i<N; i++) {
5089                results.get(i).filter = null;
5090            }
5091        }
5092
5093        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5094        return results;
5095    }
5096
5097    @Override
5098    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5099            int userId) {
5100        if (!sUserManager.exists(userId)) return Collections.emptyList();
5101        ComponentName comp = intent.getComponent();
5102        if (comp == null) {
5103            if (intent.getSelector() != null) {
5104                intent = intent.getSelector();
5105                comp = intent.getComponent();
5106            }
5107        }
5108        if (comp != null) {
5109            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5110            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5111            if (ai != null) {
5112                ResolveInfo ri = new ResolveInfo();
5113                ri.activityInfo = ai;
5114                list.add(ri);
5115            }
5116            return list;
5117        }
5118
5119        // reader
5120        synchronized (mPackages) {
5121            String pkgName = intent.getPackage();
5122            if (pkgName == null) {
5123                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5124            }
5125            final PackageParser.Package pkg = mPackages.get(pkgName);
5126            if (pkg != null) {
5127                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5128                        userId);
5129            }
5130            return null;
5131        }
5132    }
5133
5134    @Override
5135    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5136        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5137        if (!sUserManager.exists(userId)) return null;
5138        if (query != null) {
5139            if (query.size() >= 1) {
5140                // If there is more than one service with the same priority,
5141                // just arbitrarily pick the first one.
5142                return query.get(0);
5143            }
5144        }
5145        return null;
5146    }
5147
5148    @Override
5149    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5150            int userId) {
5151        if (!sUserManager.exists(userId)) return Collections.emptyList();
5152        ComponentName comp = intent.getComponent();
5153        if (comp == null) {
5154            if (intent.getSelector() != null) {
5155                intent = intent.getSelector();
5156                comp = intent.getComponent();
5157            }
5158        }
5159        if (comp != null) {
5160            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5161            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5162            if (si != null) {
5163                final ResolveInfo ri = new ResolveInfo();
5164                ri.serviceInfo = si;
5165                list.add(ri);
5166            }
5167            return list;
5168        }
5169
5170        // reader
5171        synchronized (mPackages) {
5172            String pkgName = intent.getPackage();
5173            if (pkgName == null) {
5174                return mServices.queryIntent(intent, resolvedType, flags, userId);
5175            }
5176            final PackageParser.Package pkg = mPackages.get(pkgName);
5177            if (pkg != null) {
5178                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5179                        userId);
5180            }
5181            return null;
5182        }
5183    }
5184
5185    @Override
5186    public List<ResolveInfo> queryIntentContentProviders(
5187            Intent intent, String resolvedType, int flags, int userId) {
5188        if (!sUserManager.exists(userId)) return Collections.emptyList();
5189        ComponentName comp = intent.getComponent();
5190        if (comp == null) {
5191            if (intent.getSelector() != null) {
5192                intent = intent.getSelector();
5193                comp = intent.getComponent();
5194            }
5195        }
5196        if (comp != null) {
5197            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5198            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5199            if (pi != null) {
5200                final ResolveInfo ri = new ResolveInfo();
5201                ri.providerInfo = pi;
5202                list.add(ri);
5203            }
5204            return list;
5205        }
5206
5207        // reader
5208        synchronized (mPackages) {
5209            String pkgName = intent.getPackage();
5210            if (pkgName == null) {
5211                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5212            }
5213            final PackageParser.Package pkg = mPackages.get(pkgName);
5214            if (pkg != null) {
5215                return mProviders.queryIntentForPackage(
5216                        intent, resolvedType, flags, pkg.providers, userId);
5217            }
5218            return null;
5219        }
5220    }
5221
5222    @Override
5223    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5224        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5225
5226        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5227
5228        // writer
5229        synchronized (mPackages) {
5230            ArrayList<PackageInfo> list;
5231            if (listUninstalled) {
5232                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5233                for (PackageSetting ps : mSettings.mPackages.values()) {
5234                    PackageInfo pi;
5235                    if (ps.pkg != null) {
5236                        pi = generatePackageInfo(ps.pkg, flags, userId);
5237                    } else {
5238                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5239                    }
5240                    if (pi != null) {
5241                        list.add(pi);
5242                    }
5243                }
5244            } else {
5245                list = new ArrayList<PackageInfo>(mPackages.size());
5246                for (PackageParser.Package p : mPackages.values()) {
5247                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5248                    if (pi != null) {
5249                        list.add(pi);
5250                    }
5251                }
5252            }
5253
5254            return new ParceledListSlice<PackageInfo>(list);
5255        }
5256    }
5257
5258    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5259            String[] permissions, boolean[] tmp, int flags, int userId) {
5260        int numMatch = 0;
5261        final PermissionsState permissionsState = ps.getPermissionsState();
5262        for (int i=0; i<permissions.length; i++) {
5263            final String permission = permissions[i];
5264            if (permissionsState.hasPermission(permission, userId)) {
5265                tmp[i] = true;
5266                numMatch++;
5267            } else {
5268                tmp[i] = false;
5269            }
5270        }
5271        if (numMatch == 0) {
5272            return;
5273        }
5274        PackageInfo pi;
5275        if (ps.pkg != null) {
5276            pi = generatePackageInfo(ps.pkg, flags, userId);
5277        } else {
5278            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5279        }
5280        // The above might return null in cases of uninstalled apps or install-state
5281        // skew across users/profiles.
5282        if (pi != null) {
5283            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5284                if (numMatch == permissions.length) {
5285                    pi.requestedPermissions = permissions;
5286                } else {
5287                    pi.requestedPermissions = new String[numMatch];
5288                    numMatch = 0;
5289                    for (int i=0; i<permissions.length; i++) {
5290                        if (tmp[i]) {
5291                            pi.requestedPermissions[numMatch] = permissions[i];
5292                            numMatch++;
5293                        }
5294                    }
5295                }
5296            }
5297            list.add(pi);
5298        }
5299    }
5300
5301    @Override
5302    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5303            String[] permissions, int flags, int userId) {
5304        if (!sUserManager.exists(userId)) return null;
5305        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5306
5307        // writer
5308        synchronized (mPackages) {
5309            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5310            boolean[] tmpBools = new boolean[permissions.length];
5311            if (listUninstalled) {
5312                for (PackageSetting ps : mSettings.mPackages.values()) {
5313                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5314                }
5315            } else {
5316                for (PackageParser.Package pkg : mPackages.values()) {
5317                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5318                    if (ps != null) {
5319                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5320                                userId);
5321                    }
5322                }
5323            }
5324
5325            return new ParceledListSlice<PackageInfo>(list);
5326        }
5327    }
5328
5329    @Override
5330    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5331        if (!sUserManager.exists(userId)) return null;
5332        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5333
5334        // writer
5335        synchronized (mPackages) {
5336            ArrayList<ApplicationInfo> list;
5337            if (listUninstalled) {
5338                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5339                for (PackageSetting ps : mSettings.mPackages.values()) {
5340                    ApplicationInfo ai;
5341                    if (ps.pkg != null) {
5342                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5343                                ps.readUserState(userId), userId);
5344                    } else {
5345                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5346                    }
5347                    if (ai != null) {
5348                        list.add(ai);
5349                    }
5350                }
5351            } else {
5352                list = new ArrayList<ApplicationInfo>(mPackages.size());
5353                for (PackageParser.Package p : mPackages.values()) {
5354                    if (p.mExtras != null) {
5355                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5356                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5357                        if (ai != null) {
5358                            list.add(ai);
5359                        }
5360                    }
5361                }
5362            }
5363
5364            return new ParceledListSlice<ApplicationInfo>(list);
5365        }
5366    }
5367
5368    public List<ApplicationInfo> getPersistentApplications(int flags) {
5369        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5370
5371        // reader
5372        synchronized (mPackages) {
5373            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5374            final int userId = UserHandle.getCallingUserId();
5375            while (i.hasNext()) {
5376                final PackageParser.Package p = i.next();
5377                if (p.applicationInfo != null
5378                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5379                        && (!mSafeMode || isSystemApp(p))) {
5380                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5381                    if (ps != null) {
5382                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5383                                ps.readUserState(userId), userId);
5384                        if (ai != null) {
5385                            finalList.add(ai);
5386                        }
5387                    }
5388                }
5389            }
5390        }
5391
5392        return finalList;
5393    }
5394
5395    @Override
5396    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5397        if (!sUserManager.exists(userId)) return null;
5398        // reader
5399        synchronized (mPackages) {
5400            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5401            PackageSetting ps = provider != null
5402                    ? mSettings.mPackages.get(provider.owner.packageName)
5403                    : null;
5404            return ps != null
5405                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5406                    && (!mSafeMode || (provider.info.applicationInfo.flags
5407                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5408                    ? PackageParser.generateProviderInfo(provider, flags,
5409                            ps.readUserState(userId), userId)
5410                    : null;
5411        }
5412    }
5413
5414    /**
5415     * @deprecated
5416     */
5417    @Deprecated
5418    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5419        // reader
5420        synchronized (mPackages) {
5421            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5422                    .entrySet().iterator();
5423            final int userId = UserHandle.getCallingUserId();
5424            while (i.hasNext()) {
5425                Map.Entry<String, PackageParser.Provider> entry = i.next();
5426                PackageParser.Provider p = entry.getValue();
5427                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5428
5429                if (ps != null && p.syncable
5430                        && (!mSafeMode || (p.info.applicationInfo.flags
5431                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5432                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5433                            ps.readUserState(userId), userId);
5434                    if (info != null) {
5435                        outNames.add(entry.getKey());
5436                        outInfo.add(info);
5437                    }
5438                }
5439            }
5440        }
5441    }
5442
5443    @Override
5444    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5445            int uid, int flags) {
5446        ArrayList<ProviderInfo> finalList = null;
5447        // reader
5448        synchronized (mPackages) {
5449            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5450            final int userId = processName != null ?
5451                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5452            while (i.hasNext()) {
5453                final PackageParser.Provider p = i.next();
5454                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5455                if (ps != null && p.info.authority != null
5456                        && (processName == null
5457                                || (p.info.processName.equals(processName)
5458                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5459                        && mSettings.isEnabledLPr(p.info, flags, userId)
5460                        && (!mSafeMode
5461                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5462                    if (finalList == null) {
5463                        finalList = new ArrayList<ProviderInfo>(3);
5464                    }
5465                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5466                            ps.readUserState(userId), userId);
5467                    if (info != null) {
5468                        finalList.add(info);
5469                    }
5470                }
5471            }
5472        }
5473
5474        if (finalList != null) {
5475            Collections.sort(finalList, mProviderInitOrderSorter);
5476            return new ParceledListSlice<ProviderInfo>(finalList);
5477        }
5478
5479        return null;
5480    }
5481
5482    @Override
5483    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5484            int flags) {
5485        // reader
5486        synchronized (mPackages) {
5487            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5488            return PackageParser.generateInstrumentationInfo(i, flags);
5489        }
5490    }
5491
5492    @Override
5493    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5494            int flags) {
5495        ArrayList<InstrumentationInfo> finalList =
5496            new ArrayList<InstrumentationInfo>();
5497
5498        // reader
5499        synchronized (mPackages) {
5500            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5501            while (i.hasNext()) {
5502                final PackageParser.Instrumentation p = i.next();
5503                if (targetPackage == null
5504                        || targetPackage.equals(p.info.targetPackage)) {
5505                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5506                            flags);
5507                    if (ii != null) {
5508                        finalList.add(ii);
5509                    }
5510                }
5511            }
5512        }
5513
5514        return finalList;
5515    }
5516
5517    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5518        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5519        if (overlays == null) {
5520            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5521            return;
5522        }
5523        for (PackageParser.Package opkg : overlays.values()) {
5524            // Not much to do if idmap fails: we already logged the error
5525            // and we certainly don't want to abort installation of pkg simply
5526            // because an overlay didn't fit properly. For these reasons,
5527            // ignore the return value of createIdmapForPackagePairLI.
5528            createIdmapForPackagePairLI(pkg, opkg);
5529        }
5530    }
5531
5532    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5533            PackageParser.Package opkg) {
5534        if (!opkg.mTrustedOverlay) {
5535            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5536                    opkg.baseCodePath + ": overlay not trusted");
5537            return false;
5538        }
5539        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5540        if (overlaySet == null) {
5541            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5542                    opkg.baseCodePath + " but target package has no known overlays");
5543            return false;
5544        }
5545        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5546        // TODO: generate idmap for split APKs
5547        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5548            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5549                    + opkg.baseCodePath);
5550            return false;
5551        }
5552        PackageParser.Package[] overlayArray =
5553            overlaySet.values().toArray(new PackageParser.Package[0]);
5554        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5555            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5556                return p1.mOverlayPriority - p2.mOverlayPriority;
5557            }
5558        };
5559        Arrays.sort(overlayArray, cmp);
5560
5561        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5562        int i = 0;
5563        for (PackageParser.Package p : overlayArray) {
5564            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5565        }
5566        return true;
5567    }
5568
5569    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5570        final File[] files = dir.listFiles();
5571        if (ArrayUtils.isEmpty(files)) {
5572            Log.d(TAG, "No files in app dir " + dir);
5573            return;
5574        }
5575
5576        if (DEBUG_PACKAGE_SCANNING) {
5577            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5578                    + " flags=0x" + Integer.toHexString(parseFlags));
5579        }
5580
5581        for (File file : files) {
5582            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5583                    && !PackageInstallerService.isStageName(file.getName());
5584            if (!isPackage) {
5585                // Ignore entries which are not packages
5586                continue;
5587            }
5588            try {
5589                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5590                        scanFlags, currentTime, null);
5591            } catch (PackageManagerException e) {
5592                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5593
5594                // Delete invalid userdata apps
5595                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5596                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5597                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5598                    if (file.isDirectory()) {
5599                        mInstaller.rmPackageDir(file.getAbsolutePath());
5600                    } else {
5601                        file.delete();
5602                    }
5603                }
5604            }
5605        }
5606    }
5607
5608    private static File getSettingsProblemFile() {
5609        File dataDir = Environment.getDataDirectory();
5610        File systemDir = new File(dataDir, "system");
5611        File fname = new File(systemDir, "uiderrors.txt");
5612        return fname;
5613    }
5614
5615    static void reportSettingsProblem(int priority, String msg) {
5616        logCriticalInfo(priority, msg);
5617    }
5618
5619    static void logCriticalInfo(int priority, String msg) {
5620        Slog.println(priority, TAG, msg);
5621        EventLogTags.writePmCriticalInfo(msg);
5622        try {
5623            File fname = getSettingsProblemFile();
5624            FileOutputStream out = new FileOutputStream(fname, true);
5625            PrintWriter pw = new FastPrintWriter(out);
5626            SimpleDateFormat formatter = new SimpleDateFormat();
5627            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5628            pw.println(dateString + ": " + msg);
5629            pw.close();
5630            FileUtils.setPermissions(
5631                    fname.toString(),
5632                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5633                    -1, -1);
5634        } catch (java.io.IOException e) {
5635        }
5636    }
5637
5638    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5639            PackageParser.Package pkg, File srcFile, int parseFlags)
5640            throws PackageManagerException {
5641        if (ps != null
5642                && ps.codePath.equals(srcFile)
5643                && ps.timeStamp == srcFile.lastModified()
5644                && !isCompatSignatureUpdateNeeded(pkg)
5645                && !isRecoverSignatureUpdateNeeded(pkg)) {
5646            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5647            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5648            ArraySet<PublicKey> signingKs;
5649            synchronized (mPackages) {
5650                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5651            }
5652            if (ps.signatures.mSignatures != null
5653                    && ps.signatures.mSignatures.length != 0
5654                    && signingKs != null) {
5655                // Optimization: reuse the existing cached certificates
5656                // if the package appears to be unchanged.
5657                pkg.mSignatures = ps.signatures.mSignatures;
5658                pkg.mSigningKeys = signingKs;
5659                return;
5660            }
5661
5662            Slog.w(TAG, "PackageSetting for " + ps.name
5663                    + " is missing signatures.  Collecting certs again to recover them.");
5664        } else {
5665            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5666        }
5667
5668        try {
5669            pp.collectCertificates(pkg, parseFlags);
5670            pp.collectManifestDigest(pkg);
5671        } catch (PackageParserException e) {
5672            throw PackageManagerException.from(e);
5673        }
5674    }
5675
5676    /*
5677     *  Scan a package and return the newly parsed package.
5678     *  Returns null in case of errors and the error code is stored in mLastScanError
5679     */
5680    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5681            long currentTime, UserHandle user) throws PackageManagerException {
5682        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5683        parseFlags |= mDefParseFlags;
5684        PackageParser pp = new PackageParser();
5685        pp.setSeparateProcesses(mSeparateProcesses);
5686        pp.setOnlyCoreApps(mOnlyCore);
5687        pp.setDisplayMetrics(mMetrics);
5688
5689        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5690            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5691        }
5692
5693        final PackageParser.Package pkg;
5694        try {
5695            pkg = pp.parsePackage(scanFile, parseFlags);
5696        } catch (PackageParserException e) {
5697            throw PackageManagerException.from(e);
5698        }
5699
5700        PackageSetting ps = null;
5701        PackageSetting updatedPkg;
5702        // reader
5703        synchronized (mPackages) {
5704            // Look to see if we already know about this package.
5705            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5706            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5707                // This package has been renamed to its original name.  Let's
5708                // use that.
5709                ps = mSettings.peekPackageLPr(oldName);
5710            }
5711            // If there was no original package, see one for the real package name.
5712            if (ps == null) {
5713                ps = mSettings.peekPackageLPr(pkg.packageName);
5714            }
5715            // Check to see if this package could be hiding/updating a system
5716            // package.  Must look for it either under the original or real
5717            // package name depending on our state.
5718            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5719            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5720        }
5721        boolean updatedPkgBetter = false;
5722        // First check if this is a system package that may involve an update
5723        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5724            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5725            // it needs to drop FLAG_PRIVILEGED.
5726            if (locationIsPrivileged(scanFile)) {
5727                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5728            } else {
5729                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5730            }
5731
5732            if (ps != null && !ps.codePath.equals(scanFile)) {
5733                // The path has changed from what was last scanned...  check the
5734                // version of the new path against what we have stored to determine
5735                // what to do.
5736                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5737                if (pkg.mVersionCode <= ps.versionCode) {
5738                    // The system package has been updated and the code path does not match
5739                    // Ignore entry. Skip it.
5740                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5741                            + " ignored: updated version " + ps.versionCode
5742                            + " better than this " + pkg.mVersionCode);
5743                    if (!updatedPkg.codePath.equals(scanFile)) {
5744                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5745                                + ps.name + " changing from " + updatedPkg.codePathString
5746                                + " to " + scanFile);
5747                        updatedPkg.codePath = scanFile;
5748                        updatedPkg.codePathString = scanFile.toString();
5749                        updatedPkg.resourcePath = scanFile;
5750                        updatedPkg.resourcePathString = scanFile.toString();
5751                    }
5752                    updatedPkg.pkg = pkg;
5753                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5754                            "Package " + ps.name + " at " + scanFile
5755                                    + " ignored: updated version " + ps.versionCode
5756                                    + " better than this " + pkg.mVersionCode);
5757                } else {
5758                    // The current app on the system partition is better than
5759                    // what we have updated to on the data partition; switch
5760                    // back to the system partition version.
5761                    // At this point, its safely assumed that package installation for
5762                    // apps in system partition will go through. If not there won't be a working
5763                    // version of the app
5764                    // writer
5765                    synchronized (mPackages) {
5766                        // Just remove the loaded entries from package lists.
5767                        mPackages.remove(ps.name);
5768                    }
5769
5770                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5771                            + " reverting from " + ps.codePathString
5772                            + ": new version " + pkg.mVersionCode
5773                            + " better than installed " + ps.versionCode);
5774
5775                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5776                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5777                    synchronized (mInstallLock) {
5778                        args.cleanUpResourcesLI();
5779                    }
5780                    synchronized (mPackages) {
5781                        mSettings.enableSystemPackageLPw(ps.name);
5782                    }
5783                    updatedPkgBetter = true;
5784                }
5785            }
5786        }
5787
5788        if (updatedPkg != null) {
5789            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5790            // initially
5791            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5792
5793            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5794            // flag set initially
5795            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5796                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5797            }
5798        }
5799
5800        // Verify certificates against what was last scanned
5801        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5802
5803        /*
5804         * A new system app appeared, but we already had a non-system one of the
5805         * same name installed earlier.
5806         */
5807        boolean shouldHideSystemApp = false;
5808        if (updatedPkg == null && ps != null
5809                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5810            /*
5811             * Check to make sure the signatures match first. If they don't,
5812             * wipe the installed application and its data.
5813             */
5814            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5815                    != PackageManager.SIGNATURE_MATCH) {
5816                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5817                        + " signatures don't match existing userdata copy; removing");
5818                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5819                ps = null;
5820            } else {
5821                /*
5822                 * If the newly-added system app is an older version than the
5823                 * already installed version, hide it. It will be scanned later
5824                 * and re-added like an update.
5825                 */
5826                if (pkg.mVersionCode <= ps.versionCode) {
5827                    shouldHideSystemApp = true;
5828                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5829                            + " but new version " + pkg.mVersionCode + " better than installed "
5830                            + ps.versionCode + "; hiding system");
5831                } else {
5832                    /*
5833                     * The newly found system app is a newer version that the
5834                     * one previously installed. Simply remove the
5835                     * already-installed application and replace it with our own
5836                     * while keeping the application data.
5837                     */
5838                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5839                            + " reverting from " + ps.codePathString + ": new version "
5840                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5841                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5842                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5843                    synchronized (mInstallLock) {
5844                        args.cleanUpResourcesLI();
5845                    }
5846                }
5847            }
5848        }
5849
5850        // The apk is forward locked (not public) if its code and resources
5851        // are kept in different files. (except for app in either system or
5852        // vendor path).
5853        // TODO grab this value from PackageSettings
5854        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5855            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5856                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5857            }
5858        }
5859
5860        // TODO: extend to support forward-locked splits
5861        String resourcePath = null;
5862        String baseResourcePath = null;
5863        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5864            if (ps != null && ps.resourcePathString != null) {
5865                resourcePath = ps.resourcePathString;
5866                baseResourcePath = ps.resourcePathString;
5867            } else {
5868                // Should not happen at all. Just log an error.
5869                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5870            }
5871        } else {
5872            resourcePath = pkg.codePath;
5873            baseResourcePath = pkg.baseCodePath;
5874        }
5875
5876        // Set application objects path explicitly.
5877        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5878        pkg.applicationInfo.setCodePath(pkg.codePath);
5879        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5880        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5881        pkg.applicationInfo.setResourcePath(resourcePath);
5882        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5883        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5884
5885        // Note that we invoke the following method only if we are about to unpack an application
5886        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5887                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5888
5889        /*
5890         * If the system app should be overridden by a previously installed
5891         * data, hide the system app now and let the /data/app scan pick it up
5892         * again.
5893         */
5894        if (shouldHideSystemApp) {
5895            synchronized (mPackages) {
5896                /*
5897                 * We have to grant systems permissions before we hide, because
5898                 * grantPermissions will assume the package update is trying to
5899                 * expand its permissions.
5900                 */
5901                grantPermissionsLPw(pkg, true, pkg.packageName);
5902                mSettings.disableSystemPackageLPw(pkg.packageName);
5903            }
5904        }
5905
5906        return scannedPkg;
5907    }
5908
5909    private static String fixProcessName(String defProcessName,
5910            String processName, int uid) {
5911        if (processName == null) {
5912            return defProcessName;
5913        }
5914        return processName;
5915    }
5916
5917    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5918            throws PackageManagerException {
5919        if (pkgSetting.signatures.mSignatures != null) {
5920            // Already existing package. Make sure signatures match
5921            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5922                    == PackageManager.SIGNATURE_MATCH;
5923            if (!match) {
5924                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5925                        == PackageManager.SIGNATURE_MATCH;
5926            }
5927            if (!match) {
5928                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5929                        == PackageManager.SIGNATURE_MATCH;
5930            }
5931            if (!match) {
5932                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5933                        + pkg.packageName + " signatures do not match the "
5934                        + "previously installed version; ignoring!");
5935            }
5936        }
5937
5938        // Check for shared user signatures
5939        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5940            // Already existing package. Make sure signatures match
5941            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5942                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5943            if (!match) {
5944                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5945                        == PackageManager.SIGNATURE_MATCH;
5946            }
5947            if (!match) {
5948                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5949                        == PackageManager.SIGNATURE_MATCH;
5950            }
5951            if (!match) {
5952                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5953                        "Package " + pkg.packageName
5954                        + " has no signatures that match those in shared user "
5955                        + pkgSetting.sharedUser.name + "; ignoring!");
5956            }
5957        }
5958    }
5959
5960    /**
5961     * Enforces that only the system UID or root's UID can call a method exposed
5962     * via Binder.
5963     *
5964     * @param message used as message if SecurityException is thrown
5965     * @throws SecurityException if the caller is not system or root
5966     */
5967    private static final void enforceSystemOrRoot(String message) {
5968        final int uid = Binder.getCallingUid();
5969        if (uid != Process.SYSTEM_UID && uid != 0) {
5970            throw new SecurityException(message);
5971        }
5972    }
5973
5974    @Override
5975    public void performBootDexOpt() {
5976        enforceSystemOrRoot("Only the system can request dexopt be performed");
5977
5978        // Before everything else, see whether we need to fstrim.
5979        try {
5980            IMountService ms = PackageHelper.getMountService();
5981            if (ms != null) {
5982                final boolean isUpgrade = isUpgrade();
5983                boolean doTrim = isUpgrade;
5984                if (doTrim) {
5985                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5986                } else {
5987                    final long interval = android.provider.Settings.Global.getLong(
5988                            mContext.getContentResolver(),
5989                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5990                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5991                    if (interval > 0) {
5992                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5993                        if (timeSinceLast > interval) {
5994                            doTrim = true;
5995                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5996                                    + "; running immediately");
5997                        }
5998                    }
5999                }
6000                if (doTrim) {
6001                    if (!isFirstBoot()) {
6002                        try {
6003                            ActivityManagerNative.getDefault().showBootMessage(
6004                                    mContext.getResources().getString(
6005                                            R.string.android_upgrading_fstrim), true);
6006                        } catch (RemoteException e) {
6007                        }
6008                    }
6009                    ms.runMaintenance();
6010                }
6011            } else {
6012                Slog.e(TAG, "Mount service unavailable!");
6013            }
6014        } catch (RemoteException e) {
6015            // Can't happen; MountService is local
6016        }
6017
6018        final ArraySet<PackageParser.Package> pkgs;
6019        synchronized (mPackages) {
6020            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6021        }
6022
6023        if (pkgs != null) {
6024            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6025            // in case the device runs out of space.
6026            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6027            // Give priority to core apps.
6028            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6029                PackageParser.Package pkg = it.next();
6030                if (pkg.coreApp) {
6031                    if (DEBUG_DEXOPT) {
6032                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6033                    }
6034                    sortedPkgs.add(pkg);
6035                    it.remove();
6036                }
6037            }
6038            // Give priority to system apps that listen for pre boot complete.
6039            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6040            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6041            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6042                PackageParser.Package pkg = it.next();
6043                if (pkgNames.contains(pkg.packageName)) {
6044                    if (DEBUG_DEXOPT) {
6045                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6046                    }
6047                    sortedPkgs.add(pkg);
6048                    it.remove();
6049                }
6050            }
6051            // Give priority to system apps.
6052            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6053                PackageParser.Package pkg = it.next();
6054                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6055                    if (DEBUG_DEXOPT) {
6056                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6057                    }
6058                    sortedPkgs.add(pkg);
6059                    it.remove();
6060                }
6061            }
6062            // Give priority to updated system apps.
6063            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6064                PackageParser.Package pkg = it.next();
6065                if (pkg.isUpdatedSystemApp()) {
6066                    if (DEBUG_DEXOPT) {
6067                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6068                    }
6069                    sortedPkgs.add(pkg);
6070                    it.remove();
6071                }
6072            }
6073            // Give priority to apps that listen for boot complete.
6074            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6075            pkgNames = getPackageNamesForIntent(intent);
6076            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6077                PackageParser.Package pkg = it.next();
6078                if (pkgNames.contains(pkg.packageName)) {
6079                    if (DEBUG_DEXOPT) {
6080                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6081                    }
6082                    sortedPkgs.add(pkg);
6083                    it.remove();
6084                }
6085            }
6086            // Filter out packages that aren't recently used.
6087            filterRecentlyUsedApps(pkgs);
6088            // Add all remaining apps.
6089            for (PackageParser.Package pkg : pkgs) {
6090                if (DEBUG_DEXOPT) {
6091                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6092                }
6093                sortedPkgs.add(pkg);
6094            }
6095
6096            // If we want to be lazy, filter everything that wasn't recently used.
6097            if (mLazyDexOpt) {
6098                filterRecentlyUsedApps(sortedPkgs);
6099            }
6100
6101            int i = 0;
6102            int total = sortedPkgs.size();
6103            File dataDir = Environment.getDataDirectory();
6104            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6105            if (lowThreshold == 0) {
6106                throw new IllegalStateException("Invalid low memory threshold");
6107            }
6108            for (PackageParser.Package pkg : sortedPkgs) {
6109                long usableSpace = dataDir.getUsableSpace();
6110                if (usableSpace < lowThreshold) {
6111                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6112                    break;
6113                }
6114                performBootDexOpt(pkg, ++i, total);
6115            }
6116        }
6117    }
6118
6119    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6120        // Filter out packages that aren't recently used.
6121        //
6122        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6123        // should do a full dexopt.
6124        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6125            int total = pkgs.size();
6126            int skipped = 0;
6127            long now = System.currentTimeMillis();
6128            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6129                PackageParser.Package pkg = i.next();
6130                long then = pkg.mLastPackageUsageTimeInMills;
6131                if (then + mDexOptLRUThresholdInMills < now) {
6132                    if (DEBUG_DEXOPT) {
6133                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6134                              ((then == 0) ? "never" : new Date(then)));
6135                    }
6136                    i.remove();
6137                    skipped++;
6138                }
6139            }
6140            if (DEBUG_DEXOPT) {
6141                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6142            }
6143        }
6144    }
6145
6146    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6147        List<ResolveInfo> ris = null;
6148        try {
6149            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6150                    intent, null, 0, UserHandle.USER_OWNER);
6151        } catch (RemoteException e) {
6152        }
6153        ArraySet<String> pkgNames = new ArraySet<String>();
6154        if (ris != null) {
6155            for (ResolveInfo ri : ris) {
6156                pkgNames.add(ri.activityInfo.packageName);
6157            }
6158        }
6159        return pkgNames;
6160    }
6161
6162    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6163        if (DEBUG_DEXOPT) {
6164            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6165        }
6166        if (!isFirstBoot()) {
6167            try {
6168                ActivityManagerNative.getDefault().showBootMessage(
6169                        mContext.getResources().getString(R.string.android_upgrading_apk,
6170                                curr, total), true);
6171            } catch (RemoteException e) {
6172            }
6173        }
6174        PackageParser.Package p = pkg;
6175        synchronized (mInstallLock) {
6176            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6177                    false /* force dex */, false /* defer */, true /* include dependencies */);
6178        }
6179    }
6180
6181    @Override
6182    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6183        return performDexOpt(packageName, instructionSet, false);
6184    }
6185
6186    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6187        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6188        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6189        if (!dexopt && !updateUsage) {
6190            // We aren't going to dexopt or update usage, so bail early.
6191            return false;
6192        }
6193        PackageParser.Package p;
6194        final String targetInstructionSet;
6195        synchronized (mPackages) {
6196            p = mPackages.get(packageName);
6197            if (p == null) {
6198                return false;
6199            }
6200            if (updateUsage) {
6201                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6202            }
6203            mPackageUsage.write(false);
6204            if (!dexopt) {
6205                // We aren't going to dexopt, so bail early.
6206                return false;
6207            }
6208
6209            targetInstructionSet = instructionSet != null ? instructionSet :
6210                    getPrimaryInstructionSet(p.applicationInfo);
6211            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6212                return false;
6213            }
6214        }
6215        long callingId = Binder.clearCallingIdentity();
6216        try {
6217            synchronized (mInstallLock) {
6218                final String[] instructionSets = new String[] { targetInstructionSet };
6219                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6220                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6221                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6222            }
6223        } finally {
6224            Binder.restoreCallingIdentity(callingId);
6225        }
6226    }
6227
6228    public ArraySet<String> getPackagesThatNeedDexOpt() {
6229        ArraySet<String> pkgs = null;
6230        synchronized (mPackages) {
6231            for (PackageParser.Package p : mPackages.values()) {
6232                if (DEBUG_DEXOPT) {
6233                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6234                }
6235                if (!p.mDexOptPerformed.isEmpty()) {
6236                    continue;
6237                }
6238                if (pkgs == null) {
6239                    pkgs = new ArraySet<String>();
6240                }
6241                pkgs.add(p.packageName);
6242            }
6243        }
6244        return pkgs;
6245    }
6246
6247    public void shutdown() {
6248        mPackageUsage.write(true);
6249    }
6250
6251    @Override
6252    public void forceDexOpt(String packageName) {
6253        enforceSystemOrRoot("forceDexOpt");
6254
6255        PackageParser.Package pkg;
6256        synchronized (mPackages) {
6257            pkg = mPackages.get(packageName);
6258            if (pkg == null) {
6259                throw new IllegalArgumentException("Missing package: " + packageName);
6260            }
6261        }
6262
6263        synchronized (mInstallLock) {
6264            final String[] instructionSets = new String[] {
6265                    getPrimaryInstructionSet(pkg.applicationInfo) };
6266            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6267                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6268            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6269                throw new IllegalStateException("Failed to dexopt: " + res);
6270            }
6271        }
6272    }
6273
6274    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6275        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6276            Slog.w(TAG, "Unable to update from " + oldPkg.name
6277                    + " to " + newPkg.packageName
6278                    + ": old package not in system partition");
6279            return false;
6280        } else if (mPackages.get(oldPkg.name) != null) {
6281            Slog.w(TAG, "Unable to update from " + oldPkg.name
6282                    + " to " + newPkg.packageName
6283                    + ": old package still exists");
6284            return false;
6285        }
6286        return true;
6287    }
6288
6289    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6290        int[] users = sUserManager.getUserIds();
6291        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6292        if (res < 0) {
6293            return res;
6294        }
6295        for (int user : users) {
6296            if (user != 0) {
6297                res = mInstaller.createUserData(volumeUuid, packageName,
6298                        UserHandle.getUid(user, uid), user, seinfo);
6299                if (res < 0) {
6300                    return res;
6301                }
6302            }
6303        }
6304        return res;
6305    }
6306
6307    private int removeDataDirsLI(String volumeUuid, String packageName) {
6308        int[] users = sUserManager.getUserIds();
6309        int res = 0;
6310        for (int user : users) {
6311            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6312            if (resInner < 0) {
6313                res = resInner;
6314            }
6315        }
6316
6317        return res;
6318    }
6319
6320    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6321        int[] users = sUserManager.getUserIds();
6322        int res = 0;
6323        for (int user : users) {
6324            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6325            if (resInner < 0) {
6326                res = resInner;
6327            }
6328        }
6329        return res;
6330    }
6331
6332    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6333            PackageParser.Package changingLib) {
6334        if (file.path != null) {
6335            usesLibraryFiles.add(file.path);
6336            return;
6337        }
6338        PackageParser.Package p = mPackages.get(file.apk);
6339        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6340            // If we are doing this while in the middle of updating a library apk,
6341            // then we need to make sure to use that new apk for determining the
6342            // dependencies here.  (We haven't yet finished committing the new apk
6343            // to the package manager state.)
6344            if (p == null || p.packageName.equals(changingLib.packageName)) {
6345                p = changingLib;
6346            }
6347        }
6348        if (p != null) {
6349            usesLibraryFiles.addAll(p.getAllCodePaths());
6350        }
6351    }
6352
6353    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6354            PackageParser.Package changingLib) throws PackageManagerException {
6355        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6356            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6357            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6358            for (int i=0; i<N; i++) {
6359                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6360                if (file == null) {
6361                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6362                            "Package " + pkg.packageName + " requires unavailable shared library "
6363                            + pkg.usesLibraries.get(i) + "; failing!");
6364                }
6365                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6366            }
6367            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6368            for (int i=0; i<N; i++) {
6369                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6370                if (file == null) {
6371                    Slog.w(TAG, "Package " + pkg.packageName
6372                            + " desires unavailable shared library "
6373                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6374                } else {
6375                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6376                }
6377            }
6378            N = usesLibraryFiles.size();
6379            if (N > 0) {
6380                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6381            } else {
6382                pkg.usesLibraryFiles = null;
6383            }
6384        }
6385    }
6386
6387    private static boolean hasString(List<String> list, List<String> which) {
6388        if (list == null) {
6389            return false;
6390        }
6391        for (int i=list.size()-1; i>=0; i--) {
6392            for (int j=which.size()-1; j>=0; j--) {
6393                if (which.get(j).equals(list.get(i))) {
6394                    return true;
6395                }
6396            }
6397        }
6398        return false;
6399    }
6400
6401    private void updateAllSharedLibrariesLPw() {
6402        for (PackageParser.Package pkg : mPackages.values()) {
6403            try {
6404                updateSharedLibrariesLPw(pkg, null);
6405            } catch (PackageManagerException e) {
6406                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6407            }
6408        }
6409    }
6410
6411    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6412            PackageParser.Package changingPkg) {
6413        ArrayList<PackageParser.Package> res = null;
6414        for (PackageParser.Package pkg : mPackages.values()) {
6415            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6416                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6417                if (res == null) {
6418                    res = new ArrayList<PackageParser.Package>();
6419                }
6420                res.add(pkg);
6421                try {
6422                    updateSharedLibrariesLPw(pkg, changingPkg);
6423                } catch (PackageManagerException e) {
6424                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6425                }
6426            }
6427        }
6428        return res;
6429    }
6430
6431    /**
6432     * Derive the value of the {@code cpuAbiOverride} based on the provided
6433     * value and an optional stored value from the package settings.
6434     */
6435    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6436        String cpuAbiOverride = null;
6437
6438        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6439            cpuAbiOverride = null;
6440        } else if (abiOverride != null) {
6441            cpuAbiOverride = abiOverride;
6442        } else if (settings != null) {
6443            cpuAbiOverride = settings.cpuAbiOverrideString;
6444        }
6445
6446        return cpuAbiOverride;
6447    }
6448
6449    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6450            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6451        boolean success = false;
6452        try {
6453            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6454                    currentTime, user);
6455            success = true;
6456            return res;
6457        } finally {
6458            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6459                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6460            }
6461        }
6462    }
6463
6464    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6465            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6466        final File scanFile = new File(pkg.codePath);
6467        if (pkg.applicationInfo.getCodePath() == null ||
6468                pkg.applicationInfo.getResourcePath() == null) {
6469            // Bail out. The resource and code paths haven't been set.
6470            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6471                    "Code and resource paths haven't been set correctly");
6472        }
6473
6474        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6476        } else {
6477            // Only allow system apps to be flagged as core apps.
6478            pkg.coreApp = false;
6479        }
6480
6481        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6482            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6483        }
6484
6485        if (mCustomResolverComponentName != null &&
6486                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6487            setUpCustomResolverActivity(pkg);
6488        }
6489
6490        if (pkg.packageName.equals("android")) {
6491            synchronized (mPackages) {
6492                if (mAndroidApplication != null) {
6493                    Slog.w(TAG, "*************************************************");
6494                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6495                    Slog.w(TAG, " file=" + scanFile);
6496                    Slog.w(TAG, "*************************************************");
6497                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6498                            "Core android package being redefined.  Skipping.");
6499                }
6500
6501                // Set up information for our fall-back user intent resolution activity.
6502                mPlatformPackage = pkg;
6503                pkg.mVersionCode = mSdkVersion;
6504                mAndroidApplication = pkg.applicationInfo;
6505
6506                if (!mResolverReplaced) {
6507                    mResolveActivity.applicationInfo = mAndroidApplication;
6508                    mResolveActivity.name = ResolverActivity.class.getName();
6509                    mResolveActivity.packageName = mAndroidApplication.packageName;
6510                    mResolveActivity.processName = "system:ui";
6511                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6512                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6513                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6514                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6515                    mResolveActivity.exported = true;
6516                    mResolveActivity.enabled = true;
6517                    mResolveInfo.activityInfo = mResolveActivity;
6518                    mResolveInfo.priority = 0;
6519                    mResolveInfo.preferredOrder = 0;
6520                    mResolveInfo.match = 0;
6521                    mResolveComponentName = new ComponentName(
6522                            mAndroidApplication.packageName, mResolveActivity.name);
6523                }
6524            }
6525        }
6526
6527        if (DEBUG_PACKAGE_SCANNING) {
6528            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6529                Log.d(TAG, "Scanning package " + pkg.packageName);
6530        }
6531
6532        if (mPackages.containsKey(pkg.packageName)
6533                || mSharedLibraries.containsKey(pkg.packageName)) {
6534            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6535                    "Application package " + pkg.packageName
6536                    + " already installed.  Skipping duplicate.");
6537        }
6538
6539        // If we're only installing presumed-existing packages, require that the
6540        // scanned APK is both already known and at the path previously established
6541        // for it.  Previously unknown packages we pick up normally, but if we have an
6542        // a priori expectation about this package's install presence, enforce it.
6543        // With a singular exception for new system packages. When an OTA contains
6544        // a new system package, we allow the codepath to change from a system location
6545        // to the user-installed location. If we don't allow this change, any newer,
6546        // user-installed version of the application will be ignored.
6547        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6548            if (mExpectingBetter.containsKey(pkg.packageName)) {
6549                logCriticalInfo(Log.WARN,
6550                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6551            } else {
6552                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6553                if (known != null) {
6554                    if (DEBUG_PACKAGE_SCANNING) {
6555                        Log.d(TAG, "Examining " + pkg.codePath
6556                                + " and requiring known paths " + known.codePathString
6557                                + " & " + known.resourcePathString);
6558                    }
6559                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6560                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6561                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6562                                "Application package " + pkg.packageName
6563                                + " found at " + pkg.applicationInfo.getCodePath()
6564                                + " but expected at " + known.codePathString + "; ignoring.");
6565                    }
6566                }
6567            }
6568        }
6569
6570        // Initialize package source and resource directories
6571        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6572        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6573
6574        SharedUserSetting suid = null;
6575        PackageSetting pkgSetting = null;
6576
6577        if (!isSystemApp(pkg)) {
6578            // Only system apps can use these features.
6579            pkg.mOriginalPackages = null;
6580            pkg.mRealPackage = null;
6581            pkg.mAdoptPermissions = null;
6582        }
6583
6584        // writer
6585        synchronized (mPackages) {
6586            if (pkg.mSharedUserId != null) {
6587                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6588                if (suid == null) {
6589                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6590                            "Creating application package " + pkg.packageName
6591                            + " for shared user failed");
6592                }
6593                if (DEBUG_PACKAGE_SCANNING) {
6594                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6595                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6596                                + "): packages=" + suid.packages);
6597                }
6598            }
6599
6600            // Check if we are renaming from an original package name.
6601            PackageSetting origPackage = null;
6602            String realName = null;
6603            if (pkg.mOriginalPackages != null) {
6604                // This package may need to be renamed to a previously
6605                // installed name.  Let's check on that...
6606                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6607                if (pkg.mOriginalPackages.contains(renamed)) {
6608                    // This package had originally been installed as the
6609                    // original name, and we have already taken care of
6610                    // transitioning to the new one.  Just update the new
6611                    // one to continue using the old name.
6612                    realName = pkg.mRealPackage;
6613                    if (!pkg.packageName.equals(renamed)) {
6614                        // Callers into this function may have already taken
6615                        // care of renaming the package; only do it here if
6616                        // it is not already done.
6617                        pkg.setPackageName(renamed);
6618                    }
6619
6620                } else {
6621                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6622                        if ((origPackage = mSettings.peekPackageLPr(
6623                                pkg.mOriginalPackages.get(i))) != null) {
6624                            // We do have the package already installed under its
6625                            // original name...  should we use it?
6626                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6627                                // New package is not compatible with original.
6628                                origPackage = null;
6629                                continue;
6630                            } else if (origPackage.sharedUser != null) {
6631                                // Make sure uid is compatible between packages.
6632                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6633                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6634                                            + " to " + pkg.packageName + ": old uid "
6635                                            + origPackage.sharedUser.name
6636                                            + " differs from " + pkg.mSharedUserId);
6637                                    origPackage = null;
6638                                    continue;
6639                                }
6640                            } else {
6641                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6642                                        + pkg.packageName + " to old name " + origPackage.name);
6643                            }
6644                            break;
6645                        }
6646                    }
6647                }
6648            }
6649
6650            if (mTransferedPackages.contains(pkg.packageName)) {
6651                Slog.w(TAG, "Package " + pkg.packageName
6652                        + " was transferred to another, but its .apk remains");
6653            }
6654
6655            // Just create the setting, don't add it yet. For already existing packages
6656            // the PkgSetting exists already and doesn't have to be created.
6657            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6658                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6659                    pkg.applicationInfo.primaryCpuAbi,
6660                    pkg.applicationInfo.secondaryCpuAbi,
6661                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6662                    user, false);
6663            if (pkgSetting == null) {
6664                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6665                        "Creating application package " + pkg.packageName + " failed");
6666            }
6667
6668            if (pkgSetting.origPackage != null) {
6669                // If we are first transitioning from an original package,
6670                // fix up the new package's name now.  We need to do this after
6671                // looking up the package under its new name, so getPackageLP
6672                // can take care of fiddling things correctly.
6673                pkg.setPackageName(origPackage.name);
6674
6675                // File a report about this.
6676                String msg = "New package " + pkgSetting.realName
6677                        + " renamed to replace old package " + pkgSetting.name;
6678                reportSettingsProblem(Log.WARN, msg);
6679
6680                // Make a note of it.
6681                mTransferedPackages.add(origPackage.name);
6682
6683                // No longer need to retain this.
6684                pkgSetting.origPackage = null;
6685            }
6686
6687            if (realName != null) {
6688                // Make a note of it.
6689                mTransferedPackages.add(pkg.packageName);
6690            }
6691
6692            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6693                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6694            }
6695
6696            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6697                // Check all shared libraries and map to their actual file path.
6698                // We only do this here for apps not on a system dir, because those
6699                // are the only ones that can fail an install due to this.  We
6700                // will take care of the system apps by updating all of their
6701                // library paths after the scan is done.
6702                updateSharedLibrariesLPw(pkg, null);
6703            }
6704
6705            if (mFoundPolicyFile) {
6706                SELinuxMMAC.assignSeinfoValue(pkg);
6707            }
6708
6709            pkg.applicationInfo.uid = pkgSetting.appId;
6710            pkg.mExtras = pkgSetting;
6711            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6712                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6713                    // We just determined the app is signed correctly, so bring
6714                    // over the latest parsed certs.
6715                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6716                } else {
6717                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6718                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6719                                "Package " + pkg.packageName + " upgrade keys do not match the "
6720                                + "previously installed version");
6721                    } else {
6722                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6723                        String msg = "System package " + pkg.packageName
6724                            + " signature changed; retaining data.";
6725                        reportSettingsProblem(Log.WARN, msg);
6726                    }
6727                }
6728            } else {
6729                try {
6730                    verifySignaturesLP(pkgSetting, pkg);
6731                    // We just determined the app is signed correctly, so bring
6732                    // over the latest parsed certs.
6733                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6734                } catch (PackageManagerException e) {
6735                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6736                        throw e;
6737                    }
6738                    // The signature has changed, but this package is in the system
6739                    // image...  let's recover!
6740                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6741                    // However...  if this package is part of a shared user, but it
6742                    // doesn't match the signature of the shared user, let's fail.
6743                    // What this means is that you can't change the signatures
6744                    // associated with an overall shared user, which doesn't seem all
6745                    // that unreasonable.
6746                    if (pkgSetting.sharedUser != null) {
6747                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6748                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6749                            throw new PackageManagerException(
6750                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6751                                            "Signature mismatch for shared user : "
6752                                            + pkgSetting.sharedUser);
6753                        }
6754                    }
6755                    // File a report about this.
6756                    String msg = "System package " + pkg.packageName
6757                        + " signature changed; retaining data.";
6758                    reportSettingsProblem(Log.WARN, msg);
6759                }
6760            }
6761            // Verify that this new package doesn't have any content providers
6762            // that conflict with existing packages.  Only do this if the
6763            // package isn't already installed, since we don't want to break
6764            // things that are installed.
6765            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6766                final int N = pkg.providers.size();
6767                int i;
6768                for (i=0; i<N; i++) {
6769                    PackageParser.Provider p = pkg.providers.get(i);
6770                    if (p.info.authority != null) {
6771                        String names[] = p.info.authority.split(";");
6772                        for (int j = 0; j < names.length; j++) {
6773                            if (mProvidersByAuthority.containsKey(names[j])) {
6774                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6775                                final String otherPackageName =
6776                                        ((other != null && other.getComponentName() != null) ?
6777                                                other.getComponentName().getPackageName() : "?");
6778                                throw new PackageManagerException(
6779                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6780                                                "Can't install because provider name " + names[j]
6781                                                + " (in package " + pkg.applicationInfo.packageName
6782                                                + ") is already used by " + otherPackageName);
6783                            }
6784                        }
6785                    }
6786                }
6787            }
6788
6789            if (pkg.mAdoptPermissions != null) {
6790                // This package wants to adopt ownership of permissions from
6791                // another package.
6792                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6793                    final String origName = pkg.mAdoptPermissions.get(i);
6794                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6795                    if (orig != null) {
6796                        if (verifyPackageUpdateLPr(orig, pkg)) {
6797                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6798                                    + pkg.packageName);
6799                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6800                        }
6801                    }
6802                }
6803            }
6804        }
6805
6806        final String pkgName = pkg.packageName;
6807
6808        final long scanFileTime = scanFile.lastModified();
6809        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6810        pkg.applicationInfo.processName = fixProcessName(
6811                pkg.applicationInfo.packageName,
6812                pkg.applicationInfo.processName,
6813                pkg.applicationInfo.uid);
6814
6815        File dataPath;
6816        if (mPlatformPackage == pkg) {
6817            // The system package is special.
6818            dataPath = new File(Environment.getDataDirectory(), "system");
6819
6820            pkg.applicationInfo.dataDir = dataPath.getPath();
6821
6822        } else {
6823            // This is a normal package, need to make its data directory.
6824            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6825                    UserHandle.USER_OWNER, pkg.packageName);
6826
6827            boolean uidError = false;
6828            if (dataPath.exists()) {
6829                int currentUid = 0;
6830                try {
6831                    StructStat stat = Os.stat(dataPath.getPath());
6832                    currentUid = stat.st_uid;
6833                } catch (ErrnoException e) {
6834                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6835                }
6836
6837                // If we have mismatched owners for the data path, we have a problem.
6838                if (currentUid != pkg.applicationInfo.uid) {
6839                    boolean recovered = false;
6840                    if (currentUid == 0) {
6841                        // The directory somehow became owned by root.  Wow.
6842                        // This is probably because the system was stopped while
6843                        // installd was in the middle of messing with its libs
6844                        // directory.  Ask installd to fix that.
6845                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6846                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6847                        if (ret >= 0) {
6848                            recovered = true;
6849                            String msg = "Package " + pkg.packageName
6850                                    + " unexpectedly changed to uid 0; recovered to " +
6851                                    + pkg.applicationInfo.uid;
6852                            reportSettingsProblem(Log.WARN, msg);
6853                        }
6854                    }
6855                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6856                            || (scanFlags&SCAN_BOOTING) != 0)) {
6857                        // If this is a system app, we can at least delete its
6858                        // current data so the application will still work.
6859                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6860                        if (ret >= 0) {
6861                            // TODO: Kill the processes first
6862                            // Old data gone!
6863                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6864                                    ? "System package " : "Third party package ";
6865                            String msg = prefix + pkg.packageName
6866                                    + " has changed from uid: "
6867                                    + currentUid + " to "
6868                                    + pkg.applicationInfo.uid + "; old data erased";
6869                            reportSettingsProblem(Log.WARN, msg);
6870                            recovered = true;
6871
6872                            // And now re-install the app.
6873                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6874                                    pkg.applicationInfo.seinfo);
6875                            if (ret == -1) {
6876                                // Ack should not happen!
6877                                msg = prefix + pkg.packageName
6878                                        + " could not have data directory re-created after delete.";
6879                                reportSettingsProblem(Log.WARN, msg);
6880                                throw new PackageManagerException(
6881                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6882                            }
6883                        }
6884                        if (!recovered) {
6885                            mHasSystemUidErrors = true;
6886                        }
6887                    } else if (!recovered) {
6888                        // If we allow this install to proceed, we will be broken.
6889                        // Abort, abort!
6890                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6891                                "scanPackageLI");
6892                    }
6893                    if (!recovered) {
6894                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6895                            + pkg.applicationInfo.uid + "/fs_"
6896                            + currentUid;
6897                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6898                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6899                        String msg = "Package " + pkg.packageName
6900                                + " has mismatched uid: "
6901                                + currentUid + " on disk, "
6902                                + pkg.applicationInfo.uid + " in settings";
6903                        // writer
6904                        synchronized (mPackages) {
6905                            mSettings.mReadMessages.append(msg);
6906                            mSettings.mReadMessages.append('\n');
6907                            uidError = true;
6908                            if (!pkgSetting.uidError) {
6909                                reportSettingsProblem(Log.ERROR, msg);
6910                            }
6911                        }
6912                    }
6913                }
6914                pkg.applicationInfo.dataDir = dataPath.getPath();
6915                if (mShouldRestoreconData) {
6916                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6917                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6918                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6919                }
6920            } else {
6921                if (DEBUG_PACKAGE_SCANNING) {
6922                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6923                        Log.v(TAG, "Want this data dir: " + dataPath);
6924                }
6925                //invoke installer to do the actual installation
6926                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6927                        pkg.applicationInfo.seinfo);
6928                if (ret < 0) {
6929                    // Error from installer
6930                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6931                            "Unable to create data dirs [errorCode=" + ret + "]");
6932                }
6933
6934                if (dataPath.exists()) {
6935                    pkg.applicationInfo.dataDir = dataPath.getPath();
6936                } else {
6937                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6938                    pkg.applicationInfo.dataDir = null;
6939                }
6940            }
6941
6942            pkgSetting.uidError = uidError;
6943        }
6944
6945        final String path = scanFile.getPath();
6946        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6947
6948        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6949            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6950
6951            // Some system apps still use directory structure for native libraries
6952            // in which case we might end up not detecting abi solely based on apk
6953            // structure. Try to detect abi based on directory structure.
6954            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6955                    pkg.applicationInfo.primaryCpuAbi == null) {
6956                setBundledAppAbisAndRoots(pkg, pkgSetting);
6957                setNativeLibraryPaths(pkg);
6958            }
6959
6960        } else {
6961            if ((scanFlags & SCAN_MOVE) != 0) {
6962                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6963                // but we already have this packages package info in the PackageSetting. We just
6964                // use that and derive the native library path based on the new codepath.
6965                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6966                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6967            }
6968
6969            // Set native library paths again. For moves, the path will be updated based on the
6970            // ABIs we've determined above. For non-moves, the path will be updated based on the
6971            // ABIs we determined during compilation, but the path will depend on the final
6972            // package path (after the rename away from the stage path).
6973            setNativeLibraryPaths(pkg);
6974        }
6975
6976        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6977        final int[] userIds = sUserManager.getUserIds();
6978        synchronized (mInstallLock) {
6979            // Make sure all user data directories are ready to roll; we're okay
6980            // if they already exist
6981            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6982                for (int userId : userIds) {
6983                    if (userId != 0) {
6984                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6985                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6986                                pkg.applicationInfo.seinfo);
6987                    }
6988                }
6989            }
6990
6991            // Create a native library symlink only if we have native libraries
6992            // and if the native libraries are 32 bit libraries. We do not provide
6993            // this symlink for 64 bit libraries.
6994            if (pkg.applicationInfo.primaryCpuAbi != null &&
6995                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6996                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6997                for (int userId : userIds) {
6998                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6999                            nativeLibPath, userId) < 0) {
7000                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7001                                "Failed linking native library dir (user=" + userId + ")");
7002                    }
7003                }
7004            }
7005        }
7006
7007        // This is a special case for the "system" package, where the ABI is
7008        // dictated by the zygote configuration (and init.rc). We should keep track
7009        // of this ABI so that we can deal with "normal" applications that run under
7010        // the same UID correctly.
7011        if (mPlatformPackage == pkg) {
7012            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7013                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7014        }
7015
7016        // If there's a mismatch between the abi-override in the package setting
7017        // and the abiOverride specified for the install. Warn about this because we
7018        // would've already compiled the app without taking the package setting into
7019        // account.
7020        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7021            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7022                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7023                        " for package: " + pkg.packageName);
7024            }
7025        }
7026
7027        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7028        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7029        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7030
7031        // Copy the derived override back to the parsed package, so that we can
7032        // update the package settings accordingly.
7033        pkg.cpuAbiOverride = cpuAbiOverride;
7034
7035        if (DEBUG_ABI_SELECTION) {
7036            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7037                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7038                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7039        }
7040
7041        // Push the derived path down into PackageSettings so we know what to
7042        // clean up at uninstall time.
7043        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7044
7045        if (DEBUG_ABI_SELECTION) {
7046            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7047                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7048                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7049        }
7050
7051        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7052            // We don't do this here during boot because we can do it all
7053            // at once after scanning all existing packages.
7054            //
7055            // We also do this *before* we perform dexopt on this package, so that
7056            // we can avoid redundant dexopts, and also to make sure we've got the
7057            // code and package path correct.
7058            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7059                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7060        }
7061
7062        if ((scanFlags & SCAN_NO_DEX) == 0) {
7063            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7064                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7065            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7066                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7067            }
7068        }
7069        if (mFactoryTest && pkg.requestedPermissions.contains(
7070                android.Manifest.permission.FACTORY_TEST)) {
7071            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7072        }
7073
7074        ArrayList<PackageParser.Package> clientLibPkgs = null;
7075
7076        // writer
7077        synchronized (mPackages) {
7078            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7079                // Only system apps can add new shared libraries.
7080                if (pkg.libraryNames != null) {
7081                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7082                        String name = pkg.libraryNames.get(i);
7083                        boolean allowed = false;
7084                        if (pkg.isUpdatedSystemApp()) {
7085                            // New library entries can only be added through the
7086                            // system image.  This is important to get rid of a lot
7087                            // of nasty edge cases: for example if we allowed a non-
7088                            // system update of the app to add a library, then uninstalling
7089                            // the update would make the library go away, and assumptions
7090                            // we made such as through app install filtering would now
7091                            // have allowed apps on the device which aren't compatible
7092                            // with it.  Better to just have the restriction here, be
7093                            // conservative, and create many fewer cases that can negatively
7094                            // impact the user experience.
7095                            final PackageSetting sysPs = mSettings
7096                                    .getDisabledSystemPkgLPr(pkg.packageName);
7097                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7098                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7099                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7100                                        allowed = true;
7101                                        allowed = true;
7102                                        break;
7103                                    }
7104                                }
7105                            }
7106                        } else {
7107                            allowed = true;
7108                        }
7109                        if (allowed) {
7110                            if (!mSharedLibraries.containsKey(name)) {
7111                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7112                            } else if (!name.equals(pkg.packageName)) {
7113                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7114                                        + name + " already exists; skipping");
7115                            }
7116                        } else {
7117                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7118                                    + name + " that is not declared on system image; skipping");
7119                        }
7120                    }
7121                    if ((scanFlags&SCAN_BOOTING) == 0) {
7122                        // If we are not booting, we need to update any applications
7123                        // that are clients of our shared library.  If we are booting,
7124                        // this will all be done once the scan is complete.
7125                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7126                    }
7127                }
7128            }
7129        }
7130
7131        // We also need to dexopt any apps that are dependent on this library.  Note that
7132        // if these fail, we should abort the install since installing the library will
7133        // result in some apps being broken.
7134        if (clientLibPkgs != null) {
7135            if ((scanFlags & SCAN_NO_DEX) == 0) {
7136                for (int i = 0; i < clientLibPkgs.size(); i++) {
7137                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7138                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7139                            null /* instruction sets */, forceDex,
7140                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7141                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7142                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7143                                "scanPackageLI failed to dexopt clientLibPkgs");
7144                    }
7145                }
7146            }
7147        }
7148
7149        // Request the ActivityManager to kill the process(only for existing packages)
7150        // so that we do not end up in a confused state while the user is still using the older
7151        // version of the application while the new one gets installed.
7152        if ((scanFlags & SCAN_REPLACING) != 0) {
7153            killApplication(pkg.applicationInfo.packageName,
7154                        pkg.applicationInfo.uid, "replace pkg");
7155        }
7156
7157        // Also need to kill any apps that are dependent on the library.
7158        if (clientLibPkgs != null) {
7159            for (int i=0; i<clientLibPkgs.size(); i++) {
7160                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7161                killApplication(clientPkg.applicationInfo.packageName,
7162                        clientPkg.applicationInfo.uid, "update lib");
7163            }
7164        }
7165
7166        // Make sure we're not adding any bogus keyset info
7167        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7168        ksms.assertScannedPackageValid(pkg);
7169
7170        // writer
7171        synchronized (mPackages) {
7172            // We don't expect installation to fail beyond this point
7173
7174            // Add the new setting to mSettings
7175            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7176            // Add the new setting to mPackages
7177            mPackages.put(pkg.applicationInfo.packageName, pkg);
7178            // Make sure we don't accidentally delete its data.
7179            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7180            while (iter.hasNext()) {
7181                PackageCleanItem item = iter.next();
7182                if (pkgName.equals(item.packageName)) {
7183                    iter.remove();
7184                }
7185            }
7186
7187            // Take care of first install / last update times.
7188            if (currentTime != 0) {
7189                if (pkgSetting.firstInstallTime == 0) {
7190                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7191                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7192                    pkgSetting.lastUpdateTime = currentTime;
7193                }
7194            } else if (pkgSetting.firstInstallTime == 0) {
7195                // We need *something*.  Take time time stamp of the file.
7196                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7197            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7198                if (scanFileTime != pkgSetting.timeStamp) {
7199                    // A package on the system image has changed; consider this
7200                    // to be an update.
7201                    pkgSetting.lastUpdateTime = scanFileTime;
7202                }
7203            }
7204
7205            // Add the package's KeySets to the global KeySetManagerService
7206            ksms.addScannedPackageLPw(pkg);
7207
7208            int N = pkg.providers.size();
7209            StringBuilder r = null;
7210            int i;
7211            for (i=0; i<N; i++) {
7212                PackageParser.Provider p = pkg.providers.get(i);
7213                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7214                        p.info.processName, pkg.applicationInfo.uid);
7215                mProviders.addProvider(p);
7216                p.syncable = p.info.isSyncable;
7217                if (p.info.authority != null) {
7218                    String names[] = p.info.authority.split(";");
7219                    p.info.authority = null;
7220                    for (int j = 0; j < names.length; j++) {
7221                        if (j == 1 && p.syncable) {
7222                            // We only want the first authority for a provider to possibly be
7223                            // syncable, so if we already added this provider using a different
7224                            // authority clear the syncable flag. We copy the provider before
7225                            // changing it because the mProviders object contains a reference
7226                            // to a provider that we don't want to change.
7227                            // Only do this for the second authority since the resulting provider
7228                            // object can be the same for all future authorities for this provider.
7229                            p = new PackageParser.Provider(p);
7230                            p.syncable = false;
7231                        }
7232                        if (!mProvidersByAuthority.containsKey(names[j])) {
7233                            mProvidersByAuthority.put(names[j], p);
7234                            if (p.info.authority == null) {
7235                                p.info.authority = names[j];
7236                            } else {
7237                                p.info.authority = p.info.authority + ";" + names[j];
7238                            }
7239                            if (DEBUG_PACKAGE_SCANNING) {
7240                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7241                                    Log.d(TAG, "Registered content provider: " + names[j]
7242                                            + ", className = " + p.info.name + ", isSyncable = "
7243                                            + p.info.isSyncable);
7244                            }
7245                        } else {
7246                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7247                            Slog.w(TAG, "Skipping provider name " + names[j] +
7248                                    " (in package " + pkg.applicationInfo.packageName +
7249                                    "): name already used by "
7250                                    + ((other != null && other.getComponentName() != null)
7251                                            ? other.getComponentName().getPackageName() : "?"));
7252                        }
7253                    }
7254                }
7255                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7256                    if (r == null) {
7257                        r = new StringBuilder(256);
7258                    } else {
7259                        r.append(' ');
7260                    }
7261                    r.append(p.info.name);
7262                }
7263            }
7264            if (r != null) {
7265                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7266            }
7267
7268            N = pkg.services.size();
7269            r = null;
7270            for (i=0; i<N; i++) {
7271                PackageParser.Service s = pkg.services.get(i);
7272                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7273                        s.info.processName, pkg.applicationInfo.uid);
7274                mServices.addService(s);
7275                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7276                    if (r == null) {
7277                        r = new StringBuilder(256);
7278                    } else {
7279                        r.append(' ');
7280                    }
7281                    r.append(s.info.name);
7282                }
7283            }
7284            if (r != null) {
7285                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7286            }
7287
7288            N = pkg.receivers.size();
7289            r = null;
7290            for (i=0; i<N; i++) {
7291                PackageParser.Activity a = pkg.receivers.get(i);
7292                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7293                        a.info.processName, pkg.applicationInfo.uid);
7294                mReceivers.addActivity(a, "receiver");
7295                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7296                    if (r == null) {
7297                        r = new StringBuilder(256);
7298                    } else {
7299                        r.append(' ');
7300                    }
7301                    r.append(a.info.name);
7302                }
7303            }
7304            if (r != null) {
7305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7306            }
7307
7308            N = pkg.activities.size();
7309            r = null;
7310            for (i=0; i<N; i++) {
7311                PackageParser.Activity a = pkg.activities.get(i);
7312                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7313                        a.info.processName, pkg.applicationInfo.uid);
7314                mActivities.addActivity(a, "activity");
7315                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7316                    if (r == null) {
7317                        r = new StringBuilder(256);
7318                    } else {
7319                        r.append(' ');
7320                    }
7321                    r.append(a.info.name);
7322                }
7323            }
7324            if (r != null) {
7325                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7326            }
7327
7328            N = pkg.permissionGroups.size();
7329            r = null;
7330            for (i=0; i<N; i++) {
7331                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7332                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7333                if (cur == null) {
7334                    mPermissionGroups.put(pg.info.name, pg);
7335                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7336                        if (r == null) {
7337                            r = new StringBuilder(256);
7338                        } else {
7339                            r.append(' ');
7340                        }
7341                        r.append(pg.info.name);
7342                    }
7343                } else {
7344                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7345                            + pg.info.packageName + " ignored: original from "
7346                            + cur.info.packageName);
7347                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7348                        if (r == null) {
7349                            r = new StringBuilder(256);
7350                        } else {
7351                            r.append(' ');
7352                        }
7353                        r.append("DUP:");
7354                        r.append(pg.info.name);
7355                    }
7356                }
7357            }
7358            if (r != null) {
7359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7360            }
7361
7362            N = pkg.permissions.size();
7363            r = null;
7364            for (i=0; i<N; i++) {
7365                PackageParser.Permission p = pkg.permissions.get(i);
7366
7367                // Assume by default that we did not install this permission into the system.
7368                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7369
7370                // Now that permission groups have a special meaning, we ignore permission
7371                // groups for legacy apps to prevent unexpected behavior. In particular,
7372                // permissions for one app being granted to someone just becuase they happen
7373                // to be in a group defined by another app (before this had no implications).
7374                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7375                    p.group = mPermissionGroups.get(p.info.group);
7376                    // Warn for a permission in an unknown group.
7377                    if (p.info.group != null && p.group == null) {
7378                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7379                                + p.info.packageName + " in an unknown group " + p.info.group);
7380                    }
7381                }
7382
7383                ArrayMap<String, BasePermission> permissionMap =
7384                        p.tree ? mSettings.mPermissionTrees
7385                                : mSettings.mPermissions;
7386                BasePermission bp = permissionMap.get(p.info.name);
7387
7388                // Allow system apps to redefine non-system permissions
7389                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7390                    final boolean currentOwnerIsSystem = (bp.perm != null
7391                            && isSystemApp(bp.perm.owner));
7392                    if (isSystemApp(p.owner)) {
7393                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7394                            // It's a built-in permission and no owner, take ownership now
7395                            bp.packageSetting = pkgSetting;
7396                            bp.perm = p;
7397                            bp.uid = pkg.applicationInfo.uid;
7398                            bp.sourcePackage = p.info.packageName;
7399                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7400                        } else if (!currentOwnerIsSystem) {
7401                            String msg = "New decl " + p.owner + " of permission  "
7402                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7403                            reportSettingsProblem(Log.WARN, msg);
7404                            bp = null;
7405                        }
7406                    }
7407                }
7408
7409                if (bp == null) {
7410                    bp = new BasePermission(p.info.name, p.info.packageName,
7411                            BasePermission.TYPE_NORMAL);
7412                    permissionMap.put(p.info.name, bp);
7413                }
7414
7415                if (bp.perm == null) {
7416                    if (bp.sourcePackage == null
7417                            || bp.sourcePackage.equals(p.info.packageName)) {
7418                        BasePermission tree = findPermissionTreeLP(p.info.name);
7419                        if (tree == null
7420                                || tree.sourcePackage.equals(p.info.packageName)) {
7421                            bp.packageSetting = pkgSetting;
7422                            bp.perm = p;
7423                            bp.uid = pkg.applicationInfo.uid;
7424                            bp.sourcePackage = p.info.packageName;
7425                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7426                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7427                                if (r == null) {
7428                                    r = new StringBuilder(256);
7429                                } else {
7430                                    r.append(' ');
7431                                }
7432                                r.append(p.info.name);
7433                            }
7434                        } else {
7435                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7436                                    + p.info.packageName + " ignored: base tree "
7437                                    + tree.name + " is from package "
7438                                    + tree.sourcePackage);
7439                        }
7440                    } else {
7441                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7442                                + p.info.packageName + " ignored: original from "
7443                                + bp.sourcePackage);
7444                    }
7445                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7446                    if (r == null) {
7447                        r = new StringBuilder(256);
7448                    } else {
7449                        r.append(' ');
7450                    }
7451                    r.append("DUP:");
7452                    r.append(p.info.name);
7453                }
7454                if (bp.perm == p) {
7455                    bp.protectionLevel = p.info.protectionLevel;
7456                }
7457            }
7458
7459            if (r != null) {
7460                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7461            }
7462
7463            N = pkg.instrumentation.size();
7464            r = null;
7465            for (i=0; i<N; i++) {
7466                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7467                a.info.packageName = pkg.applicationInfo.packageName;
7468                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7469                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7470                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7471                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7472                a.info.dataDir = pkg.applicationInfo.dataDir;
7473
7474                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7475                // need other information about the application, like the ABI and what not ?
7476                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7477                mInstrumentation.put(a.getComponentName(), a);
7478                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7479                    if (r == null) {
7480                        r = new StringBuilder(256);
7481                    } else {
7482                        r.append(' ');
7483                    }
7484                    r.append(a.info.name);
7485                }
7486            }
7487            if (r != null) {
7488                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7489            }
7490
7491            if (pkg.protectedBroadcasts != null) {
7492                N = pkg.protectedBroadcasts.size();
7493                for (i=0; i<N; i++) {
7494                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7495                }
7496            }
7497
7498            pkgSetting.setTimeStamp(scanFileTime);
7499
7500            // Create idmap files for pairs of (packages, overlay packages).
7501            // Note: "android", ie framework-res.apk, is handled by native layers.
7502            if (pkg.mOverlayTarget != null) {
7503                // This is an overlay package.
7504                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7505                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7506                        mOverlays.put(pkg.mOverlayTarget,
7507                                new ArrayMap<String, PackageParser.Package>());
7508                    }
7509                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7510                    map.put(pkg.packageName, pkg);
7511                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7512                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7513                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7514                                "scanPackageLI failed to createIdmap");
7515                    }
7516                }
7517            } else if (mOverlays.containsKey(pkg.packageName) &&
7518                    !pkg.packageName.equals("android")) {
7519                // This is a regular package, with one or more known overlay packages.
7520                createIdmapsForPackageLI(pkg);
7521            }
7522        }
7523
7524        return pkg;
7525    }
7526
7527    /**
7528     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7529     * is derived purely on the basis of the contents of {@code scanFile} and
7530     * {@code cpuAbiOverride}.
7531     *
7532     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7533     */
7534    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7535                                 String cpuAbiOverride, boolean extractLibs)
7536            throws PackageManagerException {
7537        // TODO: We can probably be smarter about this stuff. For installed apps,
7538        // we can calculate this information at install time once and for all. For
7539        // system apps, we can probably assume that this information doesn't change
7540        // after the first boot scan. As things stand, we do lots of unnecessary work.
7541
7542        // Give ourselves some initial paths; we'll come back for another
7543        // pass once we've determined ABI below.
7544        setNativeLibraryPaths(pkg);
7545
7546        // We would never need to extract libs for forward-locked and external packages,
7547        // since the container service will do it for us. We shouldn't attempt to
7548        // extract libs from system app when it was not updated.
7549        if (pkg.isForwardLocked() || isExternal(pkg) ||
7550            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7551            extractLibs = false;
7552        }
7553
7554        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7555        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7556
7557        NativeLibraryHelper.Handle handle = null;
7558        try {
7559            handle = NativeLibraryHelper.Handle.create(scanFile);
7560            // TODO(multiArch): This can be null for apps that didn't go through the
7561            // usual installation process. We can calculate it again, like we
7562            // do during install time.
7563            //
7564            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7565            // unnecessary.
7566            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7567
7568            // Null out the abis so that they can be recalculated.
7569            pkg.applicationInfo.primaryCpuAbi = null;
7570            pkg.applicationInfo.secondaryCpuAbi = null;
7571            if (isMultiArch(pkg.applicationInfo)) {
7572                // Warn if we've set an abiOverride for multi-lib packages..
7573                // By definition, we need to copy both 32 and 64 bit libraries for
7574                // such packages.
7575                if (pkg.cpuAbiOverride != null
7576                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7577                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7578                }
7579
7580                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7581                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7582                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7583                    if (extractLibs) {
7584                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7585                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7586                                useIsaSpecificSubdirs);
7587                    } else {
7588                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7589                    }
7590                }
7591
7592                maybeThrowExceptionForMultiArchCopy(
7593                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7594
7595                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7596                    if (extractLibs) {
7597                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7598                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7599                                useIsaSpecificSubdirs);
7600                    } else {
7601                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7602                    }
7603                }
7604
7605                maybeThrowExceptionForMultiArchCopy(
7606                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7607
7608                if (abi64 >= 0) {
7609                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7610                }
7611
7612                if (abi32 >= 0) {
7613                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7614                    if (abi64 >= 0) {
7615                        pkg.applicationInfo.secondaryCpuAbi = abi;
7616                    } else {
7617                        pkg.applicationInfo.primaryCpuAbi = abi;
7618                    }
7619                }
7620            } else {
7621                String[] abiList = (cpuAbiOverride != null) ?
7622                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7623
7624                // Enable gross and lame hacks for apps that are built with old
7625                // SDK tools. We must scan their APKs for renderscript bitcode and
7626                // not launch them if it's present. Don't bother checking on devices
7627                // that don't have 64 bit support.
7628                boolean needsRenderScriptOverride = false;
7629                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7630                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7631                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7632                    needsRenderScriptOverride = true;
7633                }
7634
7635                final int copyRet;
7636                if (extractLibs) {
7637                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7638                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7639                } else {
7640                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7641                }
7642
7643                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7644                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7645                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7646                }
7647
7648                if (copyRet >= 0) {
7649                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7650                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7651                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7652                } else if (needsRenderScriptOverride) {
7653                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7654                }
7655            }
7656        } catch (IOException ioe) {
7657            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7658        } finally {
7659            IoUtils.closeQuietly(handle);
7660        }
7661
7662        // Now that we've calculated the ABIs and determined if it's an internal app,
7663        // we will go ahead and populate the nativeLibraryPath.
7664        setNativeLibraryPaths(pkg);
7665    }
7666
7667    /**
7668     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7669     * i.e, so that all packages can be run inside a single process if required.
7670     *
7671     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7672     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7673     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7674     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7675     * updating a package that belongs to a shared user.
7676     *
7677     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7678     * adds unnecessary complexity.
7679     */
7680    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7681            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7682        String requiredInstructionSet = null;
7683        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7684            requiredInstructionSet = VMRuntime.getInstructionSet(
7685                     scannedPackage.applicationInfo.primaryCpuAbi);
7686        }
7687
7688        PackageSetting requirer = null;
7689        for (PackageSetting ps : packagesForUser) {
7690            // If packagesForUser contains scannedPackage, we skip it. This will happen
7691            // when scannedPackage is an update of an existing package. Without this check,
7692            // we will never be able to change the ABI of any package belonging to a shared
7693            // user, even if it's compatible with other packages.
7694            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7695                if (ps.primaryCpuAbiString == null) {
7696                    continue;
7697                }
7698
7699                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7700                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7701                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7702                    // this but there's not much we can do.
7703                    String errorMessage = "Instruction set mismatch, "
7704                            + ((requirer == null) ? "[caller]" : requirer)
7705                            + " requires " + requiredInstructionSet + " whereas " + ps
7706                            + " requires " + instructionSet;
7707                    Slog.w(TAG, errorMessage);
7708                }
7709
7710                if (requiredInstructionSet == null) {
7711                    requiredInstructionSet = instructionSet;
7712                    requirer = ps;
7713                }
7714            }
7715        }
7716
7717        if (requiredInstructionSet != null) {
7718            String adjustedAbi;
7719            if (requirer != null) {
7720                // requirer != null implies that either scannedPackage was null or that scannedPackage
7721                // did not require an ABI, in which case we have to adjust scannedPackage to match
7722                // the ABI of the set (which is the same as requirer's ABI)
7723                adjustedAbi = requirer.primaryCpuAbiString;
7724                if (scannedPackage != null) {
7725                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7726                }
7727            } else {
7728                // requirer == null implies that we're updating all ABIs in the set to
7729                // match scannedPackage.
7730                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7731            }
7732
7733            for (PackageSetting ps : packagesForUser) {
7734                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7735                    if (ps.primaryCpuAbiString != null) {
7736                        continue;
7737                    }
7738
7739                    ps.primaryCpuAbiString = adjustedAbi;
7740                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7741                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7742                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7743
7744                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7745                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7746                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7747                            ps.primaryCpuAbiString = null;
7748                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7749                            return;
7750                        } else {
7751                            mInstaller.rmdex(ps.codePathString,
7752                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7753                        }
7754                    }
7755                }
7756            }
7757        }
7758    }
7759
7760    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7761        synchronized (mPackages) {
7762            mResolverReplaced = true;
7763            // Set up information for custom user intent resolution activity.
7764            mResolveActivity.applicationInfo = pkg.applicationInfo;
7765            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7766            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7767            mResolveActivity.processName = pkg.applicationInfo.packageName;
7768            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7769            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7770                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7771            mResolveActivity.theme = 0;
7772            mResolveActivity.exported = true;
7773            mResolveActivity.enabled = true;
7774            mResolveInfo.activityInfo = mResolveActivity;
7775            mResolveInfo.priority = 0;
7776            mResolveInfo.preferredOrder = 0;
7777            mResolveInfo.match = 0;
7778            mResolveComponentName = mCustomResolverComponentName;
7779            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7780                    mResolveComponentName);
7781        }
7782    }
7783
7784    private static String calculateBundledApkRoot(final String codePathString) {
7785        final File codePath = new File(codePathString);
7786        final File codeRoot;
7787        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7788            codeRoot = Environment.getRootDirectory();
7789        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7790            codeRoot = Environment.getOemDirectory();
7791        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7792            codeRoot = Environment.getVendorDirectory();
7793        } else {
7794            // Unrecognized code path; take its top real segment as the apk root:
7795            // e.g. /something/app/blah.apk => /something
7796            try {
7797                File f = codePath.getCanonicalFile();
7798                File parent = f.getParentFile();    // non-null because codePath is a file
7799                File tmp;
7800                while ((tmp = parent.getParentFile()) != null) {
7801                    f = parent;
7802                    parent = tmp;
7803                }
7804                codeRoot = f;
7805                Slog.w(TAG, "Unrecognized code path "
7806                        + codePath + " - using " + codeRoot);
7807            } catch (IOException e) {
7808                // Can't canonicalize the code path -- shenanigans?
7809                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7810                return Environment.getRootDirectory().getPath();
7811            }
7812        }
7813        return codeRoot.getPath();
7814    }
7815
7816    /**
7817     * Derive and set the location of native libraries for the given package,
7818     * which varies depending on where and how the package was installed.
7819     */
7820    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7821        final ApplicationInfo info = pkg.applicationInfo;
7822        final String codePath = pkg.codePath;
7823        final File codeFile = new File(codePath);
7824        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7825        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7826
7827        info.nativeLibraryRootDir = null;
7828        info.nativeLibraryRootRequiresIsa = false;
7829        info.nativeLibraryDir = null;
7830        info.secondaryNativeLibraryDir = null;
7831
7832        if (isApkFile(codeFile)) {
7833            // Monolithic install
7834            if (bundledApp) {
7835                // If "/system/lib64/apkname" exists, assume that is the per-package
7836                // native library directory to use; otherwise use "/system/lib/apkname".
7837                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7838                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7839                        getPrimaryInstructionSet(info));
7840
7841                // This is a bundled system app so choose the path based on the ABI.
7842                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7843                // is just the default path.
7844                final String apkName = deriveCodePathName(codePath);
7845                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7846                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7847                        apkName).getAbsolutePath();
7848
7849                if (info.secondaryCpuAbi != null) {
7850                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7851                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7852                            secondaryLibDir, apkName).getAbsolutePath();
7853                }
7854            } else if (asecApp) {
7855                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7856                        .getAbsolutePath();
7857            } else {
7858                final String apkName = deriveCodePathName(codePath);
7859                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7860                        .getAbsolutePath();
7861            }
7862
7863            info.nativeLibraryRootRequiresIsa = false;
7864            info.nativeLibraryDir = info.nativeLibraryRootDir;
7865        } else {
7866            // Cluster install
7867            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7868            info.nativeLibraryRootRequiresIsa = true;
7869
7870            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7871                    getPrimaryInstructionSet(info)).getAbsolutePath();
7872
7873            if (info.secondaryCpuAbi != null) {
7874                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7875                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7876            }
7877        }
7878    }
7879
7880    /**
7881     * Calculate the abis and roots for a bundled app. These can uniquely
7882     * be determined from the contents of the system partition, i.e whether
7883     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7884     * of this information, and instead assume that the system was built
7885     * sensibly.
7886     */
7887    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7888                                           PackageSetting pkgSetting) {
7889        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7890
7891        // If "/system/lib64/apkname" exists, assume that is the per-package
7892        // native library directory to use; otherwise use "/system/lib/apkname".
7893        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7894        setBundledAppAbi(pkg, apkRoot, apkName);
7895        // pkgSetting might be null during rescan following uninstall of updates
7896        // to a bundled app, so accommodate that possibility.  The settings in
7897        // that case will be established later from the parsed package.
7898        //
7899        // If the settings aren't null, sync them up with what we've just derived.
7900        // note that apkRoot isn't stored in the package settings.
7901        if (pkgSetting != null) {
7902            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7903            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7904        }
7905    }
7906
7907    /**
7908     * Deduces the ABI of a bundled app and sets the relevant fields on the
7909     * parsed pkg object.
7910     *
7911     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7912     *        under which system libraries are installed.
7913     * @param apkName the name of the installed package.
7914     */
7915    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7916        final File codeFile = new File(pkg.codePath);
7917
7918        final boolean has64BitLibs;
7919        final boolean has32BitLibs;
7920        if (isApkFile(codeFile)) {
7921            // Monolithic install
7922            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7923            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7924        } else {
7925            // Cluster install
7926            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7927            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7928                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7929                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7930                has64BitLibs = (new File(rootDir, isa)).exists();
7931            } else {
7932                has64BitLibs = false;
7933            }
7934            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7935                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7936                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7937                has32BitLibs = (new File(rootDir, isa)).exists();
7938            } else {
7939                has32BitLibs = false;
7940            }
7941        }
7942
7943        if (has64BitLibs && !has32BitLibs) {
7944            // The package has 64 bit libs, but not 32 bit libs. Its primary
7945            // ABI should be 64 bit. We can safely assume here that the bundled
7946            // native libraries correspond to the most preferred ABI in the list.
7947
7948            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7949            pkg.applicationInfo.secondaryCpuAbi = null;
7950        } else if (has32BitLibs && !has64BitLibs) {
7951            // The package has 32 bit libs but not 64 bit libs. Its primary
7952            // ABI should be 32 bit.
7953
7954            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7955            pkg.applicationInfo.secondaryCpuAbi = null;
7956        } else if (has32BitLibs && has64BitLibs) {
7957            // The application has both 64 and 32 bit bundled libraries. We check
7958            // here that the app declares multiArch support, and warn if it doesn't.
7959            //
7960            // We will be lenient here and record both ABIs. The primary will be the
7961            // ABI that's higher on the list, i.e, a device that's configured to prefer
7962            // 64 bit apps will see a 64 bit primary ABI,
7963
7964            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7965                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7966            }
7967
7968            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7969                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7970                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7971            } else {
7972                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7973                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7974            }
7975        } else {
7976            pkg.applicationInfo.primaryCpuAbi = null;
7977            pkg.applicationInfo.secondaryCpuAbi = null;
7978        }
7979    }
7980
7981    private void killApplication(String pkgName, int appId, String reason) {
7982        // Request the ActivityManager to kill the process(only for existing packages)
7983        // so that we do not end up in a confused state while the user is still using the older
7984        // version of the application while the new one gets installed.
7985        IActivityManager am = ActivityManagerNative.getDefault();
7986        if (am != null) {
7987            try {
7988                am.killApplicationWithAppId(pkgName, appId, reason);
7989            } catch (RemoteException e) {
7990            }
7991        }
7992    }
7993
7994    void removePackageLI(PackageSetting ps, boolean chatty) {
7995        if (DEBUG_INSTALL) {
7996            if (chatty)
7997                Log.d(TAG, "Removing package " + ps.name);
7998        }
7999
8000        // writer
8001        synchronized (mPackages) {
8002            mPackages.remove(ps.name);
8003            final PackageParser.Package pkg = ps.pkg;
8004            if (pkg != null) {
8005                cleanPackageDataStructuresLILPw(pkg, chatty);
8006            }
8007        }
8008    }
8009
8010    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8011        if (DEBUG_INSTALL) {
8012            if (chatty)
8013                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8014        }
8015
8016        // writer
8017        synchronized (mPackages) {
8018            mPackages.remove(pkg.applicationInfo.packageName);
8019            cleanPackageDataStructuresLILPw(pkg, chatty);
8020        }
8021    }
8022
8023    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8024        int N = pkg.providers.size();
8025        StringBuilder r = null;
8026        int i;
8027        for (i=0; i<N; i++) {
8028            PackageParser.Provider p = pkg.providers.get(i);
8029            mProviders.removeProvider(p);
8030            if (p.info.authority == null) {
8031
8032                /* There was another ContentProvider with this authority when
8033                 * this app was installed so this authority is null,
8034                 * Ignore it as we don't have to unregister the provider.
8035                 */
8036                continue;
8037            }
8038            String names[] = p.info.authority.split(";");
8039            for (int j = 0; j < names.length; j++) {
8040                if (mProvidersByAuthority.get(names[j]) == p) {
8041                    mProvidersByAuthority.remove(names[j]);
8042                    if (DEBUG_REMOVE) {
8043                        if (chatty)
8044                            Log.d(TAG, "Unregistered content provider: " + names[j]
8045                                    + ", className = " + p.info.name + ", isSyncable = "
8046                                    + p.info.isSyncable);
8047                    }
8048                }
8049            }
8050            if (DEBUG_REMOVE && chatty) {
8051                if (r == null) {
8052                    r = new StringBuilder(256);
8053                } else {
8054                    r.append(' ');
8055                }
8056                r.append(p.info.name);
8057            }
8058        }
8059        if (r != null) {
8060            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8061        }
8062
8063        N = pkg.services.size();
8064        r = null;
8065        for (i=0; i<N; i++) {
8066            PackageParser.Service s = pkg.services.get(i);
8067            mServices.removeService(s);
8068            if (chatty) {
8069                if (r == null) {
8070                    r = new StringBuilder(256);
8071                } else {
8072                    r.append(' ');
8073                }
8074                r.append(s.info.name);
8075            }
8076        }
8077        if (r != null) {
8078            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8079        }
8080
8081        N = pkg.receivers.size();
8082        r = null;
8083        for (i=0; i<N; i++) {
8084            PackageParser.Activity a = pkg.receivers.get(i);
8085            mReceivers.removeActivity(a, "receiver");
8086            if (DEBUG_REMOVE && chatty) {
8087                if (r == null) {
8088                    r = new StringBuilder(256);
8089                } else {
8090                    r.append(' ');
8091                }
8092                r.append(a.info.name);
8093            }
8094        }
8095        if (r != null) {
8096            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8097        }
8098
8099        N = pkg.activities.size();
8100        r = null;
8101        for (i=0; i<N; i++) {
8102            PackageParser.Activity a = pkg.activities.get(i);
8103            mActivities.removeActivity(a, "activity");
8104            if (DEBUG_REMOVE && chatty) {
8105                if (r == null) {
8106                    r = new StringBuilder(256);
8107                } else {
8108                    r.append(' ');
8109                }
8110                r.append(a.info.name);
8111            }
8112        }
8113        if (r != null) {
8114            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8115        }
8116
8117        N = pkg.permissions.size();
8118        r = null;
8119        for (i=0; i<N; i++) {
8120            PackageParser.Permission p = pkg.permissions.get(i);
8121            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8122            if (bp == null) {
8123                bp = mSettings.mPermissionTrees.get(p.info.name);
8124            }
8125            if (bp != null && bp.perm == p) {
8126                bp.perm = null;
8127                if (DEBUG_REMOVE && chatty) {
8128                    if (r == null) {
8129                        r = new StringBuilder(256);
8130                    } else {
8131                        r.append(' ');
8132                    }
8133                    r.append(p.info.name);
8134                }
8135            }
8136            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8137                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8138                if (appOpPerms != null) {
8139                    appOpPerms.remove(pkg.packageName);
8140                }
8141            }
8142        }
8143        if (r != null) {
8144            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8145        }
8146
8147        N = pkg.requestedPermissions.size();
8148        r = null;
8149        for (i=0; i<N; i++) {
8150            String perm = pkg.requestedPermissions.get(i);
8151            BasePermission bp = mSettings.mPermissions.get(perm);
8152            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8153                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8154                if (appOpPerms != null) {
8155                    appOpPerms.remove(pkg.packageName);
8156                    if (appOpPerms.isEmpty()) {
8157                        mAppOpPermissionPackages.remove(perm);
8158                    }
8159                }
8160            }
8161        }
8162        if (r != null) {
8163            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8164        }
8165
8166        N = pkg.instrumentation.size();
8167        r = null;
8168        for (i=0; i<N; i++) {
8169            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8170            mInstrumentation.remove(a.getComponentName());
8171            if (DEBUG_REMOVE && chatty) {
8172                if (r == null) {
8173                    r = new StringBuilder(256);
8174                } else {
8175                    r.append(' ');
8176                }
8177                r.append(a.info.name);
8178            }
8179        }
8180        if (r != null) {
8181            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8182        }
8183
8184        r = null;
8185        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8186            // Only system apps can hold shared libraries.
8187            if (pkg.libraryNames != null) {
8188                for (i=0; i<pkg.libraryNames.size(); i++) {
8189                    String name = pkg.libraryNames.get(i);
8190                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8191                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8192                        mSharedLibraries.remove(name);
8193                        if (DEBUG_REMOVE && chatty) {
8194                            if (r == null) {
8195                                r = new StringBuilder(256);
8196                            } else {
8197                                r.append(' ');
8198                            }
8199                            r.append(name);
8200                        }
8201                    }
8202                }
8203            }
8204        }
8205        if (r != null) {
8206            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8207        }
8208    }
8209
8210    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8211        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8212            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8213                return true;
8214            }
8215        }
8216        return false;
8217    }
8218
8219    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8220    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8221    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8222
8223    private void updatePermissionsLPw(String changingPkg,
8224            PackageParser.Package pkgInfo, int flags) {
8225        // Make sure there are no dangling permission trees.
8226        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8227        while (it.hasNext()) {
8228            final BasePermission bp = it.next();
8229            if (bp.packageSetting == null) {
8230                // We may not yet have parsed the package, so just see if
8231                // we still know about its settings.
8232                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8233            }
8234            if (bp.packageSetting == null) {
8235                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8236                        + " from package " + bp.sourcePackage);
8237                it.remove();
8238            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8239                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8240                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8241                            + " from package " + bp.sourcePackage);
8242                    flags |= UPDATE_PERMISSIONS_ALL;
8243                    it.remove();
8244                }
8245            }
8246        }
8247
8248        // Make sure all dynamic permissions have been assigned to a package,
8249        // and make sure there are no dangling permissions.
8250        it = mSettings.mPermissions.values().iterator();
8251        while (it.hasNext()) {
8252            final BasePermission bp = it.next();
8253            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8254                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8255                        + bp.name + " pkg=" + bp.sourcePackage
8256                        + " info=" + bp.pendingInfo);
8257                if (bp.packageSetting == null && bp.pendingInfo != null) {
8258                    final BasePermission tree = findPermissionTreeLP(bp.name);
8259                    if (tree != null && tree.perm != null) {
8260                        bp.packageSetting = tree.packageSetting;
8261                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8262                                new PermissionInfo(bp.pendingInfo));
8263                        bp.perm.info.packageName = tree.perm.info.packageName;
8264                        bp.perm.info.name = bp.name;
8265                        bp.uid = tree.uid;
8266                    }
8267                }
8268            }
8269            if (bp.packageSetting == null) {
8270                // We may not yet have parsed the package, so just see if
8271                // we still know about its settings.
8272                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8273            }
8274            if (bp.packageSetting == null) {
8275                Slog.w(TAG, "Removing dangling permission: " + bp.name
8276                        + " from package " + bp.sourcePackage);
8277                it.remove();
8278            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8279                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8280                    Slog.i(TAG, "Removing old permission: " + bp.name
8281                            + " from package " + bp.sourcePackage);
8282                    flags |= UPDATE_PERMISSIONS_ALL;
8283                    it.remove();
8284                }
8285            }
8286        }
8287
8288        // Now update the permissions for all packages, in particular
8289        // replace the granted permissions of the system packages.
8290        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8291            for (PackageParser.Package pkg : mPackages.values()) {
8292                if (pkg != pkgInfo) {
8293                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8294                            changingPkg);
8295                }
8296            }
8297        }
8298
8299        if (pkgInfo != null) {
8300            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8301        }
8302    }
8303
8304    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8305            String packageOfInterest) {
8306        // IMPORTANT: There are two types of permissions: install and runtime.
8307        // Install time permissions are granted when the app is installed to
8308        // all device users and users added in the future. Runtime permissions
8309        // are granted at runtime explicitly to specific users. Normal and signature
8310        // protected permissions are install time permissions. Dangerous permissions
8311        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8312        // otherwise they are runtime permissions. This function does not manage
8313        // runtime permissions except for the case an app targeting Lollipop MR1
8314        // being upgraded to target a newer SDK, in which case dangerous permissions
8315        // are transformed from install time to runtime ones.
8316
8317        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8318        if (ps == null) {
8319            return;
8320        }
8321
8322        PermissionsState permissionsState = ps.getPermissionsState();
8323        PermissionsState origPermissions = permissionsState;
8324
8325        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8326
8327        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8328
8329        boolean changedInstallPermission = false;
8330
8331        if (replace) {
8332            ps.installPermissionsFixed = false;
8333            if (!ps.isSharedUser()) {
8334                origPermissions = new PermissionsState(permissionsState);
8335                permissionsState.reset();
8336            }
8337        }
8338
8339        permissionsState.setGlobalGids(mGlobalGids);
8340
8341        final int N = pkg.requestedPermissions.size();
8342        for (int i=0; i<N; i++) {
8343            final String name = pkg.requestedPermissions.get(i);
8344            final BasePermission bp = mSettings.mPermissions.get(name);
8345
8346            if (DEBUG_INSTALL) {
8347                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8348            }
8349
8350            if (bp == null || bp.packageSetting == null) {
8351                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8352                    Slog.w(TAG, "Unknown permission " + name
8353                            + " in package " + pkg.packageName);
8354                }
8355                continue;
8356            }
8357
8358            final String perm = bp.name;
8359            boolean allowedSig = false;
8360            int grant = GRANT_DENIED;
8361
8362            // Keep track of app op permissions.
8363            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8364                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8365                if (pkgs == null) {
8366                    pkgs = new ArraySet<>();
8367                    mAppOpPermissionPackages.put(bp.name, pkgs);
8368                }
8369                pkgs.add(pkg.packageName);
8370            }
8371
8372            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8373            switch (level) {
8374                case PermissionInfo.PROTECTION_NORMAL: {
8375                    // For all apps normal permissions are install time ones.
8376                    grant = GRANT_INSTALL;
8377                } break;
8378
8379                case PermissionInfo.PROTECTION_DANGEROUS: {
8380                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8381                        // For legacy apps dangerous permissions are install time ones.
8382                        grant = GRANT_INSTALL_LEGACY;
8383                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8384                        // For legacy apps that became modern, install becomes runtime.
8385                        grant = GRANT_UPGRADE;
8386                    } else if (mPromoteSystemApps
8387                            && isSystemApp(ps)
8388                            && mExistingSystemPackages.contains(ps.name)) {
8389                        // For legacy system apps, install becomes runtime.
8390                        // We cannot check hasInstallPermission() for system apps since those
8391                        // permissions were granted implicitly and not persisted pre-M.
8392                        grant = GRANT_UPGRADE;
8393                    } else {
8394                        // For modern apps keep runtime permissions unchanged.
8395                        grant = GRANT_RUNTIME;
8396                    }
8397                } break;
8398
8399                case PermissionInfo.PROTECTION_SIGNATURE: {
8400                    // For all apps signature permissions are install time ones.
8401                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8402                    if (allowedSig) {
8403                        grant = GRANT_INSTALL;
8404                    }
8405                } break;
8406            }
8407
8408            if (DEBUG_INSTALL) {
8409                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8410            }
8411
8412            if (grant != GRANT_DENIED) {
8413                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8414                    // If this is an existing, non-system package, then
8415                    // we can't add any new permissions to it.
8416                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8417                        // Except...  if this is a permission that was added
8418                        // to the platform (note: need to only do this when
8419                        // updating the platform).
8420                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8421                            grant = GRANT_DENIED;
8422                        }
8423                    }
8424                }
8425
8426                switch (grant) {
8427                    case GRANT_INSTALL: {
8428                        // Revoke this as runtime permission to handle the case of
8429                        // a runtime permission being downgraded to an install one.
8430                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8431                            if (origPermissions.getRuntimePermissionState(
8432                                    bp.name, userId) != null) {
8433                                // Revoke the runtime permission and clear the flags.
8434                                origPermissions.revokeRuntimePermission(bp, userId);
8435                                origPermissions.updatePermissionFlags(bp, userId,
8436                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8437                                // If we revoked a permission permission, we have to write.
8438                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8439                                        changedRuntimePermissionUserIds, userId);
8440                            }
8441                        }
8442                        // Grant an install permission.
8443                        if (permissionsState.grantInstallPermission(bp) !=
8444                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8445                            changedInstallPermission = true;
8446                        }
8447                    } break;
8448
8449                    case GRANT_INSTALL_LEGACY: {
8450                        // Grant an install permission.
8451                        if (permissionsState.grantInstallPermission(bp) !=
8452                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8453                            changedInstallPermission = true;
8454                        }
8455                    } break;
8456
8457                    case GRANT_RUNTIME: {
8458                        // Grant previously granted runtime permissions.
8459                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8460                            PermissionState permissionState = origPermissions
8461                                    .getRuntimePermissionState(bp.name, userId);
8462                            final int flags = permissionState != null
8463                                    ? permissionState.getFlags() : 0;
8464                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8465                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8466                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8467                                    // If we cannot put the permission as it was, we have to write.
8468                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8469                                            changedRuntimePermissionUserIds, userId);
8470                                }
8471                            }
8472                            // Propagate the permission flags.
8473                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8474                        }
8475                    } break;
8476
8477                    case GRANT_UPGRADE: {
8478                        // Grant runtime permissions for a previously held install permission.
8479                        PermissionState permissionState = origPermissions
8480                                .getInstallPermissionState(bp.name);
8481                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8482
8483                        if (origPermissions.revokeInstallPermission(bp)
8484                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8485                            // We will be transferring the permission flags, so clear them.
8486                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8487                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8488                            changedInstallPermission = true;
8489                        }
8490
8491                        // If the permission is not to be promoted to runtime we ignore it and
8492                        // also its other flags as they are not applicable to install permissions.
8493                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8494                            for (int userId : currentUserIds) {
8495                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8496                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8497                                    // Transfer the permission flags.
8498                                    permissionsState.updatePermissionFlags(bp, userId,
8499                                            flags, flags);
8500                                    // If we granted the permission, we have to write.
8501                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8502                                            changedRuntimePermissionUserIds, userId);
8503                                }
8504                            }
8505                        }
8506                    } break;
8507
8508                    default: {
8509                        if (packageOfInterest == null
8510                                || packageOfInterest.equals(pkg.packageName)) {
8511                            Slog.w(TAG, "Not granting permission " + perm
8512                                    + " to package " + pkg.packageName
8513                                    + " because it was previously installed without");
8514                        }
8515                    } break;
8516                }
8517            } else {
8518                if (permissionsState.revokeInstallPermission(bp) !=
8519                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8520                    // Also drop the permission flags.
8521                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8522                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8523                    changedInstallPermission = true;
8524                    Slog.i(TAG, "Un-granting permission " + perm
8525                            + " from package " + pkg.packageName
8526                            + " (protectionLevel=" + bp.protectionLevel
8527                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8528                            + ")");
8529                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8530                    // Don't print warning for app op permissions, since it is fine for them
8531                    // not to be granted, there is a UI for the user to decide.
8532                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8533                        Slog.w(TAG, "Not granting permission " + perm
8534                                + " to package " + pkg.packageName
8535                                + " (protectionLevel=" + bp.protectionLevel
8536                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8537                                + ")");
8538                    }
8539                }
8540            }
8541        }
8542
8543        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8544                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8545            // This is the first that we have heard about this package, so the
8546            // permissions we have now selected are fixed until explicitly
8547            // changed.
8548            ps.installPermissionsFixed = true;
8549        }
8550
8551        // Persist the runtime permissions state for users with changes.
8552        for (int userId : changedRuntimePermissionUserIds) {
8553            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8554        }
8555    }
8556
8557    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8558        boolean allowed = false;
8559        final int NP = PackageParser.NEW_PERMISSIONS.length;
8560        for (int ip=0; ip<NP; ip++) {
8561            final PackageParser.NewPermissionInfo npi
8562                    = PackageParser.NEW_PERMISSIONS[ip];
8563            if (npi.name.equals(perm)
8564                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8565                allowed = true;
8566                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8567                        + pkg.packageName);
8568                break;
8569            }
8570        }
8571        return allowed;
8572    }
8573
8574    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8575            BasePermission bp, PermissionsState origPermissions) {
8576        boolean allowed;
8577        allowed = (compareSignatures(
8578                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8579                        == PackageManager.SIGNATURE_MATCH)
8580                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8581                        == PackageManager.SIGNATURE_MATCH);
8582        if (!allowed && (bp.protectionLevel
8583                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8584            if (isSystemApp(pkg)) {
8585                // For updated system applications, a system permission
8586                // is granted only if it had been defined by the original application.
8587                if (pkg.isUpdatedSystemApp()) {
8588                    final PackageSetting sysPs = mSettings
8589                            .getDisabledSystemPkgLPr(pkg.packageName);
8590                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8591                        // If the original was granted this permission, we take
8592                        // that grant decision as read and propagate it to the
8593                        // update.
8594                        if (sysPs.isPrivileged()) {
8595                            allowed = true;
8596                        }
8597                    } else {
8598                        // The system apk may have been updated with an older
8599                        // version of the one on the data partition, but which
8600                        // granted a new system permission that it didn't have
8601                        // before.  In this case we do want to allow the app to
8602                        // now get the new permission if the ancestral apk is
8603                        // privileged to get it.
8604                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8605                            for (int j=0;
8606                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8607                                if (perm.equals(
8608                                        sysPs.pkg.requestedPermissions.get(j))) {
8609                                    allowed = true;
8610                                    break;
8611                                }
8612                            }
8613                        }
8614                    }
8615                } else {
8616                    allowed = isPrivilegedApp(pkg);
8617                }
8618            }
8619        }
8620        if (!allowed) {
8621            if (!allowed && (bp.protectionLevel
8622                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8623                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8624                // If this was a previously normal/dangerous permission that got moved
8625                // to a system permission as part of the runtime permission redesign, then
8626                // we still want to blindly grant it to old apps.
8627                allowed = true;
8628            }
8629            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8630                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8631                // If this permission is to be granted to the system installer and
8632                // this app is an installer, then it gets the permission.
8633                allowed = true;
8634            }
8635            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8636                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8637                // If this permission is to be granted to the system verifier and
8638                // this app is a verifier, then it gets the permission.
8639                allowed = true;
8640            }
8641            if (!allowed && (bp.protectionLevel
8642                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8643                    && isSystemApp(pkg)) {
8644                // Any pre-installed system app is allowed to get this permission.
8645                allowed = true;
8646            }
8647            if (!allowed && (bp.protectionLevel
8648                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8649                // For development permissions, a development permission
8650                // is granted only if it was already granted.
8651                allowed = origPermissions.hasInstallPermission(perm);
8652            }
8653        }
8654        return allowed;
8655    }
8656
8657    final class ActivityIntentResolver
8658            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8659        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8660                boolean defaultOnly, int userId) {
8661            if (!sUserManager.exists(userId)) return null;
8662            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8663            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8664        }
8665
8666        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8667                int userId) {
8668            if (!sUserManager.exists(userId)) return null;
8669            mFlags = flags;
8670            return super.queryIntent(intent, resolvedType,
8671                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8672        }
8673
8674        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8675                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8676            if (!sUserManager.exists(userId)) return null;
8677            if (packageActivities == null) {
8678                return null;
8679            }
8680            mFlags = flags;
8681            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8682            final int N = packageActivities.size();
8683            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8684                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8685
8686            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8687            for (int i = 0; i < N; ++i) {
8688                intentFilters = packageActivities.get(i).intents;
8689                if (intentFilters != null && intentFilters.size() > 0) {
8690                    PackageParser.ActivityIntentInfo[] array =
8691                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8692                    intentFilters.toArray(array);
8693                    listCut.add(array);
8694                }
8695            }
8696            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8697        }
8698
8699        public final void addActivity(PackageParser.Activity a, String type) {
8700            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8701            mActivities.put(a.getComponentName(), a);
8702            if (DEBUG_SHOW_INFO)
8703                Log.v(
8704                TAG, "  " + type + " " +
8705                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8706            if (DEBUG_SHOW_INFO)
8707                Log.v(TAG, "    Class=" + a.info.name);
8708            final int NI = a.intents.size();
8709            for (int j=0; j<NI; j++) {
8710                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8711                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8712                    intent.setPriority(0);
8713                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8714                            + a.className + " with priority > 0, forcing to 0");
8715                }
8716                if (DEBUG_SHOW_INFO) {
8717                    Log.v(TAG, "    IntentFilter:");
8718                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8719                }
8720                if (!intent.debugCheck()) {
8721                    Log.w(TAG, "==> For Activity " + a.info.name);
8722                }
8723                addFilter(intent);
8724            }
8725        }
8726
8727        public final void removeActivity(PackageParser.Activity a, String type) {
8728            mActivities.remove(a.getComponentName());
8729            if (DEBUG_SHOW_INFO) {
8730                Log.v(TAG, "  " + type + " "
8731                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8732                                : a.info.name) + ":");
8733                Log.v(TAG, "    Class=" + a.info.name);
8734            }
8735            final int NI = a.intents.size();
8736            for (int j=0; j<NI; j++) {
8737                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8738                if (DEBUG_SHOW_INFO) {
8739                    Log.v(TAG, "    IntentFilter:");
8740                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8741                }
8742                removeFilter(intent);
8743            }
8744        }
8745
8746        @Override
8747        protected boolean allowFilterResult(
8748                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8749            ActivityInfo filterAi = filter.activity.info;
8750            for (int i=dest.size()-1; i>=0; i--) {
8751                ActivityInfo destAi = dest.get(i).activityInfo;
8752                if (destAi.name == filterAi.name
8753                        && destAi.packageName == filterAi.packageName) {
8754                    return false;
8755                }
8756            }
8757            return true;
8758        }
8759
8760        @Override
8761        protected ActivityIntentInfo[] newArray(int size) {
8762            return new ActivityIntentInfo[size];
8763        }
8764
8765        @Override
8766        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8767            if (!sUserManager.exists(userId)) return true;
8768            PackageParser.Package p = filter.activity.owner;
8769            if (p != null) {
8770                PackageSetting ps = (PackageSetting)p.mExtras;
8771                if (ps != null) {
8772                    // System apps are never considered stopped for purposes of
8773                    // filtering, because there may be no way for the user to
8774                    // actually re-launch them.
8775                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8776                            && ps.getStopped(userId);
8777                }
8778            }
8779            return false;
8780        }
8781
8782        @Override
8783        protected boolean isPackageForFilter(String packageName,
8784                PackageParser.ActivityIntentInfo info) {
8785            return packageName.equals(info.activity.owner.packageName);
8786        }
8787
8788        @Override
8789        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8790                int match, int userId) {
8791            if (!sUserManager.exists(userId)) return null;
8792            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8793                return null;
8794            }
8795            final PackageParser.Activity activity = info.activity;
8796            if (mSafeMode && (activity.info.applicationInfo.flags
8797                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8798                return null;
8799            }
8800            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8801            if (ps == null) {
8802                return null;
8803            }
8804            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8805                    ps.readUserState(userId), userId);
8806            if (ai == null) {
8807                return null;
8808            }
8809            final ResolveInfo res = new ResolveInfo();
8810            res.activityInfo = ai;
8811            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8812                res.filter = info;
8813            }
8814            if (info != null) {
8815                res.handleAllWebDataURI = info.handleAllWebDataURI();
8816            }
8817            res.priority = info.getPriority();
8818            res.preferredOrder = activity.owner.mPreferredOrder;
8819            //System.out.println("Result: " + res.activityInfo.className +
8820            //                   " = " + res.priority);
8821            res.match = match;
8822            res.isDefault = info.hasDefault;
8823            res.labelRes = info.labelRes;
8824            res.nonLocalizedLabel = info.nonLocalizedLabel;
8825            if (userNeedsBadging(userId)) {
8826                res.noResourceId = true;
8827            } else {
8828                res.icon = info.icon;
8829            }
8830            res.iconResourceId = info.icon;
8831            res.system = res.activityInfo.applicationInfo.isSystemApp();
8832            return res;
8833        }
8834
8835        @Override
8836        protected void sortResults(List<ResolveInfo> results) {
8837            Collections.sort(results, mResolvePrioritySorter);
8838        }
8839
8840        @Override
8841        protected void dumpFilter(PrintWriter out, String prefix,
8842                PackageParser.ActivityIntentInfo filter) {
8843            out.print(prefix); out.print(
8844                    Integer.toHexString(System.identityHashCode(filter.activity)));
8845                    out.print(' ');
8846                    filter.activity.printComponentShortName(out);
8847                    out.print(" filter ");
8848                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8849        }
8850
8851        @Override
8852        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8853            return filter.activity;
8854        }
8855
8856        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8857            PackageParser.Activity activity = (PackageParser.Activity)label;
8858            out.print(prefix); out.print(
8859                    Integer.toHexString(System.identityHashCode(activity)));
8860                    out.print(' ');
8861                    activity.printComponentShortName(out);
8862            if (count > 1) {
8863                out.print(" ("); out.print(count); out.print(" filters)");
8864            }
8865            out.println();
8866        }
8867
8868//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8869//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8870//            final List<ResolveInfo> retList = Lists.newArrayList();
8871//            while (i.hasNext()) {
8872//                final ResolveInfo resolveInfo = i.next();
8873//                if (isEnabledLP(resolveInfo.activityInfo)) {
8874//                    retList.add(resolveInfo);
8875//                }
8876//            }
8877//            return retList;
8878//        }
8879
8880        // Keys are String (activity class name), values are Activity.
8881        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8882                = new ArrayMap<ComponentName, PackageParser.Activity>();
8883        private int mFlags;
8884    }
8885
8886    private final class ServiceIntentResolver
8887            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8888        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8889                boolean defaultOnly, int userId) {
8890            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8891            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8892        }
8893
8894        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8895                int userId) {
8896            if (!sUserManager.exists(userId)) return null;
8897            mFlags = flags;
8898            return super.queryIntent(intent, resolvedType,
8899                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8900        }
8901
8902        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8903                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8904            if (!sUserManager.exists(userId)) return null;
8905            if (packageServices == null) {
8906                return null;
8907            }
8908            mFlags = flags;
8909            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8910            final int N = packageServices.size();
8911            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8912                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8913
8914            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8915            for (int i = 0; i < N; ++i) {
8916                intentFilters = packageServices.get(i).intents;
8917                if (intentFilters != null && intentFilters.size() > 0) {
8918                    PackageParser.ServiceIntentInfo[] array =
8919                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8920                    intentFilters.toArray(array);
8921                    listCut.add(array);
8922                }
8923            }
8924            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8925        }
8926
8927        public final void addService(PackageParser.Service s) {
8928            mServices.put(s.getComponentName(), s);
8929            if (DEBUG_SHOW_INFO) {
8930                Log.v(TAG, "  "
8931                        + (s.info.nonLocalizedLabel != null
8932                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8933                Log.v(TAG, "    Class=" + s.info.name);
8934            }
8935            final int NI = s.intents.size();
8936            int j;
8937            for (j=0; j<NI; j++) {
8938                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8939                if (DEBUG_SHOW_INFO) {
8940                    Log.v(TAG, "    IntentFilter:");
8941                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8942                }
8943                if (!intent.debugCheck()) {
8944                    Log.w(TAG, "==> For Service " + s.info.name);
8945                }
8946                addFilter(intent);
8947            }
8948        }
8949
8950        public final void removeService(PackageParser.Service s) {
8951            mServices.remove(s.getComponentName());
8952            if (DEBUG_SHOW_INFO) {
8953                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8954                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8955                Log.v(TAG, "    Class=" + s.info.name);
8956            }
8957            final int NI = s.intents.size();
8958            int j;
8959            for (j=0; j<NI; j++) {
8960                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8961                if (DEBUG_SHOW_INFO) {
8962                    Log.v(TAG, "    IntentFilter:");
8963                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8964                }
8965                removeFilter(intent);
8966            }
8967        }
8968
8969        @Override
8970        protected boolean allowFilterResult(
8971                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8972            ServiceInfo filterSi = filter.service.info;
8973            for (int i=dest.size()-1; i>=0; i--) {
8974                ServiceInfo destAi = dest.get(i).serviceInfo;
8975                if (destAi.name == filterSi.name
8976                        && destAi.packageName == filterSi.packageName) {
8977                    return false;
8978                }
8979            }
8980            return true;
8981        }
8982
8983        @Override
8984        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8985            return new PackageParser.ServiceIntentInfo[size];
8986        }
8987
8988        @Override
8989        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8990            if (!sUserManager.exists(userId)) return true;
8991            PackageParser.Package p = filter.service.owner;
8992            if (p != null) {
8993                PackageSetting ps = (PackageSetting)p.mExtras;
8994                if (ps != null) {
8995                    // System apps are never considered stopped for purposes of
8996                    // filtering, because there may be no way for the user to
8997                    // actually re-launch them.
8998                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8999                            && ps.getStopped(userId);
9000                }
9001            }
9002            return false;
9003        }
9004
9005        @Override
9006        protected boolean isPackageForFilter(String packageName,
9007                PackageParser.ServiceIntentInfo info) {
9008            return packageName.equals(info.service.owner.packageName);
9009        }
9010
9011        @Override
9012        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9013                int match, int userId) {
9014            if (!sUserManager.exists(userId)) return null;
9015            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9016            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9017                return null;
9018            }
9019            final PackageParser.Service service = info.service;
9020            if (mSafeMode && (service.info.applicationInfo.flags
9021                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9022                return null;
9023            }
9024            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9025            if (ps == null) {
9026                return null;
9027            }
9028            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9029                    ps.readUserState(userId), userId);
9030            if (si == null) {
9031                return null;
9032            }
9033            final ResolveInfo res = new ResolveInfo();
9034            res.serviceInfo = si;
9035            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9036                res.filter = filter;
9037            }
9038            res.priority = info.getPriority();
9039            res.preferredOrder = service.owner.mPreferredOrder;
9040            res.match = match;
9041            res.isDefault = info.hasDefault;
9042            res.labelRes = info.labelRes;
9043            res.nonLocalizedLabel = info.nonLocalizedLabel;
9044            res.icon = info.icon;
9045            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9046            return res;
9047        }
9048
9049        @Override
9050        protected void sortResults(List<ResolveInfo> results) {
9051            Collections.sort(results, mResolvePrioritySorter);
9052        }
9053
9054        @Override
9055        protected void dumpFilter(PrintWriter out, String prefix,
9056                PackageParser.ServiceIntentInfo filter) {
9057            out.print(prefix); out.print(
9058                    Integer.toHexString(System.identityHashCode(filter.service)));
9059                    out.print(' ');
9060                    filter.service.printComponentShortName(out);
9061                    out.print(" filter ");
9062                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9063        }
9064
9065        @Override
9066        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9067            return filter.service;
9068        }
9069
9070        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9071            PackageParser.Service service = (PackageParser.Service)label;
9072            out.print(prefix); out.print(
9073                    Integer.toHexString(System.identityHashCode(service)));
9074                    out.print(' ');
9075                    service.printComponentShortName(out);
9076            if (count > 1) {
9077                out.print(" ("); out.print(count); out.print(" filters)");
9078            }
9079            out.println();
9080        }
9081
9082//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9083//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9084//            final List<ResolveInfo> retList = Lists.newArrayList();
9085//            while (i.hasNext()) {
9086//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9087//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9088//                    retList.add(resolveInfo);
9089//                }
9090//            }
9091//            return retList;
9092//        }
9093
9094        // Keys are String (activity class name), values are Activity.
9095        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9096                = new ArrayMap<ComponentName, PackageParser.Service>();
9097        private int mFlags;
9098    };
9099
9100    private final class ProviderIntentResolver
9101            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9102        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9103                boolean defaultOnly, int userId) {
9104            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9105            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9106        }
9107
9108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9109                int userId) {
9110            if (!sUserManager.exists(userId))
9111                return null;
9112            mFlags = flags;
9113            return super.queryIntent(intent, resolvedType,
9114                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9115        }
9116
9117        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9118                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9119            if (!sUserManager.exists(userId))
9120                return null;
9121            if (packageProviders == null) {
9122                return null;
9123            }
9124            mFlags = flags;
9125            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9126            final int N = packageProviders.size();
9127            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9128                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9129
9130            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9131            for (int i = 0; i < N; ++i) {
9132                intentFilters = packageProviders.get(i).intents;
9133                if (intentFilters != null && intentFilters.size() > 0) {
9134                    PackageParser.ProviderIntentInfo[] array =
9135                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9136                    intentFilters.toArray(array);
9137                    listCut.add(array);
9138                }
9139            }
9140            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9141        }
9142
9143        public final void addProvider(PackageParser.Provider p) {
9144            if (mProviders.containsKey(p.getComponentName())) {
9145                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9146                return;
9147            }
9148
9149            mProviders.put(p.getComponentName(), p);
9150            if (DEBUG_SHOW_INFO) {
9151                Log.v(TAG, "  "
9152                        + (p.info.nonLocalizedLabel != null
9153                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9154                Log.v(TAG, "    Class=" + p.info.name);
9155            }
9156            final int NI = p.intents.size();
9157            int j;
9158            for (j = 0; j < NI; j++) {
9159                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9160                if (DEBUG_SHOW_INFO) {
9161                    Log.v(TAG, "    IntentFilter:");
9162                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9163                }
9164                if (!intent.debugCheck()) {
9165                    Log.w(TAG, "==> For Provider " + p.info.name);
9166                }
9167                addFilter(intent);
9168            }
9169        }
9170
9171        public final void removeProvider(PackageParser.Provider p) {
9172            mProviders.remove(p.getComponentName());
9173            if (DEBUG_SHOW_INFO) {
9174                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9175                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9176                Log.v(TAG, "    Class=" + p.info.name);
9177            }
9178            final int NI = p.intents.size();
9179            int j;
9180            for (j = 0; j < NI; j++) {
9181                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9182                if (DEBUG_SHOW_INFO) {
9183                    Log.v(TAG, "    IntentFilter:");
9184                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9185                }
9186                removeFilter(intent);
9187            }
9188        }
9189
9190        @Override
9191        protected boolean allowFilterResult(
9192                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9193            ProviderInfo filterPi = filter.provider.info;
9194            for (int i = dest.size() - 1; i >= 0; i--) {
9195                ProviderInfo destPi = dest.get(i).providerInfo;
9196                if (destPi.name == filterPi.name
9197                        && destPi.packageName == filterPi.packageName) {
9198                    return false;
9199                }
9200            }
9201            return true;
9202        }
9203
9204        @Override
9205        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9206            return new PackageParser.ProviderIntentInfo[size];
9207        }
9208
9209        @Override
9210        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9211            if (!sUserManager.exists(userId))
9212                return true;
9213            PackageParser.Package p = filter.provider.owner;
9214            if (p != null) {
9215                PackageSetting ps = (PackageSetting) p.mExtras;
9216                if (ps != null) {
9217                    // System apps are never considered stopped for purposes of
9218                    // filtering, because there may be no way for the user to
9219                    // actually re-launch them.
9220                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9221                            && ps.getStopped(userId);
9222                }
9223            }
9224            return false;
9225        }
9226
9227        @Override
9228        protected boolean isPackageForFilter(String packageName,
9229                PackageParser.ProviderIntentInfo info) {
9230            return packageName.equals(info.provider.owner.packageName);
9231        }
9232
9233        @Override
9234        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9235                int match, int userId) {
9236            if (!sUserManager.exists(userId))
9237                return null;
9238            final PackageParser.ProviderIntentInfo info = filter;
9239            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9240                return null;
9241            }
9242            final PackageParser.Provider provider = info.provider;
9243            if (mSafeMode && (provider.info.applicationInfo.flags
9244                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9245                return null;
9246            }
9247            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9248            if (ps == null) {
9249                return null;
9250            }
9251            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9252                    ps.readUserState(userId), userId);
9253            if (pi == null) {
9254                return null;
9255            }
9256            final ResolveInfo res = new ResolveInfo();
9257            res.providerInfo = pi;
9258            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9259                res.filter = filter;
9260            }
9261            res.priority = info.getPriority();
9262            res.preferredOrder = provider.owner.mPreferredOrder;
9263            res.match = match;
9264            res.isDefault = info.hasDefault;
9265            res.labelRes = info.labelRes;
9266            res.nonLocalizedLabel = info.nonLocalizedLabel;
9267            res.icon = info.icon;
9268            res.system = res.providerInfo.applicationInfo.isSystemApp();
9269            return res;
9270        }
9271
9272        @Override
9273        protected void sortResults(List<ResolveInfo> results) {
9274            Collections.sort(results, mResolvePrioritySorter);
9275        }
9276
9277        @Override
9278        protected void dumpFilter(PrintWriter out, String prefix,
9279                PackageParser.ProviderIntentInfo filter) {
9280            out.print(prefix);
9281            out.print(
9282                    Integer.toHexString(System.identityHashCode(filter.provider)));
9283            out.print(' ');
9284            filter.provider.printComponentShortName(out);
9285            out.print(" filter ");
9286            out.println(Integer.toHexString(System.identityHashCode(filter)));
9287        }
9288
9289        @Override
9290        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9291            return filter.provider;
9292        }
9293
9294        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9295            PackageParser.Provider provider = (PackageParser.Provider)label;
9296            out.print(prefix); out.print(
9297                    Integer.toHexString(System.identityHashCode(provider)));
9298                    out.print(' ');
9299                    provider.printComponentShortName(out);
9300            if (count > 1) {
9301                out.print(" ("); out.print(count); out.print(" filters)");
9302            }
9303            out.println();
9304        }
9305
9306        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9307                = new ArrayMap<ComponentName, PackageParser.Provider>();
9308        private int mFlags;
9309    };
9310
9311    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9312            new Comparator<ResolveInfo>() {
9313        public int compare(ResolveInfo r1, ResolveInfo r2) {
9314            int v1 = r1.priority;
9315            int v2 = r2.priority;
9316            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9317            if (v1 != v2) {
9318                return (v1 > v2) ? -1 : 1;
9319            }
9320            v1 = r1.preferredOrder;
9321            v2 = r2.preferredOrder;
9322            if (v1 != v2) {
9323                return (v1 > v2) ? -1 : 1;
9324            }
9325            if (r1.isDefault != r2.isDefault) {
9326                return r1.isDefault ? -1 : 1;
9327            }
9328            v1 = r1.match;
9329            v2 = r2.match;
9330            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9331            if (v1 != v2) {
9332                return (v1 > v2) ? -1 : 1;
9333            }
9334            if (r1.system != r2.system) {
9335                return r1.system ? -1 : 1;
9336            }
9337            return 0;
9338        }
9339    };
9340
9341    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9342            new Comparator<ProviderInfo>() {
9343        public int compare(ProviderInfo p1, ProviderInfo p2) {
9344            final int v1 = p1.initOrder;
9345            final int v2 = p2.initOrder;
9346            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9347        }
9348    };
9349
9350    final void sendPackageBroadcast(final String action, final String pkg,
9351            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9352            final int[] userIds) {
9353        mHandler.post(new Runnable() {
9354            @Override
9355            public void run() {
9356                try {
9357                    final IActivityManager am = ActivityManagerNative.getDefault();
9358                    if (am == null) return;
9359                    final int[] resolvedUserIds;
9360                    if (userIds == null) {
9361                        resolvedUserIds = am.getRunningUserIds();
9362                    } else {
9363                        resolvedUserIds = userIds;
9364                    }
9365                    for (int id : resolvedUserIds) {
9366                        final Intent intent = new Intent(action,
9367                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9368                        if (extras != null) {
9369                            intent.putExtras(extras);
9370                        }
9371                        if (targetPkg != null) {
9372                            intent.setPackage(targetPkg);
9373                        }
9374                        // Modify the UID when posting to other users
9375                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9376                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9377                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9378                            intent.putExtra(Intent.EXTRA_UID, uid);
9379                        }
9380                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9381                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9382                        if (DEBUG_BROADCASTS) {
9383                            RuntimeException here = new RuntimeException("here");
9384                            here.fillInStackTrace();
9385                            Slog.d(TAG, "Sending to user " + id + ": "
9386                                    + intent.toShortString(false, true, false, false)
9387                                    + " " + intent.getExtras(), here);
9388                        }
9389                        am.broadcastIntent(null, intent, null, finishedReceiver,
9390                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9391                                null, finishedReceiver != null, false, id);
9392                    }
9393                } catch (RemoteException ex) {
9394                }
9395            }
9396        });
9397    }
9398
9399    /**
9400     * Check if the external storage media is available. This is true if there
9401     * is a mounted external storage medium or if the external storage is
9402     * emulated.
9403     */
9404    private boolean isExternalMediaAvailable() {
9405        return mMediaMounted || Environment.isExternalStorageEmulated();
9406    }
9407
9408    @Override
9409    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9410        // writer
9411        synchronized (mPackages) {
9412            if (!isExternalMediaAvailable()) {
9413                // If the external storage is no longer mounted at this point,
9414                // the caller may not have been able to delete all of this
9415                // packages files and can not delete any more.  Bail.
9416                return null;
9417            }
9418            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9419            if (lastPackage != null) {
9420                pkgs.remove(lastPackage);
9421            }
9422            if (pkgs.size() > 0) {
9423                return pkgs.get(0);
9424            }
9425        }
9426        return null;
9427    }
9428
9429    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9430        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9431                userId, andCode ? 1 : 0, packageName);
9432        if (mSystemReady) {
9433            msg.sendToTarget();
9434        } else {
9435            if (mPostSystemReadyMessages == null) {
9436                mPostSystemReadyMessages = new ArrayList<>();
9437            }
9438            mPostSystemReadyMessages.add(msg);
9439        }
9440    }
9441
9442    void startCleaningPackages() {
9443        // reader
9444        synchronized (mPackages) {
9445            if (!isExternalMediaAvailable()) {
9446                return;
9447            }
9448            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9449                return;
9450            }
9451        }
9452        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9453        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9454        IActivityManager am = ActivityManagerNative.getDefault();
9455        if (am != null) {
9456            try {
9457                am.startService(null, intent, null, mContext.getOpPackageName(),
9458                        UserHandle.USER_OWNER);
9459            } catch (RemoteException e) {
9460            }
9461        }
9462    }
9463
9464    @Override
9465    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9466            int installFlags, String installerPackageName, VerificationParams verificationParams,
9467            String packageAbiOverride) {
9468        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9469                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9470    }
9471
9472    @Override
9473    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9474            int installFlags, String installerPackageName, VerificationParams verificationParams,
9475            String packageAbiOverride, int userId) {
9476        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9477
9478        final int callingUid = Binder.getCallingUid();
9479        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9480
9481        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9482            try {
9483                if (observer != null) {
9484                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9485                }
9486            } catch (RemoteException re) {
9487            }
9488            return;
9489        }
9490
9491        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9492            installFlags |= PackageManager.INSTALL_FROM_ADB;
9493
9494        } else {
9495            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9496            // about installerPackageName.
9497
9498            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9499            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9500        }
9501
9502        UserHandle user;
9503        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9504            user = UserHandle.ALL;
9505        } else {
9506            user = new UserHandle(userId);
9507        }
9508
9509        // Only system components can circumvent runtime permissions when installing.
9510        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9511                && mContext.checkCallingOrSelfPermission(Manifest.permission
9512                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9513            throw new SecurityException("You need the "
9514                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9515                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9516        }
9517
9518        verificationParams.setInstallerUid(callingUid);
9519
9520        final File originFile = new File(originPath);
9521        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9522
9523        final Message msg = mHandler.obtainMessage(INIT_COPY);
9524        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9525                null, verificationParams, user, packageAbiOverride, null);
9526        mHandler.sendMessage(msg);
9527    }
9528
9529    void installStage(String packageName, File stagedDir, String stagedCid,
9530            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9531            String installerPackageName, int installerUid, UserHandle user) {
9532        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9533                params.referrerUri, installerUid, null);
9534        verifParams.setInstallerUid(installerUid);
9535
9536        final OriginInfo origin;
9537        if (stagedDir != null) {
9538            origin = OriginInfo.fromStagedFile(stagedDir);
9539        } else {
9540            origin = OriginInfo.fromStagedContainer(stagedCid);
9541        }
9542
9543        final Message msg = mHandler.obtainMessage(INIT_COPY);
9544        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9545                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9546                params.grantedRuntimePermissions);
9547        mHandler.sendMessage(msg);
9548    }
9549
9550    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9551        Bundle extras = new Bundle(1);
9552        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9553
9554        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9555                packageName, extras, null, null, new int[] {userId});
9556        try {
9557            IActivityManager am = ActivityManagerNative.getDefault();
9558            final boolean isSystem =
9559                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9560            if (isSystem && am.isUserRunning(userId, false)) {
9561                // The just-installed/enabled app is bundled on the system, so presumed
9562                // to be able to run automatically without needing an explicit launch.
9563                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9564                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9565                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9566                        .setPackage(packageName);
9567                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9568                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9569            }
9570        } catch (RemoteException e) {
9571            // shouldn't happen
9572            Slog.w(TAG, "Unable to bootstrap installed package", e);
9573        }
9574    }
9575
9576    @Override
9577    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9578            int userId) {
9579        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9580        PackageSetting pkgSetting;
9581        final int uid = Binder.getCallingUid();
9582        enforceCrossUserPermission(uid, userId, true, true,
9583                "setApplicationHiddenSetting for user " + userId);
9584
9585        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9586            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9587            return false;
9588        }
9589
9590        long callingId = Binder.clearCallingIdentity();
9591        try {
9592            boolean sendAdded = false;
9593            boolean sendRemoved = false;
9594            // writer
9595            synchronized (mPackages) {
9596                pkgSetting = mSettings.mPackages.get(packageName);
9597                if (pkgSetting == null) {
9598                    return false;
9599                }
9600                if (pkgSetting.getHidden(userId) != hidden) {
9601                    pkgSetting.setHidden(hidden, userId);
9602                    mSettings.writePackageRestrictionsLPr(userId);
9603                    if (hidden) {
9604                        sendRemoved = true;
9605                    } else {
9606                        sendAdded = true;
9607                    }
9608                }
9609            }
9610            if (sendAdded) {
9611                sendPackageAddedForUser(packageName, pkgSetting, userId);
9612                return true;
9613            }
9614            if (sendRemoved) {
9615                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9616                        "hiding pkg");
9617                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9618                return true;
9619            }
9620        } finally {
9621            Binder.restoreCallingIdentity(callingId);
9622        }
9623        return false;
9624    }
9625
9626    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9627            int userId) {
9628        final PackageRemovedInfo info = new PackageRemovedInfo();
9629        info.removedPackage = packageName;
9630        info.removedUsers = new int[] {userId};
9631        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9632        info.sendBroadcast(false, false, false);
9633    }
9634
9635    /**
9636     * Returns true if application is not found or there was an error. Otherwise it returns
9637     * the hidden state of the package for the given user.
9638     */
9639    @Override
9640    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9642        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9643                false, "getApplicationHidden for user " + userId);
9644        PackageSetting pkgSetting;
9645        long callingId = Binder.clearCallingIdentity();
9646        try {
9647            // writer
9648            synchronized (mPackages) {
9649                pkgSetting = mSettings.mPackages.get(packageName);
9650                if (pkgSetting == null) {
9651                    return true;
9652                }
9653                return pkgSetting.getHidden(userId);
9654            }
9655        } finally {
9656            Binder.restoreCallingIdentity(callingId);
9657        }
9658    }
9659
9660    /**
9661     * @hide
9662     */
9663    @Override
9664    public int installExistingPackageAsUser(String packageName, int userId) {
9665        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9666                null);
9667        PackageSetting pkgSetting;
9668        final int uid = Binder.getCallingUid();
9669        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9670                + userId);
9671        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9672            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9673        }
9674
9675        long callingId = Binder.clearCallingIdentity();
9676        try {
9677            boolean sendAdded = false;
9678
9679            // writer
9680            synchronized (mPackages) {
9681                pkgSetting = mSettings.mPackages.get(packageName);
9682                if (pkgSetting == null) {
9683                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9684                }
9685                if (!pkgSetting.getInstalled(userId)) {
9686                    pkgSetting.setInstalled(true, userId);
9687                    pkgSetting.setHidden(false, userId);
9688                    mSettings.writePackageRestrictionsLPr(userId);
9689                    sendAdded = true;
9690                }
9691            }
9692
9693            if (sendAdded) {
9694                sendPackageAddedForUser(packageName, pkgSetting, userId);
9695            }
9696        } finally {
9697            Binder.restoreCallingIdentity(callingId);
9698        }
9699
9700        return PackageManager.INSTALL_SUCCEEDED;
9701    }
9702
9703    boolean isUserRestricted(int userId, String restrictionKey) {
9704        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9705        if (restrictions.getBoolean(restrictionKey, false)) {
9706            Log.w(TAG, "User is restricted: " + restrictionKey);
9707            return true;
9708        }
9709        return false;
9710    }
9711
9712    @Override
9713    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9714        mContext.enforceCallingOrSelfPermission(
9715                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9716                "Only package verification agents can verify applications");
9717
9718        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9719        final PackageVerificationResponse response = new PackageVerificationResponse(
9720                verificationCode, Binder.getCallingUid());
9721        msg.arg1 = id;
9722        msg.obj = response;
9723        mHandler.sendMessage(msg);
9724    }
9725
9726    @Override
9727    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9728            long millisecondsToDelay) {
9729        mContext.enforceCallingOrSelfPermission(
9730                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9731                "Only package verification agents can extend verification timeouts");
9732
9733        final PackageVerificationState state = mPendingVerification.get(id);
9734        final PackageVerificationResponse response = new PackageVerificationResponse(
9735                verificationCodeAtTimeout, Binder.getCallingUid());
9736
9737        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9738            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9739        }
9740        if (millisecondsToDelay < 0) {
9741            millisecondsToDelay = 0;
9742        }
9743        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9744                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9745            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9746        }
9747
9748        if ((state != null) && !state.timeoutExtended()) {
9749            state.extendTimeout();
9750
9751            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9752            msg.arg1 = id;
9753            msg.obj = response;
9754            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9755        }
9756    }
9757
9758    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9759            int verificationCode, UserHandle user) {
9760        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9761        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9762        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9763        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9764        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9765
9766        mContext.sendBroadcastAsUser(intent, user,
9767                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9768    }
9769
9770    private ComponentName matchComponentForVerifier(String packageName,
9771            List<ResolveInfo> receivers) {
9772        ActivityInfo targetReceiver = null;
9773
9774        final int NR = receivers.size();
9775        for (int i = 0; i < NR; i++) {
9776            final ResolveInfo info = receivers.get(i);
9777            if (info.activityInfo == null) {
9778                continue;
9779            }
9780
9781            if (packageName.equals(info.activityInfo.packageName)) {
9782                targetReceiver = info.activityInfo;
9783                break;
9784            }
9785        }
9786
9787        if (targetReceiver == null) {
9788            return null;
9789        }
9790
9791        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9792    }
9793
9794    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9795            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9796        if (pkgInfo.verifiers.length == 0) {
9797            return null;
9798        }
9799
9800        final int N = pkgInfo.verifiers.length;
9801        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9802        for (int i = 0; i < N; i++) {
9803            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9804
9805            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9806                    receivers);
9807            if (comp == null) {
9808                continue;
9809            }
9810
9811            final int verifierUid = getUidForVerifier(verifierInfo);
9812            if (verifierUid == -1) {
9813                continue;
9814            }
9815
9816            if (DEBUG_VERIFY) {
9817                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9818                        + " with the correct signature");
9819            }
9820            sufficientVerifiers.add(comp);
9821            verificationState.addSufficientVerifier(verifierUid);
9822        }
9823
9824        return sufficientVerifiers;
9825    }
9826
9827    private int getUidForVerifier(VerifierInfo verifierInfo) {
9828        synchronized (mPackages) {
9829            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9830            if (pkg == null) {
9831                return -1;
9832            } else if (pkg.mSignatures.length != 1) {
9833                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9834                        + " has more than one signature; ignoring");
9835                return -1;
9836            }
9837
9838            /*
9839             * If the public key of the package's signature does not match
9840             * our expected public key, then this is a different package and
9841             * we should skip.
9842             */
9843
9844            final byte[] expectedPublicKey;
9845            try {
9846                final Signature verifierSig = pkg.mSignatures[0];
9847                final PublicKey publicKey = verifierSig.getPublicKey();
9848                expectedPublicKey = publicKey.getEncoded();
9849            } catch (CertificateException e) {
9850                return -1;
9851            }
9852
9853            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9854
9855            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9856                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9857                        + " does not have the expected public key; ignoring");
9858                return -1;
9859            }
9860
9861            return pkg.applicationInfo.uid;
9862        }
9863    }
9864
9865    @Override
9866    public void finishPackageInstall(int token) {
9867        enforceSystemOrRoot("Only the system is allowed to finish installs");
9868
9869        if (DEBUG_INSTALL) {
9870            Slog.v(TAG, "BM finishing package install for " + token);
9871        }
9872
9873        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9874        mHandler.sendMessage(msg);
9875    }
9876
9877    /**
9878     * Get the verification agent timeout.
9879     *
9880     * @return verification timeout in milliseconds
9881     */
9882    private long getVerificationTimeout() {
9883        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9884                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9885                DEFAULT_VERIFICATION_TIMEOUT);
9886    }
9887
9888    /**
9889     * Get the default verification agent response code.
9890     *
9891     * @return default verification response code
9892     */
9893    private int getDefaultVerificationResponse() {
9894        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9895                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9896                DEFAULT_VERIFICATION_RESPONSE);
9897    }
9898
9899    /**
9900     * Check whether or not package verification has been enabled.
9901     *
9902     * @return true if verification should be performed
9903     */
9904    private boolean isVerificationEnabled(int userId, int installFlags) {
9905        if (!DEFAULT_VERIFY_ENABLE) {
9906            return false;
9907        }
9908
9909        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9910
9911        // Check if installing from ADB
9912        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9913            // Do not run verification in a test harness environment
9914            if (ActivityManager.isRunningInTestHarness()) {
9915                return false;
9916            }
9917            if (ensureVerifyAppsEnabled) {
9918                return true;
9919            }
9920            // Check if the developer does not want package verification for ADB installs
9921            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9922                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9923                return false;
9924            }
9925        }
9926
9927        if (ensureVerifyAppsEnabled) {
9928            return true;
9929        }
9930
9931        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9932                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9933    }
9934
9935    @Override
9936    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9937            throws RemoteException {
9938        mContext.enforceCallingOrSelfPermission(
9939                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9940                "Only intentfilter verification agents can verify applications");
9941
9942        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9943        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9944                Binder.getCallingUid(), verificationCode, failedDomains);
9945        msg.arg1 = id;
9946        msg.obj = response;
9947        mHandler.sendMessage(msg);
9948    }
9949
9950    @Override
9951    public int getIntentVerificationStatus(String packageName, int userId) {
9952        synchronized (mPackages) {
9953            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9954        }
9955    }
9956
9957    @Override
9958    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9959        mContext.enforceCallingOrSelfPermission(
9960                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9961
9962        boolean result = false;
9963        synchronized (mPackages) {
9964            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9965        }
9966        if (result) {
9967            scheduleWritePackageRestrictionsLocked(userId);
9968        }
9969        return result;
9970    }
9971
9972    @Override
9973    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9974        synchronized (mPackages) {
9975            return mSettings.getIntentFilterVerificationsLPr(packageName);
9976        }
9977    }
9978
9979    @Override
9980    public List<IntentFilter> getAllIntentFilters(String packageName) {
9981        if (TextUtils.isEmpty(packageName)) {
9982            return Collections.<IntentFilter>emptyList();
9983        }
9984        synchronized (mPackages) {
9985            PackageParser.Package pkg = mPackages.get(packageName);
9986            if (pkg == null || pkg.activities == null) {
9987                return Collections.<IntentFilter>emptyList();
9988            }
9989            final int count = pkg.activities.size();
9990            ArrayList<IntentFilter> result = new ArrayList<>();
9991            for (int n=0; n<count; n++) {
9992                PackageParser.Activity activity = pkg.activities.get(n);
9993                if (activity.intents != null || activity.intents.size() > 0) {
9994                    result.addAll(activity.intents);
9995                }
9996            }
9997            return result;
9998        }
9999    }
10000
10001    @Override
10002    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10003        mContext.enforceCallingOrSelfPermission(
10004                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10005
10006        synchronized (mPackages) {
10007            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10008            if (packageName != null) {
10009                result |= updateIntentVerificationStatus(packageName,
10010                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10011                        userId);
10012                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10013                        packageName, userId);
10014            }
10015            return result;
10016        }
10017    }
10018
10019    @Override
10020    public String getDefaultBrowserPackageName(int userId) {
10021        synchronized (mPackages) {
10022            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10023        }
10024    }
10025
10026    /**
10027     * Get the "allow unknown sources" setting.
10028     *
10029     * @return the current "allow unknown sources" setting
10030     */
10031    private int getUnknownSourcesSettings() {
10032        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10033                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10034                -1);
10035    }
10036
10037    @Override
10038    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10039        final int uid = Binder.getCallingUid();
10040        // writer
10041        synchronized (mPackages) {
10042            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10043            if (targetPackageSetting == null) {
10044                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10045            }
10046
10047            PackageSetting installerPackageSetting;
10048            if (installerPackageName != null) {
10049                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10050                if (installerPackageSetting == null) {
10051                    throw new IllegalArgumentException("Unknown installer package: "
10052                            + installerPackageName);
10053                }
10054            } else {
10055                installerPackageSetting = null;
10056            }
10057
10058            Signature[] callerSignature;
10059            Object obj = mSettings.getUserIdLPr(uid);
10060            if (obj != null) {
10061                if (obj instanceof SharedUserSetting) {
10062                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10063                } else if (obj instanceof PackageSetting) {
10064                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10065                } else {
10066                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10067                }
10068            } else {
10069                throw new SecurityException("Unknown calling uid " + uid);
10070            }
10071
10072            // Verify: can't set installerPackageName to a package that is
10073            // not signed with the same cert as the caller.
10074            if (installerPackageSetting != null) {
10075                if (compareSignatures(callerSignature,
10076                        installerPackageSetting.signatures.mSignatures)
10077                        != PackageManager.SIGNATURE_MATCH) {
10078                    throw new SecurityException(
10079                            "Caller does not have same cert as new installer package "
10080                            + installerPackageName);
10081                }
10082            }
10083
10084            // Verify: if target already has an installer package, it must
10085            // be signed with the same cert as the caller.
10086            if (targetPackageSetting.installerPackageName != null) {
10087                PackageSetting setting = mSettings.mPackages.get(
10088                        targetPackageSetting.installerPackageName);
10089                // If the currently set package isn't valid, then it's always
10090                // okay to change it.
10091                if (setting != null) {
10092                    if (compareSignatures(callerSignature,
10093                            setting.signatures.mSignatures)
10094                            != PackageManager.SIGNATURE_MATCH) {
10095                        throw new SecurityException(
10096                                "Caller does not have same cert as old installer package "
10097                                + targetPackageSetting.installerPackageName);
10098                    }
10099                }
10100            }
10101
10102            // Okay!
10103            targetPackageSetting.installerPackageName = installerPackageName;
10104            scheduleWriteSettingsLocked();
10105        }
10106    }
10107
10108    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10109        // Queue up an async operation since the package installation may take a little while.
10110        mHandler.post(new Runnable() {
10111            public void run() {
10112                mHandler.removeCallbacks(this);
10113                 // Result object to be returned
10114                PackageInstalledInfo res = new PackageInstalledInfo();
10115                res.returnCode = currentStatus;
10116                res.uid = -1;
10117                res.pkg = null;
10118                res.removedInfo = new PackageRemovedInfo();
10119                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10120                    args.doPreInstall(res.returnCode);
10121                    synchronized (mInstallLock) {
10122                        installPackageLI(args, res);
10123                    }
10124                    args.doPostInstall(res.returnCode, res.uid);
10125                }
10126
10127                // A restore should be performed at this point if (a) the install
10128                // succeeded, (b) the operation is not an update, and (c) the new
10129                // package has not opted out of backup participation.
10130                final boolean update = res.removedInfo.removedPackage != null;
10131                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10132                boolean doRestore = !update
10133                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10134
10135                // Set up the post-install work request bookkeeping.  This will be used
10136                // and cleaned up by the post-install event handling regardless of whether
10137                // there's a restore pass performed.  Token values are >= 1.
10138                int token;
10139                if (mNextInstallToken < 0) mNextInstallToken = 1;
10140                token = mNextInstallToken++;
10141
10142                PostInstallData data = new PostInstallData(args, res);
10143                mRunningInstalls.put(token, data);
10144                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10145
10146                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10147                    // Pass responsibility to the Backup Manager.  It will perform a
10148                    // restore if appropriate, then pass responsibility back to the
10149                    // Package Manager to run the post-install observer callbacks
10150                    // and broadcasts.
10151                    IBackupManager bm = IBackupManager.Stub.asInterface(
10152                            ServiceManager.getService(Context.BACKUP_SERVICE));
10153                    if (bm != null) {
10154                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10155                                + " to BM for possible restore");
10156                        try {
10157                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10158                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10159                            } else {
10160                                doRestore = false;
10161                            }
10162                        } catch (RemoteException e) {
10163                            // can't happen; the backup manager is local
10164                        } catch (Exception e) {
10165                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10166                            doRestore = false;
10167                        }
10168                    } else {
10169                        Slog.e(TAG, "Backup Manager not found!");
10170                        doRestore = false;
10171                    }
10172                }
10173
10174                if (!doRestore) {
10175                    // No restore possible, or the Backup Manager was mysteriously not
10176                    // available -- just fire the post-install work request directly.
10177                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10178                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10179                    mHandler.sendMessage(msg);
10180                }
10181            }
10182        });
10183    }
10184
10185    private abstract class HandlerParams {
10186        private static final int MAX_RETRIES = 4;
10187
10188        /**
10189         * Number of times startCopy() has been attempted and had a non-fatal
10190         * error.
10191         */
10192        private int mRetries = 0;
10193
10194        /** User handle for the user requesting the information or installation. */
10195        private final UserHandle mUser;
10196
10197        HandlerParams(UserHandle user) {
10198            mUser = user;
10199        }
10200
10201        UserHandle getUser() {
10202            return mUser;
10203        }
10204
10205        final boolean startCopy() {
10206            boolean res;
10207            try {
10208                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10209
10210                if (++mRetries > MAX_RETRIES) {
10211                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10212                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10213                    handleServiceError();
10214                    return false;
10215                } else {
10216                    handleStartCopy();
10217                    res = true;
10218                }
10219            } catch (RemoteException e) {
10220                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10221                mHandler.sendEmptyMessage(MCS_RECONNECT);
10222                res = false;
10223            }
10224            handleReturnCode();
10225            return res;
10226        }
10227
10228        final void serviceError() {
10229            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10230            handleServiceError();
10231            handleReturnCode();
10232        }
10233
10234        abstract void handleStartCopy() throws RemoteException;
10235        abstract void handleServiceError();
10236        abstract void handleReturnCode();
10237    }
10238
10239    class MeasureParams extends HandlerParams {
10240        private final PackageStats mStats;
10241        private boolean mSuccess;
10242
10243        private final IPackageStatsObserver mObserver;
10244
10245        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10246            super(new UserHandle(stats.userHandle));
10247            mObserver = observer;
10248            mStats = stats;
10249        }
10250
10251        @Override
10252        public String toString() {
10253            return "MeasureParams{"
10254                + Integer.toHexString(System.identityHashCode(this))
10255                + " " + mStats.packageName + "}";
10256        }
10257
10258        @Override
10259        void handleStartCopy() throws RemoteException {
10260            synchronized (mInstallLock) {
10261                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10262            }
10263
10264            if (mSuccess) {
10265                final boolean mounted;
10266                if (Environment.isExternalStorageEmulated()) {
10267                    mounted = true;
10268                } else {
10269                    final String status = Environment.getExternalStorageState();
10270                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10271                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10272                }
10273
10274                if (mounted) {
10275                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10276
10277                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10278                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10279
10280                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10281                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10282
10283                    // Always subtract cache size, since it's a subdirectory
10284                    mStats.externalDataSize -= mStats.externalCacheSize;
10285
10286                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10287                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10288
10289                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10290                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10291                }
10292            }
10293        }
10294
10295        @Override
10296        void handleReturnCode() {
10297            if (mObserver != null) {
10298                try {
10299                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10300                } catch (RemoteException e) {
10301                    Slog.i(TAG, "Observer no longer exists.");
10302                }
10303            }
10304        }
10305
10306        @Override
10307        void handleServiceError() {
10308            Slog.e(TAG, "Could not measure application " + mStats.packageName
10309                            + " external storage");
10310        }
10311    }
10312
10313    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10314            throws RemoteException {
10315        long result = 0;
10316        for (File path : paths) {
10317            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10318        }
10319        return result;
10320    }
10321
10322    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10323        for (File path : paths) {
10324            try {
10325                mcs.clearDirectory(path.getAbsolutePath());
10326            } catch (RemoteException e) {
10327            }
10328        }
10329    }
10330
10331    static class OriginInfo {
10332        /**
10333         * Location where install is coming from, before it has been
10334         * copied/renamed into place. This could be a single monolithic APK
10335         * file, or a cluster directory. This location may be untrusted.
10336         */
10337        final File file;
10338        final String cid;
10339
10340        /**
10341         * Flag indicating that {@link #file} or {@link #cid} has already been
10342         * staged, meaning downstream users don't need to defensively copy the
10343         * contents.
10344         */
10345        final boolean staged;
10346
10347        /**
10348         * Flag indicating that {@link #file} or {@link #cid} is an already
10349         * installed app that is being moved.
10350         */
10351        final boolean existing;
10352
10353        final String resolvedPath;
10354        final File resolvedFile;
10355
10356        static OriginInfo fromNothing() {
10357            return new OriginInfo(null, null, false, false);
10358        }
10359
10360        static OriginInfo fromUntrustedFile(File file) {
10361            return new OriginInfo(file, null, false, false);
10362        }
10363
10364        static OriginInfo fromExistingFile(File file) {
10365            return new OriginInfo(file, null, false, true);
10366        }
10367
10368        static OriginInfo fromStagedFile(File file) {
10369            return new OriginInfo(file, null, true, false);
10370        }
10371
10372        static OriginInfo fromStagedContainer(String cid) {
10373            return new OriginInfo(null, cid, true, false);
10374        }
10375
10376        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10377            this.file = file;
10378            this.cid = cid;
10379            this.staged = staged;
10380            this.existing = existing;
10381
10382            if (cid != null) {
10383                resolvedPath = PackageHelper.getSdDir(cid);
10384                resolvedFile = new File(resolvedPath);
10385            } else if (file != null) {
10386                resolvedPath = file.getAbsolutePath();
10387                resolvedFile = file;
10388            } else {
10389                resolvedPath = null;
10390                resolvedFile = null;
10391            }
10392        }
10393    }
10394
10395    class MoveInfo {
10396        final int moveId;
10397        final String fromUuid;
10398        final String toUuid;
10399        final String packageName;
10400        final String dataAppName;
10401        final int appId;
10402        final String seinfo;
10403
10404        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10405                String dataAppName, int appId, String seinfo) {
10406            this.moveId = moveId;
10407            this.fromUuid = fromUuid;
10408            this.toUuid = toUuid;
10409            this.packageName = packageName;
10410            this.dataAppName = dataAppName;
10411            this.appId = appId;
10412            this.seinfo = seinfo;
10413        }
10414    }
10415
10416    class InstallParams extends HandlerParams {
10417        final OriginInfo origin;
10418        final MoveInfo move;
10419        final IPackageInstallObserver2 observer;
10420        int installFlags;
10421        final String installerPackageName;
10422        final String volumeUuid;
10423        final VerificationParams verificationParams;
10424        private InstallArgs mArgs;
10425        private int mRet;
10426        final String packageAbiOverride;
10427        final String[] grantedRuntimePermissions;
10428
10429
10430        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10431                int installFlags, String installerPackageName, String volumeUuid,
10432                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10433                String[] grantedPermissions) {
10434            super(user);
10435            this.origin = origin;
10436            this.move = move;
10437            this.observer = observer;
10438            this.installFlags = installFlags;
10439            this.installerPackageName = installerPackageName;
10440            this.volumeUuid = volumeUuid;
10441            this.verificationParams = verificationParams;
10442            this.packageAbiOverride = packageAbiOverride;
10443            this.grantedRuntimePermissions = grantedPermissions;
10444        }
10445
10446        @Override
10447        public String toString() {
10448            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10449                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10450        }
10451
10452        public ManifestDigest getManifestDigest() {
10453            if (verificationParams == null) {
10454                return null;
10455            }
10456            return verificationParams.getManifestDigest();
10457        }
10458
10459        private int installLocationPolicy(PackageInfoLite pkgLite) {
10460            String packageName = pkgLite.packageName;
10461            int installLocation = pkgLite.installLocation;
10462            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10463            // reader
10464            synchronized (mPackages) {
10465                PackageParser.Package pkg = mPackages.get(packageName);
10466                if (pkg != null) {
10467                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10468                        // Check for downgrading.
10469                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10470                            try {
10471                                checkDowngrade(pkg, pkgLite);
10472                            } catch (PackageManagerException e) {
10473                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10474                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10475                            }
10476                        }
10477                        // Check for updated system application.
10478                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10479                            if (onSd) {
10480                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10481                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10482                            }
10483                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10484                        } else {
10485                            if (onSd) {
10486                                // Install flag overrides everything.
10487                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10488                            }
10489                            // If current upgrade specifies particular preference
10490                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10491                                // Application explicitly specified internal.
10492                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10493                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10494                                // App explictly prefers external. Let policy decide
10495                            } else {
10496                                // Prefer previous location
10497                                if (isExternal(pkg)) {
10498                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10499                                }
10500                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10501                            }
10502                        }
10503                    } else {
10504                        // Invalid install. Return error code
10505                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10506                    }
10507                }
10508            }
10509            // All the special cases have been taken care of.
10510            // Return result based on recommended install location.
10511            if (onSd) {
10512                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10513            }
10514            return pkgLite.recommendedInstallLocation;
10515        }
10516
10517        /*
10518         * Invoke remote method to get package information and install
10519         * location values. Override install location based on default
10520         * policy if needed and then create install arguments based
10521         * on the install location.
10522         */
10523        public void handleStartCopy() throws RemoteException {
10524            int ret = PackageManager.INSTALL_SUCCEEDED;
10525
10526            // If we're already staged, we've firmly committed to an install location
10527            if (origin.staged) {
10528                if (origin.file != null) {
10529                    installFlags |= PackageManager.INSTALL_INTERNAL;
10530                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10531                } else if (origin.cid != null) {
10532                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10533                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10534                } else {
10535                    throw new IllegalStateException("Invalid stage location");
10536                }
10537            }
10538
10539            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10540            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10541
10542            PackageInfoLite pkgLite = null;
10543
10544            if (onInt && onSd) {
10545                // Check if both bits are set.
10546                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10547                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10548            } else {
10549                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10550                        packageAbiOverride);
10551
10552                /*
10553                 * If we have too little free space, try to free cache
10554                 * before giving up.
10555                 */
10556                if (!origin.staged && pkgLite.recommendedInstallLocation
10557                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10558                    // TODO: focus freeing disk space on the target device
10559                    final StorageManager storage = StorageManager.from(mContext);
10560                    final long lowThreshold = storage.getStorageLowBytes(
10561                            Environment.getDataDirectory());
10562
10563                    final long sizeBytes = mContainerService.calculateInstalledSize(
10564                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10565
10566                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10567                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10568                                installFlags, packageAbiOverride);
10569                    }
10570
10571                    /*
10572                     * The cache free must have deleted the file we
10573                     * downloaded to install.
10574                     *
10575                     * TODO: fix the "freeCache" call to not delete
10576                     *       the file we care about.
10577                     */
10578                    if (pkgLite.recommendedInstallLocation
10579                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10580                        pkgLite.recommendedInstallLocation
10581                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10582                    }
10583                }
10584            }
10585
10586            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10587                int loc = pkgLite.recommendedInstallLocation;
10588                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10589                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10590                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10591                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10592                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10593                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10594                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10595                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10596                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10597                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10598                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10599                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10600                } else {
10601                    // Override with defaults if needed.
10602                    loc = installLocationPolicy(pkgLite);
10603                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10604                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10605                    } else if (!onSd && !onInt) {
10606                        // Override install location with flags
10607                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10608                            // Set the flag to install on external media.
10609                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10610                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10611                        } else {
10612                            // Make sure the flag for installing on external
10613                            // media is unset
10614                            installFlags |= PackageManager.INSTALL_INTERNAL;
10615                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10616                        }
10617                    }
10618                }
10619            }
10620
10621            final InstallArgs args = createInstallArgs(this);
10622            mArgs = args;
10623
10624            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10625                 /*
10626                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10627                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10628                 */
10629                int userIdentifier = getUser().getIdentifier();
10630                if (userIdentifier == UserHandle.USER_ALL
10631                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10632                    userIdentifier = UserHandle.USER_OWNER;
10633                }
10634
10635                /*
10636                 * Determine if we have any installed package verifiers. If we
10637                 * do, then we'll defer to them to verify the packages.
10638                 */
10639                final int requiredUid = mRequiredVerifierPackage == null ? -1
10640                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10641                if (!origin.existing && requiredUid != -1
10642                        && isVerificationEnabled(userIdentifier, installFlags)) {
10643                    final Intent verification = new Intent(
10644                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10645                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10646                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10647                            PACKAGE_MIME_TYPE);
10648                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10649
10650                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10651                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10652                            0 /* TODO: Which userId? */);
10653
10654                    if (DEBUG_VERIFY) {
10655                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10656                                + verification.toString() + " with " + pkgLite.verifiers.length
10657                                + " optional verifiers");
10658                    }
10659
10660                    final int verificationId = mPendingVerificationToken++;
10661
10662                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10663
10664                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10665                            installerPackageName);
10666
10667                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10668                            installFlags);
10669
10670                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10671                            pkgLite.packageName);
10672
10673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10674                            pkgLite.versionCode);
10675
10676                    if (verificationParams != null) {
10677                        if (verificationParams.getVerificationURI() != null) {
10678                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10679                                 verificationParams.getVerificationURI());
10680                        }
10681                        if (verificationParams.getOriginatingURI() != null) {
10682                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10683                                  verificationParams.getOriginatingURI());
10684                        }
10685                        if (verificationParams.getReferrer() != null) {
10686                            verification.putExtra(Intent.EXTRA_REFERRER,
10687                                  verificationParams.getReferrer());
10688                        }
10689                        if (verificationParams.getOriginatingUid() >= 0) {
10690                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10691                                  verificationParams.getOriginatingUid());
10692                        }
10693                        if (verificationParams.getInstallerUid() >= 0) {
10694                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10695                                  verificationParams.getInstallerUid());
10696                        }
10697                    }
10698
10699                    final PackageVerificationState verificationState = new PackageVerificationState(
10700                            requiredUid, args);
10701
10702                    mPendingVerification.append(verificationId, verificationState);
10703
10704                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10705                            receivers, verificationState);
10706
10707                    // Apps installed for "all" users use the device owner to verify the app
10708                    UserHandle verifierUser = getUser();
10709                    if (verifierUser == UserHandle.ALL) {
10710                        verifierUser = UserHandle.OWNER;
10711                    }
10712
10713                    /*
10714                     * If any sufficient verifiers were listed in the package
10715                     * manifest, attempt to ask them.
10716                     */
10717                    if (sufficientVerifiers != null) {
10718                        final int N = sufficientVerifiers.size();
10719                        if (N == 0) {
10720                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10721                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10722                        } else {
10723                            for (int i = 0; i < N; i++) {
10724                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10725
10726                                final Intent sufficientIntent = new Intent(verification);
10727                                sufficientIntent.setComponent(verifierComponent);
10728                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10729                            }
10730                        }
10731                    }
10732
10733                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10734                            mRequiredVerifierPackage, receivers);
10735                    if (ret == PackageManager.INSTALL_SUCCEEDED
10736                            && mRequiredVerifierPackage != null) {
10737                        /*
10738                         * Send the intent to the required verification agent,
10739                         * but only start the verification timeout after the
10740                         * target BroadcastReceivers have run.
10741                         */
10742                        verification.setComponent(requiredVerifierComponent);
10743                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10744                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10745                                new BroadcastReceiver() {
10746                                    @Override
10747                                    public void onReceive(Context context, Intent intent) {
10748                                        final Message msg = mHandler
10749                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10750                                        msg.arg1 = verificationId;
10751                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10752                                    }
10753                                }, null, 0, null, null);
10754
10755                        /*
10756                         * We don't want the copy to proceed until verification
10757                         * succeeds, so null out this field.
10758                         */
10759                        mArgs = null;
10760                    }
10761                } else {
10762                    /*
10763                     * No package verification is enabled, so immediately start
10764                     * the remote call to initiate copy using temporary file.
10765                     */
10766                    ret = args.copyApk(mContainerService, true);
10767                }
10768            }
10769
10770            mRet = ret;
10771        }
10772
10773        @Override
10774        void handleReturnCode() {
10775            // If mArgs is null, then MCS couldn't be reached. When it
10776            // reconnects, it will try again to install. At that point, this
10777            // will succeed.
10778            if (mArgs != null) {
10779                processPendingInstall(mArgs, mRet);
10780            }
10781        }
10782
10783        @Override
10784        void handleServiceError() {
10785            mArgs = createInstallArgs(this);
10786            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10787        }
10788
10789        public boolean isForwardLocked() {
10790            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10791        }
10792    }
10793
10794    /**
10795     * Used during creation of InstallArgs
10796     *
10797     * @param installFlags package installation flags
10798     * @return true if should be installed on external storage
10799     */
10800    private static boolean installOnExternalAsec(int installFlags) {
10801        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10802            return false;
10803        }
10804        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10805            return true;
10806        }
10807        return false;
10808    }
10809
10810    /**
10811     * Used during creation of InstallArgs
10812     *
10813     * @param installFlags package installation flags
10814     * @return true if should be installed as forward locked
10815     */
10816    private static boolean installForwardLocked(int installFlags) {
10817        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10818    }
10819
10820    private InstallArgs createInstallArgs(InstallParams params) {
10821        if (params.move != null) {
10822            return new MoveInstallArgs(params);
10823        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10824            return new AsecInstallArgs(params);
10825        } else {
10826            return new FileInstallArgs(params);
10827        }
10828    }
10829
10830    /**
10831     * Create args that describe an existing installed package. Typically used
10832     * when cleaning up old installs, or used as a move source.
10833     */
10834    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10835            String resourcePath, String[] instructionSets) {
10836        final boolean isInAsec;
10837        if (installOnExternalAsec(installFlags)) {
10838            /* Apps on SD card are always in ASEC containers. */
10839            isInAsec = true;
10840        } else if (installForwardLocked(installFlags)
10841                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10842            /*
10843             * Forward-locked apps are only in ASEC containers if they're the
10844             * new style
10845             */
10846            isInAsec = true;
10847        } else {
10848            isInAsec = false;
10849        }
10850
10851        if (isInAsec) {
10852            return new AsecInstallArgs(codePath, instructionSets,
10853                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10854        } else {
10855            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10856        }
10857    }
10858
10859    static abstract class InstallArgs {
10860        /** @see InstallParams#origin */
10861        final OriginInfo origin;
10862        /** @see InstallParams#move */
10863        final MoveInfo move;
10864
10865        final IPackageInstallObserver2 observer;
10866        // Always refers to PackageManager flags only
10867        final int installFlags;
10868        final String installerPackageName;
10869        final String volumeUuid;
10870        final ManifestDigest manifestDigest;
10871        final UserHandle user;
10872        final String abiOverride;
10873        final String[] installGrantPermissions;
10874
10875        // The list of instruction sets supported by this app. This is currently
10876        // only used during the rmdex() phase to clean up resources. We can get rid of this
10877        // if we move dex files under the common app path.
10878        /* nullable */ String[] instructionSets;
10879
10880        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10881                int installFlags, String installerPackageName, String volumeUuid,
10882                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10883                String abiOverride, String[] installGrantPermissions) {
10884            this.origin = origin;
10885            this.move = move;
10886            this.installFlags = installFlags;
10887            this.observer = observer;
10888            this.installerPackageName = installerPackageName;
10889            this.volumeUuid = volumeUuid;
10890            this.manifestDigest = manifestDigest;
10891            this.user = user;
10892            this.instructionSets = instructionSets;
10893            this.abiOverride = abiOverride;
10894            this.installGrantPermissions = installGrantPermissions;
10895        }
10896
10897        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10898        abstract int doPreInstall(int status);
10899
10900        /**
10901         * Rename package into final resting place. All paths on the given
10902         * scanned package should be updated to reflect the rename.
10903         */
10904        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10905        abstract int doPostInstall(int status, int uid);
10906
10907        /** @see PackageSettingBase#codePathString */
10908        abstract String getCodePath();
10909        /** @see PackageSettingBase#resourcePathString */
10910        abstract String getResourcePath();
10911
10912        // Need installer lock especially for dex file removal.
10913        abstract void cleanUpResourcesLI();
10914        abstract boolean doPostDeleteLI(boolean delete);
10915
10916        /**
10917         * Called before the source arguments are copied. This is used mostly
10918         * for MoveParams when it needs to read the source file to put it in the
10919         * destination.
10920         */
10921        int doPreCopy() {
10922            return PackageManager.INSTALL_SUCCEEDED;
10923        }
10924
10925        /**
10926         * Called after the source arguments are copied. This is used mostly for
10927         * MoveParams when it needs to read the source file to put it in the
10928         * destination.
10929         *
10930         * @return
10931         */
10932        int doPostCopy(int uid) {
10933            return PackageManager.INSTALL_SUCCEEDED;
10934        }
10935
10936        protected boolean isFwdLocked() {
10937            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10938        }
10939
10940        protected boolean isExternalAsec() {
10941            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10942        }
10943
10944        UserHandle getUser() {
10945            return user;
10946        }
10947    }
10948
10949    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10950        if (!allCodePaths.isEmpty()) {
10951            if (instructionSets == null) {
10952                throw new IllegalStateException("instructionSet == null");
10953            }
10954            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10955            for (String codePath : allCodePaths) {
10956                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10957                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10958                    if (retCode < 0) {
10959                        Slog.w(TAG, "Couldn't remove dex file for package: "
10960                                + " at location " + codePath + ", retcode=" + retCode);
10961                        // we don't consider this to be a failure of the core package deletion
10962                    }
10963                }
10964            }
10965        }
10966    }
10967
10968    /**
10969     * Logic to handle installation of non-ASEC applications, including copying
10970     * and renaming logic.
10971     */
10972    class FileInstallArgs extends InstallArgs {
10973        private File codeFile;
10974        private File resourceFile;
10975
10976        // Example topology:
10977        // /data/app/com.example/base.apk
10978        // /data/app/com.example/split_foo.apk
10979        // /data/app/com.example/lib/arm/libfoo.so
10980        // /data/app/com.example/lib/arm64/libfoo.so
10981        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10982
10983        /** New install */
10984        FileInstallArgs(InstallParams params) {
10985            super(params.origin, params.move, params.observer, params.installFlags,
10986                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10987                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10988                    params.grantedRuntimePermissions);
10989            if (isFwdLocked()) {
10990                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10991            }
10992        }
10993
10994        /** Existing install */
10995        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10996            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10997                    null, null);
10998            this.codeFile = (codePath != null) ? new File(codePath) : null;
10999            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11000        }
11001
11002        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11003            if (origin.staged) {
11004                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11005                codeFile = origin.file;
11006                resourceFile = origin.file;
11007                return PackageManager.INSTALL_SUCCEEDED;
11008            }
11009
11010            try {
11011                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11012                codeFile = tempDir;
11013                resourceFile = tempDir;
11014            } catch (IOException e) {
11015                Slog.w(TAG, "Failed to create copy file: " + e);
11016                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11017            }
11018
11019            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11020                @Override
11021                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11022                    if (!FileUtils.isValidExtFilename(name)) {
11023                        throw new IllegalArgumentException("Invalid filename: " + name);
11024                    }
11025                    try {
11026                        final File file = new File(codeFile, name);
11027                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11028                                O_RDWR | O_CREAT, 0644);
11029                        Os.chmod(file.getAbsolutePath(), 0644);
11030                        return new ParcelFileDescriptor(fd);
11031                    } catch (ErrnoException e) {
11032                        throw new RemoteException("Failed to open: " + e.getMessage());
11033                    }
11034                }
11035            };
11036
11037            int ret = PackageManager.INSTALL_SUCCEEDED;
11038            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11039            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11040                Slog.e(TAG, "Failed to copy package");
11041                return ret;
11042            }
11043
11044            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11045            NativeLibraryHelper.Handle handle = null;
11046            try {
11047                handle = NativeLibraryHelper.Handle.create(codeFile);
11048                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11049                        abiOverride);
11050            } catch (IOException e) {
11051                Slog.e(TAG, "Copying native libraries failed", e);
11052                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11053            } finally {
11054                IoUtils.closeQuietly(handle);
11055            }
11056
11057            return ret;
11058        }
11059
11060        int doPreInstall(int status) {
11061            if (status != PackageManager.INSTALL_SUCCEEDED) {
11062                cleanUp();
11063            }
11064            return status;
11065        }
11066
11067        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11068            if (status != PackageManager.INSTALL_SUCCEEDED) {
11069                cleanUp();
11070                return false;
11071            }
11072
11073            final File targetDir = codeFile.getParentFile();
11074            final File beforeCodeFile = codeFile;
11075            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11076
11077            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11078            try {
11079                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11080            } catch (ErrnoException e) {
11081                Slog.w(TAG, "Failed to rename", e);
11082                return false;
11083            }
11084
11085            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11086                Slog.w(TAG, "Failed to restorecon");
11087                return false;
11088            }
11089
11090            // Reflect the rename internally
11091            codeFile = afterCodeFile;
11092            resourceFile = afterCodeFile;
11093
11094            // Reflect the rename in scanned details
11095            pkg.codePath = afterCodeFile.getAbsolutePath();
11096            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11097                    pkg.baseCodePath);
11098            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11099                    pkg.splitCodePaths);
11100
11101            // Reflect the rename in app info
11102            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11103            pkg.applicationInfo.setCodePath(pkg.codePath);
11104            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11105            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11106            pkg.applicationInfo.setResourcePath(pkg.codePath);
11107            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11108            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11109
11110            return true;
11111        }
11112
11113        int doPostInstall(int status, int uid) {
11114            if (status != PackageManager.INSTALL_SUCCEEDED) {
11115                cleanUp();
11116            }
11117            return status;
11118        }
11119
11120        @Override
11121        String getCodePath() {
11122            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11123        }
11124
11125        @Override
11126        String getResourcePath() {
11127            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11128        }
11129
11130        private boolean cleanUp() {
11131            if (codeFile == null || !codeFile.exists()) {
11132                return false;
11133            }
11134
11135            if (codeFile.isDirectory()) {
11136                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11137            } else {
11138                codeFile.delete();
11139            }
11140
11141            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11142                resourceFile.delete();
11143            }
11144
11145            return true;
11146        }
11147
11148        void cleanUpResourcesLI() {
11149            // Try enumerating all code paths before deleting
11150            List<String> allCodePaths = Collections.EMPTY_LIST;
11151            if (codeFile != null && codeFile.exists()) {
11152                try {
11153                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11154                    allCodePaths = pkg.getAllCodePaths();
11155                } catch (PackageParserException e) {
11156                    // Ignored; we tried our best
11157                }
11158            }
11159
11160            cleanUp();
11161            removeDexFiles(allCodePaths, instructionSets);
11162        }
11163
11164        boolean doPostDeleteLI(boolean delete) {
11165            // XXX err, shouldn't we respect the delete flag?
11166            cleanUpResourcesLI();
11167            return true;
11168        }
11169    }
11170
11171    private boolean isAsecExternal(String cid) {
11172        final String asecPath = PackageHelper.getSdFilesystem(cid);
11173        return !asecPath.startsWith(mAsecInternalPath);
11174    }
11175
11176    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11177            PackageManagerException {
11178        if (copyRet < 0) {
11179            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11180                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11181                throw new PackageManagerException(copyRet, message);
11182            }
11183        }
11184    }
11185
11186    /**
11187     * Extract the MountService "container ID" from the full code path of an
11188     * .apk.
11189     */
11190    static String cidFromCodePath(String fullCodePath) {
11191        int eidx = fullCodePath.lastIndexOf("/");
11192        String subStr1 = fullCodePath.substring(0, eidx);
11193        int sidx = subStr1.lastIndexOf("/");
11194        return subStr1.substring(sidx+1, eidx);
11195    }
11196
11197    /**
11198     * Logic to handle installation of ASEC applications, including copying and
11199     * renaming logic.
11200     */
11201    class AsecInstallArgs extends InstallArgs {
11202        static final String RES_FILE_NAME = "pkg.apk";
11203        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11204
11205        String cid;
11206        String packagePath;
11207        String resourcePath;
11208
11209        /** New install */
11210        AsecInstallArgs(InstallParams params) {
11211            super(params.origin, params.move, params.observer, params.installFlags,
11212                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11213                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11214                    params.grantedRuntimePermissions);
11215        }
11216
11217        /** Existing install */
11218        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11219                        boolean isExternal, boolean isForwardLocked) {
11220            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11221                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11222                    instructionSets, null, null);
11223            // Hackily pretend we're still looking at a full code path
11224            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11225                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11226            }
11227
11228            // Extract cid from fullCodePath
11229            int eidx = fullCodePath.lastIndexOf("/");
11230            String subStr1 = fullCodePath.substring(0, eidx);
11231            int sidx = subStr1.lastIndexOf("/");
11232            cid = subStr1.substring(sidx+1, eidx);
11233            setMountPath(subStr1);
11234        }
11235
11236        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11237            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11238                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11239                    instructionSets, null, null);
11240            this.cid = cid;
11241            setMountPath(PackageHelper.getSdDir(cid));
11242        }
11243
11244        void createCopyFile() {
11245            cid = mInstallerService.allocateExternalStageCidLegacy();
11246        }
11247
11248        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11249            if (origin.staged) {
11250                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11251                cid = origin.cid;
11252                setMountPath(PackageHelper.getSdDir(cid));
11253                return PackageManager.INSTALL_SUCCEEDED;
11254            }
11255
11256            if (temp) {
11257                createCopyFile();
11258            } else {
11259                /*
11260                 * Pre-emptively destroy the container since it's destroyed if
11261                 * copying fails due to it existing anyway.
11262                 */
11263                PackageHelper.destroySdDir(cid);
11264            }
11265
11266            final String newMountPath = imcs.copyPackageToContainer(
11267                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11268                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11269
11270            if (newMountPath != null) {
11271                setMountPath(newMountPath);
11272                return PackageManager.INSTALL_SUCCEEDED;
11273            } else {
11274                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11275            }
11276        }
11277
11278        @Override
11279        String getCodePath() {
11280            return packagePath;
11281        }
11282
11283        @Override
11284        String getResourcePath() {
11285            return resourcePath;
11286        }
11287
11288        int doPreInstall(int status) {
11289            if (status != PackageManager.INSTALL_SUCCEEDED) {
11290                // Destroy container
11291                PackageHelper.destroySdDir(cid);
11292            } else {
11293                boolean mounted = PackageHelper.isContainerMounted(cid);
11294                if (!mounted) {
11295                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11296                            Process.SYSTEM_UID);
11297                    if (newMountPath != null) {
11298                        setMountPath(newMountPath);
11299                    } else {
11300                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11301                    }
11302                }
11303            }
11304            return status;
11305        }
11306
11307        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11308            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11309            String newMountPath = null;
11310            if (PackageHelper.isContainerMounted(cid)) {
11311                // Unmount the container
11312                if (!PackageHelper.unMountSdDir(cid)) {
11313                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11314                    return false;
11315                }
11316            }
11317            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11318                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11319                        " which might be stale. Will try to clean up.");
11320                // Clean up the stale container and proceed to recreate.
11321                if (!PackageHelper.destroySdDir(newCacheId)) {
11322                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11323                    return false;
11324                }
11325                // Successfully cleaned up stale container. Try to rename again.
11326                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11327                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11328                            + " inspite of cleaning it up.");
11329                    return false;
11330                }
11331            }
11332            if (!PackageHelper.isContainerMounted(newCacheId)) {
11333                Slog.w(TAG, "Mounting container " + newCacheId);
11334                newMountPath = PackageHelper.mountSdDir(newCacheId,
11335                        getEncryptKey(), Process.SYSTEM_UID);
11336            } else {
11337                newMountPath = PackageHelper.getSdDir(newCacheId);
11338            }
11339            if (newMountPath == null) {
11340                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11341                return false;
11342            }
11343            Log.i(TAG, "Succesfully renamed " + cid +
11344                    " to " + newCacheId +
11345                    " at new path: " + newMountPath);
11346            cid = newCacheId;
11347
11348            final File beforeCodeFile = new File(packagePath);
11349            setMountPath(newMountPath);
11350            final File afterCodeFile = new File(packagePath);
11351
11352            // Reflect the rename in scanned details
11353            pkg.codePath = afterCodeFile.getAbsolutePath();
11354            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11355                    pkg.baseCodePath);
11356            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11357                    pkg.splitCodePaths);
11358
11359            // Reflect the rename in app info
11360            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11361            pkg.applicationInfo.setCodePath(pkg.codePath);
11362            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11363            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11364            pkg.applicationInfo.setResourcePath(pkg.codePath);
11365            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11366            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11367
11368            return true;
11369        }
11370
11371        private void setMountPath(String mountPath) {
11372            final File mountFile = new File(mountPath);
11373
11374            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11375            if (monolithicFile.exists()) {
11376                packagePath = monolithicFile.getAbsolutePath();
11377                if (isFwdLocked()) {
11378                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11379                } else {
11380                    resourcePath = packagePath;
11381                }
11382            } else {
11383                packagePath = mountFile.getAbsolutePath();
11384                resourcePath = packagePath;
11385            }
11386        }
11387
11388        int doPostInstall(int status, int uid) {
11389            if (status != PackageManager.INSTALL_SUCCEEDED) {
11390                cleanUp();
11391            } else {
11392                final int groupOwner;
11393                final String protectedFile;
11394                if (isFwdLocked()) {
11395                    groupOwner = UserHandle.getSharedAppGid(uid);
11396                    protectedFile = RES_FILE_NAME;
11397                } else {
11398                    groupOwner = -1;
11399                    protectedFile = null;
11400                }
11401
11402                if (uid < Process.FIRST_APPLICATION_UID
11403                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11404                    Slog.e(TAG, "Failed to finalize " + cid);
11405                    PackageHelper.destroySdDir(cid);
11406                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11407                }
11408
11409                boolean mounted = PackageHelper.isContainerMounted(cid);
11410                if (!mounted) {
11411                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11412                }
11413            }
11414            return status;
11415        }
11416
11417        private void cleanUp() {
11418            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11419
11420            // Destroy secure container
11421            PackageHelper.destroySdDir(cid);
11422        }
11423
11424        private List<String> getAllCodePaths() {
11425            final File codeFile = new File(getCodePath());
11426            if (codeFile != null && codeFile.exists()) {
11427                try {
11428                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11429                    return pkg.getAllCodePaths();
11430                } catch (PackageParserException e) {
11431                    // Ignored; we tried our best
11432                }
11433            }
11434            return Collections.EMPTY_LIST;
11435        }
11436
11437        void cleanUpResourcesLI() {
11438            // Enumerate all code paths before deleting
11439            cleanUpResourcesLI(getAllCodePaths());
11440        }
11441
11442        private void cleanUpResourcesLI(List<String> allCodePaths) {
11443            cleanUp();
11444            removeDexFiles(allCodePaths, instructionSets);
11445        }
11446
11447        String getPackageName() {
11448            return getAsecPackageName(cid);
11449        }
11450
11451        boolean doPostDeleteLI(boolean delete) {
11452            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11453            final List<String> allCodePaths = getAllCodePaths();
11454            boolean mounted = PackageHelper.isContainerMounted(cid);
11455            if (mounted) {
11456                // Unmount first
11457                if (PackageHelper.unMountSdDir(cid)) {
11458                    mounted = false;
11459                }
11460            }
11461            if (!mounted && delete) {
11462                cleanUpResourcesLI(allCodePaths);
11463            }
11464            return !mounted;
11465        }
11466
11467        @Override
11468        int doPreCopy() {
11469            if (isFwdLocked()) {
11470                if (!PackageHelper.fixSdPermissions(cid,
11471                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11472                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11473                }
11474            }
11475
11476            return PackageManager.INSTALL_SUCCEEDED;
11477        }
11478
11479        @Override
11480        int doPostCopy(int uid) {
11481            if (isFwdLocked()) {
11482                if (uid < Process.FIRST_APPLICATION_UID
11483                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11484                                RES_FILE_NAME)) {
11485                    Slog.e(TAG, "Failed to finalize " + cid);
11486                    PackageHelper.destroySdDir(cid);
11487                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11488                }
11489            }
11490
11491            return PackageManager.INSTALL_SUCCEEDED;
11492        }
11493    }
11494
11495    /**
11496     * Logic to handle movement of existing installed applications.
11497     */
11498    class MoveInstallArgs extends InstallArgs {
11499        private File codeFile;
11500        private File resourceFile;
11501
11502        /** New install */
11503        MoveInstallArgs(InstallParams params) {
11504            super(params.origin, params.move, params.observer, params.installFlags,
11505                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11506                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11507                    params.grantedRuntimePermissions);
11508        }
11509
11510        int copyApk(IMediaContainerService imcs, boolean temp) {
11511            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11512                    + move.fromUuid + " to " + move.toUuid);
11513            synchronized (mInstaller) {
11514                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11515                        move.dataAppName, move.appId, move.seinfo) != 0) {
11516                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11517                }
11518            }
11519
11520            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11521            resourceFile = codeFile;
11522            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11523
11524            return PackageManager.INSTALL_SUCCEEDED;
11525        }
11526
11527        int doPreInstall(int status) {
11528            if (status != PackageManager.INSTALL_SUCCEEDED) {
11529                cleanUp(move.toUuid);
11530            }
11531            return status;
11532        }
11533
11534        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11535            if (status != PackageManager.INSTALL_SUCCEEDED) {
11536                cleanUp(move.toUuid);
11537                return false;
11538            }
11539
11540            // Reflect the move in app info
11541            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11542            pkg.applicationInfo.setCodePath(pkg.codePath);
11543            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11544            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11545            pkg.applicationInfo.setResourcePath(pkg.codePath);
11546            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11547            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11548
11549            return true;
11550        }
11551
11552        int doPostInstall(int status, int uid) {
11553            if (status == PackageManager.INSTALL_SUCCEEDED) {
11554                cleanUp(move.fromUuid);
11555            } else {
11556                cleanUp(move.toUuid);
11557            }
11558            return status;
11559        }
11560
11561        @Override
11562        String getCodePath() {
11563            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11564        }
11565
11566        @Override
11567        String getResourcePath() {
11568            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11569        }
11570
11571        private boolean cleanUp(String volumeUuid) {
11572            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11573                    move.dataAppName);
11574            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11575            synchronized (mInstallLock) {
11576                // Clean up both app data and code
11577                removeDataDirsLI(volumeUuid, move.packageName);
11578                if (codeFile.isDirectory()) {
11579                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11580                } else {
11581                    codeFile.delete();
11582                }
11583            }
11584            return true;
11585        }
11586
11587        void cleanUpResourcesLI() {
11588            throw new UnsupportedOperationException();
11589        }
11590
11591        boolean doPostDeleteLI(boolean delete) {
11592            throw new UnsupportedOperationException();
11593        }
11594    }
11595
11596    static String getAsecPackageName(String packageCid) {
11597        int idx = packageCid.lastIndexOf("-");
11598        if (idx == -1) {
11599            return packageCid;
11600        }
11601        return packageCid.substring(0, idx);
11602    }
11603
11604    // Utility method used to create code paths based on package name and available index.
11605    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11606        String idxStr = "";
11607        int idx = 1;
11608        // Fall back to default value of idx=1 if prefix is not
11609        // part of oldCodePath
11610        if (oldCodePath != null) {
11611            String subStr = oldCodePath;
11612            // Drop the suffix right away
11613            if (suffix != null && subStr.endsWith(suffix)) {
11614                subStr = subStr.substring(0, subStr.length() - suffix.length());
11615            }
11616            // If oldCodePath already contains prefix find out the
11617            // ending index to either increment or decrement.
11618            int sidx = subStr.lastIndexOf(prefix);
11619            if (sidx != -1) {
11620                subStr = subStr.substring(sidx + prefix.length());
11621                if (subStr != null) {
11622                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11623                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11624                    }
11625                    try {
11626                        idx = Integer.parseInt(subStr);
11627                        if (idx <= 1) {
11628                            idx++;
11629                        } else {
11630                            idx--;
11631                        }
11632                    } catch(NumberFormatException e) {
11633                    }
11634                }
11635            }
11636        }
11637        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11638        return prefix + idxStr;
11639    }
11640
11641    private File getNextCodePath(File targetDir, String packageName) {
11642        int suffix = 1;
11643        File result;
11644        do {
11645            result = new File(targetDir, packageName + "-" + suffix);
11646            suffix++;
11647        } while (result.exists());
11648        return result;
11649    }
11650
11651    // Utility method that returns the relative package path with respect
11652    // to the installation directory. Like say for /data/data/com.test-1.apk
11653    // string com.test-1 is returned.
11654    static String deriveCodePathName(String codePath) {
11655        if (codePath == null) {
11656            return null;
11657        }
11658        final File codeFile = new File(codePath);
11659        final String name = codeFile.getName();
11660        if (codeFile.isDirectory()) {
11661            return name;
11662        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11663            final int lastDot = name.lastIndexOf('.');
11664            return name.substring(0, lastDot);
11665        } else {
11666            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11667            return null;
11668        }
11669    }
11670
11671    class PackageInstalledInfo {
11672        String name;
11673        int uid;
11674        // The set of users that originally had this package installed.
11675        int[] origUsers;
11676        // The set of users that now have this package installed.
11677        int[] newUsers;
11678        PackageParser.Package pkg;
11679        int returnCode;
11680        String returnMsg;
11681        PackageRemovedInfo removedInfo;
11682
11683        public void setError(int code, String msg) {
11684            returnCode = code;
11685            returnMsg = msg;
11686            Slog.w(TAG, msg);
11687        }
11688
11689        public void setError(String msg, PackageParserException e) {
11690            returnCode = e.error;
11691            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11692            Slog.w(TAG, msg, e);
11693        }
11694
11695        public void setError(String msg, PackageManagerException e) {
11696            returnCode = e.error;
11697            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11698            Slog.w(TAG, msg, e);
11699        }
11700
11701        // In some error cases we want to convey more info back to the observer
11702        String origPackage;
11703        String origPermission;
11704    }
11705
11706    /*
11707     * Install a non-existing package.
11708     */
11709    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11710            UserHandle user, String installerPackageName, String volumeUuid,
11711            PackageInstalledInfo res) {
11712        // Remember this for later, in case we need to rollback this install
11713        String pkgName = pkg.packageName;
11714
11715        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11716        final boolean dataDirExists = Environment
11717                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11718        synchronized(mPackages) {
11719            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11720                // A package with the same name is already installed, though
11721                // it has been renamed to an older name.  The package we
11722                // are trying to install should be installed as an update to
11723                // the existing one, but that has not been requested, so bail.
11724                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11725                        + " without first uninstalling package running as "
11726                        + mSettings.mRenamedPackages.get(pkgName));
11727                return;
11728            }
11729            if (mPackages.containsKey(pkgName)) {
11730                // Don't allow installation over an existing package with the same name.
11731                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11732                        + " without first uninstalling.");
11733                return;
11734            }
11735        }
11736
11737        try {
11738            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11739                    System.currentTimeMillis(), user);
11740
11741            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11742            // delete the partially installed application. the data directory will have to be
11743            // restored if it was already existing
11744            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11745                // remove package from internal structures.  Note that we want deletePackageX to
11746                // delete the package data and cache directories that it created in
11747                // scanPackageLocked, unless those directories existed before we even tried to
11748                // install.
11749                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11750                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11751                                res.removedInfo, true);
11752            }
11753
11754        } catch (PackageManagerException e) {
11755            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11756        }
11757    }
11758
11759    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11760        // Can't rotate keys during boot or if sharedUser.
11761        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11762                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11763            return false;
11764        }
11765        // app is using upgradeKeySets; make sure all are valid
11766        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11767        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11768        for (int i = 0; i < upgradeKeySets.length; i++) {
11769            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11770                Slog.wtf(TAG, "Package "
11771                         + (oldPs.name != null ? oldPs.name : "<null>")
11772                         + " contains upgrade-key-set reference to unknown key-set: "
11773                         + upgradeKeySets[i]
11774                         + " reverting to signatures check.");
11775                return false;
11776            }
11777        }
11778        return true;
11779    }
11780
11781    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11782        // Upgrade keysets are being used.  Determine if new package has a superset of the
11783        // required keys.
11784        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11785        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11786        for (int i = 0; i < upgradeKeySets.length; i++) {
11787            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11788            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11789                return true;
11790            }
11791        }
11792        return false;
11793    }
11794
11795    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11796            UserHandle user, String installerPackageName, String volumeUuid,
11797            PackageInstalledInfo res) {
11798        final PackageParser.Package oldPackage;
11799        final String pkgName = pkg.packageName;
11800        final int[] allUsers;
11801        final boolean[] perUserInstalled;
11802
11803        // First find the old package info and check signatures
11804        synchronized(mPackages) {
11805            oldPackage = mPackages.get(pkgName);
11806            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11807            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11808            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11809                if(!checkUpgradeKeySetLP(ps, pkg)) {
11810                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11811                            "New package not signed by keys specified by upgrade-keysets: "
11812                            + pkgName);
11813                    return;
11814                }
11815            } else {
11816                // default to original signature matching
11817                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11818                    != PackageManager.SIGNATURE_MATCH) {
11819                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11820                            "New package has a different signature: " + pkgName);
11821                    return;
11822                }
11823            }
11824
11825            // In case of rollback, remember per-user/profile install state
11826            allUsers = sUserManager.getUserIds();
11827            perUserInstalled = new boolean[allUsers.length];
11828            for (int i = 0; i < allUsers.length; i++) {
11829                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11830            }
11831        }
11832
11833        boolean sysPkg = (isSystemApp(oldPackage));
11834        if (sysPkg) {
11835            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11836                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11837        } else {
11838            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11839                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11840        }
11841    }
11842
11843    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11844            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11845            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11846            String volumeUuid, PackageInstalledInfo res) {
11847        String pkgName = deletedPackage.packageName;
11848        boolean deletedPkg = true;
11849        boolean updatedSettings = false;
11850
11851        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11852                + deletedPackage);
11853        long origUpdateTime;
11854        if (pkg.mExtras != null) {
11855            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11856        } else {
11857            origUpdateTime = 0;
11858        }
11859
11860        // First delete the existing package while retaining the data directory
11861        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11862                res.removedInfo, true)) {
11863            // If the existing package wasn't successfully deleted
11864            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11865            deletedPkg = false;
11866        } else {
11867            // Successfully deleted the old package; proceed with replace.
11868
11869            // If deleted package lived in a container, give users a chance to
11870            // relinquish resources before killing.
11871            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11872                if (DEBUG_INSTALL) {
11873                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11874                }
11875                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11876                final ArrayList<String> pkgList = new ArrayList<String>(1);
11877                pkgList.add(deletedPackage.applicationInfo.packageName);
11878                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11879            }
11880
11881            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11882            try {
11883                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11884                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11885                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11886                        perUserInstalled, res, user);
11887                updatedSettings = true;
11888            } catch (PackageManagerException e) {
11889                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11890            }
11891        }
11892
11893        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11894            // remove package from internal structures.  Note that we want deletePackageX to
11895            // delete the package data and cache directories that it created in
11896            // scanPackageLocked, unless those directories existed before we even tried to
11897            // install.
11898            if(updatedSettings) {
11899                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11900                deletePackageLI(
11901                        pkgName, null, true, allUsers, perUserInstalled,
11902                        PackageManager.DELETE_KEEP_DATA,
11903                                res.removedInfo, true);
11904            }
11905            // Since we failed to install the new package we need to restore the old
11906            // package that we deleted.
11907            if (deletedPkg) {
11908                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11909                File restoreFile = new File(deletedPackage.codePath);
11910                // Parse old package
11911                boolean oldExternal = isExternal(deletedPackage);
11912                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11913                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11914                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11915                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11916                try {
11917                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11918                } catch (PackageManagerException e) {
11919                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11920                            + e.getMessage());
11921                    return;
11922                }
11923                // Restore of old package succeeded. Update permissions.
11924                // writer
11925                synchronized (mPackages) {
11926                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11927                            UPDATE_PERMISSIONS_ALL);
11928                    // can downgrade to reader
11929                    mSettings.writeLPr();
11930                }
11931                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11932            }
11933        }
11934    }
11935
11936    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11937            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11938            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11939            String volumeUuid, PackageInstalledInfo res) {
11940        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11941                + ", old=" + deletedPackage);
11942        boolean disabledSystem = false;
11943        boolean updatedSettings = false;
11944        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11945        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11946                != 0) {
11947            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11948        }
11949        String packageName = deletedPackage.packageName;
11950        if (packageName == null) {
11951            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11952                    "Attempt to delete null packageName.");
11953            return;
11954        }
11955        PackageParser.Package oldPkg;
11956        PackageSetting oldPkgSetting;
11957        // reader
11958        synchronized (mPackages) {
11959            oldPkg = mPackages.get(packageName);
11960            oldPkgSetting = mSettings.mPackages.get(packageName);
11961            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11962                    (oldPkgSetting == null)) {
11963                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11964                        "Couldn't find package:" + packageName + " information");
11965                return;
11966            }
11967        }
11968
11969        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11970
11971        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11972        res.removedInfo.removedPackage = packageName;
11973        // Remove existing system package
11974        removePackageLI(oldPkgSetting, true);
11975        // writer
11976        synchronized (mPackages) {
11977            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11978            if (!disabledSystem && deletedPackage != null) {
11979                // We didn't need to disable the .apk as a current system package,
11980                // which means we are replacing another update that is already
11981                // installed.  We need to make sure to delete the older one's .apk.
11982                res.removedInfo.args = createInstallArgsForExisting(0,
11983                        deletedPackage.applicationInfo.getCodePath(),
11984                        deletedPackage.applicationInfo.getResourcePath(),
11985                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11986            } else {
11987                res.removedInfo.args = null;
11988            }
11989        }
11990
11991        // Successfully disabled the old package. Now proceed with re-installation
11992        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11993
11994        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11995        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11996
11997        PackageParser.Package newPackage = null;
11998        try {
11999            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12000            if (newPackage.mExtras != null) {
12001                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12002                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12003                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12004
12005                // is the update attempting to change shared user? that isn't going to work...
12006                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12007                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12008                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12009                            + " to " + newPkgSetting.sharedUser);
12010                    updatedSettings = true;
12011                }
12012            }
12013
12014            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12015                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12016                        perUserInstalled, res, user);
12017                updatedSettings = true;
12018            }
12019
12020        } catch (PackageManagerException e) {
12021            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12022        }
12023
12024        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12025            // Re installation failed. Restore old information
12026            // Remove new pkg information
12027            if (newPackage != null) {
12028                removeInstalledPackageLI(newPackage, true);
12029            }
12030            // Add back the old system package
12031            try {
12032                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12033            } catch (PackageManagerException e) {
12034                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12035            }
12036            // Restore the old system information in Settings
12037            synchronized (mPackages) {
12038                if (disabledSystem) {
12039                    mSettings.enableSystemPackageLPw(packageName);
12040                }
12041                if (updatedSettings) {
12042                    mSettings.setInstallerPackageName(packageName,
12043                            oldPkgSetting.installerPackageName);
12044                }
12045                mSettings.writeLPr();
12046            }
12047        }
12048    }
12049
12050    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12051            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12052            UserHandle user) {
12053        String pkgName = newPackage.packageName;
12054        synchronized (mPackages) {
12055            //write settings. the installStatus will be incomplete at this stage.
12056            //note that the new package setting would have already been
12057            //added to mPackages. It hasn't been persisted yet.
12058            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12059            mSettings.writeLPr();
12060        }
12061
12062        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12063
12064        synchronized (mPackages) {
12065            updatePermissionsLPw(newPackage.packageName, newPackage,
12066                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12067                            ? UPDATE_PERMISSIONS_ALL : 0));
12068            // For system-bundled packages, we assume that installing an upgraded version
12069            // of the package implies that the user actually wants to run that new code,
12070            // so we enable the package.
12071            PackageSetting ps = mSettings.mPackages.get(pkgName);
12072            if (ps != null) {
12073                if (isSystemApp(newPackage)) {
12074                    // NB: implicit assumption that system package upgrades apply to all users
12075                    if (DEBUG_INSTALL) {
12076                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12077                    }
12078                    if (res.origUsers != null) {
12079                        for (int userHandle : res.origUsers) {
12080                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12081                                    userHandle, installerPackageName);
12082                        }
12083                    }
12084                    // Also convey the prior install/uninstall state
12085                    if (allUsers != null && perUserInstalled != null) {
12086                        for (int i = 0; i < allUsers.length; i++) {
12087                            if (DEBUG_INSTALL) {
12088                                Slog.d(TAG, "    user " + allUsers[i]
12089                                        + " => " + perUserInstalled[i]);
12090                            }
12091                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12092                        }
12093                        // these install state changes will be persisted in the
12094                        // upcoming call to mSettings.writeLPr().
12095                    }
12096                }
12097                // It's implied that when a user requests installation, they want the app to be
12098                // installed and enabled.
12099                int userId = user.getIdentifier();
12100                if (userId != UserHandle.USER_ALL) {
12101                    ps.setInstalled(true, userId);
12102                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12103                }
12104            }
12105            res.name = pkgName;
12106            res.uid = newPackage.applicationInfo.uid;
12107            res.pkg = newPackage;
12108            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12109            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12110            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12111            //to update install status
12112            mSettings.writeLPr();
12113        }
12114    }
12115
12116    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12117        final int installFlags = args.installFlags;
12118        final String installerPackageName = args.installerPackageName;
12119        final String volumeUuid = args.volumeUuid;
12120        final File tmpPackageFile = new File(args.getCodePath());
12121        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12122        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12123                || (args.volumeUuid != null));
12124        boolean replace = false;
12125        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12126        if (args.move != null) {
12127            // moving a complete application; perfom an initial scan on the new install location
12128            scanFlags |= SCAN_INITIAL;
12129        }
12130        // Result object to be returned
12131        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12132
12133        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12134        // Retrieve PackageSettings and parse package
12135        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12136                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12137                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12138        PackageParser pp = new PackageParser();
12139        pp.setSeparateProcesses(mSeparateProcesses);
12140        pp.setDisplayMetrics(mMetrics);
12141
12142        final PackageParser.Package pkg;
12143        try {
12144            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12145        } catch (PackageParserException e) {
12146            res.setError("Failed parse during installPackageLI", e);
12147            return;
12148        }
12149
12150        // Mark that we have an install time CPU ABI override.
12151        pkg.cpuAbiOverride = args.abiOverride;
12152
12153        String pkgName = res.name = pkg.packageName;
12154        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12155            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12156                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12157                return;
12158            }
12159        }
12160
12161        try {
12162            pp.collectCertificates(pkg, parseFlags);
12163            pp.collectManifestDigest(pkg);
12164        } catch (PackageParserException e) {
12165            res.setError("Failed collect during installPackageLI", e);
12166            return;
12167        }
12168
12169        /* If the installer passed in a manifest digest, compare it now. */
12170        if (args.manifestDigest != null) {
12171            if (DEBUG_INSTALL) {
12172                final String parsedManifest = pkg.manifestDigest == null ? "null"
12173                        : pkg.manifestDigest.toString();
12174                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12175                        + parsedManifest);
12176            }
12177
12178            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12179                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12180                return;
12181            }
12182        } else if (DEBUG_INSTALL) {
12183            final String parsedManifest = pkg.manifestDigest == null
12184                    ? "null" : pkg.manifestDigest.toString();
12185            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12186        }
12187
12188        // Get rid of all references to package scan path via parser.
12189        pp = null;
12190        String oldCodePath = null;
12191        boolean systemApp = false;
12192        synchronized (mPackages) {
12193            // Check if installing already existing package
12194            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12195                String oldName = mSettings.mRenamedPackages.get(pkgName);
12196                if (pkg.mOriginalPackages != null
12197                        && pkg.mOriginalPackages.contains(oldName)
12198                        && mPackages.containsKey(oldName)) {
12199                    // This package is derived from an original package,
12200                    // and this device has been updating from that original
12201                    // name.  We must continue using the original name, so
12202                    // rename the new package here.
12203                    pkg.setPackageName(oldName);
12204                    pkgName = pkg.packageName;
12205                    replace = true;
12206                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12207                            + oldName + " pkgName=" + pkgName);
12208                } else if (mPackages.containsKey(pkgName)) {
12209                    // This package, under its official name, already exists
12210                    // on the device; we should replace it.
12211                    replace = true;
12212                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12213                }
12214
12215                // Prevent apps opting out from runtime permissions
12216                if (replace) {
12217                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12218                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12219                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12220                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12221                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12222                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12223                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12224                                        + " doesn't support runtime permissions but the old"
12225                                        + " target SDK " + oldTargetSdk + " does.");
12226                        return;
12227                    }
12228                }
12229            }
12230
12231            PackageSetting ps = mSettings.mPackages.get(pkgName);
12232            if (ps != null) {
12233                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12234
12235                // Quick sanity check that we're signed correctly if updating;
12236                // we'll check this again later when scanning, but we want to
12237                // bail early here before tripping over redefined permissions.
12238                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12239                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12240                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12241                                + pkg.packageName + " upgrade keys do not match the "
12242                                + "previously installed version");
12243                        return;
12244                    }
12245                } else {
12246                    try {
12247                        verifySignaturesLP(ps, pkg);
12248                    } catch (PackageManagerException e) {
12249                        res.setError(e.error, e.getMessage());
12250                        return;
12251                    }
12252                }
12253
12254                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12255                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12256                    systemApp = (ps.pkg.applicationInfo.flags &
12257                            ApplicationInfo.FLAG_SYSTEM) != 0;
12258                }
12259                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12260            }
12261
12262            // Check whether the newly-scanned package wants to define an already-defined perm
12263            int N = pkg.permissions.size();
12264            for (int i = N-1; i >= 0; i--) {
12265                PackageParser.Permission perm = pkg.permissions.get(i);
12266                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12267                if (bp != null) {
12268                    // If the defining package is signed with our cert, it's okay.  This
12269                    // also includes the "updating the same package" case, of course.
12270                    // "updating same package" could also involve key-rotation.
12271                    final boolean sigsOk;
12272                    if (bp.sourcePackage.equals(pkg.packageName)
12273                            && (bp.packageSetting instanceof PackageSetting)
12274                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12275                                    scanFlags))) {
12276                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12277                    } else {
12278                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12279                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12280                    }
12281                    if (!sigsOk) {
12282                        // If the owning package is the system itself, we log but allow
12283                        // install to proceed; we fail the install on all other permission
12284                        // redefinitions.
12285                        if (!bp.sourcePackage.equals("android")) {
12286                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12287                                    + pkg.packageName + " attempting to redeclare permission "
12288                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12289                            res.origPermission = perm.info.name;
12290                            res.origPackage = bp.sourcePackage;
12291                            return;
12292                        } else {
12293                            Slog.w(TAG, "Package " + pkg.packageName
12294                                    + " attempting to redeclare system permission "
12295                                    + perm.info.name + "; ignoring new declaration");
12296                            pkg.permissions.remove(i);
12297                        }
12298                    }
12299                }
12300            }
12301
12302        }
12303
12304        if (systemApp && onExternal) {
12305            // Disable updates to system apps on sdcard
12306            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12307                    "Cannot install updates to system apps on sdcard");
12308            return;
12309        }
12310
12311        if (args.move != null) {
12312            // We did an in-place move, so dex is ready to roll
12313            scanFlags |= SCAN_NO_DEX;
12314            scanFlags |= SCAN_MOVE;
12315
12316            synchronized (mPackages) {
12317                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12318                if (ps == null) {
12319                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12320                            "Missing settings for moved package " + pkgName);
12321                }
12322
12323                // We moved the entire application as-is, so bring over the
12324                // previously derived ABI information.
12325                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12326                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12327            }
12328
12329        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12330            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12331            scanFlags |= SCAN_NO_DEX;
12332
12333            try {
12334                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12335                        true /* extract libs */);
12336            } catch (PackageManagerException pme) {
12337                Slog.e(TAG, "Error deriving application ABI", pme);
12338                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12339                return;
12340            }
12341
12342            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12343            int result = mPackageDexOptimizer
12344                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12345                            false /* defer */, false /* inclDependencies */);
12346            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12347                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12348                return;
12349            }
12350        }
12351
12352        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12353            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12354            return;
12355        }
12356
12357        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12358
12359        if (replace) {
12360            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12361                    installerPackageName, volumeUuid, res);
12362        } else {
12363            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12364                    args.user, installerPackageName, volumeUuid, res);
12365        }
12366        synchronized (mPackages) {
12367            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12368            if (ps != null) {
12369                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12370            }
12371        }
12372    }
12373
12374    private void startIntentFilterVerifications(int userId, boolean replacing,
12375            PackageParser.Package pkg) {
12376        if (mIntentFilterVerifierComponent == null) {
12377            Slog.w(TAG, "No IntentFilter verification will not be done as "
12378                    + "there is no IntentFilterVerifier available!");
12379            return;
12380        }
12381
12382        final int verifierUid = getPackageUid(
12383                mIntentFilterVerifierComponent.getPackageName(),
12384                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12385
12386        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12387        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12388        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12389        mHandler.sendMessage(msg);
12390    }
12391
12392    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12393            PackageParser.Package pkg) {
12394        int size = pkg.activities.size();
12395        if (size == 0) {
12396            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12397                    "No activity, so no need to verify any IntentFilter!");
12398            return;
12399        }
12400
12401        final boolean hasDomainURLs = hasDomainURLs(pkg);
12402        if (!hasDomainURLs) {
12403            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12404                    "No domain URLs, so no need to verify any IntentFilter!");
12405            return;
12406        }
12407
12408        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12409                + " if any IntentFilter from the " + size
12410                + " Activities needs verification ...");
12411
12412        int count = 0;
12413        final String packageName = pkg.packageName;
12414
12415        synchronized (mPackages) {
12416            // If this is a new install and we see that we've already run verification for this
12417            // package, we have nothing to do: it means the state was restored from backup.
12418            if (!replacing) {
12419                IntentFilterVerificationInfo ivi =
12420                        mSettings.getIntentFilterVerificationLPr(packageName);
12421                if (ivi != null) {
12422                    if (DEBUG_DOMAIN_VERIFICATION) {
12423                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12424                                + ivi.getStatusString());
12425                    }
12426                    return;
12427                }
12428            }
12429
12430            // If any filters need to be verified, then all need to be.
12431            boolean needToVerify = false;
12432            for (PackageParser.Activity a : pkg.activities) {
12433                for (ActivityIntentInfo filter : a.intents) {
12434                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12435                        if (DEBUG_DOMAIN_VERIFICATION) {
12436                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12437                        }
12438                        needToVerify = true;
12439                        break;
12440                    }
12441                }
12442            }
12443
12444            if (needToVerify) {
12445                final int verificationId = mIntentFilterVerificationToken++;
12446                for (PackageParser.Activity a : pkg.activities) {
12447                    for (ActivityIntentInfo filter : a.intents) {
12448                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12449                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12450                                    "Verification needed for IntentFilter:" + filter.toString());
12451                            mIntentFilterVerifier.addOneIntentFilterVerification(
12452                                    verifierUid, userId, verificationId, filter, packageName);
12453                            count++;
12454                        }
12455                    }
12456                }
12457            }
12458        }
12459
12460        if (count > 0) {
12461            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12462                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12463                    +  " for userId:" + userId);
12464            mIntentFilterVerifier.startVerifications(userId);
12465        } else {
12466            if (DEBUG_DOMAIN_VERIFICATION) {
12467                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12468            }
12469        }
12470    }
12471
12472    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12473        final ComponentName cn  = filter.activity.getComponentName();
12474        final String packageName = cn.getPackageName();
12475
12476        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12477                packageName);
12478        if (ivi == null) {
12479            return true;
12480        }
12481        int status = ivi.getStatus();
12482        switch (status) {
12483            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12484            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12485                return true;
12486
12487            default:
12488                // Nothing to do
12489                return false;
12490        }
12491    }
12492
12493    private static boolean isMultiArch(PackageSetting ps) {
12494        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12495    }
12496
12497    private static boolean isMultiArch(ApplicationInfo info) {
12498        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12499    }
12500
12501    private static boolean isExternal(PackageParser.Package pkg) {
12502        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12503    }
12504
12505    private static boolean isExternal(PackageSetting ps) {
12506        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12507    }
12508
12509    private static boolean isExternal(ApplicationInfo info) {
12510        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12511    }
12512
12513    private static boolean isSystemApp(PackageParser.Package pkg) {
12514        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12515    }
12516
12517    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12518        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12519    }
12520
12521    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12522        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12523    }
12524
12525    private static boolean isSystemApp(PackageSetting ps) {
12526        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12527    }
12528
12529    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12530        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12531    }
12532
12533    private int packageFlagsToInstallFlags(PackageSetting ps) {
12534        int installFlags = 0;
12535        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12536            // This existing package was an external ASEC install when we have
12537            // the external flag without a UUID
12538            installFlags |= PackageManager.INSTALL_EXTERNAL;
12539        }
12540        if (ps.isForwardLocked()) {
12541            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12542        }
12543        return installFlags;
12544    }
12545
12546    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12547        if (isExternal(pkg)) {
12548            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12549                return mSettings.getExternalVersion();
12550            } else {
12551                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12552            }
12553        } else {
12554            return mSettings.getInternalVersion();
12555        }
12556    }
12557
12558    private void deleteTempPackageFiles() {
12559        final FilenameFilter filter = new FilenameFilter() {
12560            public boolean accept(File dir, String name) {
12561                return name.startsWith("vmdl") && name.endsWith(".tmp");
12562            }
12563        };
12564        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12565            file.delete();
12566        }
12567    }
12568
12569    @Override
12570    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12571            int flags) {
12572        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12573                flags);
12574    }
12575
12576    @Override
12577    public void deletePackage(final String packageName,
12578            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12579        mContext.enforceCallingOrSelfPermission(
12580                android.Manifest.permission.DELETE_PACKAGES, null);
12581        Preconditions.checkNotNull(packageName);
12582        Preconditions.checkNotNull(observer);
12583        final int uid = Binder.getCallingUid();
12584        if (UserHandle.getUserId(uid) != userId) {
12585            mContext.enforceCallingPermission(
12586                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12587                    "deletePackage for user " + userId);
12588        }
12589        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12590            try {
12591                observer.onPackageDeleted(packageName,
12592                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12593            } catch (RemoteException re) {
12594            }
12595            return;
12596        }
12597
12598        boolean uninstallBlocked = false;
12599        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12600            int[] users = sUserManager.getUserIds();
12601            for (int i = 0; i < users.length; ++i) {
12602                if (getBlockUninstallForUser(packageName, users[i])) {
12603                    uninstallBlocked = true;
12604                    break;
12605                }
12606            }
12607        } else {
12608            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12609        }
12610        if (uninstallBlocked) {
12611            try {
12612                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12613                        null);
12614            } catch (RemoteException re) {
12615            }
12616            return;
12617        }
12618
12619        if (DEBUG_REMOVE) {
12620            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12621        }
12622        // Queue up an async operation since the package deletion may take a little while.
12623        mHandler.post(new Runnable() {
12624            public void run() {
12625                mHandler.removeCallbacks(this);
12626                final int returnCode = deletePackageX(packageName, userId, flags);
12627                if (observer != null) {
12628                    try {
12629                        observer.onPackageDeleted(packageName, returnCode, null);
12630                    } catch (RemoteException e) {
12631                        Log.i(TAG, "Observer no longer exists.");
12632                    } //end catch
12633                } //end if
12634            } //end run
12635        });
12636    }
12637
12638    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12639        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12640                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12641        try {
12642            if (dpm != null) {
12643                if (dpm.isDeviceOwner(packageName)) {
12644                    return true;
12645                }
12646                int[] users;
12647                if (userId == UserHandle.USER_ALL) {
12648                    users = sUserManager.getUserIds();
12649                } else {
12650                    users = new int[]{userId};
12651                }
12652                for (int i = 0; i < users.length; ++i) {
12653                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12654                        return true;
12655                    }
12656                }
12657            }
12658        } catch (RemoteException e) {
12659        }
12660        return false;
12661    }
12662
12663    /**
12664     *  This method is an internal method that could be get invoked either
12665     *  to delete an installed package or to clean up a failed installation.
12666     *  After deleting an installed package, a broadcast is sent to notify any
12667     *  listeners that the package has been installed. For cleaning up a failed
12668     *  installation, the broadcast is not necessary since the package's
12669     *  installation wouldn't have sent the initial broadcast either
12670     *  The key steps in deleting a package are
12671     *  deleting the package information in internal structures like mPackages,
12672     *  deleting the packages base directories through installd
12673     *  updating mSettings to reflect current status
12674     *  persisting settings for later use
12675     *  sending a broadcast if necessary
12676     */
12677    private int deletePackageX(String packageName, int userId, int flags) {
12678        final PackageRemovedInfo info = new PackageRemovedInfo();
12679        final boolean res;
12680
12681        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12682                ? UserHandle.ALL : new UserHandle(userId);
12683
12684        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12685            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12686            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12687        }
12688
12689        boolean removedForAllUsers = false;
12690        boolean systemUpdate = false;
12691
12692        // for the uninstall-updates case and restricted profiles, remember the per-
12693        // userhandle installed state
12694        int[] allUsers;
12695        boolean[] perUserInstalled;
12696        synchronized (mPackages) {
12697            PackageSetting ps = mSettings.mPackages.get(packageName);
12698            allUsers = sUserManager.getUserIds();
12699            perUserInstalled = new boolean[allUsers.length];
12700            for (int i = 0; i < allUsers.length; i++) {
12701                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12702            }
12703        }
12704
12705        synchronized (mInstallLock) {
12706            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12707            res = deletePackageLI(packageName, removeForUser,
12708                    true, allUsers, perUserInstalled,
12709                    flags | REMOVE_CHATTY, info, true);
12710            systemUpdate = info.isRemovedPackageSystemUpdate;
12711            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12712                removedForAllUsers = true;
12713            }
12714            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12715                    + " removedForAllUsers=" + removedForAllUsers);
12716        }
12717
12718        if (res) {
12719            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12720
12721            // If the removed package was a system update, the old system package
12722            // was re-enabled; we need to broadcast this information
12723            if (systemUpdate) {
12724                Bundle extras = new Bundle(1);
12725                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12726                        ? info.removedAppId : info.uid);
12727                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12728
12729                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12730                        extras, null, null, null);
12731                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12732                        extras, null, null, null);
12733                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12734                        null, packageName, null, null);
12735            }
12736        }
12737        // Force a gc here.
12738        Runtime.getRuntime().gc();
12739        // Delete the resources here after sending the broadcast to let
12740        // other processes clean up before deleting resources.
12741        if (info.args != null) {
12742            synchronized (mInstallLock) {
12743                info.args.doPostDeleteLI(true);
12744            }
12745        }
12746
12747        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12748    }
12749
12750    class PackageRemovedInfo {
12751        String removedPackage;
12752        int uid = -1;
12753        int removedAppId = -1;
12754        int[] removedUsers = null;
12755        boolean isRemovedPackageSystemUpdate = false;
12756        // Clean up resources deleted packages.
12757        InstallArgs args = null;
12758
12759        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12760            Bundle extras = new Bundle(1);
12761            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12762            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12763            if (replacing) {
12764                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12765            }
12766            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12767            if (removedPackage != null) {
12768                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12769                        extras, null, null, removedUsers);
12770                if (fullRemove && !replacing) {
12771                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12772                            extras, null, null, removedUsers);
12773                }
12774            }
12775            if (removedAppId >= 0) {
12776                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12777                        removedUsers);
12778            }
12779        }
12780    }
12781
12782    /*
12783     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12784     * flag is not set, the data directory is removed as well.
12785     * make sure this flag is set for partially installed apps. If not its meaningless to
12786     * delete a partially installed application.
12787     */
12788    private void removePackageDataLI(PackageSetting ps,
12789            int[] allUserHandles, boolean[] perUserInstalled,
12790            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12791        String packageName = ps.name;
12792        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12793        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12794        // Retrieve object to delete permissions for shared user later on
12795        final PackageSetting deletedPs;
12796        // reader
12797        synchronized (mPackages) {
12798            deletedPs = mSettings.mPackages.get(packageName);
12799            if (outInfo != null) {
12800                outInfo.removedPackage = packageName;
12801                outInfo.removedUsers = deletedPs != null
12802                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12803                        : null;
12804            }
12805        }
12806        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12807            removeDataDirsLI(ps.volumeUuid, packageName);
12808            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12809        }
12810        // writer
12811        synchronized (mPackages) {
12812            if (deletedPs != null) {
12813                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12814                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12815                    clearDefaultBrowserIfNeeded(packageName);
12816                    if (outInfo != null) {
12817                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12818                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12819                    }
12820                    updatePermissionsLPw(deletedPs.name, null, 0);
12821                    if (deletedPs.sharedUser != null) {
12822                        // Remove permissions associated with package. Since runtime
12823                        // permissions are per user we have to kill the removed package
12824                        // or packages running under the shared user of the removed
12825                        // package if revoking the permissions requested only by the removed
12826                        // package is successful and this causes a change in gids.
12827                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12828                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12829                                    userId);
12830                            if (userIdToKill == UserHandle.USER_ALL
12831                                    || userIdToKill >= UserHandle.USER_OWNER) {
12832                                // If gids changed for this user, kill all affected packages.
12833                                mHandler.post(new Runnable() {
12834                                    @Override
12835                                    public void run() {
12836                                        // This has to happen with no lock held.
12837                                        killApplication(deletedPs.name, deletedPs.appId,
12838                                                KILL_APP_REASON_GIDS_CHANGED);
12839                                    }
12840                                });
12841                                break;
12842                            }
12843                        }
12844                    }
12845                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12846                }
12847                // make sure to preserve per-user disabled state if this removal was just
12848                // a downgrade of a system app to the factory package
12849                if (allUserHandles != null && perUserInstalled != null) {
12850                    if (DEBUG_REMOVE) {
12851                        Slog.d(TAG, "Propagating install state across downgrade");
12852                    }
12853                    for (int i = 0; i < allUserHandles.length; i++) {
12854                        if (DEBUG_REMOVE) {
12855                            Slog.d(TAG, "    user " + allUserHandles[i]
12856                                    + " => " + perUserInstalled[i]);
12857                        }
12858                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12859                    }
12860                }
12861            }
12862            // can downgrade to reader
12863            if (writeSettings) {
12864                // Save settings now
12865                mSettings.writeLPr();
12866            }
12867        }
12868        if (outInfo != null) {
12869            // A user ID was deleted here. Go through all users and remove it
12870            // from KeyStore.
12871            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12872        }
12873    }
12874
12875    static boolean locationIsPrivileged(File path) {
12876        try {
12877            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12878                    .getCanonicalPath();
12879            return path.getCanonicalPath().startsWith(privilegedAppDir);
12880        } catch (IOException e) {
12881            Slog.e(TAG, "Unable to access code path " + path);
12882        }
12883        return false;
12884    }
12885
12886    /*
12887     * Tries to delete system package.
12888     */
12889    private boolean deleteSystemPackageLI(PackageSetting newPs,
12890            int[] allUserHandles, boolean[] perUserInstalled,
12891            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12892        final boolean applyUserRestrictions
12893                = (allUserHandles != null) && (perUserInstalled != null);
12894        PackageSetting disabledPs = null;
12895        // Confirm if the system package has been updated
12896        // An updated system app can be deleted. This will also have to restore
12897        // the system pkg from system partition
12898        // reader
12899        synchronized (mPackages) {
12900            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12901        }
12902        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12903                + " disabledPs=" + disabledPs);
12904        if (disabledPs == null) {
12905            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12906            return false;
12907        } else if (DEBUG_REMOVE) {
12908            Slog.d(TAG, "Deleting system pkg from data partition");
12909        }
12910        if (DEBUG_REMOVE) {
12911            if (applyUserRestrictions) {
12912                Slog.d(TAG, "Remembering install states:");
12913                for (int i = 0; i < allUserHandles.length; i++) {
12914                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12915                }
12916            }
12917        }
12918        // Delete the updated package
12919        outInfo.isRemovedPackageSystemUpdate = true;
12920        if (disabledPs.versionCode < newPs.versionCode) {
12921            // Delete data for downgrades
12922            flags &= ~PackageManager.DELETE_KEEP_DATA;
12923        } else {
12924            // Preserve data by setting flag
12925            flags |= PackageManager.DELETE_KEEP_DATA;
12926        }
12927        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12928                allUserHandles, perUserInstalled, outInfo, writeSettings);
12929        if (!ret) {
12930            return false;
12931        }
12932        // writer
12933        synchronized (mPackages) {
12934            // Reinstate the old system package
12935            mSettings.enableSystemPackageLPw(newPs.name);
12936            // Remove any native libraries from the upgraded package.
12937            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12938        }
12939        // Install the system package
12940        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12941        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12942        if (locationIsPrivileged(disabledPs.codePath)) {
12943            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12944        }
12945
12946        final PackageParser.Package newPkg;
12947        try {
12948            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12949        } catch (PackageManagerException e) {
12950            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12951            return false;
12952        }
12953
12954        // writer
12955        synchronized (mPackages) {
12956            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12957
12958            // Propagate the permissions state as we do not want to drop on the floor
12959            // runtime permissions. The update permissions method below will take
12960            // care of removing obsolete permissions and grant install permissions.
12961            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12962            updatePermissionsLPw(newPkg.packageName, newPkg,
12963                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12964
12965            if (applyUserRestrictions) {
12966                if (DEBUG_REMOVE) {
12967                    Slog.d(TAG, "Propagating install state across reinstall");
12968                }
12969                for (int i = 0; i < allUserHandles.length; i++) {
12970                    if (DEBUG_REMOVE) {
12971                        Slog.d(TAG, "    user " + allUserHandles[i]
12972                                + " => " + perUserInstalled[i]);
12973                    }
12974                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12975
12976                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12977                }
12978                // Regardless of writeSettings we need to ensure that this restriction
12979                // state propagation is persisted
12980                mSettings.writeAllUsersPackageRestrictionsLPr();
12981            }
12982            // can downgrade to reader here
12983            if (writeSettings) {
12984                mSettings.writeLPr();
12985            }
12986        }
12987        return true;
12988    }
12989
12990    private boolean deleteInstalledPackageLI(PackageSetting ps,
12991            boolean deleteCodeAndResources, int flags,
12992            int[] allUserHandles, boolean[] perUserInstalled,
12993            PackageRemovedInfo outInfo, boolean writeSettings) {
12994        if (outInfo != null) {
12995            outInfo.uid = ps.appId;
12996        }
12997
12998        // Delete package data from internal structures and also remove data if flag is set
12999        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13000
13001        // Delete application code and resources
13002        if (deleteCodeAndResources && (outInfo != null)) {
13003            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13004                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13005            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13006        }
13007        return true;
13008    }
13009
13010    @Override
13011    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13012            int userId) {
13013        mContext.enforceCallingOrSelfPermission(
13014                android.Manifest.permission.DELETE_PACKAGES, null);
13015        synchronized (mPackages) {
13016            PackageSetting ps = mSettings.mPackages.get(packageName);
13017            if (ps == null) {
13018                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13019                return false;
13020            }
13021            if (!ps.getInstalled(userId)) {
13022                // Can't block uninstall for an app that is not installed or enabled.
13023                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13024                return false;
13025            }
13026            ps.setBlockUninstall(blockUninstall, userId);
13027            mSettings.writePackageRestrictionsLPr(userId);
13028        }
13029        return true;
13030    }
13031
13032    @Override
13033    public boolean getBlockUninstallForUser(String packageName, int userId) {
13034        synchronized (mPackages) {
13035            PackageSetting ps = mSettings.mPackages.get(packageName);
13036            if (ps == null) {
13037                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13038                return false;
13039            }
13040            return ps.getBlockUninstall(userId);
13041        }
13042    }
13043
13044    /*
13045     * This method handles package deletion in general
13046     */
13047    private boolean deletePackageLI(String packageName, UserHandle user,
13048            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13049            int flags, PackageRemovedInfo outInfo,
13050            boolean writeSettings) {
13051        if (packageName == null) {
13052            Slog.w(TAG, "Attempt to delete null packageName.");
13053            return false;
13054        }
13055        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13056        PackageSetting ps;
13057        boolean dataOnly = false;
13058        int removeUser = -1;
13059        int appId = -1;
13060        synchronized (mPackages) {
13061            ps = mSettings.mPackages.get(packageName);
13062            if (ps == null) {
13063                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13064                return false;
13065            }
13066            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13067                    && user.getIdentifier() != UserHandle.USER_ALL) {
13068                // The caller is asking that the package only be deleted for a single
13069                // user.  To do this, we just mark its uninstalled state and delete
13070                // its data.  If this is a system app, we only allow this to happen if
13071                // they have set the special DELETE_SYSTEM_APP which requests different
13072                // semantics than normal for uninstalling system apps.
13073                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13074                final int userId = user.getIdentifier();
13075                ps.setUserState(userId,
13076                        COMPONENT_ENABLED_STATE_DEFAULT,
13077                        false, //installed
13078                        true,  //stopped
13079                        true,  //notLaunched
13080                        false, //hidden
13081                        null, null, null,
13082                        false, // blockUninstall
13083                        ps.readUserState(userId).domainVerificationStatus, 0);
13084                if (!isSystemApp(ps)) {
13085                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13086                        // Other user still have this package installed, so all
13087                        // we need to do is clear this user's data and save that
13088                        // it is uninstalled.
13089                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13090                        removeUser = user.getIdentifier();
13091                        appId = ps.appId;
13092                        scheduleWritePackageRestrictionsLocked(removeUser);
13093                    } else {
13094                        // We need to set it back to 'installed' so the uninstall
13095                        // broadcasts will be sent correctly.
13096                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13097                        ps.setInstalled(true, user.getIdentifier());
13098                    }
13099                } else {
13100                    // This is a system app, so we assume that the
13101                    // other users still have this package installed, so all
13102                    // we need to do is clear this user's data and save that
13103                    // it is uninstalled.
13104                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13105                    removeUser = user.getIdentifier();
13106                    appId = ps.appId;
13107                    scheduleWritePackageRestrictionsLocked(removeUser);
13108                }
13109            }
13110        }
13111
13112        if (removeUser >= 0) {
13113            // From above, we determined that we are deleting this only
13114            // for a single user.  Continue the work here.
13115            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13116            if (outInfo != null) {
13117                outInfo.removedPackage = packageName;
13118                outInfo.removedAppId = appId;
13119                outInfo.removedUsers = new int[] {removeUser};
13120            }
13121            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13122            removeKeystoreDataIfNeeded(removeUser, appId);
13123            schedulePackageCleaning(packageName, removeUser, false);
13124            synchronized (mPackages) {
13125                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13126                    scheduleWritePackageRestrictionsLocked(removeUser);
13127                }
13128                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13129            }
13130            return true;
13131        }
13132
13133        if (dataOnly) {
13134            // Delete application data first
13135            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13136            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13137            return true;
13138        }
13139
13140        boolean ret = false;
13141        if (isSystemApp(ps)) {
13142            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13143            // When an updated system application is deleted we delete the existing resources as well and
13144            // fall back to existing code in system partition
13145            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13146                    flags, outInfo, writeSettings);
13147        } else {
13148            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13149            // Kill application pre-emptively especially for apps on sd.
13150            killApplication(packageName, ps.appId, "uninstall pkg");
13151            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13152                    allUserHandles, perUserInstalled,
13153                    outInfo, writeSettings);
13154        }
13155
13156        return ret;
13157    }
13158
13159    private final class ClearStorageConnection implements ServiceConnection {
13160        IMediaContainerService mContainerService;
13161
13162        @Override
13163        public void onServiceConnected(ComponentName name, IBinder service) {
13164            synchronized (this) {
13165                mContainerService = IMediaContainerService.Stub.asInterface(service);
13166                notifyAll();
13167            }
13168        }
13169
13170        @Override
13171        public void onServiceDisconnected(ComponentName name) {
13172        }
13173    }
13174
13175    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13176        final boolean mounted;
13177        if (Environment.isExternalStorageEmulated()) {
13178            mounted = true;
13179        } else {
13180            final String status = Environment.getExternalStorageState();
13181
13182            mounted = status.equals(Environment.MEDIA_MOUNTED)
13183                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13184        }
13185
13186        if (!mounted) {
13187            return;
13188        }
13189
13190        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13191        int[] users;
13192        if (userId == UserHandle.USER_ALL) {
13193            users = sUserManager.getUserIds();
13194        } else {
13195            users = new int[] { userId };
13196        }
13197        final ClearStorageConnection conn = new ClearStorageConnection();
13198        if (mContext.bindServiceAsUser(
13199                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13200            try {
13201                for (int curUser : users) {
13202                    long timeout = SystemClock.uptimeMillis() + 5000;
13203                    synchronized (conn) {
13204                        long now = SystemClock.uptimeMillis();
13205                        while (conn.mContainerService == null && now < timeout) {
13206                            try {
13207                                conn.wait(timeout - now);
13208                            } catch (InterruptedException e) {
13209                            }
13210                        }
13211                    }
13212                    if (conn.mContainerService == null) {
13213                        return;
13214                    }
13215
13216                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13217                    clearDirectory(conn.mContainerService,
13218                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13219                    if (allData) {
13220                        clearDirectory(conn.mContainerService,
13221                                userEnv.buildExternalStorageAppDataDirs(packageName));
13222                        clearDirectory(conn.mContainerService,
13223                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13224                    }
13225                }
13226            } finally {
13227                mContext.unbindService(conn);
13228            }
13229        }
13230    }
13231
13232    @Override
13233    public void clearApplicationUserData(final String packageName,
13234            final IPackageDataObserver observer, final int userId) {
13235        mContext.enforceCallingOrSelfPermission(
13236                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13237        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13238        // Queue up an async operation since the package deletion may take a little while.
13239        mHandler.post(new Runnable() {
13240            public void run() {
13241                mHandler.removeCallbacks(this);
13242                final boolean succeeded;
13243                synchronized (mInstallLock) {
13244                    succeeded = clearApplicationUserDataLI(packageName, userId);
13245                }
13246                clearExternalStorageDataSync(packageName, userId, true);
13247                if (succeeded) {
13248                    // invoke DeviceStorageMonitor's update method to clear any notifications
13249                    DeviceStorageMonitorInternal
13250                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13251                    if (dsm != null) {
13252                        dsm.checkMemory();
13253                    }
13254                }
13255                if(observer != null) {
13256                    try {
13257                        observer.onRemoveCompleted(packageName, succeeded);
13258                    } catch (RemoteException e) {
13259                        Log.i(TAG, "Observer no longer exists.");
13260                    }
13261                } //end if observer
13262            } //end run
13263        });
13264    }
13265
13266    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13267        if (packageName == null) {
13268            Slog.w(TAG, "Attempt to delete null packageName.");
13269            return false;
13270        }
13271
13272        // Try finding details about the requested package
13273        PackageParser.Package pkg;
13274        synchronized (mPackages) {
13275            pkg = mPackages.get(packageName);
13276            if (pkg == null) {
13277                final PackageSetting ps = mSettings.mPackages.get(packageName);
13278                if (ps != null) {
13279                    pkg = ps.pkg;
13280                }
13281            }
13282
13283            if (pkg == null) {
13284                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13285                return false;
13286            }
13287
13288            PackageSetting ps = (PackageSetting) pkg.mExtras;
13289            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13290        }
13291
13292        // Always delete data directories for package, even if we found no other
13293        // record of app. This helps users recover from UID mismatches without
13294        // resorting to a full data wipe.
13295        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13296        if (retCode < 0) {
13297            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13298            return false;
13299        }
13300
13301        final int appId = pkg.applicationInfo.uid;
13302        removeKeystoreDataIfNeeded(userId, appId);
13303
13304        // Create a native library symlink only if we have native libraries
13305        // and if the native libraries are 32 bit libraries. We do not provide
13306        // this symlink for 64 bit libraries.
13307        if (pkg.applicationInfo.primaryCpuAbi != null &&
13308                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13309            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13310            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13311                    nativeLibPath, userId) < 0) {
13312                Slog.w(TAG, "Failed linking native library dir");
13313                return false;
13314            }
13315        }
13316
13317        return true;
13318    }
13319
13320    /**
13321     * Reverts user permission state changes (permissions and flags) in
13322     * all packages for a given user.
13323     *
13324     * @param userId The device user for which to do a reset.
13325     */
13326    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13327        final int packageCount = mPackages.size();
13328        for (int i = 0; i < packageCount; i++) {
13329            PackageParser.Package pkg = mPackages.valueAt(i);
13330            PackageSetting ps = (PackageSetting) pkg.mExtras;
13331            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13332        }
13333    }
13334
13335    /**
13336     * Reverts user permission state changes (permissions and flags).
13337     *
13338     * @param ps The package for which to reset.
13339     * @param userId The device user for which to do a reset.
13340     */
13341    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13342            final PackageSetting ps, final int userId) {
13343        if (ps.pkg == null) {
13344            return;
13345        }
13346
13347        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13348                | FLAG_PERMISSION_USER_FIXED
13349                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13350
13351        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13352                | FLAG_PERMISSION_POLICY_FIXED;
13353
13354        boolean writeInstallPermissions = false;
13355        boolean writeRuntimePermissions = false;
13356
13357        final int permissionCount = ps.pkg.requestedPermissions.size();
13358        for (int i = 0; i < permissionCount; i++) {
13359            String permission = ps.pkg.requestedPermissions.get(i);
13360
13361            BasePermission bp = mSettings.mPermissions.get(permission);
13362            if (bp == null) {
13363                continue;
13364            }
13365
13366            // If shared user we just reset the state to which only this app contributed.
13367            if (ps.sharedUser != null) {
13368                boolean used = false;
13369                final int packageCount = ps.sharedUser.packages.size();
13370                for (int j = 0; j < packageCount; j++) {
13371                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13372                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13373                            && pkg.pkg.requestedPermissions.contains(permission)) {
13374                        used = true;
13375                        break;
13376                    }
13377                }
13378                if (used) {
13379                    continue;
13380                }
13381            }
13382
13383            PermissionsState permissionsState = ps.getPermissionsState();
13384
13385            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13386
13387            // Always clear the user settable flags.
13388            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13389                    bp.name) != null;
13390            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13391                if (hasInstallState) {
13392                    writeInstallPermissions = true;
13393                } else {
13394                    writeRuntimePermissions = true;
13395                }
13396            }
13397
13398            // Below is only runtime permission handling.
13399            if (!bp.isRuntime()) {
13400                continue;
13401            }
13402
13403            // Never clobber system or policy.
13404            if ((oldFlags & policyOrSystemFlags) != 0) {
13405                continue;
13406            }
13407
13408            // If this permission was granted by default, make sure it is.
13409            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13410                if (permissionsState.grantRuntimePermission(bp, userId)
13411                        != PERMISSION_OPERATION_FAILURE) {
13412                    writeRuntimePermissions = true;
13413                }
13414            } else {
13415                // Otherwise, reset the permission.
13416                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13417                switch (revokeResult) {
13418                    case PERMISSION_OPERATION_SUCCESS: {
13419                        writeRuntimePermissions = true;
13420                    } break;
13421
13422                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13423                        writeRuntimePermissions = true;
13424                        final int appId = ps.appId;
13425                        mHandler.post(new Runnable() {
13426                            @Override
13427                            public void run() {
13428                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13429                            }
13430                        });
13431                    } break;
13432                }
13433            }
13434        }
13435
13436        // Synchronously write as we are taking permissions away.
13437        if (writeRuntimePermissions) {
13438            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13439        }
13440
13441        // Synchronously write as we are taking permissions away.
13442        if (writeInstallPermissions) {
13443            mSettings.writeLPr();
13444        }
13445    }
13446
13447    /**
13448     * Remove entries from the keystore daemon. Will only remove it if the
13449     * {@code appId} is valid.
13450     */
13451    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13452        if (appId < 0) {
13453            return;
13454        }
13455
13456        final KeyStore keyStore = KeyStore.getInstance();
13457        if (keyStore != null) {
13458            if (userId == UserHandle.USER_ALL) {
13459                for (final int individual : sUserManager.getUserIds()) {
13460                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13461                }
13462            } else {
13463                keyStore.clearUid(UserHandle.getUid(userId, appId));
13464            }
13465        } else {
13466            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13467        }
13468    }
13469
13470    @Override
13471    public void deleteApplicationCacheFiles(final String packageName,
13472            final IPackageDataObserver observer) {
13473        mContext.enforceCallingOrSelfPermission(
13474                android.Manifest.permission.DELETE_CACHE_FILES, null);
13475        // Queue up an async operation since the package deletion may take a little while.
13476        final int userId = UserHandle.getCallingUserId();
13477        mHandler.post(new Runnable() {
13478            public void run() {
13479                mHandler.removeCallbacks(this);
13480                final boolean succeded;
13481                synchronized (mInstallLock) {
13482                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13483                }
13484                clearExternalStorageDataSync(packageName, userId, false);
13485                if (observer != null) {
13486                    try {
13487                        observer.onRemoveCompleted(packageName, succeded);
13488                    } catch (RemoteException e) {
13489                        Log.i(TAG, "Observer no longer exists.");
13490                    }
13491                } //end if observer
13492            } //end run
13493        });
13494    }
13495
13496    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13497        if (packageName == null) {
13498            Slog.w(TAG, "Attempt to delete null packageName.");
13499            return false;
13500        }
13501        PackageParser.Package p;
13502        synchronized (mPackages) {
13503            p = mPackages.get(packageName);
13504        }
13505        if (p == null) {
13506            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13507            return false;
13508        }
13509        final ApplicationInfo applicationInfo = p.applicationInfo;
13510        if (applicationInfo == null) {
13511            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13512            return false;
13513        }
13514        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13515        if (retCode < 0) {
13516            Slog.w(TAG, "Couldn't remove cache files for package: "
13517                       + packageName + " u" + userId);
13518            return false;
13519        }
13520        return true;
13521    }
13522
13523    @Override
13524    public void getPackageSizeInfo(final String packageName, int userHandle,
13525            final IPackageStatsObserver observer) {
13526        mContext.enforceCallingOrSelfPermission(
13527                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13528        if (packageName == null) {
13529            throw new IllegalArgumentException("Attempt to get size of null packageName");
13530        }
13531
13532        PackageStats stats = new PackageStats(packageName, userHandle);
13533
13534        /*
13535         * Queue up an async operation since the package measurement may take a
13536         * little while.
13537         */
13538        Message msg = mHandler.obtainMessage(INIT_COPY);
13539        msg.obj = new MeasureParams(stats, observer);
13540        mHandler.sendMessage(msg);
13541    }
13542
13543    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13544            PackageStats pStats) {
13545        if (packageName == null) {
13546            Slog.w(TAG, "Attempt to get size of null packageName.");
13547            return false;
13548        }
13549        PackageParser.Package p;
13550        boolean dataOnly = false;
13551        String libDirRoot = null;
13552        String asecPath = null;
13553        PackageSetting ps = null;
13554        synchronized (mPackages) {
13555            p = mPackages.get(packageName);
13556            ps = mSettings.mPackages.get(packageName);
13557            if(p == null) {
13558                dataOnly = true;
13559                if((ps == null) || (ps.pkg == null)) {
13560                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13561                    return false;
13562                }
13563                p = ps.pkg;
13564            }
13565            if (ps != null) {
13566                libDirRoot = ps.legacyNativeLibraryPathString;
13567            }
13568            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13569                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13570                if (secureContainerId != null) {
13571                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13572                }
13573            }
13574        }
13575        String publicSrcDir = null;
13576        if(!dataOnly) {
13577            final ApplicationInfo applicationInfo = p.applicationInfo;
13578            if (applicationInfo == null) {
13579                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13580                return false;
13581            }
13582            if (p.isForwardLocked()) {
13583                publicSrcDir = applicationInfo.getBaseResourcePath();
13584            }
13585        }
13586        // TODO: extend to measure size of split APKs
13587        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13588        // not just the first level.
13589        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13590        // just the primary.
13591        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13592        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13593                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13594        if (res < 0) {
13595            return false;
13596        }
13597
13598        // Fix-up for forward-locked applications in ASEC containers.
13599        if (!isExternal(p)) {
13600            pStats.codeSize += pStats.externalCodeSize;
13601            pStats.externalCodeSize = 0L;
13602        }
13603
13604        return true;
13605    }
13606
13607
13608    @Override
13609    public void addPackageToPreferred(String packageName) {
13610        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13611    }
13612
13613    @Override
13614    public void removePackageFromPreferred(String packageName) {
13615        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13616    }
13617
13618    @Override
13619    public List<PackageInfo> getPreferredPackages(int flags) {
13620        return new ArrayList<PackageInfo>();
13621    }
13622
13623    private int getUidTargetSdkVersionLockedLPr(int uid) {
13624        Object obj = mSettings.getUserIdLPr(uid);
13625        if (obj instanceof SharedUserSetting) {
13626            final SharedUserSetting sus = (SharedUserSetting) obj;
13627            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13628            final Iterator<PackageSetting> it = sus.packages.iterator();
13629            while (it.hasNext()) {
13630                final PackageSetting ps = it.next();
13631                if (ps.pkg != null) {
13632                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13633                    if (v < vers) vers = v;
13634                }
13635            }
13636            return vers;
13637        } else if (obj instanceof PackageSetting) {
13638            final PackageSetting ps = (PackageSetting) obj;
13639            if (ps.pkg != null) {
13640                return ps.pkg.applicationInfo.targetSdkVersion;
13641            }
13642        }
13643        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13644    }
13645
13646    @Override
13647    public void addPreferredActivity(IntentFilter filter, int match,
13648            ComponentName[] set, ComponentName activity, int userId) {
13649        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13650                "Adding preferred");
13651    }
13652
13653    private void addPreferredActivityInternal(IntentFilter filter, int match,
13654            ComponentName[] set, ComponentName activity, boolean always, int userId,
13655            String opname) {
13656        // writer
13657        int callingUid = Binder.getCallingUid();
13658        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13659        if (filter.countActions() == 0) {
13660            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13661            return;
13662        }
13663        synchronized (mPackages) {
13664            if (mContext.checkCallingOrSelfPermission(
13665                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13666                    != PackageManager.PERMISSION_GRANTED) {
13667                if (getUidTargetSdkVersionLockedLPr(callingUid)
13668                        < Build.VERSION_CODES.FROYO) {
13669                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13670                            + callingUid);
13671                    return;
13672                }
13673                mContext.enforceCallingOrSelfPermission(
13674                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13675            }
13676
13677            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13678            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13679                    + userId + ":");
13680            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13681            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13682            scheduleWritePackageRestrictionsLocked(userId);
13683        }
13684    }
13685
13686    @Override
13687    public void replacePreferredActivity(IntentFilter filter, int match,
13688            ComponentName[] set, ComponentName activity, int userId) {
13689        if (filter.countActions() != 1) {
13690            throw new IllegalArgumentException(
13691                    "replacePreferredActivity expects filter to have only 1 action.");
13692        }
13693        if (filter.countDataAuthorities() != 0
13694                || filter.countDataPaths() != 0
13695                || filter.countDataSchemes() > 1
13696                || filter.countDataTypes() != 0) {
13697            throw new IllegalArgumentException(
13698                    "replacePreferredActivity expects filter to have no data authorities, " +
13699                    "paths, or types; and at most one scheme.");
13700        }
13701
13702        final int callingUid = Binder.getCallingUid();
13703        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13704        synchronized (mPackages) {
13705            if (mContext.checkCallingOrSelfPermission(
13706                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13707                    != PackageManager.PERMISSION_GRANTED) {
13708                if (getUidTargetSdkVersionLockedLPr(callingUid)
13709                        < Build.VERSION_CODES.FROYO) {
13710                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13711                            + Binder.getCallingUid());
13712                    return;
13713                }
13714                mContext.enforceCallingOrSelfPermission(
13715                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13716            }
13717
13718            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13719            if (pir != null) {
13720                // Get all of the existing entries that exactly match this filter.
13721                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13722                if (existing != null && existing.size() == 1) {
13723                    PreferredActivity cur = existing.get(0);
13724                    if (DEBUG_PREFERRED) {
13725                        Slog.i(TAG, "Checking replace of preferred:");
13726                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13727                        if (!cur.mPref.mAlways) {
13728                            Slog.i(TAG, "  -- CUR; not mAlways!");
13729                        } else {
13730                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13731                            Slog.i(TAG, "  -- CUR: mSet="
13732                                    + Arrays.toString(cur.mPref.mSetComponents));
13733                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13734                            Slog.i(TAG, "  -- NEW: mMatch="
13735                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13736                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13737                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13738                        }
13739                    }
13740                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13741                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13742                            && cur.mPref.sameSet(set)) {
13743                        // Setting the preferred activity to what it happens to be already
13744                        if (DEBUG_PREFERRED) {
13745                            Slog.i(TAG, "Replacing with same preferred activity "
13746                                    + cur.mPref.mShortComponent + " for user "
13747                                    + userId + ":");
13748                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13749                        }
13750                        return;
13751                    }
13752                }
13753
13754                if (existing != null) {
13755                    if (DEBUG_PREFERRED) {
13756                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13757                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13758                    }
13759                    for (int i = 0; i < existing.size(); i++) {
13760                        PreferredActivity pa = existing.get(i);
13761                        if (DEBUG_PREFERRED) {
13762                            Slog.i(TAG, "Removing existing preferred activity "
13763                                    + pa.mPref.mComponent + ":");
13764                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13765                        }
13766                        pir.removeFilter(pa);
13767                    }
13768                }
13769            }
13770            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13771                    "Replacing preferred");
13772        }
13773    }
13774
13775    @Override
13776    public void clearPackagePreferredActivities(String packageName) {
13777        final int uid = Binder.getCallingUid();
13778        // writer
13779        synchronized (mPackages) {
13780            PackageParser.Package pkg = mPackages.get(packageName);
13781            if (pkg == null || pkg.applicationInfo.uid != uid) {
13782                if (mContext.checkCallingOrSelfPermission(
13783                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13784                        != PackageManager.PERMISSION_GRANTED) {
13785                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13786                            < Build.VERSION_CODES.FROYO) {
13787                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13788                                + Binder.getCallingUid());
13789                        return;
13790                    }
13791                    mContext.enforceCallingOrSelfPermission(
13792                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13793                }
13794            }
13795
13796            int user = UserHandle.getCallingUserId();
13797            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13798                scheduleWritePackageRestrictionsLocked(user);
13799            }
13800        }
13801    }
13802
13803    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13804    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13805        ArrayList<PreferredActivity> removed = null;
13806        boolean changed = false;
13807        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13808            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13809            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13810            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13811                continue;
13812            }
13813            Iterator<PreferredActivity> it = pir.filterIterator();
13814            while (it.hasNext()) {
13815                PreferredActivity pa = it.next();
13816                // Mark entry for removal only if it matches the package name
13817                // and the entry is of type "always".
13818                if (packageName == null ||
13819                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13820                                && pa.mPref.mAlways)) {
13821                    if (removed == null) {
13822                        removed = new ArrayList<PreferredActivity>();
13823                    }
13824                    removed.add(pa);
13825                }
13826            }
13827            if (removed != null) {
13828                for (int j=0; j<removed.size(); j++) {
13829                    PreferredActivity pa = removed.get(j);
13830                    pir.removeFilter(pa);
13831                }
13832                changed = true;
13833            }
13834        }
13835        return changed;
13836    }
13837
13838    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13839    private void clearIntentFilterVerificationsLPw(int userId) {
13840        final int packageCount = mPackages.size();
13841        for (int i = 0; i < packageCount; i++) {
13842            PackageParser.Package pkg = mPackages.valueAt(i);
13843            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13844        }
13845    }
13846
13847    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13848    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13849        if (userId == UserHandle.USER_ALL) {
13850            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13851                    sUserManager.getUserIds())) {
13852                for (int oneUserId : sUserManager.getUserIds()) {
13853                    scheduleWritePackageRestrictionsLocked(oneUserId);
13854                }
13855            }
13856        } else {
13857            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13858                scheduleWritePackageRestrictionsLocked(userId);
13859            }
13860        }
13861    }
13862
13863    void clearDefaultBrowserIfNeeded(String packageName) {
13864        for (int oneUserId : sUserManager.getUserIds()) {
13865            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13866            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13867            if (packageName.equals(defaultBrowserPackageName)) {
13868                setDefaultBrowserPackageName(null, oneUserId);
13869            }
13870        }
13871    }
13872
13873    @Override
13874    public void resetApplicationPreferences(int userId) {
13875        mContext.enforceCallingOrSelfPermission(
13876                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13877        // writer
13878        synchronized (mPackages) {
13879            final long identity = Binder.clearCallingIdentity();
13880            try {
13881                clearPackagePreferredActivitiesLPw(null, userId);
13882                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13883                // TODO: We have to reset the default SMS and Phone. This requires
13884                // significant refactoring to keep all default apps in the package
13885                // manager (cleaner but more work) or have the services provide
13886                // callbacks to the package manager to request a default app reset.
13887                applyFactoryDefaultBrowserLPw(userId);
13888                clearIntentFilterVerificationsLPw(userId);
13889                primeDomainVerificationsLPw(userId);
13890                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13891                scheduleWritePackageRestrictionsLocked(userId);
13892            } finally {
13893                Binder.restoreCallingIdentity(identity);
13894            }
13895        }
13896    }
13897
13898    @Override
13899    public int getPreferredActivities(List<IntentFilter> outFilters,
13900            List<ComponentName> outActivities, String packageName) {
13901
13902        int num = 0;
13903        final int userId = UserHandle.getCallingUserId();
13904        // reader
13905        synchronized (mPackages) {
13906            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13907            if (pir != null) {
13908                final Iterator<PreferredActivity> it = pir.filterIterator();
13909                while (it.hasNext()) {
13910                    final PreferredActivity pa = it.next();
13911                    if (packageName == null
13912                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13913                                    && pa.mPref.mAlways)) {
13914                        if (outFilters != null) {
13915                            outFilters.add(new IntentFilter(pa));
13916                        }
13917                        if (outActivities != null) {
13918                            outActivities.add(pa.mPref.mComponent);
13919                        }
13920                    }
13921                }
13922            }
13923        }
13924
13925        return num;
13926    }
13927
13928    @Override
13929    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13930            int userId) {
13931        int callingUid = Binder.getCallingUid();
13932        if (callingUid != Process.SYSTEM_UID) {
13933            throw new SecurityException(
13934                    "addPersistentPreferredActivity can only be run by the system");
13935        }
13936        if (filter.countActions() == 0) {
13937            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13938            return;
13939        }
13940        synchronized (mPackages) {
13941            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13942                    " :");
13943            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13944            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13945                    new PersistentPreferredActivity(filter, activity));
13946            scheduleWritePackageRestrictionsLocked(userId);
13947        }
13948    }
13949
13950    @Override
13951    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13952        int callingUid = Binder.getCallingUid();
13953        if (callingUid != Process.SYSTEM_UID) {
13954            throw new SecurityException(
13955                    "clearPackagePersistentPreferredActivities can only be run by the system");
13956        }
13957        ArrayList<PersistentPreferredActivity> removed = null;
13958        boolean changed = false;
13959        synchronized (mPackages) {
13960            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13961                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13962                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13963                        .valueAt(i);
13964                if (userId != thisUserId) {
13965                    continue;
13966                }
13967                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13968                while (it.hasNext()) {
13969                    PersistentPreferredActivity ppa = it.next();
13970                    // Mark entry for removal only if it matches the package name.
13971                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13972                        if (removed == null) {
13973                            removed = new ArrayList<PersistentPreferredActivity>();
13974                        }
13975                        removed.add(ppa);
13976                    }
13977                }
13978                if (removed != null) {
13979                    for (int j=0; j<removed.size(); j++) {
13980                        PersistentPreferredActivity ppa = removed.get(j);
13981                        ppir.removeFilter(ppa);
13982                    }
13983                    changed = true;
13984                }
13985            }
13986
13987            if (changed) {
13988                scheduleWritePackageRestrictionsLocked(userId);
13989            }
13990        }
13991    }
13992
13993    /**
13994     * Common machinery for picking apart a restored XML blob and passing
13995     * it to a caller-supplied functor to be applied to the running system.
13996     */
13997    private void restoreFromXml(XmlPullParser parser, int userId,
13998            String expectedStartTag, BlobXmlRestorer functor)
13999            throws IOException, XmlPullParserException {
14000        int type;
14001        while ((type = parser.next()) != XmlPullParser.START_TAG
14002                && type != XmlPullParser.END_DOCUMENT) {
14003        }
14004        if (type != XmlPullParser.START_TAG) {
14005            // oops didn't find a start tag?!
14006            if (DEBUG_BACKUP) {
14007                Slog.e(TAG, "Didn't find start tag during restore");
14008            }
14009            return;
14010        }
14011
14012        // this is supposed to be TAG_PREFERRED_BACKUP
14013        if (!expectedStartTag.equals(parser.getName())) {
14014            if (DEBUG_BACKUP) {
14015                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14016            }
14017            return;
14018        }
14019
14020        // skip interfering stuff, then we're aligned with the backing implementation
14021        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14022        functor.apply(parser, userId);
14023    }
14024
14025    private interface BlobXmlRestorer {
14026        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14027    }
14028
14029    /**
14030     * Non-Binder method, support for the backup/restore mechanism: write the
14031     * full set of preferred activities in its canonical XML format.  Returns the
14032     * XML output as a byte array, or null if there is none.
14033     */
14034    @Override
14035    public byte[] getPreferredActivityBackup(int userId) {
14036        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14037            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14038        }
14039
14040        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14041        try {
14042            final XmlSerializer serializer = new FastXmlSerializer();
14043            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14044            serializer.startDocument(null, true);
14045            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14046
14047            synchronized (mPackages) {
14048                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14049            }
14050
14051            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14052            serializer.endDocument();
14053            serializer.flush();
14054        } catch (Exception e) {
14055            if (DEBUG_BACKUP) {
14056                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14057            }
14058            return null;
14059        }
14060
14061        return dataStream.toByteArray();
14062    }
14063
14064    @Override
14065    public void restorePreferredActivities(byte[] backup, int userId) {
14066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14067            throw new SecurityException("Only the system may call restorePreferredActivities()");
14068        }
14069
14070        try {
14071            final XmlPullParser parser = Xml.newPullParser();
14072            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14073            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14074                    new BlobXmlRestorer() {
14075                        @Override
14076                        public void apply(XmlPullParser parser, int userId)
14077                                throws XmlPullParserException, IOException {
14078                            synchronized (mPackages) {
14079                                mSettings.readPreferredActivitiesLPw(parser, userId);
14080                            }
14081                        }
14082                    } );
14083        } catch (Exception e) {
14084            if (DEBUG_BACKUP) {
14085                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14086            }
14087        }
14088    }
14089
14090    /**
14091     * Non-Binder method, support for the backup/restore mechanism: write the
14092     * default browser (etc) settings in its canonical XML format.  Returns the default
14093     * browser XML representation as a byte array, or null if there is none.
14094     */
14095    @Override
14096    public byte[] getDefaultAppsBackup(int userId) {
14097        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14098            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14099        }
14100
14101        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14102        try {
14103            final XmlSerializer serializer = new FastXmlSerializer();
14104            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14105            serializer.startDocument(null, true);
14106            serializer.startTag(null, TAG_DEFAULT_APPS);
14107
14108            synchronized (mPackages) {
14109                mSettings.writeDefaultAppsLPr(serializer, userId);
14110            }
14111
14112            serializer.endTag(null, TAG_DEFAULT_APPS);
14113            serializer.endDocument();
14114            serializer.flush();
14115        } catch (Exception e) {
14116            if (DEBUG_BACKUP) {
14117                Slog.e(TAG, "Unable to write default apps for backup", e);
14118            }
14119            return null;
14120        }
14121
14122        return dataStream.toByteArray();
14123    }
14124
14125    @Override
14126    public void restoreDefaultApps(byte[] backup, int userId) {
14127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14128            throw new SecurityException("Only the system may call restoreDefaultApps()");
14129        }
14130
14131        try {
14132            final XmlPullParser parser = Xml.newPullParser();
14133            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14134            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14135                    new BlobXmlRestorer() {
14136                        @Override
14137                        public void apply(XmlPullParser parser, int userId)
14138                                throws XmlPullParserException, IOException {
14139                            synchronized (mPackages) {
14140                                mSettings.readDefaultAppsLPw(parser, userId);
14141                            }
14142                        }
14143                    } );
14144        } catch (Exception e) {
14145            if (DEBUG_BACKUP) {
14146                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14147            }
14148        }
14149    }
14150
14151    @Override
14152    public byte[] getIntentFilterVerificationBackup(int userId) {
14153        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14154            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14155        }
14156
14157        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14158        try {
14159            final XmlSerializer serializer = new FastXmlSerializer();
14160            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14161            serializer.startDocument(null, true);
14162            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14163
14164            synchronized (mPackages) {
14165                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14166            }
14167
14168            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14169            serializer.endDocument();
14170            serializer.flush();
14171        } catch (Exception e) {
14172            if (DEBUG_BACKUP) {
14173                Slog.e(TAG, "Unable to write default apps for backup", e);
14174            }
14175            return null;
14176        }
14177
14178        return dataStream.toByteArray();
14179    }
14180
14181    @Override
14182    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14184            throw new SecurityException("Only the system may call restorePreferredActivities()");
14185        }
14186
14187        try {
14188            final XmlPullParser parser = Xml.newPullParser();
14189            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14190            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14191                    new BlobXmlRestorer() {
14192                        @Override
14193                        public void apply(XmlPullParser parser, int userId)
14194                                throws XmlPullParserException, IOException {
14195                            synchronized (mPackages) {
14196                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14197                                mSettings.writeLPr();
14198                            }
14199                        }
14200                    } );
14201        } catch (Exception e) {
14202            if (DEBUG_BACKUP) {
14203                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14204            }
14205        }
14206    }
14207
14208    @Override
14209    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14210            int sourceUserId, int targetUserId, int flags) {
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        if (intentFilter.countActions() == 0) {
14217            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14218            return;
14219        }
14220        synchronized (mPackages) {
14221            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14222                    ownerPackage, targetUserId, flags);
14223            CrossProfileIntentResolver resolver =
14224                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14225            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14226            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14227            if (existing != null) {
14228                int size = existing.size();
14229                for (int i = 0; i < size; i++) {
14230                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14231                        return;
14232                    }
14233                }
14234            }
14235            resolver.addFilter(newFilter);
14236            scheduleWritePackageRestrictionsLocked(sourceUserId);
14237        }
14238    }
14239
14240    @Override
14241    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14242        mContext.enforceCallingOrSelfPermission(
14243                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14244        int callingUid = Binder.getCallingUid();
14245        enforceOwnerRights(ownerPackage, callingUid);
14246        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14247        synchronized (mPackages) {
14248            CrossProfileIntentResolver resolver =
14249                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14250            ArraySet<CrossProfileIntentFilter> set =
14251                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14252            for (CrossProfileIntentFilter filter : set) {
14253                if (filter.getOwnerPackage().equals(ownerPackage)) {
14254                    resolver.removeFilter(filter);
14255                }
14256            }
14257            scheduleWritePackageRestrictionsLocked(sourceUserId);
14258        }
14259    }
14260
14261    // Enforcing that callingUid is owning pkg on userId
14262    private void enforceOwnerRights(String pkg, int callingUid) {
14263        // The system owns everything.
14264        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14265            return;
14266        }
14267        int callingUserId = UserHandle.getUserId(callingUid);
14268        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14269        if (pi == null) {
14270            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14271                    + callingUserId);
14272        }
14273        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14274            throw new SecurityException("Calling uid " + callingUid
14275                    + " does not own package " + pkg);
14276        }
14277    }
14278
14279    @Override
14280    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14281        Intent intent = new Intent(Intent.ACTION_MAIN);
14282        intent.addCategory(Intent.CATEGORY_HOME);
14283
14284        final int callingUserId = UserHandle.getCallingUserId();
14285        List<ResolveInfo> list = queryIntentActivities(intent, null,
14286                PackageManager.GET_META_DATA, callingUserId);
14287        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14288                true, false, false, callingUserId);
14289
14290        allHomeCandidates.clear();
14291        if (list != null) {
14292            for (ResolveInfo ri : list) {
14293                allHomeCandidates.add(ri);
14294            }
14295        }
14296        return (preferred == null || preferred.activityInfo == null)
14297                ? null
14298                : new ComponentName(preferred.activityInfo.packageName,
14299                        preferred.activityInfo.name);
14300    }
14301
14302    @Override
14303    public void setApplicationEnabledSetting(String appPackageName,
14304            int newState, int flags, int userId, String callingPackage) {
14305        if (!sUserManager.exists(userId)) return;
14306        if (callingPackage == null) {
14307            callingPackage = Integer.toString(Binder.getCallingUid());
14308        }
14309        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14310    }
14311
14312    @Override
14313    public void setComponentEnabledSetting(ComponentName componentName,
14314            int newState, int flags, int userId) {
14315        if (!sUserManager.exists(userId)) return;
14316        setEnabledSetting(componentName.getPackageName(),
14317                componentName.getClassName(), newState, flags, userId, null);
14318    }
14319
14320    private void setEnabledSetting(final String packageName, String className, int newState,
14321            final int flags, int userId, String callingPackage) {
14322        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14323              || newState == COMPONENT_ENABLED_STATE_ENABLED
14324              || newState == COMPONENT_ENABLED_STATE_DISABLED
14325              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14326              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14327            throw new IllegalArgumentException("Invalid new component state: "
14328                    + newState);
14329        }
14330        PackageSetting pkgSetting;
14331        final int uid = Binder.getCallingUid();
14332        final int permission = mContext.checkCallingOrSelfPermission(
14333                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14334        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14335        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14336        boolean sendNow = false;
14337        boolean isApp = (className == null);
14338        String componentName = isApp ? packageName : className;
14339        int packageUid = -1;
14340        ArrayList<String> components;
14341
14342        // writer
14343        synchronized (mPackages) {
14344            pkgSetting = mSettings.mPackages.get(packageName);
14345            if (pkgSetting == null) {
14346                if (className == null) {
14347                    throw new IllegalArgumentException(
14348                            "Unknown package: " + packageName);
14349                }
14350                throw new IllegalArgumentException(
14351                        "Unknown component: " + packageName
14352                        + "/" + className);
14353            }
14354            // Allow root and verify that userId is not being specified by a different user
14355            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14356                throw new SecurityException(
14357                        "Permission Denial: attempt to change component state from pid="
14358                        + Binder.getCallingPid()
14359                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14360            }
14361            if (className == null) {
14362                // We're dealing with an application/package level state change
14363                if (pkgSetting.getEnabled(userId) == newState) {
14364                    // Nothing to do
14365                    return;
14366                }
14367                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14368                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14369                    // Don't care about who enables an app.
14370                    callingPackage = null;
14371                }
14372                pkgSetting.setEnabled(newState, userId, callingPackage);
14373                // pkgSetting.pkg.mSetEnabled = newState;
14374            } else {
14375                // We're dealing with a component level state change
14376                // First, verify that this is a valid class name.
14377                PackageParser.Package pkg = pkgSetting.pkg;
14378                if (pkg == null || !pkg.hasComponentClassName(className)) {
14379                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14380                        throw new IllegalArgumentException("Component class " + className
14381                                + " does not exist in " + packageName);
14382                    } else {
14383                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14384                                + className + " does not exist in " + packageName);
14385                    }
14386                }
14387                switch (newState) {
14388                case COMPONENT_ENABLED_STATE_ENABLED:
14389                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14390                        return;
14391                    }
14392                    break;
14393                case COMPONENT_ENABLED_STATE_DISABLED:
14394                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14395                        return;
14396                    }
14397                    break;
14398                case COMPONENT_ENABLED_STATE_DEFAULT:
14399                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14400                        return;
14401                    }
14402                    break;
14403                default:
14404                    Slog.e(TAG, "Invalid new component state: " + newState);
14405                    return;
14406                }
14407            }
14408            scheduleWritePackageRestrictionsLocked(userId);
14409            components = mPendingBroadcasts.get(userId, packageName);
14410            final boolean newPackage = components == null;
14411            if (newPackage) {
14412                components = new ArrayList<String>();
14413            }
14414            if (!components.contains(componentName)) {
14415                components.add(componentName);
14416            }
14417            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14418                sendNow = true;
14419                // Purge entry from pending broadcast list if another one exists already
14420                // since we are sending one right away.
14421                mPendingBroadcasts.remove(userId, packageName);
14422            } else {
14423                if (newPackage) {
14424                    mPendingBroadcasts.put(userId, packageName, components);
14425                }
14426                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14427                    // Schedule a message
14428                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14429                }
14430            }
14431        }
14432
14433        long callingId = Binder.clearCallingIdentity();
14434        try {
14435            if (sendNow) {
14436                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14437                sendPackageChangedBroadcast(packageName,
14438                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14439            }
14440        } finally {
14441            Binder.restoreCallingIdentity(callingId);
14442        }
14443    }
14444
14445    private void sendPackageChangedBroadcast(String packageName,
14446            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14447        if (DEBUG_INSTALL)
14448            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14449                    + componentNames);
14450        Bundle extras = new Bundle(4);
14451        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14452        String nameList[] = new String[componentNames.size()];
14453        componentNames.toArray(nameList);
14454        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14455        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14456        extras.putInt(Intent.EXTRA_UID, packageUid);
14457        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14458                new int[] {UserHandle.getUserId(packageUid)});
14459    }
14460
14461    @Override
14462    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14463        if (!sUserManager.exists(userId)) return;
14464        final int uid = Binder.getCallingUid();
14465        final int permission = mContext.checkCallingOrSelfPermission(
14466                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14467        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14468        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14469        // writer
14470        synchronized (mPackages) {
14471            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14472                    allowedByPermission, uid, userId)) {
14473                scheduleWritePackageRestrictionsLocked(userId);
14474            }
14475        }
14476    }
14477
14478    @Override
14479    public String getInstallerPackageName(String packageName) {
14480        // reader
14481        synchronized (mPackages) {
14482            return mSettings.getInstallerPackageNameLPr(packageName);
14483        }
14484    }
14485
14486    @Override
14487    public int getApplicationEnabledSetting(String packageName, int userId) {
14488        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14489        int uid = Binder.getCallingUid();
14490        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14491        // reader
14492        synchronized (mPackages) {
14493            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14494        }
14495    }
14496
14497    @Override
14498    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14499        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14500        int uid = Binder.getCallingUid();
14501        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14502        // reader
14503        synchronized (mPackages) {
14504            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14505        }
14506    }
14507
14508    @Override
14509    public void enterSafeMode() {
14510        enforceSystemOrRoot("Only the system can request entering safe mode");
14511
14512        if (!mSystemReady) {
14513            mSafeMode = true;
14514        }
14515    }
14516
14517    @Override
14518    public void systemReady() {
14519        mSystemReady = true;
14520
14521        // Read the compatibilty setting when the system is ready.
14522        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14523                mContext.getContentResolver(),
14524                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14525        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14526        if (DEBUG_SETTINGS) {
14527            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14528        }
14529
14530        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14531
14532        synchronized (mPackages) {
14533            // Verify that all of the preferred activity components actually
14534            // exist.  It is possible for applications to be updated and at
14535            // that point remove a previously declared activity component that
14536            // had been set as a preferred activity.  We try to clean this up
14537            // the next time we encounter that preferred activity, but it is
14538            // possible for the user flow to never be able to return to that
14539            // situation so here we do a sanity check to make sure we haven't
14540            // left any junk around.
14541            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14542            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14543                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14544                removed.clear();
14545                for (PreferredActivity pa : pir.filterSet()) {
14546                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14547                        removed.add(pa);
14548                    }
14549                }
14550                if (removed.size() > 0) {
14551                    for (int r=0; r<removed.size(); r++) {
14552                        PreferredActivity pa = removed.get(r);
14553                        Slog.w(TAG, "Removing dangling preferred activity: "
14554                                + pa.mPref.mComponent);
14555                        pir.removeFilter(pa);
14556                    }
14557                    mSettings.writePackageRestrictionsLPr(
14558                            mSettings.mPreferredActivities.keyAt(i));
14559                }
14560            }
14561
14562            for (int userId : UserManagerService.getInstance().getUserIds()) {
14563                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14564                    grantPermissionsUserIds = ArrayUtils.appendInt(
14565                            grantPermissionsUserIds, userId);
14566                }
14567            }
14568        }
14569        sUserManager.systemReady();
14570
14571        // If we upgraded grant all default permissions before kicking off.
14572        for (int userId : grantPermissionsUserIds) {
14573            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14574        }
14575
14576        // Kick off any messages waiting for system ready
14577        if (mPostSystemReadyMessages != null) {
14578            for (Message msg : mPostSystemReadyMessages) {
14579                msg.sendToTarget();
14580            }
14581            mPostSystemReadyMessages = null;
14582        }
14583
14584        // Watch for external volumes that come and go over time
14585        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14586        storage.registerListener(mStorageListener);
14587
14588        mInstallerService.systemReady();
14589        mPackageDexOptimizer.systemReady();
14590
14591        MountServiceInternal mountServiceInternal = LocalServices.getService(
14592                MountServiceInternal.class);
14593        mountServiceInternal.addExternalStoragePolicy(
14594                new MountServiceInternal.ExternalStorageMountPolicy() {
14595            @Override
14596            public int getMountMode(int uid, String packageName) {
14597                if (Process.isIsolated(uid)) {
14598                    return Zygote.MOUNT_EXTERNAL_NONE;
14599                }
14600                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14601                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14602                }
14603                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14604                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14605                }
14606                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14607                    return Zygote.MOUNT_EXTERNAL_READ;
14608                }
14609                return Zygote.MOUNT_EXTERNAL_WRITE;
14610            }
14611
14612            @Override
14613            public boolean hasExternalStorage(int uid, String packageName) {
14614                return true;
14615            }
14616        });
14617    }
14618
14619    @Override
14620    public boolean isSafeMode() {
14621        return mSafeMode;
14622    }
14623
14624    @Override
14625    public boolean hasSystemUidErrors() {
14626        return mHasSystemUidErrors;
14627    }
14628
14629    static String arrayToString(int[] array) {
14630        StringBuffer buf = new StringBuffer(128);
14631        buf.append('[');
14632        if (array != null) {
14633            for (int i=0; i<array.length; i++) {
14634                if (i > 0) buf.append(", ");
14635                buf.append(array[i]);
14636            }
14637        }
14638        buf.append(']');
14639        return buf.toString();
14640    }
14641
14642    static class DumpState {
14643        public static final int DUMP_LIBS = 1 << 0;
14644        public static final int DUMP_FEATURES = 1 << 1;
14645        public static final int DUMP_RESOLVERS = 1 << 2;
14646        public static final int DUMP_PERMISSIONS = 1 << 3;
14647        public static final int DUMP_PACKAGES = 1 << 4;
14648        public static final int DUMP_SHARED_USERS = 1 << 5;
14649        public static final int DUMP_MESSAGES = 1 << 6;
14650        public static final int DUMP_PROVIDERS = 1 << 7;
14651        public static final int DUMP_VERIFIERS = 1 << 8;
14652        public static final int DUMP_PREFERRED = 1 << 9;
14653        public static final int DUMP_PREFERRED_XML = 1 << 10;
14654        public static final int DUMP_KEYSETS = 1 << 11;
14655        public static final int DUMP_VERSION = 1 << 12;
14656        public static final int DUMP_INSTALLS = 1 << 13;
14657        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14658        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14659
14660        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14661
14662        private int mTypes;
14663
14664        private int mOptions;
14665
14666        private boolean mTitlePrinted;
14667
14668        private SharedUserSetting mSharedUser;
14669
14670        public boolean isDumping(int type) {
14671            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14672                return true;
14673            }
14674
14675            return (mTypes & type) != 0;
14676        }
14677
14678        public void setDump(int type) {
14679            mTypes |= type;
14680        }
14681
14682        public boolean isOptionEnabled(int option) {
14683            return (mOptions & option) != 0;
14684        }
14685
14686        public void setOptionEnabled(int option) {
14687            mOptions |= option;
14688        }
14689
14690        public boolean onTitlePrinted() {
14691            final boolean printed = mTitlePrinted;
14692            mTitlePrinted = true;
14693            return printed;
14694        }
14695
14696        public boolean getTitlePrinted() {
14697            return mTitlePrinted;
14698        }
14699
14700        public void setTitlePrinted(boolean enabled) {
14701            mTitlePrinted = enabled;
14702        }
14703
14704        public SharedUserSetting getSharedUser() {
14705            return mSharedUser;
14706        }
14707
14708        public void setSharedUser(SharedUserSetting user) {
14709            mSharedUser = user;
14710        }
14711    }
14712
14713    @Override
14714    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14715        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14716                != PackageManager.PERMISSION_GRANTED) {
14717            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14718                    + Binder.getCallingPid()
14719                    + ", uid=" + Binder.getCallingUid()
14720                    + " without permission "
14721                    + android.Manifest.permission.DUMP);
14722            return;
14723        }
14724
14725        DumpState dumpState = new DumpState();
14726        boolean fullPreferred = false;
14727        boolean checkin = false;
14728
14729        String packageName = null;
14730        ArraySet<String> permissionNames = null;
14731
14732        int opti = 0;
14733        while (opti < args.length) {
14734            String opt = args[opti];
14735            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14736                break;
14737            }
14738            opti++;
14739
14740            if ("-a".equals(opt)) {
14741                // Right now we only know how to print all.
14742            } else if ("-h".equals(opt)) {
14743                pw.println("Package manager dump options:");
14744                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14745                pw.println("    --checkin: dump for a checkin");
14746                pw.println("    -f: print details of intent filters");
14747                pw.println("    -h: print this help");
14748                pw.println("  cmd may be one of:");
14749                pw.println("    l[ibraries]: list known shared libraries");
14750                pw.println("    f[ibraries]: list device features");
14751                pw.println("    k[eysets]: print known keysets");
14752                pw.println("    r[esolvers]: dump intent resolvers");
14753                pw.println("    perm[issions]: dump permissions");
14754                pw.println("    permission [name ...]: dump declaration and use of given permission");
14755                pw.println("    pref[erred]: print preferred package settings");
14756                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14757                pw.println("    prov[iders]: dump content providers");
14758                pw.println("    p[ackages]: dump installed packages");
14759                pw.println("    s[hared-users]: dump shared user IDs");
14760                pw.println("    m[essages]: print collected runtime messages");
14761                pw.println("    v[erifiers]: print package verifier info");
14762                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14763                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14764                pw.println("    version: print database version info");
14765                pw.println("    write: write current settings now");
14766                pw.println("    installs: details about install sessions");
14767                pw.println("    <package.name>: info about given package");
14768                return;
14769            } else if ("--checkin".equals(opt)) {
14770                checkin = true;
14771            } else if ("-f".equals(opt)) {
14772                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14773            } else {
14774                pw.println("Unknown argument: " + opt + "; use -h for help");
14775            }
14776        }
14777
14778        // Is the caller requesting to dump a particular piece of data?
14779        if (opti < args.length) {
14780            String cmd = args[opti];
14781            opti++;
14782            // Is this a package name?
14783            if ("android".equals(cmd) || cmd.contains(".")) {
14784                packageName = cmd;
14785                // When dumping a single package, we always dump all of its
14786                // filter information since the amount of data will be reasonable.
14787                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14788            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14789                dumpState.setDump(DumpState.DUMP_LIBS);
14790            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14791                dumpState.setDump(DumpState.DUMP_FEATURES);
14792            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14793                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14794            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14795                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14796            } else if ("permission".equals(cmd)) {
14797                if (opti >= args.length) {
14798                    pw.println("Error: permission requires permission name");
14799                    return;
14800                }
14801                permissionNames = new ArraySet<>();
14802                while (opti < args.length) {
14803                    permissionNames.add(args[opti]);
14804                    opti++;
14805                }
14806                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14807                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14808            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14809                dumpState.setDump(DumpState.DUMP_PREFERRED);
14810            } else if ("preferred-xml".equals(cmd)) {
14811                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14812                if (opti < args.length && "--full".equals(args[opti])) {
14813                    fullPreferred = true;
14814                    opti++;
14815                }
14816            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14817                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14818            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14819                dumpState.setDump(DumpState.DUMP_PACKAGES);
14820            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14821                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14822            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14823                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14824            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14825                dumpState.setDump(DumpState.DUMP_MESSAGES);
14826            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14827                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14828            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14829                    || "intent-filter-verifiers".equals(cmd)) {
14830                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14831            } else if ("version".equals(cmd)) {
14832                dumpState.setDump(DumpState.DUMP_VERSION);
14833            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14834                dumpState.setDump(DumpState.DUMP_KEYSETS);
14835            } else if ("installs".equals(cmd)) {
14836                dumpState.setDump(DumpState.DUMP_INSTALLS);
14837            } else if ("write".equals(cmd)) {
14838                synchronized (mPackages) {
14839                    mSettings.writeLPr();
14840                    pw.println("Settings written.");
14841                    return;
14842                }
14843            }
14844        }
14845
14846        if (checkin) {
14847            pw.println("vers,1");
14848        }
14849
14850        // reader
14851        synchronized (mPackages) {
14852            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14853                if (!checkin) {
14854                    if (dumpState.onTitlePrinted())
14855                        pw.println();
14856                    pw.println("Database versions:");
14857                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14858                }
14859            }
14860
14861            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14862                if (!checkin) {
14863                    if (dumpState.onTitlePrinted())
14864                        pw.println();
14865                    pw.println("Verifiers:");
14866                    pw.print("  Required: ");
14867                    pw.print(mRequiredVerifierPackage);
14868                    pw.print(" (uid=");
14869                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14870                    pw.println(")");
14871                } else if (mRequiredVerifierPackage != null) {
14872                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14873                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14874                }
14875            }
14876
14877            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14878                    packageName == null) {
14879                if (mIntentFilterVerifierComponent != null) {
14880                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14881                    if (!checkin) {
14882                        if (dumpState.onTitlePrinted())
14883                            pw.println();
14884                        pw.println("Intent Filter Verifier:");
14885                        pw.print("  Using: ");
14886                        pw.print(verifierPackageName);
14887                        pw.print(" (uid=");
14888                        pw.print(getPackageUid(verifierPackageName, 0));
14889                        pw.println(")");
14890                    } else if (verifierPackageName != null) {
14891                        pw.print("ifv,"); pw.print(verifierPackageName);
14892                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14893                    }
14894                } else {
14895                    pw.println();
14896                    pw.println("No Intent Filter Verifier available!");
14897                }
14898            }
14899
14900            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14901                boolean printedHeader = false;
14902                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14903                while (it.hasNext()) {
14904                    String name = it.next();
14905                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14906                    if (!checkin) {
14907                        if (!printedHeader) {
14908                            if (dumpState.onTitlePrinted())
14909                                pw.println();
14910                            pw.println("Libraries:");
14911                            printedHeader = true;
14912                        }
14913                        pw.print("  ");
14914                    } else {
14915                        pw.print("lib,");
14916                    }
14917                    pw.print(name);
14918                    if (!checkin) {
14919                        pw.print(" -> ");
14920                    }
14921                    if (ent.path != null) {
14922                        if (!checkin) {
14923                            pw.print("(jar) ");
14924                            pw.print(ent.path);
14925                        } else {
14926                            pw.print(",jar,");
14927                            pw.print(ent.path);
14928                        }
14929                    } else {
14930                        if (!checkin) {
14931                            pw.print("(apk) ");
14932                            pw.print(ent.apk);
14933                        } else {
14934                            pw.print(",apk,");
14935                            pw.print(ent.apk);
14936                        }
14937                    }
14938                    pw.println();
14939                }
14940            }
14941
14942            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14943                if (dumpState.onTitlePrinted())
14944                    pw.println();
14945                if (!checkin) {
14946                    pw.println("Features:");
14947                }
14948                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14949                while (it.hasNext()) {
14950                    String name = it.next();
14951                    if (!checkin) {
14952                        pw.print("  ");
14953                    } else {
14954                        pw.print("feat,");
14955                    }
14956                    pw.println(name);
14957                }
14958            }
14959
14960            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14961                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14962                        : "Activity Resolver Table:", "  ", packageName,
14963                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14964                    dumpState.setTitlePrinted(true);
14965                }
14966                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14967                        : "Receiver Resolver Table:", "  ", packageName,
14968                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14969                    dumpState.setTitlePrinted(true);
14970                }
14971                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14972                        : "Service Resolver Table:", "  ", packageName,
14973                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14974                    dumpState.setTitlePrinted(true);
14975                }
14976                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14977                        : "Provider Resolver Table:", "  ", packageName,
14978                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14979                    dumpState.setTitlePrinted(true);
14980                }
14981            }
14982
14983            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14984                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14985                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14986                    int user = mSettings.mPreferredActivities.keyAt(i);
14987                    if (pir.dump(pw,
14988                            dumpState.getTitlePrinted()
14989                                ? "\nPreferred Activities User " + user + ":"
14990                                : "Preferred Activities User " + user + ":", "  ",
14991                            packageName, true, false)) {
14992                        dumpState.setTitlePrinted(true);
14993                    }
14994                }
14995            }
14996
14997            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14998                pw.flush();
14999                FileOutputStream fout = new FileOutputStream(fd);
15000                BufferedOutputStream str = new BufferedOutputStream(fout);
15001                XmlSerializer serializer = new FastXmlSerializer();
15002                try {
15003                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15004                    serializer.startDocument(null, true);
15005                    serializer.setFeature(
15006                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15007                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15008                    serializer.endDocument();
15009                    serializer.flush();
15010                } catch (IllegalArgumentException e) {
15011                    pw.println("Failed writing: " + e);
15012                } catch (IllegalStateException e) {
15013                    pw.println("Failed writing: " + e);
15014                } catch (IOException e) {
15015                    pw.println("Failed writing: " + e);
15016                }
15017            }
15018
15019            if (!checkin
15020                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15021                    && packageName == null) {
15022                pw.println();
15023                int count = mSettings.mPackages.size();
15024                if (count == 0) {
15025                    pw.println("No applications!");
15026                    pw.println();
15027                } else {
15028                    final String prefix = "  ";
15029                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15030                    if (allPackageSettings.size() == 0) {
15031                        pw.println("No domain preferred apps!");
15032                        pw.println();
15033                    } else {
15034                        pw.println("App verification status:");
15035                        pw.println();
15036                        count = 0;
15037                        for (PackageSetting ps : allPackageSettings) {
15038                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15039                            if (ivi == null || ivi.getPackageName() == null) continue;
15040                            pw.println(prefix + "Package: " + ivi.getPackageName());
15041                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15042                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15043                            pw.println();
15044                            count++;
15045                        }
15046                        if (count == 0) {
15047                            pw.println(prefix + "No app verification established.");
15048                            pw.println();
15049                        }
15050                        for (int userId : sUserManager.getUserIds()) {
15051                            pw.println("App linkages for user " + userId + ":");
15052                            pw.println();
15053                            count = 0;
15054                            for (PackageSetting ps : allPackageSettings) {
15055                                final long status = ps.getDomainVerificationStatusForUser(userId);
15056                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15057                                    continue;
15058                                }
15059                                pw.println(prefix + "Package: " + ps.name);
15060                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15061                                String statusStr = IntentFilterVerificationInfo.
15062                                        getStatusStringFromValue(status);
15063                                pw.println(prefix + "Status:  " + statusStr);
15064                                pw.println();
15065                                count++;
15066                            }
15067                            if (count == 0) {
15068                                pw.println(prefix + "No configured app linkages.");
15069                                pw.println();
15070                            }
15071                        }
15072                    }
15073                }
15074            }
15075
15076            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15077                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15078                if (packageName == null && permissionNames == null) {
15079                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15080                        if (iperm == 0) {
15081                            if (dumpState.onTitlePrinted())
15082                                pw.println();
15083                            pw.println("AppOp Permissions:");
15084                        }
15085                        pw.print("  AppOp Permission ");
15086                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15087                        pw.println(":");
15088                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15089                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15090                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15091                        }
15092                    }
15093                }
15094            }
15095
15096            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15097                boolean printedSomething = false;
15098                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15099                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15100                        continue;
15101                    }
15102                    if (!printedSomething) {
15103                        if (dumpState.onTitlePrinted())
15104                            pw.println();
15105                        pw.println("Registered ContentProviders:");
15106                        printedSomething = true;
15107                    }
15108                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15109                    pw.print("    "); pw.println(p.toString());
15110                }
15111                printedSomething = false;
15112                for (Map.Entry<String, PackageParser.Provider> entry :
15113                        mProvidersByAuthority.entrySet()) {
15114                    PackageParser.Provider p = entry.getValue();
15115                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15116                        continue;
15117                    }
15118                    if (!printedSomething) {
15119                        if (dumpState.onTitlePrinted())
15120                            pw.println();
15121                        pw.println("ContentProvider Authorities:");
15122                        printedSomething = true;
15123                    }
15124                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15125                    pw.print("    "); pw.println(p.toString());
15126                    if (p.info != null && p.info.applicationInfo != null) {
15127                        final String appInfo = p.info.applicationInfo.toString();
15128                        pw.print("      applicationInfo="); pw.println(appInfo);
15129                    }
15130                }
15131            }
15132
15133            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15134                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15135            }
15136
15137            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15138                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15139            }
15140
15141            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15142                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15143            }
15144
15145            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15146                // XXX should handle packageName != null by dumping only install data that
15147                // the given package is involved with.
15148                if (dumpState.onTitlePrinted()) pw.println();
15149                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15150            }
15151
15152            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15153                if (dumpState.onTitlePrinted()) pw.println();
15154                mSettings.dumpReadMessagesLPr(pw, dumpState);
15155
15156                pw.println();
15157                pw.println("Package warning messages:");
15158                BufferedReader in = null;
15159                String line = null;
15160                try {
15161                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15162                    while ((line = in.readLine()) != null) {
15163                        if (line.contains("ignored: updated version")) continue;
15164                        pw.println(line);
15165                    }
15166                } catch (IOException ignored) {
15167                } finally {
15168                    IoUtils.closeQuietly(in);
15169                }
15170            }
15171
15172            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15173                BufferedReader in = null;
15174                String line = null;
15175                try {
15176                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15177                    while ((line = in.readLine()) != null) {
15178                        if (line.contains("ignored: updated version")) continue;
15179                        pw.print("msg,");
15180                        pw.println(line);
15181                    }
15182                } catch (IOException ignored) {
15183                } finally {
15184                    IoUtils.closeQuietly(in);
15185                }
15186            }
15187        }
15188    }
15189
15190    private String dumpDomainString(String packageName) {
15191        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15192        List<IntentFilter> filters = getAllIntentFilters(packageName);
15193
15194        ArraySet<String> result = new ArraySet<>();
15195        if (iviList.size() > 0) {
15196            for (IntentFilterVerificationInfo ivi : iviList) {
15197                for (String host : ivi.getDomains()) {
15198                    result.add(host);
15199                }
15200            }
15201        }
15202        if (filters != null && filters.size() > 0) {
15203            for (IntentFilter filter : filters) {
15204                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15205                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15206                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15207                    result.addAll(filter.getHostsList());
15208                }
15209            }
15210        }
15211
15212        StringBuilder sb = new StringBuilder(result.size() * 16);
15213        for (String domain : result) {
15214            if (sb.length() > 0) sb.append(" ");
15215            sb.append(domain);
15216        }
15217        return sb.toString();
15218    }
15219
15220    // ------- apps on sdcard specific code -------
15221    static final boolean DEBUG_SD_INSTALL = false;
15222
15223    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15224
15225    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15226
15227    private boolean mMediaMounted = false;
15228
15229    static String getEncryptKey() {
15230        try {
15231            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15232                    SD_ENCRYPTION_KEYSTORE_NAME);
15233            if (sdEncKey == null) {
15234                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15235                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15236                if (sdEncKey == null) {
15237                    Slog.e(TAG, "Failed to create encryption keys");
15238                    return null;
15239                }
15240            }
15241            return sdEncKey;
15242        } catch (NoSuchAlgorithmException nsae) {
15243            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15244            return null;
15245        } catch (IOException ioe) {
15246            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15247            return null;
15248        }
15249    }
15250
15251    /*
15252     * Update media status on PackageManager.
15253     */
15254    @Override
15255    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15256        int callingUid = Binder.getCallingUid();
15257        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15258            throw new SecurityException("Media status can only be updated by the system");
15259        }
15260        // reader; this apparently protects mMediaMounted, but should probably
15261        // be a different lock in that case.
15262        synchronized (mPackages) {
15263            Log.i(TAG, "Updating external media status from "
15264                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15265                    + (mediaStatus ? "mounted" : "unmounted"));
15266            if (DEBUG_SD_INSTALL)
15267                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15268                        + ", mMediaMounted=" + mMediaMounted);
15269            if (mediaStatus == mMediaMounted) {
15270                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15271                        : 0, -1);
15272                mHandler.sendMessage(msg);
15273                return;
15274            }
15275            mMediaMounted = mediaStatus;
15276        }
15277        // Queue up an async operation since the package installation may take a
15278        // little while.
15279        mHandler.post(new Runnable() {
15280            public void run() {
15281                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15282            }
15283        });
15284    }
15285
15286    /**
15287     * Called by MountService when the initial ASECs to scan are available.
15288     * Should block until all the ASEC containers are finished being scanned.
15289     */
15290    public void scanAvailableAsecs() {
15291        updateExternalMediaStatusInner(true, false, false);
15292        if (mShouldRestoreconData) {
15293            SELinuxMMAC.setRestoreconDone();
15294            mShouldRestoreconData = false;
15295        }
15296    }
15297
15298    /*
15299     * Collect information of applications on external media, map them against
15300     * existing containers and update information based on current mount status.
15301     * Please note that we always have to report status if reportStatus has been
15302     * set to true especially when unloading packages.
15303     */
15304    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15305            boolean externalStorage) {
15306        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15307        int[] uidArr = EmptyArray.INT;
15308
15309        final String[] list = PackageHelper.getSecureContainerList();
15310        if (ArrayUtils.isEmpty(list)) {
15311            Log.i(TAG, "No secure containers found");
15312        } else {
15313            // Process list of secure containers and categorize them
15314            // as active or stale based on their package internal state.
15315
15316            // reader
15317            synchronized (mPackages) {
15318                for (String cid : list) {
15319                    // Leave stages untouched for now; installer service owns them
15320                    if (PackageInstallerService.isStageName(cid)) continue;
15321
15322                    if (DEBUG_SD_INSTALL)
15323                        Log.i(TAG, "Processing container " + cid);
15324                    String pkgName = getAsecPackageName(cid);
15325                    if (pkgName == null) {
15326                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15327                        continue;
15328                    }
15329                    if (DEBUG_SD_INSTALL)
15330                        Log.i(TAG, "Looking for pkg : " + pkgName);
15331
15332                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15333                    if (ps == null) {
15334                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15335                        continue;
15336                    }
15337
15338                    /*
15339                     * Skip packages that are not external if we're unmounting
15340                     * external storage.
15341                     */
15342                    if (externalStorage && !isMounted && !isExternal(ps)) {
15343                        continue;
15344                    }
15345
15346                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15347                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15348                    // The package status is changed only if the code path
15349                    // matches between settings and the container id.
15350                    if (ps.codePathString != null
15351                            && ps.codePathString.startsWith(args.getCodePath())) {
15352                        if (DEBUG_SD_INSTALL) {
15353                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15354                                    + " at code path: " + ps.codePathString);
15355                        }
15356
15357                        // We do have a valid package installed on sdcard
15358                        processCids.put(args, ps.codePathString);
15359                        final int uid = ps.appId;
15360                        if (uid != -1) {
15361                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15362                        }
15363                    } else {
15364                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15365                                + ps.codePathString);
15366                    }
15367                }
15368            }
15369
15370            Arrays.sort(uidArr);
15371        }
15372
15373        // Process packages with valid entries.
15374        if (isMounted) {
15375            if (DEBUG_SD_INSTALL)
15376                Log.i(TAG, "Loading packages");
15377            loadMediaPackages(processCids, uidArr);
15378            startCleaningPackages();
15379            mInstallerService.onSecureContainersAvailable();
15380        } else {
15381            if (DEBUG_SD_INSTALL)
15382                Log.i(TAG, "Unloading packages");
15383            unloadMediaPackages(processCids, uidArr, reportStatus);
15384        }
15385    }
15386
15387    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15388            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15389        final int size = infos.size();
15390        final String[] packageNames = new String[size];
15391        final int[] packageUids = new int[size];
15392        for (int i = 0; i < size; i++) {
15393            final ApplicationInfo info = infos.get(i);
15394            packageNames[i] = info.packageName;
15395            packageUids[i] = info.uid;
15396        }
15397        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15398                finishedReceiver);
15399    }
15400
15401    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15402            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15403        sendResourcesChangedBroadcast(mediaStatus, replacing,
15404                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15405    }
15406
15407    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15408            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15409        int size = pkgList.length;
15410        if (size > 0) {
15411            // Send broadcasts here
15412            Bundle extras = new Bundle();
15413            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15414            if (uidArr != null) {
15415                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15416            }
15417            if (replacing) {
15418                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15419            }
15420            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15421                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15422            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15423        }
15424    }
15425
15426   /*
15427     * Look at potentially valid container ids from processCids If package
15428     * information doesn't match the one on record or package scanning fails,
15429     * the cid is added to list of removeCids. We currently don't delete stale
15430     * containers.
15431     */
15432    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15433        ArrayList<String> pkgList = new ArrayList<String>();
15434        Set<AsecInstallArgs> keys = processCids.keySet();
15435
15436        for (AsecInstallArgs args : keys) {
15437            String codePath = processCids.get(args);
15438            if (DEBUG_SD_INSTALL)
15439                Log.i(TAG, "Loading container : " + args.cid);
15440            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15441            try {
15442                // Make sure there are no container errors first.
15443                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15444                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15445                            + " when installing from sdcard");
15446                    continue;
15447                }
15448                // Check code path here.
15449                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15450                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15451                            + " does not match one in settings " + codePath);
15452                    continue;
15453                }
15454                // Parse package
15455                int parseFlags = mDefParseFlags;
15456                if (args.isExternalAsec()) {
15457                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15458                }
15459                if (args.isFwdLocked()) {
15460                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15461                }
15462
15463                synchronized (mInstallLock) {
15464                    PackageParser.Package pkg = null;
15465                    try {
15466                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15467                    } catch (PackageManagerException e) {
15468                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15469                    }
15470                    // Scan the package
15471                    if (pkg != null) {
15472                        /*
15473                         * TODO why is the lock being held? doPostInstall is
15474                         * called in other places without the lock. This needs
15475                         * to be straightened out.
15476                         */
15477                        // writer
15478                        synchronized (mPackages) {
15479                            retCode = PackageManager.INSTALL_SUCCEEDED;
15480                            pkgList.add(pkg.packageName);
15481                            // Post process args
15482                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15483                                    pkg.applicationInfo.uid);
15484                        }
15485                    } else {
15486                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15487                    }
15488                }
15489
15490            } finally {
15491                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15492                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15493                }
15494            }
15495        }
15496        // writer
15497        synchronized (mPackages) {
15498            // If the platform SDK has changed since the last time we booted,
15499            // we need to re-grant app permission to catch any new ones that
15500            // appear. This is really a hack, and means that apps can in some
15501            // cases get permissions that the user didn't initially explicitly
15502            // allow... it would be nice to have some better way to handle
15503            // this situation.
15504            final VersionInfo ver = mSettings.getExternalVersion();
15505
15506            int updateFlags = UPDATE_PERMISSIONS_ALL;
15507            if (ver.sdkVersion != mSdkVersion) {
15508                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15509                        + mSdkVersion + "; regranting permissions for external");
15510                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15511            }
15512            updatePermissionsLPw(null, null, updateFlags);
15513
15514            // Yay, everything is now upgraded
15515            ver.forceCurrent();
15516
15517            // can downgrade to reader
15518            // Persist settings
15519            mSettings.writeLPr();
15520        }
15521        // Send a broadcast to let everyone know we are done processing
15522        if (pkgList.size() > 0) {
15523            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15524        }
15525    }
15526
15527   /*
15528     * Utility method to unload a list of specified containers
15529     */
15530    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15531        // Just unmount all valid containers.
15532        for (AsecInstallArgs arg : cidArgs) {
15533            synchronized (mInstallLock) {
15534                arg.doPostDeleteLI(false);
15535           }
15536       }
15537   }
15538
15539    /*
15540     * Unload packages mounted on external media. This involves deleting package
15541     * data from internal structures, sending broadcasts about diabled packages,
15542     * gc'ing to free up references, unmounting all secure containers
15543     * corresponding to packages on external media, and posting a
15544     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15545     * that we always have to post this message if status has been requested no
15546     * matter what.
15547     */
15548    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15549            final boolean reportStatus) {
15550        if (DEBUG_SD_INSTALL)
15551            Log.i(TAG, "unloading media packages");
15552        ArrayList<String> pkgList = new ArrayList<String>();
15553        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15554        final Set<AsecInstallArgs> keys = processCids.keySet();
15555        for (AsecInstallArgs args : keys) {
15556            String pkgName = args.getPackageName();
15557            if (DEBUG_SD_INSTALL)
15558                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15559            // Delete package internally
15560            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15561            synchronized (mInstallLock) {
15562                boolean res = deletePackageLI(pkgName, null, false, null, null,
15563                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15564                if (res) {
15565                    pkgList.add(pkgName);
15566                } else {
15567                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15568                    failedList.add(args);
15569                }
15570            }
15571        }
15572
15573        // reader
15574        synchronized (mPackages) {
15575            // We didn't update the settings after removing each package;
15576            // write them now for all packages.
15577            mSettings.writeLPr();
15578        }
15579
15580        // We have to absolutely send UPDATED_MEDIA_STATUS only
15581        // after confirming that all the receivers processed the ordered
15582        // broadcast when packages get disabled, force a gc to clean things up.
15583        // and unload all the containers.
15584        if (pkgList.size() > 0) {
15585            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15586                    new IIntentReceiver.Stub() {
15587                public void performReceive(Intent intent, int resultCode, String data,
15588                        Bundle extras, boolean ordered, boolean sticky,
15589                        int sendingUser) throws RemoteException {
15590                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15591                            reportStatus ? 1 : 0, 1, keys);
15592                    mHandler.sendMessage(msg);
15593                }
15594            });
15595        } else {
15596            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15597                    keys);
15598            mHandler.sendMessage(msg);
15599        }
15600    }
15601
15602    private void loadPrivatePackages(VolumeInfo vol) {
15603        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15604        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15605        synchronized (mInstallLock) {
15606        synchronized (mPackages) {
15607            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15608            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15609            for (PackageSetting ps : packages) {
15610                final PackageParser.Package pkg;
15611                try {
15612                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15613                    loaded.add(pkg.applicationInfo);
15614                } catch (PackageManagerException e) {
15615                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15616                }
15617
15618                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15619                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15620                }
15621            }
15622
15623            int updateFlags = UPDATE_PERMISSIONS_ALL;
15624            if (ver.sdkVersion != mSdkVersion) {
15625                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15626                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15627                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15628            }
15629            updatePermissionsLPw(null, null, updateFlags);
15630
15631            // Yay, everything is now upgraded
15632            ver.forceCurrent();
15633
15634            mSettings.writeLPr();
15635        }
15636        }
15637
15638        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15639        sendResourcesChangedBroadcast(true, false, loaded, null);
15640    }
15641
15642    private void unloadPrivatePackages(VolumeInfo vol) {
15643        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15644        synchronized (mInstallLock) {
15645        synchronized (mPackages) {
15646            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15647            for (PackageSetting ps : packages) {
15648                if (ps.pkg == null) continue;
15649
15650                final ApplicationInfo info = ps.pkg.applicationInfo;
15651                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15652                if (deletePackageLI(ps.name, null, false, null, null,
15653                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15654                    unloaded.add(info);
15655                } else {
15656                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15657                }
15658            }
15659
15660            mSettings.writeLPr();
15661        }
15662        }
15663
15664        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15665        sendResourcesChangedBroadcast(false, false, unloaded, null);
15666    }
15667
15668    /**
15669     * Examine all users present on given mounted volume, and destroy data
15670     * belonging to users that are no longer valid, or whose user ID has been
15671     * recycled.
15672     */
15673    private void reconcileUsers(String volumeUuid) {
15674        final File[] files = FileUtils
15675                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15676        for (File file : files) {
15677            if (!file.isDirectory()) continue;
15678
15679            final int userId;
15680            final UserInfo info;
15681            try {
15682                userId = Integer.parseInt(file.getName());
15683                info = sUserManager.getUserInfo(userId);
15684            } catch (NumberFormatException e) {
15685                Slog.w(TAG, "Invalid user directory " + file);
15686                continue;
15687            }
15688
15689            boolean destroyUser = false;
15690            if (info == null) {
15691                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15692                        + " because no matching user was found");
15693                destroyUser = true;
15694            } else {
15695                try {
15696                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15697                } catch (IOException e) {
15698                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15699                            + " because we failed to enforce serial number: " + e);
15700                    destroyUser = true;
15701                }
15702            }
15703
15704            if (destroyUser) {
15705                synchronized (mInstallLock) {
15706                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15707                }
15708            }
15709        }
15710
15711        final UserManager um = mContext.getSystemService(UserManager.class);
15712        for (UserInfo user : um.getUsers()) {
15713            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15714            if (userDir.exists()) continue;
15715
15716            try {
15717                UserManagerService.prepareUserDirectory(userDir);
15718                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15719            } catch (IOException e) {
15720                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15721            }
15722        }
15723    }
15724
15725    /**
15726     * Examine all apps present on given mounted volume, and destroy apps that
15727     * aren't expected, either due to uninstallation or reinstallation on
15728     * another volume.
15729     */
15730    private void reconcileApps(String volumeUuid) {
15731        final File[] files = FileUtils
15732                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15733        for (File file : files) {
15734            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15735                    && !PackageInstallerService.isStageName(file.getName());
15736            if (!isPackage) {
15737                // Ignore entries which are not packages
15738                continue;
15739            }
15740
15741            boolean destroyApp = false;
15742            String packageName = null;
15743            try {
15744                final PackageLite pkg = PackageParser.parsePackageLite(file,
15745                        PackageParser.PARSE_MUST_BE_APK);
15746                packageName = pkg.packageName;
15747
15748                synchronized (mPackages) {
15749                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15750                    if (ps == null) {
15751                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15752                                + volumeUuid + " because we found no install record");
15753                        destroyApp = true;
15754                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15755                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15756                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15757                        destroyApp = true;
15758                    }
15759                }
15760
15761            } catch (PackageParserException e) {
15762                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15763                destroyApp = true;
15764            }
15765
15766            if (destroyApp) {
15767                synchronized (mInstallLock) {
15768                    if (packageName != null) {
15769                        removeDataDirsLI(volumeUuid, packageName);
15770                    }
15771                    if (file.isDirectory()) {
15772                        mInstaller.rmPackageDir(file.getAbsolutePath());
15773                    } else {
15774                        file.delete();
15775                    }
15776                }
15777            }
15778        }
15779    }
15780
15781    private void unfreezePackage(String packageName) {
15782        synchronized (mPackages) {
15783            final PackageSetting ps = mSettings.mPackages.get(packageName);
15784            if (ps != null) {
15785                ps.frozen = false;
15786            }
15787        }
15788    }
15789
15790    @Override
15791    public int movePackage(final String packageName, final String volumeUuid) {
15792        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15793
15794        final int moveId = mNextMoveId.getAndIncrement();
15795        try {
15796            movePackageInternal(packageName, volumeUuid, moveId);
15797        } catch (PackageManagerException e) {
15798            Slog.w(TAG, "Failed to move " + packageName, e);
15799            mMoveCallbacks.notifyStatusChanged(moveId,
15800                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15801        }
15802        return moveId;
15803    }
15804
15805    private void movePackageInternal(final String packageName, final String volumeUuid,
15806            final int moveId) throws PackageManagerException {
15807        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15808        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15809        final PackageManager pm = mContext.getPackageManager();
15810
15811        final boolean currentAsec;
15812        final String currentVolumeUuid;
15813        final File codeFile;
15814        final String installerPackageName;
15815        final String packageAbiOverride;
15816        final int appId;
15817        final String seinfo;
15818        final String label;
15819
15820        // reader
15821        synchronized (mPackages) {
15822            final PackageParser.Package pkg = mPackages.get(packageName);
15823            final PackageSetting ps = mSettings.mPackages.get(packageName);
15824            if (pkg == null || ps == null) {
15825                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15826            }
15827
15828            if (pkg.applicationInfo.isSystemApp()) {
15829                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15830                        "Cannot move system application");
15831            }
15832
15833            if (pkg.applicationInfo.isExternalAsec()) {
15834                currentAsec = true;
15835                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15836            } else if (pkg.applicationInfo.isForwardLocked()) {
15837                currentAsec = true;
15838                currentVolumeUuid = "forward_locked";
15839            } else {
15840                currentAsec = false;
15841                currentVolumeUuid = ps.volumeUuid;
15842
15843                final File probe = new File(pkg.codePath);
15844                final File probeOat = new File(probe, "oat");
15845                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15846                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15847                            "Move only supported for modern cluster style installs");
15848                }
15849            }
15850
15851            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15852                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15853                        "Package already moved to " + volumeUuid);
15854            }
15855
15856            if (ps.frozen) {
15857                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15858                        "Failed to move already frozen package");
15859            }
15860            ps.frozen = true;
15861
15862            codeFile = new File(pkg.codePath);
15863            installerPackageName = ps.installerPackageName;
15864            packageAbiOverride = ps.cpuAbiOverrideString;
15865            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15866            seinfo = pkg.applicationInfo.seinfo;
15867            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15868        }
15869
15870        // Now that we're guarded by frozen state, kill app during move
15871        final long token = Binder.clearCallingIdentity();
15872        try {
15873            killApplication(packageName, appId, "move pkg");
15874        } finally {
15875            Binder.restoreCallingIdentity(token);
15876        }
15877
15878        final Bundle extras = new Bundle();
15879        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15880        extras.putString(Intent.EXTRA_TITLE, label);
15881        mMoveCallbacks.notifyCreated(moveId, extras);
15882
15883        int installFlags;
15884        final boolean moveCompleteApp;
15885        final File measurePath;
15886
15887        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15888            installFlags = INSTALL_INTERNAL;
15889            moveCompleteApp = !currentAsec;
15890            measurePath = Environment.getDataAppDirectory(volumeUuid);
15891        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15892            installFlags = INSTALL_EXTERNAL;
15893            moveCompleteApp = false;
15894            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15895        } else {
15896            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15897            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15898                    || !volume.isMountedWritable()) {
15899                unfreezePackage(packageName);
15900                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15901                        "Move location not mounted private volume");
15902            }
15903
15904            Preconditions.checkState(!currentAsec);
15905
15906            installFlags = INSTALL_INTERNAL;
15907            moveCompleteApp = true;
15908            measurePath = Environment.getDataAppDirectory(volumeUuid);
15909        }
15910
15911        final PackageStats stats = new PackageStats(null, -1);
15912        synchronized (mInstaller) {
15913            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15914                unfreezePackage(packageName);
15915                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15916                        "Failed to measure package size");
15917            }
15918        }
15919
15920        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15921                + stats.dataSize);
15922
15923        final long startFreeBytes = measurePath.getFreeSpace();
15924        final long sizeBytes;
15925        if (moveCompleteApp) {
15926            sizeBytes = stats.codeSize + stats.dataSize;
15927        } else {
15928            sizeBytes = stats.codeSize;
15929        }
15930
15931        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15932            unfreezePackage(packageName);
15933            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15934                    "Not enough free space to move");
15935        }
15936
15937        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15938
15939        final CountDownLatch installedLatch = new CountDownLatch(1);
15940        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15941            @Override
15942            public void onUserActionRequired(Intent intent) throws RemoteException {
15943                throw new IllegalStateException();
15944            }
15945
15946            @Override
15947            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15948                    Bundle extras) throws RemoteException {
15949                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15950                        + PackageManager.installStatusToString(returnCode, msg));
15951
15952                installedLatch.countDown();
15953
15954                // Regardless of success or failure of the move operation,
15955                // always unfreeze the package
15956                unfreezePackage(packageName);
15957
15958                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15959                switch (status) {
15960                    case PackageInstaller.STATUS_SUCCESS:
15961                        mMoveCallbacks.notifyStatusChanged(moveId,
15962                                PackageManager.MOVE_SUCCEEDED);
15963                        break;
15964                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15965                        mMoveCallbacks.notifyStatusChanged(moveId,
15966                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15967                        break;
15968                    default:
15969                        mMoveCallbacks.notifyStatusChanged(moveId,
15970                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15971                        break;
15972                }
15973            }
15974        };
15975
15976        final MoveInfo move;
15977        if (moveCompleteApp) {
15978            // Kick off a thread to report progress estimates
15979            new Thread() {
15980                @Override
15981                public void run() {
15982                    while (true) {
15983                        try {
15984                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15985                                break;
15986                            }
15987                        } catch (InterruptedException ignored) {
15988                        }
15989
15990                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15991                        final int progress = 10 + (int) MathUtils.constrain(
15992                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15993                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15994                    }
15995                }
15996            }.start();
15997
15998            final String dataAppName = codeFile.getName();
15999            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16000                    dataAppName, appId, seinfo);
16001        } else {
16002            move = null;
16003        }
16004
16005        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16006
16007        final Message msg = mHandler.obtainMessage(INIT_COPY);
16008        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16009        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16010                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16011        mHandler.sendMessage(msg);
16012    }
16013
16014    @Override
16015    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16016        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16017
16018        final int realMoveId = mNextMoveId.getAndIncrement();
16019        final Bundle extras = new Bundle();
16020        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16021        mMoveCallbacks.notifyCreated(realMoveId, extras);
16022
16023        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16024            @Override
16025            public void onCreated(int moveId, Bundle extras) {
16026                // Ignored
16027            }
16028
16029            @Override
16030            public void onStatusChanged(int moveId, int status, long estMillis) {
16031                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16032            }
16033        };
16034
16035        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16036        storage.setPrimaryStorageUuid(volumeUuid, callback);
16037        return realMoveId;
16038    }
16039
16040    @Override
16041    public int getMoveStatus(int moveId) {
16042        mContext.enforceCallingOrSelfPermission(
16043                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16044        return mMoveCallbacks.mLastStatus.get(moveId);
16045    }
16046
16047    @Override
16048    public void registerMoveCallback(IPackageMoveObserver callback) {
16049        mContext.enforceCallingOrSelfPermission(
16050                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16051        mMoveCallbacks.register(callback);
16052    }
16053
16054    @Override
16055    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16056        mContext.enforceCallingOrSelfPermission(
16057                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16058        mMoveCallbacks.unregister(callback);
16059    }
16060
16061    @Override
16062    public boolean setInstallLocation(int loc) {
16063        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16064                null);
16065        if (getInstallLocation() == loc) {
16066            return true;
16067        }
16068        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16069                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16070            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16071                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16072            return true;
16073        }
16074        return false;
16075   }
16076
16077    @Override
16078    public int getInstallLocation() {
16079        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16080                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16081                PackageHelper.APP_INSTALL_AUTO);
16082    }
16083
16084    /** Called by UserManagerService */
16085    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16086        mDirtyUsers.remove(userHandle);
16087        mSettings.removeUserLPw(userHandle);
16088        mPendingBroadcasts.remove(userHandle);
16089        if (mInstaller != null) {
16090            // Technically, we shouldn't be doing this with the package lock
16091            // held.  However, this is very rare, and there is already so much
16092            // other disk I/O going on, that we'll let it slide for now.
16093            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16094            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16095                final String volumeUuid = vol.getFsUuid();
16096                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16097                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16098            }
16099        }
16100        mUserNeedsBadging.delete(userHandle);
16101        removeUnusedPackagesLILPw(userManager, userHandle);
16102    }
16103
16104    /**
16105     * We're removing userHandle and would like to remove any downloaded packages
16106     * that are no longer in use by any other user.
16107     * @param userHandle the user being removed
16108     */
16109    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16110        final boolean DEBUG_CLEAN_APKS = false;
16111        int [] users = userManager.getUserIdsLPr();
16112        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16113        while (psit.hasNext()) {
16114            PackageSetting ps = psit.next();
16115            if (ps.pkg == null) {
16116                continue;
16117            }
16118            final String packageName = ps.pkg.packageName;
16119            // Skip over if system app
16120            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16121                continue;
16122            }
16123            if (DEBUG_CLEAN_APKS) {
16124                Slog.i(TAG, "Checking package " + packageName);
16125            }
16126            boolean keep = false;
16127            for (int i = 0; i < users.length; i++) {
16128                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16129                    keep = true;
16130                    if (DEBUG_CLEAN_APKS) {
16131                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16132                                + users[i]);
16133                    }
16134                    break;
16135                }
16136            }
16137            if (!keep) {
16138                if (DEBUG_CLEAN_APKS) {
16139                    Slog.i(TAG, "  Removing package " + packageName);
16140                }
16141                mHandler.post(new Runnable() {
16142                    public void run() {
16143                        deletePackageX(packageName, userHandle, 0);
16144                    } //end run
16145                });
16146            }
16147        }
16148    }
16149
16150    /** Called by UserManagerService */
16151    void createNewUserLILPw(int userHandle) {
16152        if (mInstaller != null) {
16153            mInstaller.createUserConfig(userHandle);
16154            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16155            applyFactoryDefaultBrowserLPw(userHandle);
16156            primeDomainVerificationsLPw(userHandle);
16157        }
16158    }
16159
16160    void newUserCreated(final int userHandle) {
16161        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16162    }
16163
16164    @Override
16165    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16166        mContext.enforceCallingOrSelfPermission(
16167                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16168                "Only package verification agents can read the verifier device identity");
16169
16170        synchronized (mPackages) {
16171            return mSettings.getVerifierDeviceIdentityLPw();
16172        }
16173    }
16174
16175    @Override
16176    public void setPermissionEnforced(String permission, boolean enforced) {
16177        // TODO: Now that we no longer change GID for storage, this should to away.
16178        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16179                "setPermissionEnforced");
16180        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16181            synchronized (mPackages) {
16182                if (mSettings.mReadExternalStorageEnforced == null
16183                        || mSettings.mReadExternalStorageEnforced != enforced) {
16184                    mSettings.mReadExternalStorageEnforced = enforced;
16185                    mSettings.writeLPr();
16186                }
16187            }
16188            // kill any non-foreground processes so we restart them and
16189            // grant/revoke the GID.
16190            final IActivityManager am = ActivityManagerNative.getDefault();
16191            if (am != null) {
16192                final long token = Binder.clearCallingIdentity();
16193                try {
16194                    am.killProcessesBelowForeground("setPermissionEnforcement");
16195                } catch (RemoteException e) {
16196                } finally {
16197                    Binder.restoreCallingIdentity(token);
16198                }
16199            }
16200        } else {
16201            throw new IllegalArgumentException("No selective enforcement for " + permission);
16202        }
16203    }
16204
16205    @Override
16206    @Deprecated
16207    public boolean isPermissionEnforced(String permission) {
16208        return true;
16209    }
16210
16211    @Override
16212    public boolean isStorageLow() {
16213        final long token = Binder.clearCallingIdentity();
16214        try {
16215            final DeviceStorageMonitorInternal
16216                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16217            if (dsm != null) {
16218                return dsm.isMemoryLow();
16219            } else {
16220                return false;
16221            }
16222        } finally {
16223            Binder.restoreCallingIdentity(token);
16224        }
16225    }
16226
16227    @Override
16228    public IPackageInstaller getPackageInstaller() {
16229        return mInstallerService;
16230    }
16231
16232    private boolean userNeedsBadging(int userId) {
16233        int index = mUserNeedsBadging.indexOfKey(userId);
16234        if (index < 0) {
16235            final UserInfo userInfo;
16236            final long token = Binder.clearCallingIdentity();
16237            try {
16238                userInfo = sUserManager.getUserInfo(userId);
16239            } finally {
16240                Binder.restoreCallingIdentity(token);
16241            }
16242            final boolean b;
16243            if (userInfo != null && userInfo.isManagedProfile()) {
16244                b = true;
16245            } else {
16246                b = false;
16247            }
16248            mUserNeedsBadging.put(userId, b);
16249            return b;
16250        }
16251        return mUserNeedsBadging.valueAt(index);
16252    }
16253
16254    @Override
16255    public KeySet getKeySetByAlias(String packageName, String alias) {
16256        if (packageName == null || alias == null) {
16257            return null;
16258        }
16259        synchronized(mPackages) {
16260            final PackageParser.Package pkg = mPackages.get(packageName);
16261            if (pkg == null) {
16262                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16263                throw new IllegalArgumentException("Unknown package: " + packageName);
16264            }
16265            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16266            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16267        }
16268    }
16269
16270    @Override
16271    public KeySet getSigningKeySet(String packageName) {
16272        if (packageName == null) {
16273            return null;
16274        }
16275        synchronized(mPackages) {
16276            final PackageParser.Package pkg = mPackages.get(packageName);
16277            if (pkg == null) {
16278                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16279                throw new IllegalArgumentException("Unknown package: " + packageName);
16280            }
16281            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16282                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16283                throw new SecurityException("May not access signing KeySet of other apps.");
16284            }
16285            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16286            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16287        }
16288    }
16289
16290    @Override
16291    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16292        if (packageName == null || ks == null) {
16293            return false;
16294        }
16295        synchronized(mPackages) {
16296            final PackageParser.Package pkg = mPackages.get(packageName);
16297            if (pkg == null) {
16298                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16299                throw new IllegalArgumentException("Unknown package: " + packageName);
16300            }
16301            IBinder ksh = ks.getToken();
16302            if (ksh instanceof KeySetHandle) {
16303                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16304                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16305            }
16306            return false;
16307        }
16308    }
16309
16310    @Override
16311    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16312        if (packageName == null || ks == null) {
16313            return false;
16314        }
16315        synchronized(mPackages) {
16316            final PackageParser.Package pkg = mPackages.get(packageName);
16317            if (pkg == null) {
16318                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16319                throw new IllegalArgumentException("Unknown package: " + packageName);
16320            }
16321            IBinder ksh = ks.getToken();
16322            if (ksh instanceof KeySetHandle) {
16323                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16324                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16325            }
16326            return false;
16327        }
16328    }
16329
16330    public void getUsageStatsIfNoPackageUsageInfo() {
16331        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16332            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16333            if (usm == null) {
16334                throw new IllegalStateException("UsageStatsManager must be initialized");
16335            }
16336            long now = System.currentTimeMillis();
16337            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16338            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16339                String packageName = entry.getKey();
16340                PackageParser.Package pkg = mPackages.get(packageName);
16341                if (pkg == null) {
16342                    continue;
16343                }
16344                UsageStats usage = entry.getValue();
16345                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16346                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16347            }
16348        }
16349    }
16350
16351    /**
16352     * Check and throw if the given before/after packages would be considered a
16353     * downgrade.
16354     */
16355    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16356            throws PackageManagerException {
16357        if (after.versionCode < before.mVersionCode) {
16358            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16359                    "Update version code " + after.versionCode + " is older than current "
16360                    + before.mVersionCode);
16361        } else if (after.versionCode == before.mVersionCode) {
16362            if (after.baseRevisionCode < before.baseRevisionCode) {
16363                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16364                        "Update base revision code " + after.baseRevisionCode
16365                        + " is older than current " + before.baseRevisionCode);
16366            }
16367
16368            if (!ArrayUtils.isEmpty(after.splitNames)) {
16369                for (int i = 0; i < after.splitNames.length; i++) {
16370                    final String splitName = after.splitNames[i];
16371                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16372                    if (j != -1) {
16373                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16374                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16375                                    "Update split " + splitName + " revision code "
16376                                    + after.splitRevisionCodes[i] + " is older than current "
16377                                    + before.splitRevisionCodes[j]);
16378                        }
16379                    }
16380                }
16381            }
16382        }
16383    }
16384
16385    private static class MoveCallbacks extends Handler {
16386        private static final int MSG_CREATED = 1;
16387        private static final int MSG_STATUS_CHANGED = 2;
16388
16389        private final RemoteCallbackList<IPackageMoveObserver>
16390                mCallbacks = new RemoteCallbackList<>();
16391
16392        private final SparseIntArray mLastStatus = new SparseIntArray();
16393
16394        public MoveCallbacks(Looper looper) {
16395            super(looper);
16396        }
16397
16398        public void register(IPackageMoveObserver callback) {
16399            mCallbacks.register(callback);
16400        }
16401
16402        public void unregister(IPackageMoveObserver callback) {
16403            mCallbacks.unregister(callback);
16404        }
16405
16406        @Override
16407        public void handleMessage(Message msg) {
16408            final SomeArgs args = (SomeArgs) msg.obj;
16409            final int n = mCallbacks.beginBroadcast();
16410            for (int i = 0; i < n; i++) {
16411                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16412                try {
16413                    invokeCallback(callback, msg.what, args);
16414                } catch (RemoteException ignored) {
16415                }
16416            }
16417            mCallbacks.finishBroadcast();
16418            args.recycle();
16419        }
16420
16421        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16422                throws RemoteException {
16423            switch (what) {
16424                case MSG_CREATED: {
16425                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16426                    break;
16427                }
16428                case MSG_STATUS_CHANGED: {
16429                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16430                    break;
16431                }
16432            }
16433        }
16434
16435        private void notifyCreated(int moveId, Bundle extras) {
16436            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16437
16438            final SomeArgs args = SomeArgs.obtain();
16439            args.argi1 = moveId;
16440            args.arg2 = extras;
16441            obtainMessage(MSG_CREATED, args).sendToTarget();
16442        }
16443
16444        private void notifyStatusChanged(int moveId, int status) {
16445            notifyStatusChanged(moveId, status, -1);
16446        }
16447
16448        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16449            Slog.v(TAG, "Move " + moveId + " status " + status);
16450
16451            final SomeArgs args = SomeArgs.obtain();
16452            args.argi1 = moveId;
16453            args.argi2 = status;
16454            args.arg3 = estMillis;
16455            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16456
16457            synchronized (mLastStatus) {
16458                mLastStatus.put(moveId, status);
16459            }
16460        }
16461    }
16462
16463    private final class OnPermissionChangeListeners extends Handler {
16464        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16465
16466        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16467                new RemoteCallbackList<>();
16468
16469        public OnPermissionChangeListeners(Looper looper) {
16470            super(looper);
16471        }
16472
16473        @Override
16474        public void handleMessage(Message msg) {
16475            switch (msg.what) {
16476                case MSG_ON_PERMISSIONS_CHANGED: {
16477                    final int uid = msg.arg1;
16478                    handleOnPermissionsChanged(uid);
16479                } break;
16480            }
16481        }
16482
16483        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16484            mPermissionListeners.register(listener);
16485
16486        }
16487
16488        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16489            mPermissionListeners.unregister(listener);
16490        }
16491
16492        public void onPermissionsChanged(int uid) {
16493            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16494                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16495            }
16496        }
16497
16498        private void handleOnPermissionsChanged(int uid) {
16499            final int count = mPermissionListeners.beginBroadcast();
16500            try {
16501                for (int i = 0; i < count; i++) {
16502                    IOnPermissionsChangeListener callback = mPermissionListeners
16503                            .getBroadcastItem(i);
16504                    try {
16505                        callback.onPermissionsChanged(uid);
16506                    } catch (RemoteException e) {
16507                        Log.e(TAG, "Permission listener is dead", e);
16508                    }
16509                }
16510            } finally {
16511                mPermissionListeners.finishBroadcast();
16512            }
16513        }
16514    }
16515
16516    private class PackageManagerInternalImpl extends PackageManagerInternal {
16517        @Override
16518        public void setLocationPackagesProvider(PackagesProvider provider) {
16519            synchronized (mPackages) {
16520                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16521            }
16522        }
16523
16524        @Override
16525        public void setImePackagesProvider(PackagesProvider provider) {
16526            synchronized (mPackages) {
16527                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16528            }
16529        }
16530
16531        @Override
16532        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16533            synchronized (mPackages) {
16534                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16535            }
16536        }
16537
16538        @Override
16539        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16540            synchronized (mPackages) {
16541                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16542            }
16543        }
16544
16545        @Override
16546        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16547            synchronized (mPackages) {
16548                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16549            }
16550        }
16551
16552        @Override
16553        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16554            synchronized (mPackages) {
16555                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16556            }
16557        }
16558
16559        @Override
16560        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16561            synchronized (mPackages) {
16562                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16563            }
16564        }
16565
16566        @Override
16567        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16568            synchronized (mPackages) {
16569                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16570                        packageName, userId);
16571            }
16572        }
16573
16574        @Override
16575        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16576            synchronized (mPackages) {
16577                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16578                        packageName, userId);
16579            }
16580        }
16581        @Override
16582        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16583            synchronized (mPackages) {
16584                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16585                        packageName, userId);
16586            }
16587        }
16588    }
16589
16590    @Override
16591    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16592        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16593        synchronized (mPackages) {
16594            final long identity = Binder.clearCallingIdentity();
16595            try {
16596                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16597                        packageNames, userId);
16598            } finally {
16599                Binder.restoreCallingIdentity(identity);
16600            }
16601        }
16602    }
16603
16604    private static void enforceSystemOrPhoneCaller(String tag) {
16605        int callingUid = Binder.getCallingUid();
16606        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16607            throw new SecurityException(
16608                    "Cannot call " + tag + " from UID " + callingUid);
16609        }
16610    }
16611}
16612